Files
themiz/eunomia/web/dist/assets/react-force-graph-3d-MeqEw_23.js
T

5329 lines
1.3 MiB
Plaintext

import{d as e,f as t}from"./index-fLiDJSpq.js";import{_ as n,a as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _,u as v,v as y}from"./Connections-BbZyMe5U.js";var b={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},x={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},S=1e3,C=1001,w=1002,T=1003,E=1004,D=1005,O=1006,k=1007,ee=1008,te=1009,ne=1010,re=1011,ie=1012,ae=1013,oe=1014,se=1015,ce=1016,le=1017,ue=1018,de=1020,fe=35902,pe=35899,me=1021,he=1022,ge=1023,_e=1026,ve=1027,ye=1028,be=1029,xe=1030,Se=1031,Ce=1032,we=1033,Te=33776,Ee=33777,De=33778,Oe=33779,ke=35840,Ae=35841,je=35842,Me=35843,Ne=36196,Pe=37492,Fe=37496,Ie=37488,Le=37489,Re=37490,A=37491,ze=37808,Be=37809,Ve=37810,j=37811,He=37812,Ue=37813,We=37814,Ge=37815,Ke=37816,qe=37817,Je=37818,Ye=37819,Xe=37820,Ze=37821,Qe=36492,$e=36494,et=36495,tt=36283,nt=36284,rt=36285,it=36286,at=2300,ot=2301,st=2302,ct=2303,lt=2400,ut=2401,dt=2402,ft=3200,pt=`srgb`,mt=`srgb-linear`,ht=`linear`,gt=`srgb`,_t=7680,vt=7681,yt=7682,bt=7683,xt=34055,St=34056,Ct=5386,wt=35044,Tt=35048,Et=2e3,Dt=2001,Ot={COMPUTE:`compute`,RENDER:`render`},kt={TEXTURE_COMPARE:`depthTextureCompare`},At={NONE:0,SHARED:1,FULL:2};function jt(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Mt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Nt(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function Pt(){let e=Nt(`canvas`);return e.style.display=`block`,e}var Ft={};function It(...e){let t=`THREE.`+e.shift();console.log(t,...e)}function Lt(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function M(...e){e=Lt(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function N(...e){e=Lt(e);let t=`THREE.`+e.shift();{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function Rt(...e){let t=e.join(` `);t in Ft||(Ft[t]=!0,M(...e))}function zt(){return typeof self<`u`&&self.scheduler!==void 0&&self.scheduler.yield!==void 0?self.scheduler.yield():new Promise(e=>{requestAnimationFrame(e)})}function Bt(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var Vt={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},Ht=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n!==void 0&&n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}},Ut=`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`.split(`.`),Wt=1234567,Gt=Math.PI/180,Kt=180/Math.PI;function qt(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(Ut[e&255]+Ut[e>>8&255]+Ut[e>>16&255]+Ut[e>>24&255]+`-`+Ut[t&255]+Ut[t>>8&255]+`-`+Ut[t>>16&15|64]+Ut[t>>24&255]+`-`+Ut[n&63|128]+Ut[n>>8&255]+`-`+Ut[n>>16&255]+Ut[n>>24&255]+Ut[r&255]+Ut[r>>8&255]+Ut[r>>16&255]+Ut[r>>24&255]).toLowerCase()}function Jt(e,t,n){return Math.max(t,Math.min(n,e))}function Yt(e,t){return(e%t+t)%t}function Xt(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function Zt(e,t,n){return e===t?0:(n-e)/(t-e)}function Qt(e,t,n){return(1-n)*e+n*t}function $t(e,t,n,r){return Qt(e,t,1-Math.exp(-n*r))}function en(e,t=1){return t-Math.abs(Yt(e,t*2)-t)}function tn(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function nn(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function rn(e,t){return e+Math.floor(Math.random()*(t-e+1))}function an(e,t){return e+Math.random()*(t-e)}function on(e){return e*(.5-Math.random())}function sn(e){e!==void 0&&(Wt=e);let t=Wt+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function cn(e){return e*Gt}function ln(e){return e*Kt}function un(e){return e>0&&Number.isInteger(e)&&2**Math.round(Math.log2(e))===e}function dn(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function fn(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function pn(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),f=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*f,s*l);break;case`YZY`:e.set(c*f,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*f,s*u,s*l);break;case`XZX`:e.set(s*u,c*m,c*p,s*l);break;case`YXY`:e.set(c*p,s*u,c*m,s*l);break;case`ZYZ`:e.set(c*m,c*p,s*u,s*l);break;default:M(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function mn(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:case Uint8ClampedArray:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}function hn(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:case Uint8ClampedArray:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`THREE.MathUtils: Invalid component type.`)}}var gn={DEG2RAD:Gt,RAD2DEG:Kt,generateUUID:qt,clamp:Jt,euclideanModulo:Yt,mapLinear:Xt,inverseLerp:Zt,lerp:Qt,damp:$t,pingpong:en,smoothstep:tn,smootherstep:nn,randInt:rn,randFloat:an,randFloatSpread:on,seededRandom:sn,degToRad:cn,radToDeg:ln,isPowerOfTwo:un,ceilPowerOfTwo:dn,floorPowerOfTwo:fn,setQuaternionFromProperEuler:pn,normalize:hn,denormalize:mn},P=class e{static{e.prototype.isVector2=!0}constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`THREE.Vector2: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`THREE.Vector2: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Jt(this.x,e.x,t.x),this.y=Jt(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Jt(this.x,e,t),this.y=Jt(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Jt(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){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Jt(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let 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){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},_n=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*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,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:M(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Jt(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},F=class e{static{e.prototype.isVector3=!0}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 Error(`THREE.Vector3: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`THREE.Vector3: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(yn.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(yn.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Jt(this.x,e.x,t.x),this.y=Jt(this.y,e.y,t.y),this.z=Jt(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Jt(this.x,e,t),this.y=Jt(this.y,e,t),this.z=Jt(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Jt(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){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return vn.copy(this).projectOnVector(e),this.sub(vn)}reflect(e){return this.sub(vn.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Jt(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,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(){let 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}},vn=new F,yn=new _n,bn=class e{static{e.prototype.isMatrix3=!0}constructor(e,t,n,r,i,a,o,s,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,r,i,a,o,s,c)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let 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){let 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){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let 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(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,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){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return Rt(`Matrix3: .scale() is deprecated. Use .makeScale() instead.`),this.premultiply(xn.makeScale(e,t)),this}rotate(e){return Rt(`Matrix3: .rotate() is deprecated. Use .makeRotation() instead.`),this.premultiply(xn.makeRotation(-e)),this}translate(e,t){return Rt(`Matrix3: .translate() is deprecated. Use .makeTranslation() instead.`),this.premultiply(xn.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){let 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){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let 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)}},xn=new bn,Sn=new bn().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Cn=new bn().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function wn(){let e={enabled:!0,workingColorSpace:mt,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=Tn(e.r),e.g=Tn(e.g),e.b=Tn(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=En(e.r),e.g=En(e.g),e.b=En(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?ht:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return Rt(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return Rt(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[mt]:{primaries:t,whitePoint:r,transfer:ht,toXYZ:Sn,fromXYZ:Cn,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:pt},outputColorSpaceConfig:{drawingBufferColorSpace:pt}},[pt]:{primaries:t,whitePoint:r,transfer:gt,toXYZ:Sn,fromXYZ:Cn,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:pt}}}),e}var I=wn();function Tn(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function En(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var Dn,On=class{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{Dn===void 0&&(Dn=Nt(`canvas`)),Dn.width=e.width,Dn.height=e.height;let t=Dn.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Dn}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){let t=Nt(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=Tn(i[e]/255)*255;return n.putImageData(r,0,0),t}if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(Tn(t[e]/255)*255):t[e]=Tn(t[e]);return{data:t,width:e.width,height:e.height}}return M(`ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},kn=0,An=class{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:kn++}),this.uuid=qt(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let 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(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(jn(r[t].image)):e.push(jn(r[t]))}else e=jn(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function jn(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?On.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(M(`Texture: Unable to serialize Texture.`),{})}var Mn=0,Nn=new F,Pn=class e extends Ht{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=C,i=C,a=O,o=ee,s=ge,c=te,l=e.DEFAULT_ANISOTROPY,u=``){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Mn++}),this.uuid=qt(),this.name=``,this.source=new An(t),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=a,this.minFilter=o,this.anisotropy=l,this.format=s,this.internalFormat=null,this.type=c,this.offset=new P(0,0),this.repeat=new P(1,1),this.center=new P(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new bn,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=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Nn).x}get height(){return this.source.getSize(Nn).y}get depth(){return this.source.getSize(Nn).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(let t in e){let n=e[t];if(n===void 0){M(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){M(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let 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!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case S:e.x-=Math.floor(e.x);break;case C:e.x=e.x<0?0:1;break;case w:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case S:e.y-=Math.floor(e.y);break;case C:e.y=e.y<0?0:1;break;case w:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y)}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=300,Pn.DEFAULT_ANISOTROPY=1;var Fn=class e{static{e.prototype.isVector4=!0}constructor(e=0,t=0,n=0,r=1){this.x=e,this.y=t,this.z=n,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`THREE.Vector4: index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`THREE.Vector4: index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,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){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let 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=Jt(this.x,e.x,t.x),this.y=Jt(this.y,e.y,t.y),this.z=Jt(this.z,e.z,t.z),this.w=Jt(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Jt(this.x,e,t),this.y=Jt(this.y,e,t),this.z=Jt(this.z,e,t),this.w=Jt(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Jt(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}},In=class extends Ht{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:O,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Fn(0,0,e,t),this.scissorTest=!1,this.viewport=new Fn(0,0,e,t),this.textures=[];let r=new Pn({width:e,height:t,depth:n.depth}),i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveColorBuffer=n.resolveColorBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this.storeMultisampledColorBuffer=n.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=n.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=n.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(e={}){let t={minFilter:O,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 e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&this._depthTexture.renderTarget===this&&(this._depthTexture.renderTarget=null),e!==null&&e.renderTarget===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 r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isData3DTexture!==!0&&(this.textures[r].isArrayTexture=this.textures[r].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new An(n)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,e.depthTexture!==null){if(e.depthTexture.renderTarget===e){let t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture}return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:`dispose`})}},Ln=class extends In{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},Rn=class extends Pn{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=T,this.minFilter=T,this.wrapR=C,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},zn=class extends Pn{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=T,this.minFilter=T,this.wrapR=C,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}},Bn=class e{static{e.prototype.isMatrix4=!0}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){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,r,i,a,o,s,c,l,u,d,f,p,m,h)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,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 e().fromArray(this.elements)}copy(e){let 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){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let 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.determinantAffine()===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.determinantAffine()===0)return this.identity();let t=this.elements,n=e.elements,r=1/Vn.setFromMatrixColumn(e,0).length(),i=1/Vn.setFromMatrixColumn(e,1).length(),a=1/Vn.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Un,e,Wn)}lookAt(e,t,n){let r=this.elements;return qn.subVectors(e,t),qn.lengthSq()===0&&(qn.z=1),qn.normalize(),Gn.crossVectors(n,qn),Gn.lengthSq()===0&&(Math.abs(n.z)===1?qn.x+=1e-4:qn.z+=1e-4,qn.normalize(),Gn.crossVectors(n,qn)),Gn.normalize(),Kn.crossVectors(qn,Gn),r[0]=Gn.x,r[4]=Kn.x,r[8]=qn.x,r[1]=Gn.y,r[5]=Kn.y,r[9]=qn.y,r[2]=Gn.z,r[6]=Kn.z,r[10]=qn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],O=r[13],k=r[2],ee=r[6],te=r[10],ne=r[14],re=r[3],ie=r[7],ae=r[11],oe=r[15];return i[0]=a*x+o*T+s*k+c*re,i[4]=a*S+o*E+s*ee+c*ie,i[8]=a*C+o*D+s*te+c*ae,i[12]=a*w+o*O+s*ne+c*oe,i[1]=l*x+u*T+d*k+f*re,i[5]=l*S+u*E+d*ee+f*ie,i[9]=l*C+u*D+d*te+f*ae,i[13]=l*w+u*O+d*ne+f*oe,i[2]=p*x+m*T+h*k+g*re,i[6]=p*S+m*E+h*ee+g*ie,i[10]=p*C+m*D+h*te+g*ae,i[14]=p*w+m*O+h*ne+g*oe,i[3]=_*x+v*T+y*k+b*re,i[7]=_*S+v*E+y*ee+b*ie,i[11]=_*C+v*D+y*te+b*ae,i[15]=_*w+v*O+y*ne+b*oe,this}multiplyScalar(e){let 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(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15],_=s*f-c*d,v=o*f-c*u,y=o*d-s*u,b=a*f-c*l,x=a*d-s*l,S=a*u-o*l;return t*(m*_-h*v+g*y)-n*(p*_-h*b+g*x)+r*(p*v-m*b+g*S)-i*(p*y-m*x+h*S)}determinantAffine(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[1],a=e[5],o=e[9],s=e[2],c=e[6],l=e[10];return t*(a*l-o*c)-n*(i*l-o*s)+r*(i*c-a*s)}transpose(){let e=this.elements,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){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=t*o-n*a,v=t*s-r*a,y=t*c-i*a,b=n*s-r*o,x=n*c-i*o,S=r*c-i*s,C=l*m-u*p,w=l*h-d*p,T=l*g-f*p,E=u*h-d*m,D=u*g-f*m,O=d*g-f*h,k=_*O-v*D+y*E+b*T-x*w+S*C;if(k===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let ee=1/k;return e[0]=(o*O-s*D+c*E)*ee,e[1]=(r*D-n*O-i*E)*ee,e[2]=(m*S-h*x+g*b)*ee,e[3]=(d*x-u*S-f*b)*ee,e[4]=(s*T-a*O-c*w)*ee,e[5]=(t*O-r*T+i*w)*ee,e[6]=(h*y-p*S-g*v)*ee,e[7]=(l*S-d*y+f*v)*ee,e[8]=(a*D-o*T+c*C)*ee,e[9]=(n*T-t*D-i*C)*ee,e[10]=(p*x-m*y+g*_)*ee,e[11]=(u*y-l*x-f*_)*ee,e[12]=(o*w-a*E-s*C)*ee,e[13]=(t*E-n*w+r*C)*ee,e[14]=(m*v-p*b-h*_)*ee,e[15]=(l*b-u*v+d*_)*ee,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let 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){let 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){let 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){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements;e.x=r[12],e.y=r[13],e.z=r[14];let i=this.determinantAffine();if(i===0)return n.set(1,1,1),t.identity(),this;let a=Vn.set(r[0],r[1],r[2]).length(),o=Vn.set(r[4],r[5],r[6]).length(),s=Vn.set(r[8],r[9],r[10]).length();i<0&&(a=-a),Hn.copy(this);let c=1/a,l=1/o,u=1/s;return Hn.elements[0]*=c,Hn.elements[1]*=c,Hn.elements[2]*=c,Hn.elements[4]*=l,Hn.elements[5]*=l,Hn.elements[6]*=l,Hn.elements[8]*=u,Hn.elements[9]*=u,Hn.elements[10]*=u,t.setFromRotationMatrix(Hn),n.x=a,n.y=o,n.z=s,this}makePerspective(e,t,n,r,i,a,o=Et,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=Et,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let 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}},Vn=new F,Hn=new Bn,Un=new F(0,0,0),Wn=new F(1,1,1),Gn=new F,Kn=new F,qn=new F,Jn=new Bn,Yn=new _n,Xn=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,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,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin(Jt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-Jt(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin(Jt(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-Jt(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin(Jt(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-Jt(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:M(`Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Jn.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Jn,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Yn.setFromEuler(this),this.setFromQuaternion(Yn,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}};Xn.DEFAULT_ORDER=`XYZ`;var Zn=class{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))}},Qn=0,$n=new F,er=new _n,tr=new Bn,nr=new F,rr=new F,ir=new F,ar=new _n,or=new F(1,0,0),sr=new F(0,1,0),cr=new F(0,0,1),lr={type:`added`},ur={type:`removed`},dr={type:`childadded`,child:null},fr={type:`childremoved`,child:null},pr=class e extends Ht{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Qn++}),this.uuid=qt(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new F,n=new Xn,r=new _n,i=new F(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Bn},normalMatrix:{value:new bn}}),this.matrix=new Bn,this.matrixWorld=new Bn,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Zn,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 er.setFromAxisAngle(e,t),this.quaternion.multiply(er),this}rotateOnWorldAxis(e,t){return er.setFromAxisAngle(e,t),this.quaternion.premultiply(er),this}rotateX(e){return this.rotateOnAxis(or,e)}rotateY(e){return this.rotateOnAxis(sr,e)}rotateZ(e){return this.rotateOnAxis(cr,e)}translateOnAxis(e,t){return $n.copy(e).applyQuaternion(this.quaternion),this.position.add($n.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(or,e)}translateY(e){return this.translateOnAxis(sr,e)}translateZ(e){return this.translateOnAxis(cr,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(tr.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?nr.copy(e):nr.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),rr.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?tr.lookAt(rr,nr,this.up):tr.lookAt(nr,rr,this.up),this.quaternion.setFromRotationMatrix(tr),r&&(tr.extractRotation(r.matrixWorld),er.setFromRotationMatrix(tr),this.quaternion.premultiply(er.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(N(`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(lr),dr.child=e,this.dispatchEvent(dr),dr.child=null):N(`Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(ur),fr.child=e,this.dispatchEvent(fr),fr.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),tr.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),tr.multiply(e.parent.matrixWorld)),e.applyMatrix4(tr),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(lr),dr.child=e,this.dispatchEvent(dr),dr.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rr,e,ir),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(rr,ar,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let e=this.pivot;if(e!==null){let t=e.x,n=e.y,r=e.z,i=this.matrix.elements;i[12]+=t-i[0]*t-i[4]*n-i[8]*r,i[13]+=n-i[1]*t-i[5]*n-i[9]*r,i[14]+=r-i[2]*t-i[6]*n-i[10]*r}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);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t,n=!1){let r=this.parent;if(e===!0&&r!==null&&r.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||n)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,n=!0),t===!0){let e=this.children;for(let t=0,r=e.length;t<r;t++)e[t].updateWorldMatrix(!1,!0,n)}}toJSON(e){let 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`});let r={};r.uuid=this.uuid,r.type=this.type,r.name=this.name,r.castShadow=this.castShadow,r.receiveShadow=this.receiveShadow,r.visible=this.visible,r.frustumCulled=this.frustumCulled,r.renderOrder=this.renderOrder,r.static=this.static,r.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0){if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material)}if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot===null?null:e.pivot.clone(),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 t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}dispose(){this.dispatchEvent({type:`dispose`})}};pr.DEFAULT_UP=new F(0,1,0),pr.DEFAULT_MATRIX_AUTO_UPDATE=!0,pr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var mr=class extends pr{constructor(){super(),this.isGroup=!0,this.type=`Group`}},hr={type:`move`},gr=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new mr,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 mr,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new F,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new F),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new mr,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new F,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new F,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){let t=this._hand;if(t)for(let 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 r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position);c.inputState.pinching&&o>.025?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=.015&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,s.eventsEnabled&&s.dispatchEvent({type:`gripUpdated`,data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(hr)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new mr;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},_r={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},vr={h:0,s:0,l:0},yr={h:0,s:0,l:0};function br(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var L=class{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){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=pt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,I.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=I.workingColorSpace){return this.r=e,this.g=t,this.b=n,I.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=I.workingColorSpace){if(e=Yt(e,1),t=Jt(t,0,1),n=Jt(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=br(i,r,e+1/3),this.g=br(i,r,e),this.b=br(i,r,e-1/3)}return I.colorSpaceToWorking(this,r),this}setStyle(e,t=pt){function n(t){t!==void 0&&parseFloat(t)<1&&M(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:M(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);M(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=pt){let n=_r[e.toLowerCase()];return n===void 0?M(`Color: Unknown color `+e):this.setHex(n,t),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=Tn(e.r),this.g=Tn(e.g),this.b=Tn(e.b),this}copyLinearToSRGB(e){return this.r=En(e.r),this.g=En(e.g),this.b=En(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=pt){return I.workingToColorSpace(xr.copy(this),e),Math.round(Jt(xr.r*255,0,255))*65536+Math.round(Jt(xr.g*255,0,255))*256+Math.round(Jt(xr.b*255,0,255))}getHexString(e=pt){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=I.workingColorSpace){I.workingToColorSpace(xr.copy(this),t);let n=xr.r,r=xr.g,i=xr.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=I.workingColorSpace){return I.workingToColorSpace(xr.copy(this),t),e.r=xr.r,e.g=xr.g,e.b=xr.b,e}getStyle(e=pt){I.workingToColorSpace(xr.copy(this),e);let t=xr.r,n=xr.g,r=xr.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(vr),this.setHSL(vr.h+e,vr.s+t,vr.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(vr),e.getHSL(yr);let n=Qt(vr.h,yr.h,t),r=Qt(vr.s,yr.s,t),i=Qt(vr.l,yr.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},xr=new L;L.NAMES=_r;var Sr=class extends pr{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 Xn,this.environmentIntensity=1,this.environmentRotation=new Xn,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){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}},Cr=new F,wr=new F,Tr=new F,Er=new F,Dr=new F,Or=new F,kr=new F,Ar=new F,jr=new F,Mr=new F,Nr=new Fn,Pr=new Fn,Fr=new Fn,Ir=class e{constructor(e=new F,t=new F,n=new F){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),Cr.subVectors(e,t),r.cross(Cr);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){Cr.subVectors(r,t),wr.subVectors(n,t),Tr.subVectors(e,t);let a=Cr.dot(Cr),o=Cr.dot(wr),s=Cr.dot(Tr),c=wr.dot(wr),l=wr.dot(Tr),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Er)!==null&&Er.x>=0&&Er.y>=0&&Er.x+Er.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Er)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,Er.x),s.addScaledVector(a,Er.y),s.addScaledVector(o,Er.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return Nr.setScalar(0),Pr.setScalar(0),Fr.setScalar(0),Nr.fromBufferAttribute(e,t),Pr.fromBufferAttribute(e,n),Fr.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(Nr,i.x),a.addScaledVector(Pr,i.y),a.addScaledVector(Fr,i.z),a}static isFrontFacing(e,t,n,r){return Cr.subVectors(n,t),wr.subVectors(e,t),Cr.cross(wr).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Cr.subVectors(this.c,this.b),wr.subVectors(this.a,this.b),Cr.cross(wr).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;Dr.subVectors(r,n),Or.subVectors(i,n),Ar.subVectors(e,n);let s=Dr.dot(Ar),c=Or.dot(Ar);if(s<=0&&c<=0)return t.copy(n);jr.subVectors(e,r);let l=Dr.dot(jr),u=Or.dot(jr);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(Dr,a);Mr.subVectors(e,i);let f=Dr.dot(Mr),p=Or.dot(Mr);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(Or,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return kr.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(kr,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Dr,a).addScaledVector(Or,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Lr=class{constructor(e=new F(1/0,1/0,1/0),t=new F(-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(zr.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(zr.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){let n=zr.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);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,zr):zr.fromBufferAttribute(r,t),zr.applyMatrix4(e.matrixWorld),this.expandByPoint(zr);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Br.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Br.copy(e.boundingBox)),Br.applyMatrix4(e.matrixWorld),this.union(Br)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,zr),zr.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(qr),Jr.subVectors(this.max,qr),Vr.subVectors(e.a,qr),Hr.subVectors(e.b,qr),Ur.subVectors(e.c,qr),Wr.subVectors(Hr,Vr),Gr.subVectors(Ur,Hr),Kr.subVectors(Vr,Ur);let t=[0,-Wr.z,Wr.y,0,-Gr.z,Gr.y,0,-Kr.z,Kr.y,Wr.z,0,-Wr.x,Gr.z,0,-Gr.x,Kr.z,0,-Kr.x,-Wr.y,Wr.x,0,-Gr.y,Gr.x,0,-Kr.y,Kr.x,0];return!Zr(t,Vr,Hr,Ur,Jr)||(t=[1,0,0,0,1,0,0,0,1],!Zr(t,Vr,Hr,Ur,Jr))?!1:(Yr.crossVectors(Wr,Gr),t=[Yr.x,Yr.y,Yr.z],Zr(t,Vr,Hr,Ur,Jr))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,zr).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(zr).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:(Rr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Rr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Rr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Rr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Rr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Rr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Rr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Rr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Rr),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}},Rr=[new F,new F,new F,new F,new F,new F,new F,new F],zr=new F,Br=new Lr,Vr=new F,Hr=new F,Ur=new F,Wr=new F,Gr=new F,Kr=new F,qr=new F,Jr=new F,Yr=new F,Xr=new F;function Zr(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){Xr.fromArray(e,a);let o=i.x*Math.abs(Xr.x)+i.y*Math.abs(Xr.y)+i.z*Math.abs(Xr.z),s=t.dot(Xr),c=n.dot(Xr),l=r.dot(Xr);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var Qr=$r();function $r(){let e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),r=new Uint32Array(512),i=new Uint32Array(512);for(let e=0;e<256;++e){let t=e-127;t<-27?(r[e]=0,r[e|256]=32768,i[e]=24,i[e|256]=24):t<-14?(r[e]=1024>>-t-14,r[e|256]=1024>>-t-14|32768,i[e]=-t-1,i[e|256]=-t-1):t<=15?(r[e]=t+15<<10,r[e|256]=t+15<<10|32768,i[e]=13,i[e|256]=13):t<128?(r[e]=31744,r[e|256]=64512,i[e]=24,i[e|256]=24):(r[e]=31744,r[e|256]=64512,i[e]=13,i[e|256]=13)}let a=new Uint32Array(2048),o=new Uint32Array(64),s=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(t&8388608);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,a[e]=t|n}for(let e=1024;e<2048;++e)a[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)e!==32&&(s[e]=1024);return{floatView:t,uint32View:n,baseTable:r,shiftTable:i,mantissaTable:a,exponentTable:o,offsetTable:s}}function ei(e){Math.abs(e)>65504&&M(`DataUtils.toHalfFloat(): Value out of range.`),e=Jt(e,-65504,65504),Qr.floatView[0]=e;let t=Qr.uint32View[0],n=t>>23&511;return Qr.baseTable[n]+((t&8388607)>>Qr.shiftTable[n])}function ti(e){let t=e>>10;return Qr.uint32View[0]=Qr.mantissaTable[Qr.offsetTable[t]+(e&1023)]+Qr.exponentTable[t],Qr.floatView[0]}var ni=new F,ri=new P,ii=0,ai=class extends Ht{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:ii++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=wt,this.updateRanges=[],this.gpuType=se,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 r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)ri.fromBufferAttribute(this,t),ri.applyMatrix3(e),this.setXY(t,ri.x,ri.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)ni.fromBufferAttribute(this,t),ni.applyMatrix3(e),this.setXYZ(t,ni.x,ni.y,ni.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)ni.fromBufferAttribute(this,t),ni.applyMatrix4(e),this.setXYZ(t,ni.x,ni.y,ni.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)ni.fromBufferAttribute(this,t),ni.applyNormalMatrix(e),this.setXYZ(t,ni.x,ni.y,ni.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)ni.fromBufferAttribute(this,t),ni.transformDirection(e),this.setXYZ(t,ni.x,ni.y,ni.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=mn(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=hn(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=mn(t,this.array)),t}setX(e,t){return this.normalized&&(t=hn(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=mn(t,this.array)),t}setY(e,t){return this.normalized&&(t=hn(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=mn(t,this.array)),t}setZ(e,t){return this.normalized&&(t=hn(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=mn(t,this.array)),t}setW(e,t){return this.normalized&&(t=hn(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=hn(t,this.array),n=hn(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=hn(t,this.array),n=hn(n,this.array),r=hn(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=hn(t,this.array),n=hn(n,this.array),r=hn(r,this.array),i=hn(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:`dispose`})}},oi=class extends ai{constructor(e,t,n){super(new Uint16Array(e),t,n)}},si=class extends ai{constructor(e,t,n){super(new Uint32Array(e),t,n)}},ci=class extends ai{constructor(e,t,n){super(new Uint16Array(e),t,n),this.isFloat16BufferAttribute=!0}getX(e){let t=ti(this.array[e*this.itemSize]);return this.normalized&&(t=mn(t,this.array)),t}setX(e,t){return this.normalized&&(t=hn(t,this.array)),this.array[e*this.itemSize]=ei(t),this}getY(e){let t=ti(this.array[e*this.itemSize+1]);return this.normalized&&(t=mn(t,this.array)),t}setY(e,t){return this.normalized&&(t=hn(t,this.array)),this.array[e*this.itemSize+1]=ei(t),this}getZ(e){let t=ti(this.array[e*this.itemSize+2]);return this.normalized&&(t=mn(t,this.array)),t}setZ(e,t){return this.normalized&&(t=hn(t,this.array)),this.array[e*this.itemSize+2]=ei(t),this}getW(e){let t=ti(this.array[e*this.itemSize+3]);return this.normalized&&(t=mn(t,this.array)),t}setW(e,t){return this.normalized&&(t=hn(t,this.array)),this.array[e*this.itemSize+3]=ei(t),this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=hn(t,this.array),n=hn(n,this.array)),this.array[e+0]=ei(t),this.array[e+1]=ei(n),this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=hn(t,this.array),n=hn(n,this.array),r=hn(r,this.array)),this.array[e+0]=ei(t),this.array[e+1]=ei(n),this.array[e+2]=ei(r),this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=hn(t,this.array),n=hn(n,this.array),r=hn(r,this.array),i=hn(i,this.array)),this.array[e+0]=ei(t),this.array[e+1]=ei(n),this.array[e+2]=ei(r),this.array[e+3]=ei(i),this}},li=class extends ai{constructor(e,t,n){super(new Float32Array(e),t,n)}},ui=new Lr,di=new F,fi=new F,pi=class{constructor(e=new F,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){let n=this.center;t===void 0?ui.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let 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){let 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*=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;di.subVectors(e,this.center);let t=di.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(di,n/e),this.radius+=n}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):(fi.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(di.copy(e.center).add(fi)),this.expandByPoint(di.copy(e.center).sub(fi))),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}},mi=0,hi=new Bn,gi=new pr,_i=new F,vi=new Lr,yi=new Lr,bi=new F,xi=class e extends Ht{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:mi++}),this.uuid=qt(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return this.index=Array.isArray(e)?new(jt(e)?si:oi)(e,1):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){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new bn().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return hi.makeRotationFromQuaternion(e),this.applyMatrix4(hi),this}rotateX(e){return hi.makeRotationX(e),this.applyMatrix4(hi),this}rotateY(e){return hi.makeRotationY(e),this.applyMatrix4(hi),this}rotateZ(e){return hi.makeRotationZ(e),this.applyMatrix4(hi),this}translate(e,t,n){return hi.makeTranslation(e,t,n),this.applyMatrix4(hi),this}scale(e,t,n){return hi.makeScale(e,t,n),this.applyMatrix4(hi),this}lookAt(e){return gi.lookAt(e),gi.updateMatrix(),this.applyMatrix4(gi.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(_i).negate(),this.translate(_i.x,_i.y,_i.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new li(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&M(`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 Lr);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){N(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new F(-1/0,-1/0,-1/0),new F(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];vi.setFromBufferAttribute(n),this.morphTargetsRelative?(bi.addVectors(this.boundingBox.min,vi.min),this.boundingBox.expandByPoint(bi),bi.addVectors(this.boundingBox.max,vi.max),this.boundingBox.expandByPoint(bi)):(this.boundingBox.expandByPoint(vi.min),this.boundingBox.expandByPoint(vi.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&N(`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 pi);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){N(`BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new F,1/0);return}if(e){let n=this.boundingSphere.center;if(vi.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];yi.setFromBufferAttribute(n),this.morphTargetsRelative?(bi.addVectors(vi.min,yi.min),vi.expandByPoint(bi),bi.addVectors(vi.max,yi.max),vi.expandByPoint(bi)):(vi.expandByPoint(yi.min),vi.expandByPoint(yi.max))}vi.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)bi.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(bi));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)bi.fromBufferAttribute(a,t),o&&(_i.fromBufferAttribute(e,t),bi.add(_i)),r=Math.max(r,n.distanceToSquared(bi))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&N(`BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){N(`BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv,a=this.getAttribute(`tangent`);(a===void 0||a.count!==n.count)&&(a=new ai(new Float32Array(4*n.count),4),this.setAttribute(`tangent`,a));let o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new F,s[e]=new F;let c=new F,l=new F,u=new F,d=new P,f=new P,p=new P,m=new F,h=new F;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new F,y=new F,b=new F,x=new F;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}this._transformed=!0}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0||n.count!==t.count)n=new ai(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new F,i=new F,a=new F,o=new F,s=new F,c=new F,l=new F,u=new F;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)bi.fromBufferAttribute(e,t),bi.normalize(),e.setXYZ(t,bi.x,bi.y,bi.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new ai(a,r,i)}if(this.index===null)return M(`BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.parameters!==void 0&&this._transformed===!0?`BufferGeometry`:this.type,e.name=this.name,Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.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;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:`dispose`})}},Si=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e===void 0?0:e.length/t,this.usage=wt,this.updateRanges=[],this.version=0,this.uuid=qt()}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 r=0,i=this.stride;r<i;r++)this.array[e+r]=t.array[n+r];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=qt()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let 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){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=qt()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer)));let t={uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride};return t.usage=this.usage,t}},Ci=new F,wi=class e{constructor(e,t,n,r=!1){this.isInterleavedBufferAttribute=!0,this.name=``,this.data=e,this.itemSize=t,this.offset=n,this.normalized=r}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)Ci.fromBufferAttribute(this,t),Ci.applyMatrix4(e),this.setXYZ(t,Ci.x,Ci.y,Ci.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Ci.fromBufferAttribute(this,t),Ci.applyNormalMatrix(e),this.setXYZ(t,Ci.x,Ci.y,Ci.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Ci.fromBufferAttribute(this,t),Ci.transformDirection(e),this.setXYZ(t,Ci.x,Ci.y,Ci.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=mn(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=hn(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=hn(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=hn(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=hn(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=hn(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=mn(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=mn(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=mn(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=mn(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=hn(t,this.array),n=hn(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=hn(t,this.array),n=hn(n,this.array),r=hn(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=hn(t,this.array),n=hn(n,this.array),r=hn(r,this.array),i=hn(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this.data.array[e+3]=i,this}clone(t){if(t===void 0){It(`InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return new ai(new this.array.constructor(e),this.itemSize,this.normalized)}return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new e(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){It(`InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}return 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}}},Ti=new F,Ei=new F,Di=new bn,Oi=class{constructor(e=new F(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=Ti.subVectors(n,t).cross(Ei.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let 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){let r=e.delta(Ti),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let a=-(e.start.dot(this.normal)+this.constant)/i;return n===!0&&(a<0||a>1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let 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){let n=t||Di.getNormalMatrix(e),r=this.coplanarPoint(Ti).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}},ki=0,Ai=class extends Ht{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:ki++}),this.uuid=qt(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new L(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=_t,this.stencilZFail=_t,this.stencilZPass=_t,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(let t in e){let n=e[t];if(n===void 0){M(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){M(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector2&&n&&n.isVector2||r&&r.isEuler&&n&&n.isEuler||r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,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&&(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.retroreflectivity!==void 0&&(n.retroreflectivity=this.retroreflectivity),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&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(e=>e.toJSON())),this.rotation!==void 0&&(n.rotation=this.rotation),this.depthPacking!==void 0&&(n.depthPacking=this.depthPacking),this.linewidth!==void 0&&(n.linewidth=this.linewidth),this.linecap!==void 0&&(n.linecap=this.linecap),this.linejoin!==void 0&&(n.linejoin=this.linejoin),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.wireframe!==void 0&&(n.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(n.flatShading=this.flatShading),this.fog!==void 0&&(n.fog=this.fog),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new L().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.retroreflectivity!==void 0&&(this.retroreflectivity=e.retroreflectivity),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.clippingPlanes!==void 0&&(this.clippingPlanes=e.clippingPlanes.map(e=>new Oi().fromJSON(e))),e.clipIntersection!==void 0&&(this.clipIntersection=e.clipIntersection),e.clipShadows!==void 0&&(this.clipShadows=e.clipShadows),e.depthPacking!==void 0&&(this.depthPacking=e.depthPacking),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.linecap!==void 0&&(this.linecap=e.linecap),e.linejoin!==void 0&&(this.linejoin=e.linejoin),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(this.vertexColors=typeof e.vertexColors==`number`?e.vertexColors>0:e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let t=e.normalScale;Array.isArray(t)===!1&&(t=[t,t]),this.normalScale=new P().fromArray(t)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new P().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},ji=class extends Ai{constructor(e){super(),this.isSpriteMaterial=!0,this.type=`SpriteMaterial`,this.color=new L(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}},Mi=new F,Ni=new F,Pi=new F,Fi=new F,Ii=class{constructor(e=new F,t=new F(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,Mi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let 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){let t=Mi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Mi.copy(this.origin).addScaledVector(this.direction,t),Mi.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){Ni.copy(e).add(t).multiplyScalar(.5),Pi.copy(t).sub(e).normalize(),Fi.copy(this.origin).sub(Ni);let i=e.distanceTo(t)*.5,a=-this.direction.dot(Pi),o=Fi.dot(this.direction),s=-Fi.dot(Pi),c=Fi.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0){if(u=a*s-o,d=a*o-s,p=i*l,u>=0){if(d>=-p){if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c}else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c)}else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(Ni).addScaledVector(Pi,d),f}intersectSphere(e,t){if(e.radius<0)return null;Mi.subVectors(e.center,this.origin);let n=Mi.dot(this.direction),r=Mi.dot(Mi)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,Mi)!==null}intersectTriangle(e,t,n,r,i){let a=this.origin,o=this.direction,s=o.x,c=o.y,l=o.z,u=e.x-a.x,d=e.y-a.y,f=e.z-a.z,p=t.x-a.x,m=t.y-a.y,h=t.z-a.z,g=n.x-a.x,_=n.y-a.y,v=n.z-a.z,y=Math.abs(s),b=Math.abs(c),x=Math.abs(l),S,C,w,T,E,D,O,k,ee,te,ne,re;if(y>=b&&y>=x?(w=s,D=u,ee=p,re=g,s>=0?(S=c,C=l,T=d,E=f,O=m,k=h,te=_,ne=v):(S=l,C=c,T=f,E=d,O=h,k=m,te=v,ne=_)):b>=x?(w=c,D=d,ee=m,re=_,c>=0?(S=l,C=s,T=f,E=u,O=h,k=p,te=v,ne=g):(S=s,C=l,T=u,E=f,O=p,k=h,te=g,ne=v)):(w=l,D=f,ee=h,re=v,l>=0?(S=s,C=c,T=u,E=d,O=p,k=m,te=g,ne=_):(S=c,C=s,T=d,E=u,O=m,k=p,te=_,ne=g)),w===0)return null;let ie=S/w,ae=C/w,oe=1/w,se=T-ie*D,ce=E-ae*D,le=O-ie*ee,ue=k-ae*ee,de=te-ie*re,fe=ne-ae*re,pe=de*ue-fe*le,me=se*fe-ce*de,he=le*ce-ue*se;if(r){if(pe<0||me<0||he<0)return null}else if((pe<0||me<0||he<0)&&(pe>0||me>0||he>0))return null;let ge=pe+me+he;if(ge===0)return null;let _e=oe*(pe*D+me*ee+he*re);return(ge>0?_e<0:_e>0)?null:this.at(_e/ge,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},Li=class extends Ai{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new L(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 Xn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},Ri=new Bn,zi=new Ii,Bi=new pi,Vi=new F,Hi=new F,Ui=new F,Wi=new F,Gi=new F,Ki=new F,qi=new F,Ji=new F,Yi=class extends pr{constructor(e=new xi,t=new Li){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(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){Ki.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(Gi.fromBufferAttribute(s,e),a?Ki.addScaledVector(Gi,r):Ki.addScaledVector(Gi.sub(t),r))}t.add(Ki)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Bi.copy(n.boundingSphere),Bi.applyMatrix4(i),zi.copy(e.ray).recast(e.near),!(Bi.containsPoint(zi.origin)===!1&&(zi.intersectSphere(Bi,Vi)===null||zi.origin.distanceToSquared(Vi)>(e.far-e.near)**2))&&(Ri.copy(i).invert(),zi.copy(e.ray).applyMatrix4(Ri),(n.boundingBox===null||zi.intersectsBox(n.boundingBox)!==!1)&&this._computeIntersections(e,t,zi)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null){if(Array.isArray(a))for(let i=0,s=d.length;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=Zi(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=Zi(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}}else if(s!==void 0){if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=Zi(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=Zi(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}}};function Xi(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;Ji.copy(s),Ji.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(Ji);return l<n.near||l>n.far?null:{distance:l,point:Ji.clone(),object:e}}function Zi(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,Hi),e.getVertexPosition(c,Ui),e.getVertexPosition(l,Wi);let u=Xi(e,t,n,r,Hi,Ui,Wi,qi);if(u){let e=new F;Ir.getBarycoord(qi,Hi,Ui,Wi,e),i&&(u.uv=Ir.getInterpolatedAttribute(i,s,c,l,e,new P)),a&&(u.uv1=Ir.getInterpolatedAttribute(a,s,c,l,e,new P)),o&&(u.normal=Ir.getInterpolatedAttribute(o,s,c,l,e,new F),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new F,materialIndex:0};Ir.getNormal(Hi,Ui,Wi,t.normal),u.face=t,u.barycoord=e}return u}var Qi=class extends Pn{constructor(e=null,t=1,n=1,r,i,a,o,s,c=T,l=T,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},$i=class extends ai{constructor(e,t,n,r=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=r}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){let e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}},ea=new pi,ta=new P(.5,.5),na=new F,ra=class{constructor(e=new Oi,t=new Oi,n=new Oi,r=new Oi,i=new Oi,a=new Oi){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Et,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),ea.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ea.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ea)}intersectsSprite(e){return ea.center.set(0,0,0),ea.radius=.7071067811865476+ta.distanceTo(e.center),ea.applyMatrix4(e.matrixWorld),this.intersectsSphere(ea)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(na.x=r.normal.x>0?e.max.x:e.min.x,na.y=r.normal.y>0?e.max.y:e.min.y,na.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(na)<0)return!1}return!0}containsPoint(e){let 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)}},ia=new Bn,aa=class e{constructor(){this.coordinateSystem=Et,this._frustums=[],this._count=0}setFromArrayCamera(e){let t=e.cameras,n=this._frustums;for(let e=0;e<t.length;e++){let r=t[e];ia.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),n[e]===void 0&&(n[e]=new ra),n[e].setFromProjectionMatrix(ia,r.coordinateSystem,r.reversedDepth)}return this._count=t.length,this}intersectsObject(e){let t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsObject(e))return!0;return!1}intersectsSprite(e){let t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsSprite(e))return!0;return!1}intersectsSphere(e){let t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsSphere(e))return!0;return!1}intersectsBox(e){let t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].intersectsBox(e))return!0;return!1}containsPoint(e){let t=this._frustums;for(let n=0;n<this._count;n++)if(t[n].containsPoint(e))return!0;return!1}copy(e){this.coordinateSystem=e.coordinateSystem;let t=this._frustums,n=e._frustums;for(let r=0;r<e._count;r++)t[r]===void 0&&(t[r]=new ra),t[r].copy(n[r]);return this._count=e._count,this}clone(){return new e().copy(this)}},oa=class extends Ai{constructor(e){super(),this.isLineBasicMaterial=!0,this.type=`LineBasicMaterial`,this.color=new L(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}},sa=new F,ca=new F,la=new Bn,ua=new Ii,da=new pi,fa=new F,pa=new F,ma=class extends pr{constructor(e=new xi,t=new oa){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(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let e=1,r=t.count;e<r;e++)sa.fromBufferAttribute(t,e-1),ca.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=sa.distanceTo(ca);e.setAttribute(`lineDistance`,new li(n,1))}else M(`Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){let n=this.geometry,r=this.matrixWorld,i=e.params.Line.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),da.copy(n.boundingSphere),da.applyMatrix4(r),da.radius+=i,e.ray.intersectsSphere(da)===!1)return;la.copy(r).invert(),ua.copy(e.ray).applyMatrix4(la);let o=i/((this.scale.x+this.scale.y+this.scale.z)/3),s=o*o,c=this.isLineSegments?2:1,l=n.index,u=n.attributes.position;if(l!==null){let n=Math.max(0,a.start),r=Math.min(l.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=l.getX(i),r=l.getX(i+1),a=ha(this,e,ua,s,n,r,i);a&&t.push(a)}if(this.isLineLoop){let i=l.getX(r-1),a=l.getX(n),o=ha(this,e,ua,s,i,a,r-1);o&&t.push(o)}}else{let n=Math.max(0,a.start),r=Math.min(u.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=ha(this,e,ua,s,i,i+1,i);n&&t.push(n)}if(this.isLineLoop){let i=ha(this,e,ua,s,r-1,n,r-1);i&&t.push(i)}}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}};function ha(e,t,n,r,i,a,o){let s=e.geometry.attributes.position;if(sa.fromBufferAttribute(s,i),ca.fromBufferAttribute(s,a),n.distanceSqToSegment(sa,ca,fa,pa)>r)return;fa.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(fa);if(!(c<t.near||c>t.far))return{distance:c,point:pa.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var ga=class extends Ai{constructor(e){super(),this.isPointsMaterial=!0,this.type=`PointsMaterial`,this.color=new L(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}},_a=class extends Pn{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=T,this.minFilter=T,this.generateMipmaps=!1,this.needsUpdate=!0}},va=class extends Pn{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},ya=class extends Pn{constructor(e,t,n=oe,r,i,a,o=T,s=T,c,l=_e,u=1){if(l!==1026&&l!==1027)throw Error(`THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:u},r,i,a,o,s,l,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new An(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}},ba=class extends ya{constructor(e,t=oe,n=301,r,i,a=T,o=T,s,c=_e){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,r,i,a,o,s,c),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},xa=class extends Pn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},Sa=class e extends xi{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new li(c,3)),this.setAttribute(`normal`,new li(l,3)),this.setAttribute(`uv`,new li(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new F;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}},Ca=class e extends xi{constructor(e=1,t=1,n=1,r=32,i=1,a=!1,o=0,s=Math.PI*2){super(),this.type=`CylinderGeometry`,this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:r,heightSegments:i,openEnded:a,thetaStart:o,thetaLength:s};let c=this;r=Math.floor(r),i=Math.floor(i);let l=[],u=[],d=[],f=[],p=0,m=[],h=n/2,g=0;_(),a===!1&&(e>0&&v(!0),t>0&&v(!1)),this.setIndex(l),this.setAttribute(`position`,new li(u,3)),this.setAttribute(`normal`,new li(d,3)),this.setAttribute(`uv`,new li(f,2));function _(){let a=new F,_=new F,v=0,y=(t-e)/n;for(let c=0;c<=i;c++){let l=[],g=c/i,v=g*(t-e)+e;for(let e=0;e<=r;e++){let t=e/r,i=t*s+o,c=Math.sin(i),m=Math.cos(i);_.x=v*c,_.y=-g*n+h,_.z=v*m,u.push(_.x,_.y,_.z),a.set(c,y,m).normalize(),d.push(a.x,a.y,a.z),f.push(t,1-g),l.push(p++)}m.push(l)}for(let n=0;n<r;n++)for(let r=0;r<i;r++){let a=m[r][n],o=m[r+1][n],s=m[r+1][n+1],c=m[r][n+1];(e>0||r!==0)&&(l.push(a,o,c),v+=3),(t>0||r!==i-1)&&(l.push(o,s,c),v+=3)}c.addGroup(g,v,0),g+=v}function v(n){let i=p,a=new P,m=new F,_=0,v=n===!0?e:t,y=n===!0?1:-1;for(let e=1;e<=r;e++)u.push(0,h*y,0),d.push(0,y,0),f.push(.5,.5),p++;let b=p;for(let e=0;e<=r;e++){let t=e/r*s+o,n=Math.cos(t),i=Math.sin(t);m.x=v*i,m.y=h*y,m.z=v*n,u.push(m.x,m.y,m.z),d.push(0,y,0),a.x=n*.5+.5,a.y=i*.5*y+.5,f.push(a.x,a.y),p++}for(let e=0;e<r;e++){let t=i+e,r=b+e;n===!0?l.push(r,r+1,t):l.push(r+1,r,t),_+=3}c.addGroup(g,_,n===!0?1:2),g+=_}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},wa=class e extends Ca{constructor(e=1,t=1,n=32,r=1,i=!1,a=0,o=Math.PI*2){super(0,e,t,n,r,i,a,o),this.type=`ConeGeometry`,this.parameters={radius:e,height:t,radialSegments:n,heightSegments:r,openEnded:i,thetaStart:a,thetaLength:o}}static fromJSON(t){return new e(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},Ta=class{constructor(){this.type=`Curve`,this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){M(`Curve: .getPoint() not implemented.`)}getPointAt(e,t){let n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){let t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){let t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){let 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;let t=[],n,r=this.getPoint(0),i=0;t.push(0);for(let a=1;a<=e;a++)n=this.getPoint(a/e),i+=n.distanceTo(r),t.push(i),r=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){let n=this.getLengths(),r=0,i=n.length,a;a=t||e*n[i-1];let o=0,s=i-1,c;for(;o<=s;)if(r=Math.floor(o+(s-o)/2),c=n[r]-a,c<0)o=r+1;else if(c>0)s=r-1;else{s=r;break}if(r=s,n[r]===a)return r/(i-1);let l=n[r],u=n[r+1]-l,d=(a-l)/u;return(r+d)/(i-1)}getTangent(e,t){let n=1e-4,r=e-n,i=e+n;r<0&&(r=0),i>1&&(i=1);let a=this.getPoint(r),o=this.getPoint(i),s=t||(a.isVector2?new P:new F);return s.copy(o).sub(a).normalize(),s}getTangentAt(e,t){let n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){let n=new F,r=[],i=[],a=[],o=new F,s=new Bn;for(let t=0;t<=e;t++){let n=t/e;r[t]=this.getTangentAt(n,new F)}i[0]=new F,a[0]=new F;let c=Number.MAX_VALUE,l=Math.abs(r[0].x),u=Math.abs(r[0].y),d=Math.abs(r[0].z);l<=c&&(c=l,n.set(1,0,0)),u<=c&&(c=u,n.set(0,1,0)),d<=c&&n.set(0,0,1),o.crossVectors(r[0],n).normalize(),i[0].crossVectors(r[0],o),a[0].crossVectors(r[0],i[0]);for(let t=1;t<=e;t++){if(i[t]=i[t-1].clone(),a[t]=a[t-1].clone(),o.crossVectors(r[t-1],r[t]),o.length()>2**-52){o.normalize();let e=Math.acos(Jt(r[t-1].dot(r[t]),-1,1));i[t].applyMatrix4(s.makeRotationAxis(o,e))}a[t].crossVectors(r[t],i[t])}if(t===!0){let t=Math.acos(Jt(i[0].dot(i[e]),-1,1));t/=e,r[0].dot(o.crossVectors(i[0],i[e]))>0&&(t=-t);for(let n=1;n<=e;n++)i[n].applyMatrix4(s.makeRotationAxis(r[n],t*n)),a[n].crossVectors(r[n],i[n])}return{tangents:r,normals:i,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){let 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}},Ea=class extends Ta{constructor(e=0,t=0,n=1,r=1,i=0,a=Math.PI*2,o=!1,s=0){super(),this.isEllipseCurve=!0,this.type=`EllipseCurve`,this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=r,this.aStartAngle=i,this.aEndAngle=a,this.aClockwise=o,this.aRotation=s}getPoint(e,t=new P){let n=t,r=Math.PI*2,i=this.aEndAngle-this.aStartAngle,a=Math.abs(i)<2**-52;for(;i<0;)i+=r;for(;i>r;)i-=r;i<2**-52&&(i=a?0:r),this.aClockwise===!0&&!a&&(i===r?i=-r:i-=r);let o=this.aStartAngle+e*i,s=this.aX+this.xRadius*Math.cos(o),c=this.aY+this.yRadius*Math.sin(o);if(this.aRotation!==0){let e=Math.cos(this.aRotation),t=Math.sin(this.aRotation),n=s-this.aX,r=c-this.aY;s=n*e-r*t+this.aX,c=n*t+r*e+this.aY}return n.set(s,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(){let 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}},Da=class extends Ea{constructor(e,t,n,r,i,a){super(e,t,n,n,r,i,a),this.isArcCurve=!0,this.type=`ArcCurve`}};function Oa(){let e=0,t=0,n=0,r=0;function i(i,a,o,s){e=i,t=o,n=-3*i+3*a-2*o-s,r=2*i-2*a+o+s}return{initCatmullRom:function(e,t,n,r,a){i(t,n,a*(n-e),a*(r-t))},initNonuniformCatmullRom:function(e,t,n,r,a,o,s){let c=(t-e)/a-(n-e)/(a+o)+(n-t)/o,l=(n-t)/o-(r-t)/(o+s)+(r-n)/s;c*=o,l*=o,i(t,n,c,l)},calc:function(i){let a=i*i,o=a*i;return e+t*i+n*a+r*o}}}var ka=new F,Aa=new F,ja=new Oa,Ma=new Oa,Na=new Oa,Pa=class extends Ta{constructor(e=[],t=!1,n=`centripetal`,r=.5){super(),this.isCatmullRomCurve3=!0,this.type=`CatmullRomCurve3`,this.points=e,this.closed=t,this.curveType=n,this.tension=r}getPoint(e,t=new F){let n=t,r=this.points,i=r.length,a=(i-+!this.closed)*e,o=Math.floor(a),s=a-o;this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/i)+1)*i:s===0&&o===i-1&&(o=i-2,s=1);let c,l;this.closed||o>0?c=r[(o-1)%i]:(Aa.subVectors(r[0],r[1]).add(r[0]),c=Aa);let u=r[o%i],d=r[(o+1)%i];if(this.closed||o+2<i?l=r[(o+2)%i]:(ka.subVectors(r[i-1],r[i-2]).add(r[i-1]),l=ka),this.curveType===`centripetal`||this.curveType===`chordal`){let e=this.curveType===`chordal`?.5:.25,t=c.distanceToSquared(u)**+e,n=u.distanceToSquared(d)**+e,r=d.distanceToSquared(l)**+e;n<1e-4&&(n=1),t<1e-4&&(t=n),r<1e-4&&(r=n),ja.initNonuniformCatmullRom(c.x,u.x,d.x,l.x,t,n,r),Ma.initNonuniformCatmullRom(c.y,u.y,d.y,l.y,t,n,r),Na.initNonuniformCatmullRom(c.z,u.z,d.z,l.z,t,n,r)}else this.curveType===`catmullrom`&&(ja.initCatmullRom(c.x,u.x,d.x,l.x,this.tension),Ma.initCatmullRom(c.y,u.y,d.y,l.y,this.tension),Na.initCatmullRom(c.z,u.z,d.z,l.z,this.tension));return n.set(ja.calc(s),Ma.calc(s),Na.calc(s)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let n=e.points[t];this.points.push(n.clone())}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}toJSON(){let e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){let n=this.points[t];e.points.push(n.toArray())}return e.closed=this.closed,e.curveType=this.curveType,e.tension=this.tension,e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let n=e.points[t];this.points.push(new F().fromArray(n))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}};function Fa(e,t,n,r,i){let a=(r-t)*.5,o=(i-n)*.5,s=e*e,c=e*s;return(2*n-2*r+a+o)*c+(-3*n+3*r-2*a-o)*s+a*e+n}function Ia(e,t){let n=1-e;return n*n*t}function La(e,t){return 2*(1-e)*e*t}function Ra(e,t){return e*e*t}function za(e,t,n,r){return Ia(e,t)+La(e,n)+Ra(e,r)}function Ba(e,t){let n=1-e;return n*n*n*t}function Va(e,t){let n=1-e;return 3*n*n*e*t}function Ha(e,t){return 3*(1-e)*e*e*t}function Ua(e,t){return e*e*e*t}function Wa(e,t,n,r,i){return Ba(e,t)+Va(e,n)+Ha(e,r)+Ua(e,i)}var Ga=class extends Ta{constructor(e=new P,t=new P,n=new P,r=new P){super(),this.isCubicBezierCurve=!0,this.type=`CubicBezierCurve`,this.v0=e,this.v1=t,this.v2=n,this.v3=r}getPoint(e,t=new P){let n=t,r=this.v0,i=this.v1,a=this.v2,o=this.v3;return n.set(Wa(e,r.x,i.x,a.x,o.x),Wa(e,r.y,i.y,a.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.v3.copy(e.v3),this}toJSON(){let 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}},Ka=class extends Ta{constructor(e=new F,t=new F,n=new F,r=new F){super(),this.isCubicBezierCurve3=!0,this.type=`CubicBezierCurve3`,this.v0=e,this.v1=t,this.v2=n,this.v3=r}getPoint(e,t=new F){let n=t,r=this.v0,i=this.v1,a=this.v2,o=this.v3;return n.set(Wa(e,r.x,i.x,a.x,o.x),Wa(e,r.y,i.y,a.y,o.y),Wa(e,r.z,i.z,a.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.v3.copy(e.v3),this}toJSON(){let 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}},qa=class extends Ta{constructor(e=new P,t=new P){super(),this.isLineCurve=!0,this.type=`LineCurve`,this.v1=e,this.v2=t}getPoint(e,t=new P){let 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 P){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(){let 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}},Ja=class extends Ta{constructor(e=new F,t=new F){super(),this.isLineCurve3=!0,this.type=`LineCurve3`,this.v1=e,this.v2=t}getPoint(e,t=new F){let 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 F){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(){let 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}},Ya=class extends Ta{constructor(e=new P,t=new P,n=new P){super(),this.isQuadraticBezierCurve=!0,this.type=`QuadraticBezierCurve`,this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new P){let n=t,r=this.v0,i=this.v1,a=this.v2;return n.set(za(e,r.x,i.x,a.x),za(e,r.y,i.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}toJSON(){let 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}},Xa=class extends Ta{constructor(e=new F,t=new F,n=new F){super(),this.isQuadraticBezierCurve3=!0,this.type=`QuadraticBezierCurve3`,this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new F){let n=t,r=this.v0,i=this.v1,a=this.v2;return n.set(za(e,r.x,i.x,a.x),za(e,r.y,i.y,a.y),za(e,r.z,i.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}toJSON(){let 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}},Za=Object.freeze({__proto__:null,ArcCurve:Da,CatmullRomCurve3:Pa,CubicBezierCurve:Ga,CubicBezierCurve3:Ka,EllipseCurve:Ea,LineCurve:qa,LineCurve3:Ja,QuadraticBezierCurve:Ya,QuadraticBezierCurve3:Xa,SplineCurve:class extends Ta{constructor(e=[]){super(),this.isSplineCurve=!0,this.type=`SplineCurve`,this.points=e}getPoint(e,t=new P){let n=t,r=this.points,i=(r.length-1)*e,a=Math.floor(i),o=i-a,s=r[a===0?a:a-1],c=r[a],l=r[a>r.length-2?r.length-1:a+1],u=r[a>r.length-3?r.length-1:a+2];return n.set(Fa(o,s.x,c.x,l.x,u.x),Fa(o,s.y,c.y,l.y,u.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let n=e.points[t];this.points.push(n.clone())}return this}toJSON(){let e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){let n=this.points[t];e.points.push(n.toArray())}return e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let n=e.points[t];this.points.push(new P().fromArray(n))}return this}}}),Qa=class e extends xi{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e<l;e++){let t=e*d-a;for(let n=0;n<c;n++){let r=n*u-i;p.push(r,-t,0),m.push(0,0,1),h.push(n/o),h.push(1-e/s)}}for(let e=0;e<s;e++)for(let t=0;t<o;t++){let n=t+c*e,r=t+c*(e+1),i=t+1+c*(e+1),a=t+1+c*e;f.push(n,r,a),f.push(r,i,a)}this.setIndex(f),this.setAttribute(`position`,new li(p,3)),this.setAttribute(`normal`,new li(m,3)),this.setAttribute(`uv`,new li(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}},$a=class e extends xi{constructor(e=1,t=32,n=16,r=0,i=Math.PI*2,a=0,o=Math.PI){super(),this.type=`SphereGeometry`,this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:r,phiLength:i,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));let s=Math.min(a+o,Math.PI),c=0,l=[],u=new F,d=new F,f=[],p=[],m=[],h=[];for(let f=0;f<=n;f++){let g=[],_=f/n,v=a+_*o,y=e*Math.cos(v),b=Math.sqrt(e*e-y*y),x=0;f===0&&a===0?x=.5/t:f===n&&s===Math.PI&&(x=-.5/t);for(let e=0;e<=t;e++){let n=e/t,a=r+n*i;u.x=-b*Math.cos(a),u.y=y,u.z=b*Math.sin(a),p.push(u.x,u.y,u.z),d.copy(u).normalize(),m.push(d.x,d.y,d.z),h.push(n+x,1-_),g.push(c++)}l.push(g)}for(let e=0;e<n;e++)for(let r=0;r<t;r++){let t=l[e][r+1],i=l[e][r],o=l[e+1][r],c=l[e+1][r+1];(e!==0||a>0)&&f.push(t,i,c),(e!==n-1||s<Math.PI)&&f.push(i,o,c)}this.setIndex(f),this.setAttribute(`position`,new li(p,3)),this.setAttribute(`normal`,new li(m,3)),this.setAttribute(`uv`,new li(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}},eo=class e extends xi{constructor(e=new Xa(new F(-1,-1,0),new F(-1,1,0),new F(1,1,0)),t=64,n=1,r=8,i=!1){super(),this.type=`TubeGeometry`,this.parameters={path:e,tubularSegments:t,radius:n,radialSegments:r,closed:i};let a=e.computeFrenetFrames(t,i);this.tangents=a.tangents,this.normals=a.normals,this.binormals=a.binormals;let o=new F,s=new F,c=new P,l=new F,u=[],d=[],f=[],p=[];m(),this.setIndex(p),this.setAttribute(`position`,new li(u,3)),this.setAttribute(`normal`,new li(d,3)),this.setAttribute(`uv`,new li(f,2));function m(){for(let e=0;e<t;e++)h(e);h(i===!1?t:0),_(),g()}function h(i){l=e.getPointAt(i/t,l);let c=a.normals[i],f=a.binormals[i];for(let e=0;e<=r;e++){let t=e/r*Math.PI*2,i=Math.sin(t),a=-Math.cos(t);s.x=a*c.x+i*f.x,s.y=a*c.y+i*f.y,s.z=a*c.z+i*f.z,s.normalize(),d.push(s.x,s.y,s.z),o.x=l.x+n*s.x,o.y=l.y+n*s.y,o.z=l.z+n*s.z,u.push(o.x,o.y,o.z)}}function g(){for(let e=1;e<=t;e++)for(let t=1;t<=r;t++){let n=(r+1)*(e-1)+(t-1),i=(r+1)*e+(t-1),a=(r+1)*e+t,o=(r+1)*(e-1)+t;p.push(n,i,o),p.push(i,a,o)}}function _(){for(let e=0;e<=t;e++)for(let n=0;n<=r;n++)c.x=e/t,c.y=n/r,f.push(c.x,c.y)}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){let e=super.toJSON();return e.path=this.parameters.path.toJSON(),e}static fromJSON(t){return new e(new Za[t.path.type]().fromJSON(t.path),t.tubularSegments,t.radius,t.radialSegments,t.closed)}},to=class extends Ai{constructor(e){super(),this.isShadowMaterial=!0,this.type=`ShadowMaterial`,this.color=new L(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 no(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];if(io(i))i.isRenderTargetTexture?(M(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone();else if(Array.isArray(i)){if(io(i[0])){let e=[];for(let t=0,n=i.length;t<n;t++)e[t]=i[t].clone();t[n][r]=e}else t[n][r]=i.slice()}else t[n][r]=i}}return t}function ro(e){let t={};for(let n=0;n<e.length;n++){let r=no(e[n]);for(let e in r)t[e]=r[e]}return t}function io(e){return e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture||e.isQuaternion)}function ao(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function oo(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:I.workingColorSpace}var so={clone:no,merge:ro},co=`void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,lo=`void main() {
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`,uo=class extends Ai{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=co,this.fragmentShader=lo,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=no(e.uniforms),this.uniformsGroups=ao(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){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let r=e.uniforms[n];switch(this.uniforms[n]={},r.type){case`t`:this.uniforms[n].value=t[r.value]||null;break;case`c`:this.uniforms[n].value=new L().setHex(r.value);break;case`v2`:this.uniforms[n].value=new P().fromArray(r.value);break;case`v3`:this.uniforms[n].value=new F().fromArray(r.value);break;case`v4`:this.uniforms[n].value=new Fn().fromArray(r.value);break;case`m3`:this.uniforms[n].value=new bn().fromArray(r.value);break;case`m4`:this.uniforms[n].value=new Bn().fromArray(r.value);break;default:this.uniforms[n].value=r.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let t in e.extensions)this.extensions[t]=e.extensions[t];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},fo=class extends uo{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},po=class extends Ai{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type=`MeshStandardMaterial`,this.defines={STANDARD:``},this.color=new L(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 L(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new P(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 Xn,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}},mo=class extends po{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 P(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Jt(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new L(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 L(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new L(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._retroreflectivity=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get retroreflectivity(){return this._retroreflectivity}set retroreflectivity(e){this._retroreflectivity>0!=e>0&&this.version++,this._retroreflectivity=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:``,PHYSICAL:``},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.retroreflectivity=e.retroreflectivity,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},ho=class extends Ai{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type=`MeshPhongMaterial`,this.color=new L(16777215),this.specular=new L(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new L(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new P(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Xn,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},go=class extends Ai{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:``},this.type=`MeshToonMaterial`,this.color=new L(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new L(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new P(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}},_o=class extends Ai{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type=`MeshNormalMaterial`,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new P(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}},vo=class extends Ai{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type=`MeshLambertMaterial`,this.color=new L(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new L(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new P(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Xn,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},yo=class extends Ai{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=ft,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}},bo=class extends Ai{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}},xo=class extends Ai{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:``},this.type=`MeshMatcapMaterial`,this.color=new L(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new P(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}},So=class extends oa{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}};function Co(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function wo(e){return e!==void 0&&e.inTangents!==void 0&&e.outTangents!==void 0}var To=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`THREE.Interpolant: Call to abstract method.`)}intervalChanged_(){}},Eo=class extends To{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:lt,endingEnd:lt}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case ut:i=e,o=2*t-n;break;case dt:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case ut:a=e,s=2*n-t;break;case dt:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},Do=class extends To{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},Oo=class extends To{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},ko=class extends To{interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this.inTangents,u=this.outTangents;if(!l||!u){let e=(n-t)/(r-t),l=1-e;for(let t=0;t!==o;++t)i[t]=a[c+t]*l+a[s+t]*e;return i}let d=o*2,f=e-1;for(let p=0;p!==o;++p){let o=a[c+p],m=a[s+p],h=f*d+p*2,g=u[h],_=u[h+1],v=e*d+p*2,y=l[v],b=l[v+1],x=Mo(n,t,g,y,r);i[p]=Ao(x,o,_,b,m)}return i}};function Ao(e,t,n,r,i){let a=1-e;return a*a*a*t+3*a*a*e*n+3*a*e*e*r+e*e*e*i}function jo(e,t,n,r,i){let a=1-e;return 3*a*a*(n-t)+6*a*e*(r-n)+3*e*e*(i-r)}function Mo(e,t,n,r,i){let a=(e-t)/(i-t);for(let o=0;o<8;o++){let o=Ao(a,t,n,r,i)-e;if(Math.abs(o)<1e-10)break;let s=jo(a,t,n,r,i);if(Math.abs(s)<1e-10)break;a=Math.max(0,Math.min(1,a-o/s))}return a}var No=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=Co(t,this.TimeBufferType),this.values=Co(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:Co(e.times,Array),values:Co(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t),wo(e.settings)&&(n.settings={inTangents:Co(e.settings.inTangents,Array),outTangents:Co(e.settings.outTangents,Array)})}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Oo(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Do(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Eo(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodBezier(e){let t=new ko(this.times,this.values,this.getValueSize(),e);return this.settings&&(t.inTangents=this.settings.inTangents,t.outTangents=this.settings.outTangents),t}setInterpolation(e){let t;switch(e){case at:t=this.InterpolantFactoryMethodDiscrete;break;case ot:t=this.InterpolantFactoryMethodLinear;break;case st:t=this.InterpolantFactoryMethodSmooth;break;case ct:t=this.InterpolantFactoryMethodBezier}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0){if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t)}return M(`KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return at;case this.InterpolantFactoryMethodLinear:return ot;case this.InterpolantFactoryMethodSmooth:return st;case this.InterpolantFactoryMethodBezier:return ct}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e;wo(this.settings)&&(Po(this.settings.inTangents,e),Po(this.settings.outTangents,e))}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(N(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(N(`KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){N(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){N(`KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&Mt(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){N(`KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===st,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0])){if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,wo(this.settings)&&(r.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()}),r}};function Po(e,t){for(let n=0,r=e.length;n!==r;n+=2)e[n]*=t}No.prototype.ValueTypeName=``,No.prototype.TimeBufferType=Float32Array,No.prototype.ValueBufferType=Float32Array,No.prototype.DefaultInterpolation=ot;var Fo=class extends No{constructor(e,t,n){super(e,t,n)}};Fo.prototype.ValueTypeName=`bool`,Fo.prototype.ValueBufferType=Array,Fo.prototype.DefaultInterpolation=at,Fo.prototype.InterpolantFactoryMethodLinear=void 0,Fo.prototype.InterpolantFactoryMethodSmooth=void 0;var Io=class extends No{constructor(e,t,n,r){super(e,t,n,r)}};Io.prototype.ValueTypeName=`color`;var Lo=class extends No{constructor(e,t,n,r){super(e,t,n,r)}};Lo.prototype.ValueTypeName=`number`;var Ro=class extends To{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)_n.slerpFlat(i,0,a,c-o,a,c,s);return i}},zo=class extends No{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new Ro(this.times,this.values,this.getValueSize(),e)}};zo.prototype.ValueTypeName=`quaternion`,zo.prototype.InterpolantFactoryMethodSmooth=void 0;var Bo=class extends No{constructor(e,t,n){super(e,t,n)}};Bo.prototype.ValueTypeName=`string`,Bo.prototype.ValueBufferType=Array,Bo.prototype.DefaultInterpolation=at,Bo.prototype.InterpolantFactoryMethodLinear=void 0,Bo.prototype.InterpolantFactoryMethodSmooth=void 0;var Vo=class extends No{constructor(e,t,n,r){super(e,t,n,r)}};Vo.prototype.ValueTypeName=`vector`;var Ho={enabled:!1,files:{},add:function(e,t){this.enabled!==!1&&(Uo(e)||(this.files[e]=t))},get:function(e){if(this.enabled!==!1&&!Uo(e))return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function Uo(e){try{let t=e.slice(e.indexOf(`:`)+1);return new URL(t).protocol===`blob:`}catch{return!1}}var Wo=new class{constructor(e,t,n){let r=this,i=!1,a=0,o=0,s,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(e){o++,i===!1&&r.onStart!==void 0&&r.onStart(e,a,o),i=!0},this.itemEnd=function(e){a++,r.onProgress!==void 0&&r.onProgress(e,a,o),a===o&&(i=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(e){r.onError!==void 0&&r.onError(e)},this.resolveURL=function(e){return e=e.normalize(`NFC`),s?s(e):e},this.setURLModifier=function(e){return s=e,this},this.addHandler=function(e,t){return c.push(e,t),this},this.removeHandler=function(e){let t=c.indexOf(e);return t!==-1&&c.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=c.length;t<n;t+=2){let n=c[t],r=c[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return r}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||=new AbortController,this._abortController}},Go=class{constructor(e){this.manager=e===void 0?Wo:e,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){let n=this;return new Promise(function(r,i){n.load(e,r,t,i)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}};Go.DEFAULT_MATERIAL_NAME=`__DEFAULT`;var Ko=new WeakMap,qo=class extends Go{constructor(e){super(e)}load(e,t,n,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=Ho.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)i.manager.itemStart(e),setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0);else{let e=Ko.get(a);e===void 0&&(e=[],Ko.set(a,e)),e.push({onLoad:t,onError:r})}return a}let o=Nt(`img`);function s(){l(),t&&t(this);let n=Ko.get(this)||[];for(let e=0;e<n.length;e++){let t=n[e];t.onLoad&&t.onLoad(this)}Ko.delete(this),i.manager.itemEnd(e)}function c(t){l(),r&&r(t),Ho.remove(`image:${e}`);let n=Ko.get(this)||[];for(let e=0;e<n.length;e++){let r=n[e];r.onError&&r.onError(t)}Ko.delete(this),i.manager.itemError(e),i.manager.itemEnd(e)}function l(){o.removeEventListener(`load`,s,!1),o.removeEventListener(`error`,c,!1)}return o.addEventListener(`load`,s,!1),o.addEventListener(`error`,c,!1),e.slice(0,5)!==`data:`&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),Ho.add(`image:${e}`,o),i.manager.itemStart(e),o.src=e,o}},Jo=class extends Go{constructor(e){super(e)}load(e,t,n,r){let i=new Pn,a=new qo(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(e){i.image=e,i.needsUpdate=!0,t!==void 0&&t(i)},n,r),i}},Yo=class extends pr{constructor(e,t=1){super(),this.isLight=!0,this.type=`Light`,this.color=new L(e),this.intensity=t}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}},Xo=class extends Yo{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type=`HemisphereLight`,this.position.copy(pr.DEFAULT_UP),this.updateMatrix(),this.groundColor=new L(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){let t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}},Zo=new Bn,Qo=new F,$o=new F,es=class{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 P(512,512),this.mapType=te,this.map=null,this.mapPass=null,this.matrix=new Bn,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new ra,this._frameExtents=new P(1,1),this._viewportCount=1,this._viewports=[new Fn(0,0,1,1)]}getViewportCount(){return this._viewportCount}getCamera(){return this.camera}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera;Qo.setFromMatrixPosition(e.matrixWorld),t.position.copy(Qo),$o.setFromMatrixPosition(e.target.matrixWorld),t.lookAt($o),t.updateMatrixWorld(),this._updateMatrix(t,this.matrix,this._frustum)}_updateMatrix(e,t,n,r){Zo.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),n.setFromProjectionMatrix(Zo,e.coordinateSystem,e.reversedDepth);let i=this._frameExtents,a=r?r.z/i.x:1,o=r?r.w/i.y:1,s=r?r.x/i.x:0,c=r?r.y/i.y:0;e.coordinateSystem===2001||e.reversedDepth?t.set(.5*a,0,0,.5*a+s,0,.5*o,0,.5*o+c,0,0,1,0,0,0,0,1):t.set(.5*a,0,0,.5*a+s,0,.5*o,0,.5*o+c,0,0,.5,.5,0,0,0,1),t.multiply(Zo)}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(){let e={};return e.intensity=this.intensity,e.bias=this.bias,e.normalBias=this.normalBias,e.radius=this.radius,e.blurSamples=this.blurSamples,e.mapSize=this.mapSize.toArray(),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},ts=new F,ns=new _n,rs=new F,is=class extends pr{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new Bn,this.projectionMatrix=new Bn,this.projectionMatrixInverse=new Bn,this.coordinateSystem=Et,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(ts,ns,rs),rs.x===1&&rs.y===1&&rs.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(ts,ns,rs.set(1,1,1)).invert()}updateWorldMatrix(e,t,n=!1){super.updateWorldMatrix(e,t,n),this.matrixWorld.decompose(ts,ns,rs),rs.x===1&&rs.y===1&&rs.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(ts,ns,rs.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},as=new F,os=new P,ss=new P,cs=class extends is{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=Kt*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(Gt*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Kt*2*Math.atan(Math.tan(Gt*.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){as.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(as.x,as.y).multiplyScalar(-e/as.z),as.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(as.x,as.y).multiplyScalar(-e/as.z)}getViewSize(e,t){return this.getViewBounds(e,os,ss),t.subVectors(ss,os)}setViewOffset(e,t,n,r,i,a){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=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(Gt*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let 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}},ls=class extends es{constructor(){super(new cs(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=Kt*2*e.angle*this.focus,r=this.mapSize.width/this.mapSize.height*this.aspect,i=e.distance||t.far;(n!==t.fov||r!==t.aspect||i!==t.far)&&(t.fov=n,t.aspect=r,t.far=i,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this.aspect=e.aspect,this}toJSON(){let e=super.toJSON();return e.focus=this.focus,e.aspect=this.aspect,e}},us=class extends Yo{constructor(e,t,n=0,r=Math.PI/3,i=0,a=2){super(e,t),this.isSpotLight=!0,this.type=`SpotLight`,this.position.copy(pr.DEFAULT_UP),this.updateMatrix(),this.target=new pr,this.distance=n,this.angle=r,this.penumbra=i,this.decay=a,this.map=null,this.shadow=new ls}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){let 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}},ds=class extends es{constructor(){super(new cs(90,1,.5,500)),this.isPointLightShadow=!0}},fs=class extends Yo{constructor(e,t,n=0,r=2){super(e,t),this.isPointLight=!0,this.type=`PointLight`,this.distance=n,this.decay=r,this.shadow=new ds}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){let t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}},ps=class extends is{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,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,r,i,a){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=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let 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}},ms=class extends es{constructor(){super(new ps(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},hs=class extends Yo{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type=`DirectionalLight`,this.position.copy(pr.DEFAULT_UP),this.updateMatrix(),this.target=new pr,this.shadow=new ms}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){let t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}},gs=class extends Yo{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type=`AmbientLight`}},_s=class extends Yo{constructor(e,t,n=10,r=10){super(e,t),this.isRectAreaLight=!0,this.type=`RectAreaLight`,this.width=n,this.height=r}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){let t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}},vs=class{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new F)}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){let n=e.x,r=e.y,i=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.282095),t.addScaledVector(a[1],.488603*r),t.addScaledVector(a[2],.488603*i),t.addScaledVector(a[3],.488603*n),t.addScaledVector(a[4],n*r*1.092548),t.addScaledVector(a[5],r*i*1.092548),t.addScaledVector(a[6],.315392*(3*i*i-1)),t.addScaledVector(a[7],n*i*1.092548),t.addScaledVector(a[8],.546274*(n*n-r*r)),t}getIrradianceAt(e,t){let n=e.x,r=e.y,i=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.886227),t.addScaledVector(a[1],1.023328*r),t.addScaledVector(a[2],1.023328*i),t.addScaledVector(a[3],1.023328*n),t.addScaledVector(a[4],.858086*n*r),t.addScaledVector(a[5],.858086*r*i),t.addScaledVector(a[6],.743125*i*i-.247708),t.addScaledVector(a[7],.858086*n*i),t.addScaledVector(a[8],.429043*(n*n-r*r)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(e.coefficients[n],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let n=0;n<9;n++)this.coefficients[n].lerp(e.coefficients[n],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){let n=this.coefficients;for(let r=0;r<9;r++)n[r].fromArray(e,t+r*3);return this}toArray(e=[],t=0){let n=this.coefficients;for(let r=0;r<9;r++)n[r].toArray(e,t+r*3);return e}static getBasisAt(e,t){let n=e.x,r=e.y,i=e.z;t[0]=.282095,t[1]=.488603*r,t[2]=.488603*i,t[3]=.488603*n,t[4]=1.092548*n*r,t[5]=1.092548*r*i,t[6]=.315392*(3*i*i-1),t[7]=1.092548*n*i,t[8]=.546274*(n*n-r*r)}},ys=class extends Yo{constructor(e=new vs,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){let t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}},bs=-90,xs=1,Ss=class extends pr{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new cs(bs,xs,e,t);r.layers=this.layers,this.add(r);let i=new cs(bs,xs,e,t);i.layers=this.layers,this.add(i);let a=new cs(bs,xs,e,t);a.layers=this.layers,this.add(a);let o=new cs(bs,xs,e,t);o.layers=this.layers,this.add(o);let s=new cs(bs,xs,e,t);s.layers=this.layers,this.add(s);let c=new cs(bs,xs,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let h=!1;h=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,i),e.setRenderTarget(n,1,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,4,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},Cs=class extends cs{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},ws=class{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=Ts.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?performance.now():e)-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function Ts(){this._document.hidden===!1&&this.reset()}var Es=`\\[\\]\\.:\\/`,Ds=RegExp(`[\\[\\]\\.:\\/]`,`g`),Os=`[^\\[\\]\\.:\\/]`,ks=`[^`+Es.replace(`\\.`,``)+`]`,As=`((?:WC+[\\/:])*)`.replace(`WC`,Os),js=`(WCOD+)?`.replace(`WCOD`,ks),Ms=`(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,Os),Ns=`\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,Os),Ps=RegExp(`^`+As+js+Ms+Ns+`$`),Fs=[`material`,`materials`,`bones`,`map`],Is=class{constructor(e,t,n){let r=n||Ls.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},Ls=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(Ds,``)}static parseTrackName(e){let t=Ps.exec(e);if(t===null)throw Error(`THREE.PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);Fs.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`THREE.PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){M(`PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){N(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){N(`PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){N(`PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){N(`PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){N(`PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){N(`PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){N(`PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;N(`PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){N(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){N(`PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};Ls.Composite=Is,Ls.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Ls.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Ls.prototype.GetterByBindingType=[Ls.prototype._getValue_direct,Ls.prototype._getValue_array,Ls.prototype._getValue_arrayElement,Ls.prototype._getValue_toArray],Ls.prototype.SetterByBindingTypeAndVersioning=[[Ls.prototype._setValue_direct,Ls.prototype._setValue_direct_setNeedsUpdate,Ls.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Ls.prototype._setValue_array,Ls.prototype._setValue_array_setNeedsUpdate,Ls.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Ls.prototype._setValue_arrayElement,Ls.prototype._setValue_arrayElement_setNeedsUpdate,Ls.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Ls.prototype._setValue_fromArray,Ls.prototype._setValue_fromArray_setNeedsUpdate,Ls.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var Rs=class extends Si{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){let t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){let t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}},zs=new Bn,Bs=class{constructor(e,t,n=0,r=1/0){this.ray=new Ii(e,t),this.near=n,this.far=r,this.camera=null,this.layers=new Zn,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.projectionMatrix.elements[14]).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):N(`Raycaster: Unsupported camera type: `+t.type)}setFromXRController(e){return zs.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(zs),this}intersectObject(e,t=!0,n=[]){return Hs(e,this,n,t),n.sort(Vs),n}intersectObjects(e,t=!0,n=[]){for(let r=0,i=e.length;r<i;r++)Hs(e[r],this,n,t);return n.sort(Vs),n}};function Vs(e,t){return e.distance-t.distance}function Hs(e,t,n,r){let i=!0;if(e.layers.test(t.layers)&&e.raycast(t,n)===!1&&(i=!1),i===!0&&r===!0){let r=e.children;for(let e=0,i=r.length;e<i;e++)Hs(r[e],t,n,!0)}}var Us=class{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(){let e=1e-6;return this.phi=Jt(this.phi,e,Math.PI-e),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(Jt(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}},Ws=class e{static{e.prototype.isMatrix2=!0}constructor(e,t,n,r){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,r){let i=this.elements;return i[0]=e,i[2]=t,i[1]=n,i[3]=r,this}},Gs=class extends Ht{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){this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}};function Ks(e,t,n,r){let i=qs(r);switch(n){case me:return e*t;case ye:return e*t/i.components*i.byteLength;case be:return e*t/i.components*i.byteLength;case xe:return e*t*2/i.components*i.byteLength;case Se:return e*t*2/i.components*i.byteLength;case he:return e*t*3/i.components*i.byteLength;case ge:return e*t*4/i.components*i.byteLength;case we:return e*t*4/i.components*i.byteLength;case Te:case Ee:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case De:case Oe:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ae:case Me:return Math.max(e,16)*Math.max(t,8)/4;case ke:case je:return Math.max(e,8)*Math.max(t,8)/2;case Ne:case Pe:case Ie:case Le:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Fe:case Re:case A:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case ze:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Be:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Ve:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case j:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case He:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case Ue:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case We:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Ge:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case Ke:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case qe:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case Je:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case Ye:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case Xe:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case Ze:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case Qe:case $e:case et:return Math.ceil(e/4)*Math.ceil(t/4)*16;case tt:case nt:return Math.ceil(e/4)*Math.ceil(t/4)*8;case rt:case it:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function qs(e){switch(e){case te:case ne:return{byteLength:1,components:1};case ie:case re:case ce:return{byteLength:2,components:1};case le:case ue:return{byteLength:2,components:4};case oe:case ae:case se:return{byteLength:4,components:1};case fe:case pe:return{byteLength:4,components:3}}throw Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`186`}})),typeof window<`u`&&(window.__THREE__?M(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`186`);function Js(){let e=null,t=!1,n=null,r=null;function i(t,a){r=e.requestAnimationFrame(i),n(t,a)}return{start:function(){t!==!0&&n!==null&&e!==null&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e!==null&&e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function Ys(e){let t=new WeakMap;function n(t,n){let r=t.array,i=t.usage,a=r.byteLength,o=e.createBuffer();e.bindBuffer(n,o),e.bufferData(n,r,i),t.onUploadCallback();let s;if(r instanceof Float32Array)s=e.FLOAT;else if(typeof Float16Array<`u`&&r instanceof Float16Array)s=e.HALF_FLOAT;else if(r instanceof Uint16Array)s=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)s=e.SHORT;else if(r instanceof Uint32Array)s=e.UNSIGNED_INT;else if(r instanceof Int32Array)s=e.INT;else if(r instanceof Int8Array)s=e.BYTE;else if(r instanceof Uint8Array)s=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)s=e.UNSIGNED_BYTE;else throw Error(`THREE.WebGLAttributes: Unsupported buffer data format: `+r);return{buffer:o,type:s,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:a}}function r(t,n,r){let i=n.array,a=n.updateRanges;if(e.bindBuffer(r,t),a.length===0)e.bufferSubData(r,0,i);else{a.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<a.length;e++){let n=a[t],r=a[e];r.start<=n.start+n.count+1?n.count=Math.max(n.count,r.start+r.count-n.start):(++t,a[t]=r)}a.length=t+1;for(let t=0,n=a.length;t<n;t++){let n=a[t];e.bufferSubData(r,n.start*i.BYTES_PER_ELEMENT,i,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}function i(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)}function a(n){n.isInterleavedBufferAttribute&&(n=n.data);let r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))}function o(e,i){if(e.isInterleavedBufferAttribute&&(e=e.data),e.isGLBufferAttribute){let n=t.get(e);(!n||n.version<e.version)&&t.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version});return}let a=t.get(e);if(a===void 0)t.set(e,n(e,i));else if(a.version<e.version){if(a.size!==e.array.byteLength)throw Error(`THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.`);r(a.buffer,e,i),a.version=e.version}}return{get:i,remove:a,update:o}}var Xs={alphahash_fragment:`#ifdef USE_ALPHAHASH
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,alphahash_pars_fragment:`#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`,alphamap_fragment:`#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`,alphamap_pars_fragment:`#ifdef USE_ALPHAMAP
uniform sampler2D alphaMap;
#endif`,alphatest_fragment:`#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`,alphatest_pars_fragment:`#ifdef USE_ALPHATEST
uniform float alphaTest;
#endif`,aomap_fragment:`#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`,aomap_pars_fragment:`#ifdef USE_AOMAP
uniform sampler2D aoMap;
uniform float aoMapIntensity;
#endif`,batching_pars_vertex:`#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`,batching_vertex:`#ifdef USE_BATCHING
mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`,begin_vertex:`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
vPosition = vec3( position );
#endif`,beginnormal_vertex:`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
vec3 objectTangent = vec3( tangent.xyz );
#endif`,bsdfs:`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`,iridescence_fragment:`#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`,bumpmap_pars_fragment:`#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`,clipping_planes_fragment:`#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`,clipping_planes_pars_fragment:`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,clipping_planes_pars_vertex:`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
#endif`,clipping_planes_vertex:`#if NUM_CLIPPING_PLANES > 0
vClipPosition = - mvPosition.xyz;
#endif`,color_fragment:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
diffuseColor *= vColor;
#endif`,color_pars_fragment:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
varying vec4 vColor;
#endif`,color_pars_vertex:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
varying vec4 vColor;
#endif`,color_vertex:`#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`,common:`#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 );
}
#define inverseTransformDirection transformDirectionByInverseViewMatrix
vec3 transformNormalByInverseViewMatrix( in vec3 normal, in mat4 viewMatrix ) {
return normalize( ( vec4( normal, 0.0 ) * viewMatrix ).xyz );
}
vec3 transformDirectionByInverseViewMatrix( in vec3 dir, in mat4 viewMatrix ) {
return normalize( ( vec4( dir, 0.0 ) * viewMatrix ).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`,cube_uv_reflection_fragment:`#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`,defaultnormal_vertex:`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;
#endif`,displacementmap_pars_vertex:`#ifdef USE_DISPLACEMENTMAP
uniform sampler2D displacementMap;
uniform float displacementScale;
uniform float displacementBias;
#endif`,displacementmap_vertex:`#ifdef USE_DISPLACEMENTMAP
transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,emissivemap_fragment:`#ifdef USE_EMISSIVEMAP
vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
emissiveColor = sRGBTransferEOTF( emissiveColor );
#endif
totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,emissivemap_pars_fragment:`#ifdef USE_EMISSIVEMAP
uniform sampler2D emissiveMap;
#endif`,colorspace_fragment:`gl_FragColor = linearToOutputTexel( gl_FragColor );`,colorspace_pars_fragment:`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 );
}`,envmap_fragment:`#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 = transformNormalByInverseViewMatrix( 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`,envmap_common_pars_fragment:`#ifdef USE_ENVMAP
uniform float envMapIntensity;
uniform mat3 envMapRotation;
#ifdef ENVMAP_TYPE_CUBE
uniform samplerCube envMap;
#else
uniform sampler2D envMap;
#endif
#endif`,envmap_pars_fragment:`#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`,envmap_pars_vertex:`#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`,envmap_physical_pars_fragment:`#ifdef USE_ENVMAP
vec3 getIBLIrradiance( const in vec3 normal ) {
#ifdef ENVMAP_TYPE_CUBE_UV
vec3 worldNormal = transformNormalByInverseViewMatrix( 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 = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix );
vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
return envMapColor.rgb * envMapIntensity;
#else
return vec3( 0.0 );
#endif
}
#ifdef USE_RETROREFLECTION
vec3 getIBLRetroRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
#ifdef ENVMAP_TYPE_CUBE_UV
vec3 retroVec = normalize( mix( viewDir, normal, pow4( roughness ) ) );
retroVec = transformDirectionByInverseViewMatrix( retroVec, viewMatrix );
vec4 envMapColor = textureCubeUV( envMap, envMapRotation * retroVec, roughness );
return envMapColor.rgb * envMapIntensity;
#else
return vec3( 0.0 );
#endif
}
#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
}
#ifdef USE_RETROREFLECTION
vec3 getIBLAnisotropyRetroRadiance( 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 getIBLRetroRadiance( viewDir, bentNormal, roughness );
#else
return vec3( 0.0 );
#endif
}
#endif
#endif
#endif`,envmap_vertex:`#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 = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );
#ifdef ENVMAP_MODE_REFLECTION
vReflect = reflect( cameraToVertex, worldNormal );
#else
vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
#endif
#endif
#endif`,fog_vertex:`#ifdef USE_FOG
vFogDepth = - mvPosition.z;
#endif`,fog_pars_vertex:`#ifdef USE_FOG
varying float vFogDepth;
#endif`,fog_fragment:`#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`,fog_pars_fragment:`#ifdef USE_FOG
uniform vec3 fogColor;
varying float vFogDepth;
#ifdef FOG_EXP2
uniform float fogDensity;
#else
uniform float fogNear;
uniform float fogFar;
#endif
#endif`,gradientmap_pars_fragment:`#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
}`,lightmap_pars_fragment:`#ifdef USE_LIGHTMAP
uniform sampler2D lightMap;
uniform float lightMapIntensity;
#endif`,lights_lambert_fragment:`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,lights_lambert_pars_fragment:`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`,lights_pars_begin:`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 = transformNormalByInverseViewMatrix( 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_SUN_LIGHTS > 0
struct SunLight {
vec3 direction;
vec3 color;
};
uniform SunLight sunLights[ NUM_SUN_LIGHTS ];
void getSunLightInfo( const in SunLight sunLight, out IncidentLight light ) {
light.color = sunLight.color;
light.direction = sunLight.direction;
light.visible = true;
}
#endif
#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>`,lights_toon_fragment:`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,lights_toon_pars_fragment:`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`,lights_phong_fragment:`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,lights_phong_pars_fragment:`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`,lights_physical_fragment:`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_RETROREFLECTION
material.retroreflectivity = retroreflectivity;
#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`,lights_physical_pars_fragment:`uniform sampler2D dfgLUT;
struct PhysicalMaterial {
vec3 diffuseColor;
vec3 diffuseContribution;
vec3 specularColor;
vec3 specularColorBlended;
float roughness;
float metalness;
float specularF90;
float dispersion;
vec2 dfg;
vec3 multiScatteringCompensation;
#ifdef USE_RETROREFLECTION
float retroreflectivity;
#endif
#ifdef USE_CLEARCOAT
float clearcoat;
float clearcoatRoughness;
vec3 clearcoatF0;
float clearcoatF90;
#endif
#ifdef USE_IRIDESCENCE
float iridescence;
float iridescenceIOR;
float iridescenceThickness;
vec3 iridescenceFresnel;
vec3 iridescenceF0Dielectric;
vec3 iridescenceF0Metallic;
#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 vec2 fab, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, inout vec3 singleScatter, inout vec3 multiScatter ) {
#else
void computeMultiscattering( const in vec2 fab, const in vec3 specularColor, const in float specularF90, inout vec3 singleScatter, inout vec3 multiScatter ) {
#endif
#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;
}
#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
vec3 specularBRDF = BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
#ifdef USE_RETROREFLECTION
vec3 retroViewDir = reflect( - geometryViewDir, geometryNormal );
vec3 retroSpecularBRDF = BRDF_GGX( directLight.direction, retroViewDir, geometryNormal, material );
specularBRDF = mix( specularBRDF, retroSpecularBRDF, saturate( material.retroreflectivity ) );
#endif
reflectedLight.directSpecular += irradiance * specularBRDF * material.multiScatteringCompensation;
vec3 halfDir = normalize( directLight.direction + geometryViewDir );
float dotVH = saturate( dot( geometryViewDir, halfDir ) );
vec3 F = F_Schlick( material.specularColor, material.specularF90, dotVH );
#ifdef USE_RETROREFLECTION
vec3 retroHalfDir = normalize( directLight.direction + retroViewDir );
float dotRetroVH = saturate( dot( retroViewDir, retroHalfDir ) );
vec3 retroF = F_Schlick( material.specularColor, material.specularF90, dotRetroVH );
F = mix( F, retroF, saturate( material.retroreflectivity ) );
#endif
reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - F );
}
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 singleScattering = vec3( 0.0 );
vec3 multiScattering = vec3( 0.0 );
#ifdef USE_IRIDESCENCE
computeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScattering, multiScattering );
#else
computeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScattering, multiScattering );
#endif
vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - singleScattering - multiScattering );
#ifdef USE_SHEEN
float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
sheenSpecularIndirect += irradiance * material.sheenColor * sheenAlbedo * RECIPROCAL_PI;
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( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScatteringDielectric, multiScatteringDielectric );
computeMultiscatteringIridescence( material.dfg, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceF0Metallic, singleScatteringMetallic, multiScatteringMetallic );
#else
computeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScatteringDielectric, multiScatteringDielectric );
computeMultiscattering( material.dfg, material.diffuseColor, material.specularF90, 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 );
}`,lights_fragment_begin:`
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 ) {
vec3 iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
vec3 iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );
material.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, material.metalness );
material.iridescenceF0Dielectric = Schlick_to_F0( iridescenceFresnelDielectric, 1.0, dotNVi );
material.iridescenceF0Metallic = Schlick_to_F0( iridescenceFresnelMetallic, 1.0, dotNVi );
}
#endif
#ifdef STANDARD
float dotNVms = saturate( dot( geometryNormal, geometryViewDir ) );
material.dfg = texture2D( dfgLUT, vec2( material.roughness, dotNVms ) ).rg;
#if ( NUM_SUN_LIGHTS > 0 || NUM_DIR_LIGHTS > 0 || NUM_POINT_LIGHTS > 0 || NUM_SPOT_LIGHTS > 0 )
float EssMs = material.dfg.x + material.dfg.y;
material.multiScatteringCompensation = 1.0 + material.specularColorBlended * ( 1.0 / EssMs - 1.0 );
#endif
#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_SUN_LIGHTS > 0 ) && defined( RE_Direct )
SunLight sunLight;
#if defined( USE_SHADOWMAP ) && NUM_SUN_LIGHT_SHADOWS > 0
SunLightShadow sunLightShadow;
#endif
#pragma unroll_loop_start
for ( int i = 0; i < NUM_SUN_LIGHTS; i ++ ) {
sunLight = sunLights[ i ];
getSunLightInfo( sunLight, directLight );
#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SUN_LIGHT_SHADOWS )
sunLightShadow = sunLightShadows[ i ];
directLight.color *= ( directLight.visible && receiveShadow ) ? getSunShadow( sunShadowMap[ i ], sunLightShadow, UNROLLED_LOOP_INDEX ) : 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 = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix );
irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );
#endif
#endif
#if defined( RE_IndirectSpecular )
vec3 radiance = vec3( 0.0 );
vec3 clearcoatRadiance = vec3( 0.0 );
#endif`,lights_fragment_maps:`#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
vec3 iblRadiance = getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
#else
vec3 iblRadiance = getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
#endif
#ifdef USE_RETROREFLECTION
#ifdef USE_ANISOTROPY
vec3 retroIBLRadiance = getIBLAnisotropyRetroRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
#else
vec3 retroIBLRadiance = getIBLRetroRadiance( geometryViewDir, geometryNormal, material.roughness );
#endif
iblRadiance = mix( iblRadiance, retroIBLRadiance, saturate( material.retroreflectivity ) );
#endif
radiance += iblRadiance;
#ifdef USE_CLEARCOAT
clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
#endif
#endif`,lights_fragment_end:`#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`,lightprobes_pars_fragment:`#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`,logdepthbuf_fragment:`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,logdepthbuf_pars_fragment:`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
uniform float logDepthBufFC;
varying float vFragDepth;
varying float vIsPerspective;
#endif`,logdepthbuf_pars_vertex:`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
varying float vFragDepth;
varying float vIsPerspective;
#endif`,logdepthbuf_vertex:`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
vFragDepth = 1.0 + gl_Position.w;
vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,map_fragment:`#ifdef USE_MAP
vec4 sampledDiffuseColor = texture2D( map, vMapUv );
#ifdef DECODE_VIDEO_TEXTURE
sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
#endif
diffuseColor *= sampledDiffuseColor;
#endif`,map_pars_fragment:`#ifdef USE_MAP
uniform sampler2D map;
#endif`,map_particle_fragment:`#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`,map_particle_pars_fragment:`#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`,metalnessmap_fragment:`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
metalnessFactor *= texelMetalness.b;
#endif`,metalnessmap_pars_fragment:`#ifdef USE_METALNESSMAP
uniform sampler2D metalnessMap;
#endif`,morphinstance_vertex:`#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`,morphcolor_vertex:`#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`,morphnormal_vertex:`#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`,morphtarget_pars_vertex:`#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`,morphtarget_vertex:`#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`,normal_fragment_begin:`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
#ifdef DOUBLE_SIDED
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
#ifdef DOUBLE_SIDED
tbn2[0] *= faceDirection;
tbn2[1] *= faceDirection;
#endif
#endif
vec3 nonPerturbedNormal = normal;`,normal_fragment_maps:`#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`,normal_pars_fragment:`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
#endif`,normal_pars_vertex:`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
#endif`,normal_vertex:`#ifndef FLAT_SHADED
vNormal = normalize( transformedNormal );
#ifdef USE_TANGENT
vTangent = normalize( transformedTangent );
vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
#ifdef FLIP_SIDED
vBitangent = - vBitangent;
#endif
#endif
#endif`,normalmap_pars_fragment:`#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`,clearcoat_normal_fragment_begin:`#ifdef USE_CLEARCOAT
vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,clearcoat_normal_fragment_maps:`#ifdef USE_CLEARCOAT_NORMALMAP
vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
clearcoatMapN.xy *= clearcoatNormalScale;
clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,clearcoat_pars_fragment:`#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`,iridescence_pars_fragment:`#ifdef USE_IRIDESCENCEMAP
uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
uniform sampler2D iridescenceThicknessMap;
#endif`,opaque_fragment:`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,packing:`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
}`,premultiplied_alpha_fragment:`#ifdef PREMULTIPLIED_ALPHA
gl_FragColor.rgb *= gl_FragColor.a;
#endif`,project_vertex:`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;`,dithering_fragment:`#ifdef DITHERING
gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,dithering_pars_fragment:`#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`,roughnessmap_fragment:`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
roughnessFactor *= texelRoughness.g;
#endif`,roughnessmap_pars_fragment:`#ifdef USE_ROUGHNESSMAP
uniform sampler2D roughnessMap;
#endif`,shadowmap_pars_fragment:`#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_SUN_LIGHT_SHADOWS > 0
#define SUN_LIGHT_CASCADES 2
#if defined( SHADOWMAP_TYPE_PCF )
uniform sampler2DShadow sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];
#else
uniform sampler2D sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];
#endif
uniform mat4 sunShadowMatrix[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ];
uniform vec4 sunShadowCascade[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ];
varying vec4 vSunShadowWorldPosition;
varying vec3 vSunShadowWorldNormal;
struct SunLightShadow {
float shadowIntensity;
float shadowBias;
float shadowNormalBias;
float shadowRadius;
vec2 shadowMapSize;
};
uniform SunLightShadow sunLightShadows[ NUM_SUN_LIGHT_SHADOWS ];
#endif
#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_SUN_LIGHT_SHADOWS > 0
float getSunShadow(
#if defined( SHADOWMAP_TYPE_PCF )
sampler2DShadow shadowMap,
#else
sampler2D shadowMap,
#endif
SunLightShadow sunLightShadow,
int shadowIndex
) {
vec4 shadowWorldPosition = vec4( vSunShadowWorldPosition.xyz + vSunShadowWorldNormal * sunLightShadow.shadowNormalBias, 1.0 );
float viewDepth = vSunShadowWorldPosition.w;
int cascadeOffset = shadowIndex * SUN_LIGHT_CASCADES;
float shadow = 1.0;
for ( int i = SUN_LIGHT_CASCADES - 1; i >= 0; i -- ) {
vec4 cascade = sunShadowCascade[ cascadeOffset + i ];
if ( viewDepth >= cascade.x && viewDepth < cascade.y ) {
float cascadeShadow = getShadow(
shadowMap,
sunLightShadow.shadowMapSize,
sunLightShadow.shadowIntensity,
sunLightShadow.shadowBias,
sunLightShadow.shadowRadius,
sunShadowMatrix[ cascadeOffset + i ] * shadowWorldPosition
);
shadow = mix( cascadeShadow, shadow, smoothstep( cascade.z, cascade.y, viewDepth ) );
}
}
return shadow;
}
#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`,shadowmap_pars_vertex:`#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_SUN_LIGHT_SHADOWS > 0
varying vec4 vSunShadowWorldPosition;
varying vec3 vSunShadowWorldNormal;
#endif
#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`,shadowmap_vertex:`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
#ifdef HAS_NORMAL
vec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );
#else
vec3 shadowWorldNormal = vec3( 0.0 );
#endif
vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
#if NUM_SUN_LIGHT_SHADOWS > 0
vSunShadowWorldPosition = vec4( worldPosition.xyz, - mvPosition.z );
vSunShadowWorldNormal = shadowWorldNormal;
#endif
#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`,shadowmask_pars_fragment:`float getShadowMask() {
float shadow = 1.0;
#ifdef USE_SHADOWMAP
#if NUM_SUN_LIGHT_SHADOWS > 0
SunLightShadow sunLight;
#pragma unroll_loop_start
for ( int i = 0; i < NUM_SUN_LIGHT_SHADOWS; i ++ ) {
sunLight = sunLightShadows[ i ];
shadow *= receiveShadow ? getSunShadow( sunShadowMap[ i ], sunLight, UNROLLED_LOOP_INDEX ) : 1.0;
}
#pragma unroll_loop_end
#endif
#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;
}`,skinbase_vertex:`#ifdef USE_SKINNING
mat4 boneMatX = getBoneMatrix( skinIndex.x );
mat4 boneMatY = getBoneMatrix( skinIndex.y );
mat4 boneMatZ = getBoneMatrix( skinIndex.z );
mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,skinning_pars_vertex:`#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`,skinning_vertex:`#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`,skinnormal_vertex:`#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`,specularmap_fragment:`float specularStrength;
#ifdef USE_SPECULARMAP
vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
specularStrength = texelSpecular.r;
#else
specularStrength = 1.0;
#endif`,specularmap_pars_fragment:`#ifdef USE_SPECULARMAP
uniform sampler2D specularMap;
#endif`,tonemapping_fragment:`#if defined( TONE_MAPPING )
gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,tonemapping_pars_fragment:`#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; }`,transmission_fragment:`#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 = transformNormalByInverseViewMatrix( 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`,transmission_pars_fragment:`#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`,uv_pars_fragment:`#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`,uv_pars_vertex:`#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`,uv_vertex:`#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`,worldpos_vertex:`#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`,background_vert:`varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
gl_Position = vec4( position.xy, 1.0, 1.0 );
}`,background_frag:`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>
}`,backgroundCube_vert:`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
}`,backgroundCube_frag:`#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>
}`,cube_vert:`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
}`,cube_frag:`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>
}`,depth_vert:`#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;
}`,depth_frag:`#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
}`,distance_vert:`#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;
}`,distance_frag:`#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 );
}`,equirect_vert:`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
}`,equirect_frag:`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>
}`,linedashed_vert:`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>
}`,linedashed_frag:`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>
}`,meshbasic_vert:`#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>
}`,meshbasic_frag:`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>
}`,meshlambert_vert:`#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>
}`,meshlambert_frag:`#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>
}`,meshmatcap_vert:`#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;
}`,meshmatcap_frag:`#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>
}`,meshnormal_vert:`#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
}`,meshnormal_frag:`#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
}`,meshphong_vert:`#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>
}`,meshphong_frag:`#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>
}`,meshphysical_vert:`#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
}`,meshphysical_frag:`#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_RETROREFLECTION
uniform float retroreflectivity;
#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>
}`,meshtoon_vert:`#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>
}`,meshtoon_frag:`#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>
}`,points_vert:`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>
}`,points_frag:`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>
}`,shadow_vert:`#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>
}`,shadow_frag:`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>
}`,sprite_vert:`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>
}`,sprite_frag:`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>
}`},R={common:{diffuse:{value:new L(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new bn},alphaMap:{value:null},alphaMapTransform:{value:new bn},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new bn}},envmap:{envMap:{value:null},envMapRotation:{value:new bn},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new bn}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new bn}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new bn},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new bn},normalScale:{value:new P(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new bn},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new bn}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new bn}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new bn}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new L(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{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 F},probesMax:{value:new F},probesResolution:{value:new F}},points:{diffuse:{value:new L(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new bn},alphaTest:{value:0},uvTransform:{value:new bn}},sprite:{diffuse:{value:new L(16777215)},opacity:{value:1},center:{value:new P(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new bn},alphaMap:{value:null},alphaMapTransform:{value:new bn},alphaTest:{value:0}}},Zs={basic:{uniforms:ro([R.common,R.specularmap,R.envmap,R.aomap,R.lightmap,R.fog]),vertexShader:Xs.meshbasic_vert,fragmentShader:Xs.meshbasic_frag},lambert:{uniforms:ro([R.common,R.specularmap,R.envmap,R.aomap,R.lightmap,R.emissivemap,R.bumpmap,R.normalmap,R.displacementmap,R.fog,R.lights,{emissive:{value:new L(0)},envMapIntensity:{value:1}}]),vertexShader:Xs.meshlambert_vert,fragmentShader:Xs.meshlambert_frag},phong:{uniforms:ro([R.common,R.specularmap,R.envmap,R.aomap,R.lightmap,R.emissivemap,R.bumpmap,R.normalmap,R.displacementmap,R.fog,R.lights,{emissive:{value:new L(0)},specular:{value:new L(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Xs.meshphong_vert,fragmentShader:Xs.meshphong_frag},standard:{uniforms:ro([R.common,R.envmap,R.aomap,R.lightmap,R.emissivemap,R.bumpmap,R.normalmap,R.displacementmap,R.roughnessmap,R.metalnessmap,R.fog,R.lights,{emissive:{value:new L(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Xs.meshphysical_vert,fragmentShader:Xs.meshphysical_frag},toon:{uniforms:ro([R.common,R.aomap,R.lightmap,R.emissivemap,R.bumpmap,R.normalmap,R.displacementmap,R.gradientmap,R.fog,R.lights,{emissive:{value:new L(0)}}]),vertexShader:Xs.meshtoon_vert,fragmentShader:Xs.meshtoon_frag},matcap:{uniforms:ro([R.common,R.bumpmap,R.normalmap,R.displacementmap,R.fog,{matcap:{value:null}}]),vertexShader:Xs.meshmatcap_vert,fragmentShader:Xs.meshmatcap_frag},points:{uniforms:ro([R.points,R.fog]),vertexShader:Xs.points_vert,fragmentShader:Xs.points_frag},dashed:{uniforms:ro([R.common,R.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Xs.linedashed_vert,fragmentShader:Xs.linedashed_frag},depth:{uniforms:ro([R.common,R.displacementmap]),vertexShader:Xs.depth_vert,fragmentShader:Xs.depth_frag},normal:{uniforms:ro([R.common,R.bumpmap,R.normalmap,R.displacementmap,{opacity:{value:1}}]),vertexShader:Xs.meshnormal_vert,fragmentShader:Xs.meshnormal_frag},sprite:{uniforms:ro([R.sprite,R.fog]),vertexShader:Xs.sprite_vert,fragmentShader:Xs.sprite_frag},background:{uniforms:{uvTransform:{value:new bn},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Xs.background_vert,fragmentShader:Xs.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new bn}},vertexShader:Xs.backgroundCube_vert,fragmentShader:Xs.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Xs.cube_vert,fragmentShader:Xs.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Xs.equirect_vert,fragmentShader:Xs.equirect_frag},distance:{uniforms:ro([R.common,R.displacementmap,{referencePosition:{value:new F},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Xs.distance_vert,fragmentShader:Xs.distance_frag},shadow:{uniforms:ro([R.lights,R.fog,{color:{value:new L(0)},opacity:{value:1}}]),vertexShader:Xs.shadow_vert,fragmentShader:Xs.shadow_frag}};Zs.physical={uniforms:ro([Zs.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new bn},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new bn},clearcoatNormalScale:{value:new P(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new bn},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new bn},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new bn},sheen:{value:0},sheenColor:{value:new L(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new bn},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new bn},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new bn},transmissionSamplerSize:{value:new P},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new bn},attenuationDistance:{value:0},attenuationColor:{value:new L(0)},specularColor:{value:new L(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new bn},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new bn},anisotropyVector:{value:new P},anisotropyMap:{value:null},anisotropyMapTransform:{value:new bn}}]),vertexShader:Xs.meshphysical_vert,fragmentShader:Xs.meshphysical_frag};var Qs={r:0,b:0,g:0},$s=new Bn,ec=new bn;ec.set(-1,0,0,0,1,0,0,0,1);function tc(e,t,n,r,i,a){let o=new L(0),s=i===!0?0:1,c,l,u=null,d=0,f=null;function p(e){let n=e.isScene===!0?e.background:null;if(n&&n.isTexture){let r=e.backgroundBlurriness>0;n=t.get(n,r)}return n}function m(t){let r=!1,i=p(t);i===null?g(o,s):i&&i.isColor&&(g(i,1),r=!0);let c=e.xr.getEnvironmentBlendMode();c===`additive`?n.buffers.color.setClear(0,0,0,1,a):c===`alpha-blend`&&n.buffers.color.setClear(0,0,0,0,a),(e.autoClear||r)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function h(t,n){let i=p(n);i&&(i.isCubeTexture||i.mapping===306)?(l===void 0&&(l=new Yi(new Sa(1,1,1),new uo({name:`BackgroundCubeMaterial`,uniforms:no(Zs.backgroundCube.uniforms),vertexShader:Zs.backgroundCube.vertexShader,fragmentShader:Zs.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),l.geometry.deleteAttribute(`uv`),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(l)),l.material.uniforms.envMap.value=i,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4($s.makeRotationFromEuler(n.backgroundRotation)).transpose(),i.isCubeTexture&&i.isRenderTargetTexture===!1&&l.material.uniforms.backgroundRotation.value.premultiply(ec),l.material.toneMapped=I.getTransfer(i.colorSpace)!==gt,(u!==i||d!==i.version||f!==e.toneMapping)&&(l.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):i&&i.isTexture&&(c===void 0&&(c=new Yi(new Qa(2,2),new uo({name:`BackgroundMaterial`,uniforms:no(Zs.background.uniforms),vertexShader:Zs.background.vertexShader,fragmentShader:Zs.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute(`normal`),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(c)),c.material.uniforms.t2D.value=i,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.toneMapped=I.getTransfer(i.colorSpace)!==gt,i.matrixAutoUpdate===!0&&i.updateMatrix(),c.material.uniforms.uvTransform.value.copy(i.matrix),(u!==i||d!==i.version||f!==e.toneMapping)&&(c.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null))}function g(t,r){t.getRGB(Qs,oo(e)),n.buffers.color.setClear(Qs.r,Qs.g,Qs.b,r,a)}function _(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),s=t,g(o,s)},getClearAlpha:function(){return s},setClearAlpha:function(e){s=e,g(o,s)},render:m,addToRenderList:h,dispose:_}}function nc(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(n,s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n,i){let a=i.wireframe===!0,o=r[t.id];o===void 0&&(o={},r[t.id]=o);let s=e.isInstancedMesh===!0?e.id:0,l=o[s];l===void 0&&(l={},o[s]=l);let u=l[n.id];u===void 0&&(u={},l[n.id]=u);let d=u[a];return d===void 0&&(d=f(c()),u[a]=d),d}function f(e){let t=[],r=[],i=[];for(let e=0;e<n;e++)t[e]=0,r[e]=0,i[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:i,object:e,attributes:{},index:null}}function p(e,t,n,r){let i=a.attributes,o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function g(e){_(e,0)}function _(t,n){let r=a.newAttributes,i=a.enabledAttributes,o=a.attributeDivisors;r[t]=1,i[t]===0&&(e.enableVertexAttribArray(t),i[t]=1),o[t]!==n&&(e.vertexAttribDivisor(t,n),o[t]=n)}function v(){let t=a.newAttributes,n=a.enabledAttributes;for(let r=0,i=n.length;r<i;r++)n[r]!==t[r]&&(e.disableVertexAttribArray(r),n[r]=0)}function y(t,n,r,i,a,o,s){s===!0?e.vertexAttribIPointer(t,n,r,a,o):e.vertexAttribPointer(t,n,r,i,a,o)}function b(n,r,i,a){h();let o=a.attributes,s=i.getAttributes(),c=r.defaultAttributeValues;for(let r in s){let i=s[r];if(i.location>=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)_(i.location+e,t.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,c*d,(p+o/i.locationSize*e)*d,f)}else{if(s.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)_(i.location+e,s.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,o*d,o/i.locationSize*e*d,f)}}else if(c!==void 0){let t=c[r];if(t!==void 0)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}v()}function x(){T();for(let e in r){let t=r[e];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e]}}function S(e){if(r[e.id]===void 0)return;let t=r[e.id];for(let e in t){let n=t[e];for(let e in n){let t=n[e];for(let e in t)u(t[e].object),delete t[e];delete n[e]}}delete r[e.id]}function C(e){for(let t in r){let n=r[t];for(let t in n){let r=n[t];if(r[e.id]===void 0)continue;let i=r[e.id];for(let e in i)u(i[e].object),delete i[e];delete r[e.id]}}}function w(e){for(let t in r){let n=r[t],i=e.isInstancedMesh===!0?e.id:0,a=n[i];if(a!==void 0){for(let e in a){let t=a[e];for(let e in t)u(t[e].object),delete t[e];delete a[e]}delete n[i],Object.keys(n).length===0&&delete r[t]}}}function T(){E(),o=!0,a!==i&&(a=i,l(a.object))}function E(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:s,reset:T,resetDefaultState:E,dispose:x,releaseStatesOfGeometry:S,releaseStatesOfObject:w,releaseStatesOfProgram:C,initAttributes:h,enableAttribute:g,disableUnusedAttributes:v}}function rc(e,t,n){let r;function i(e){r=e}function a(t,i){e.drawArrays(r,t,i),n.update(i,r,1)}function o(t,i,a){a!==0&&(e.drawArraysInstanced(r,t,i,a),n.update(i,r,a))}function s(e,i,a){if(a===0)return;t.get(`WEBGL_multi_draw`).multiDrawArraysWEBGL(r,e,0,i,0,a);let o=0;for(let e=0;e<a;e++)o+=i[e];n.update(o,r,1)}this.setMode=i,this.render=a,this.renderInstances=o,this.renderMultiDraw=s}function ic(e,t,n,r){let i;function a(){if(i!==void 0)return i;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let n=t.get(`EXT_texture_filter_anisotropic`);i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(t){return t===1023||r.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)}function s(n){let i=n===1016&&(t.has(`EXT_color_buffer_half_float`)||t.has(`EXT_color_buffer_float`));return!(n!==1009&&n!==1015&&!i&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE))}function c(t){if(t===`highp`){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(M(`WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has(`EXT_clip_control`);n.reversedDepthBuffer===!0&&f===!1&&M(`WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.`);let p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=e.getParameter(e.MAX_SAMPLES),S=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,maxSamples:x,samples:S}}function ac(e){let t=this,n=null,r=0,i=!1,a=!1,o=new Oi,s=new bn,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length<t)&&(l=new Float32Array(t));for(let t=0,n=r;t!==a;++t,n+=4)o.copy(e[t]).applyMatrix4(i,s),o.normal.toArray(l,n),l[n+3]=o.constant}c.value=l,c.needsUpdate=!0}return t.numPlanes=a,t.numIntersection=0,l}}var oc=4,sc=6,cc=20,lc=256,uc=new ps,dc=new L,fc=null,pc=0,mc=0,hc=!1,gc=new F,_c=new F,vc=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=gc}=i;fc=this._renderer.getRenderTarget(),pc=this._renderer.getActiveCubeFace(),mc=this._renderer.getActiveMipmapLevel(),hc=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Tc(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=wc(),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=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(fc,pc,mc),this._renderer.xr.enabled=hc,e.scissorTest=!1,xc(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),fc=this._renderer.getRenderTarget(),pc=this._renderer.getActiveCubeFace(),mc=this._renderer.getActiveMipmapLevel(),hc=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:O,minFilter:O,generateMipmaps:!1,type:ce,format:ge,colorSpace:mt,depthBuffer:!1},r=bc(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=bc(e,t,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=yc(r)),this._blurMaterial=Cc(r,e,t),this._ggxMaterial=Sc(r,e,t)}return r}_compileMaterial(e){let t=new Yi(new xi,e);this._renderer.compile(t,uc)}_sceneToCubeUV(e,t,n,r,i){let a=new cs(90,1,t,n),o=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,u=c.toneMapping;c.getClearColor(dc),c.toneMapping=0,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(r),c.clearDepth(),c.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new Yi(new Sa,new Li({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1})));let d=this._backgroundBox,f=d.material,p=!1,m=e.background;m?m.isColor&&(f.color.copy(m),e.background=null,p=!0):(f.color.copy(dc),p=!0);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;xc(r,n*l,t>2?l:0,l,l),c.setRenderTarget(r),p&&c.render(d,a),c.render(e,a)}c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=Tc()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=wc());let i=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=i;let o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;xc(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,uc)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;t<r;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){let r=this._renderer,i=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;let s=a.uniforms,c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l)*(c*1.25),{_lodMax:d}=this,f=this._sizeLods[n],p=3*f*(n>d-oc?n-d+oc:0),m=4*(this._cubeSize-f);s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,xc(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,uc),s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,xc(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,uc)}_blur(e,t,n,r){let i=this._pingPongRenderTarget,a=Math.min(r,Math.PI)/Math.SQRT2;this._blurPass(e,i,t,n,a),this._blurPass(i,e,n,n,a)}_blurPass(e,t,n,r,i){let a=this._renderer,o=this._blurMaterial,s=this._lodMeshes[r];s.material=o;let c=o.uniforms;c.envMap.value=e.texture,c.sigma.value=i,c.mipInt.value=this._lodMax-n;let l=this._sizeLods[r];xc(t,3*l*(r>this._lodMax-oc?r-this._lodMax+oc:0),4*(this._cubeSize-l),3*l,2*l),a.setRenderTarget(t),a.render(s,uc)}};function yc(e){let t=[],n=[],r=e,i=e-oc+1+sc;for(let e=0;e<i;e++){let e=2**r;t.push(e);let i=1/(e-2),a=-i,o=1+i,s=[a,a,o,a,o,o,a,a,o,o,a,o],c=new Float32Array(108),l=new Float32Array(108);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];c.set(r,18*e);for(let t=0;t<6;t++){let n=s[t*2]*2-1,r=s[t*2+1]*2-1;e===0?_c.set(1,r,n):e===1?_c.set(-n,1,-r):e===2?_c.set(-n,r,1):e===3?_c.set(-1,r,-n):e===4?_c.set(-n,-1,r):_c.set(n,r,-1),_c.toArray(l,(e*6+t)*3)}}let u=new xi;u.setAttribute(`position`,new ai(c,3)),u.setAttribute(`outputDirection`,new ai(l,3)),n.push(new Yi(u,null)),r>oc&&r--}return{lodMeshes:n,sizeLods:t}}function bc(e,t,n){let r=new Ln(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function xc(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function Sc(e,t,n){return new uo({name:`PMREMGGXConvolution`,defines:{GGX_SAMPLES:lc,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Ec(),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:0,depthTest:!1,depthWrite:!1})}function Cc(e,t,n){return new uo({name:`SphericalGaussianBlur`,defines:{SAMPLES:cc,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},sigma:{value:0},mipInt:{value:0}},vertexShader:Ec(),fragmentShader:`
precision highp float;
precision highp int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
uniform float sigma;
uniform float mipInt;
#define ENVMAP_TYPE_CUBE_UV
#include <cube_uv_reflection_fragment>
#define PI 3.14159265359
#define GOLDEN_ANGLE 2.39996322973
void main() {
if ( sigma == 0.0 ) {
gl_FragColor = vec4( bilinearCubeUV( envMap, vOutputDirection, mipInt ), 1.0 );
return;
}
vec3 outputDirection = normalize( vOutputDirection );
vec3 up = abs( outputDirection.z ) < 0.999 ? vec3( 0.0, 0.0, 1.0 ) : vec3( 1.0, 0.0, 0.0 );
vec3 tangent = normalize( cross( up, outputDirection ) );
vec3 bitangent = cross( outputDirection, tangent );
// Truncate the kernel at three standard deviations or at the antipode.
float thetaMax = min( 3.0 * sigma, PI );
float truncation = 1.0 - exp( - 0.5 * thetaMax * thetaMax / ( sigma * sigma ) );
vec3 accumColor = vec3( 0.0 );
float accumWeight = 0.0;
for ( int i = 0; i < SAMPLES; i ++ ) {
// Stratified inverse-CDF sampling of the Gaussian, placed on a golden-angle spiral.
float stratum = ( float( i ) + 0.5 ) / float( SAMPLES );
float theta = sigma * sqrt( - 2.0 * log( 1.0 - stratum * truncation ) );
float phi = float( i ) * GOLDEN_ANGLE;
vec3 offset = cos( phi ) * tangent + sin( phi ) * bitangent;
vec3 sampleDirection = cos( theta ) * outputDirection + sin( theta ) * offset;
// Correct the planar sample density to solid angle.
float weight = sin( theta ) / theta;
accumColor += weight * bilinearCubeUV( envMap, sampleDirection, mipInt );
accumWeight += weight;
}
gl_FragColor = vec4( accumColor / accumWeight, 1.0 );
}
`,blending:0,depthTest:!1,depthWrite:!1})}function wc(){return new uo({name:`EquirectangularToCubeUV`,uniforms:{envMap:{value:null}},vertexShader:Ec(),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:0,depthTest:!1,depthWrite:!1})}function Tc(){return new uo({name:`CubemapToCubeUV`,uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ec(),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:0,depthTest:!1,depthWrite:!1})}function Ec(){return`
precision mediump float;
precision mediump int;
attribute vec3 outputDirection;
varying vec3 vOutputDirection;
void main() {
vOutputDirection = outputDirection;
gl_Position = vec4( position, 1.0 );
}
`}var Dc=class extends Ln{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},r=[n,n,n,n,n,n];this.texture=new va(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let 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 );
}
`},r=new Sa(5,5,5),i=new uo({name:`CubemapFromEquirect`,uniforms:no(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;let a=new Yi(r,i),o=t.minFilter;return t.minFilter===1008&&(t.minFilter=O),new Ss(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}};function Oc(e){let t=new WeakMap,n=new WeakMap,r=null;function i(e,t=!1){return e==null?null:t?o(e):a(e)}function a(n){if(n&&n.isTexture){let r=n.mapping;if(r===303||r===304){if(t.has(n)){let e=t.get(n).texture;return s(e,n.mapping)}{let r=n.image;if(r&&r.height>0){let i=new Dc(r.height);return i.fromEquirectangularTexture(e,n),t.set(n,i),n.addEventListener(`dispose`,l),s(i.texture,n.mapping)}return null}}}return n}function o(t){if(t&&t.isTexture){let i=t.mapping,a=i===303||i===304,o=i===301||i===302;if(a||o){let i=n.get(t),s=i===void 0?0:i.texture.pmremVersion;if(t.isRenderTargetTexture&&t.pmremVersion!==s)return r===null&&(r=new vc(e)),i=a?r.fromEquirectangular(t,i):r.fromCubemap(t,i),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),i.texture;if(i!==void 0)return i.texture;{let s=t.image;return a&&s&&s.height>0||o&&s&&c(s)?(r===null&&(r=new vc(e)),i=a?r.fromEquirectangular(t):r.fromCubemap(t),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),t.addEventListener(`dispose`,u),i.texture):null}}}return t}function s(e,t){return t===303?e.mapping=301:t===304&&(e.mapping=302),e}function c(e){let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}function l(e){let n=e.target;n.removeEventListener(`dispose`,l);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function u(e){let t=e.target;t.removeEventListener(`dispose`,u);let r=n.get(t);r!==void 0&&(n.delete(t),r.dispose())}function d(){t=new WeakMap,n=new WeakMap,r!==null&&(r.dispose(),r=null)}return{get:i,dispose:d}}function kc(e){let t={};function n(n){if(t[n]!==void 0)return t[n];let r=e.getExtension(n);return t[n]=r,r}return{has:function(e){return n(e)!==null},init:function(){n(`EXT_color_buffer_float`),n(`WEBGL_clip_cull_distance`),n(`OES_texture_float_linear`),n(`EXT_color_buffer_half_float`),n(`WEBGL_multisampled_render_to_texture`),n(`WEBGL_render_shared_exponent`)},get:function(e){let t=n(e);return t===null&&Rt(`WebGLRenderer: `+e+` extension not supported.`),t}}}function Ac(e,t,n,r){let i={},a=new WeakMap;function o(e){let s=e.target;s.index!==null&&t.remove(s.index);for(let e in s.attributes)t.remove(s.attributes[e]);s.removeEventListener(`dispose`,o),delete i[s.id];let c=a.get(s);c&&(t.remove(c),a.delete(s)),r.releaseStatesOfGeometry(s),s.isInstancedBufferGeometry===!0&&delete s._maxInstanceCount,n.memory.geometries--}function s(e,t){return i[t.id]===!0?t:(t.addEventListener(`dispose`,o),i[t.id]=!0,n.memory.geometries++,t)}function c(n){let r=n.attributes;for(let n in r)t.update(r[n],e.ARRAY_BUFFER)}function l(e){let n=[],r=e.index,i=e.attributes.position,o=0;if(i===void 0)return;if(r!==null){let e=r.array;o=r.version;for(let t=0,r=e.length;t<r;t+=3){let r=e[t+0],i=e[t+1],a=e[t+2];n.push(r,i,i,a,a,r)}}else{let e=i.array;o=i.version;for(let t=0,r=e.length/3-1;t<r;t+=3){let e=t+0,r=t+1,i=t+2;n.push(e,r,r,i,i,e)}}let s=new(i.count>=65535?si:oi)(n,1);s.version=o;let c=a.get(e);c&&t.remove(c),a.set(e,s)}function u(e){let t=a.get(e);if(t){let n=e.index;n!==null&&t.version<n.version&&l(e)}else l(e);return a.get(e)}return{get:s,update:c,getWireframeAttribute:u}}function jc(e,t,n){let r;function i(e){r=e}let a,o;function s(e){a=e.type,o=e.bytesPerElement}function c(t,i){e.drawElements(r,i,a,t*o),n.update(i,r,1)}function l(t,i,s){s!==0&&(e.drawElementsInstanced(r,i,a,t*o,s),n.update(i,r,s))}function u(e,i,o){if(o===0)return;t.get(`WEBGL_multi_draw`).multiDrawElementsWEBGL(r,i,0,a,e,0,o);let s=0;for(let e=0;e<o;e++)s+=i[e];n.update(s,r,1)}this.setMode=i,this.setIndex=s,this.render=c,this.renderInstances=l,this.renderMultiDraw=u}function Mc(e){let t={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function r(t,r,i){switch(n.calls++,r){case e.TRIANGLES:n.triangles+=t/3*i;break;case e.LINES:n.lines+=t/2*i;break;case e.LINE_STRIP:n.lines+=i*(t-1);break;case e.LINE_LOOP:n.lines+=i*t;break;case e.POINTS:n.points+=i*t;break;default:N(`WebGLInfo: Unknown draw mode:`,r)}}function i(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:t,render:n,programs:null,autoReset:!0,reset:i,update:r}}function Nc(e,t,n){let r=new WeakMap,i=new Fn;function a(a,o,s){let c=a.morphTargetInfluences,l=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=l===void 0?0:l.length,d=r.get(o);if(d===void 0||d.count!==u){d!==void 0&&d.texture.dispose();let e=o.morphAttributes.position!==void 0,n=o.morphAttributes.normal!==void 0,a=o.morphAttributes.color!==void 0,s=o.morphAttributes.position||[],c=o.morphAttributes.normal||[],l=o.morphAttributes.color||[],f=0;e===!0&&(f=1),n===!0&&(f=2),a===!0&&(f=3);let p=o.attributes.position.count*f,m=1;p>t.maxTextureSize&&(m=Math.ceil(p/t.maxTextureSize),p=t.maxTextureSize);let h=new Float32Array(p*m*4*u),g=new Rn(h,p,m,u);g.type=se,g.needsUpdate=!0;let _=f*4;for(let t=0;t<u;t++){let r=s[t],o=c[t],u=l[t],d=p*m*4*t;for(let t=0;t<r.count;t++){let s=t*_;e===!0&&(i.fromBufferAttribute(r,t),h[d+s+0]=i.x,h[d+s+1]=i.y,h[d+s+2]=i.z,h[d+s+3]=0),n===!0&&(i.fromBufferAttribute(o,t),h[d+s+4]=i.x,h[d+s+5]=i.y,h[d+s+6]=i.z,h[d+s+7]=0),a===!0&&(i.fromBufferAttribute(u,t),h[d+s+8]=i.x,h[d+s+9]=i.y,h[d+s+10]=i.z,h[d+s+11]=u.itemSize===4?i.w:1)}}d={count:u,texture:g,size:new P(p,m)},r.set(o,d);function v(){g.dispose(),r.delete(o),o.removeEventListener(`dispose`,v)}o.addEventListener(`dispose`,v)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)s.getUniforms().setValue(e,`morphTexture`,a.morphTexture,n);else{let t=0;for(let e=0;e<c.length;e++)t+=c[e];let n=o.morphTargetsRelative?1:1-t;s.getUniforms().setValue(e,`morphTargetBaseInfluence`,n),s.getUniforms().setValue(e,`morphTargetInfluences`,c)}s.getUniforms().setValue(e,`morphTargetsTexture`,d.texture,n),s.getUniforms().setValue(e,`morphTargetsTextureSize`,d.size)}return{update:a}}function Pc(e,t,n,r,i){let a=new WeakMap;function o(r){let o=i.render.frame,s=r.geometry,l=t.get(r,s);if(a.get(l)!==o&&(t.update(l),a.set(l,o)),r.isInstancedMesh&&(r.hasEventListener(`dispose`,c)===!1&&r.addEventListener(`dispose`,c),a.get(r)!==o&&(n.update(r.instanceMatrix,e.ARRAY_BUFFER),r.instanceColor!==null&&n.update(r.instanceColor,e.ARRAY_BUFFER),a.set(r,o))),r.isSkinnedMesh){let e=r.skeleton;a.get(e)!==o&&(e.update(),a.set(e,o))}return l}function s(){a=new WeakMap}function c(e){let t=e.target;t.removeEventListener(`dispose`,c),r.releaseStatesOfObject(t),n.remove(t.instanceMatrix),t.instanceColor!==null&&n.remove(t.instanceColor)}return{update:o,dispose:s}}var Fc={1:`LINEAR_TONE_MAPPING`,2:`REINHARD_TONE_MAPPING`,3:`CINEON_TONE_MAPPING`,4:`ACES_FILMIC_TONE_MAPPING`,6:`AGX_TONE_MAPPING`,7:`NEUTRAL_TONE_MAPPING`,5:`CUSTOM_TONE_MAPPING`};function Ic(e,t,n,r,i,a){let o=new Ln(t,n,{type:e,depthBuffer:i,stencilBuffer:a,samples:r?4:0,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),s=null,c=null,l=new xi;l.setAttribute(`position`,new li([-1,3,0,-1,-1,0,3,-1,0],3)),l.setAttribute(`uv`,new li([0,2,0,0,2,0],2));let u=new fo({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}),d=new Yi(l,u),f=new ps(-1,1,1,-1,0,1),p=null,m=null,h=!1,g,_=null,v=[],y=!1;this.setSize=function(e,t){o.setSize(e,t),s!==null&&s.setSize(e,t),c!==null&&c.setSize(e,t);for(let n=0;n<v.length;n++){let r=v[n];r.setSize&&r.setSize(e,t)}},this.setEffects=function(e){v=e,y=v.length>0&&v[0].isRenderPass===!0;let t=o.width,n=o.height;v.length>0&&s===null&&(s=new Ln(t,n,{type:ce,depthBuffer:!1,stencilBuffer:!1}),c=new Ln(t,n,{type:ce,depthBuffer:!1,stencilBuffer:!1}));for(let e=0;e<v.length;e++){let r=v[e];r.setSize&&r.setSize(t,n)}},this.begin=function(e,t){if(h||e.toneMapping===0&&v.length===0)return!1;if(_=t,t!==null){let e=t.width,n=t.height;(o.width!==e||o.height!==n)&&this.setSize(e,n)}return y===!1&&e.setRenderTarget(o),g=e.toneMapping,e.toneMapping=0,!0},this.hasRenderPass=function(){return y},this.end=function(e,t){e.toneMapping=g,h=!0;let n=o,r=s;for(let i=0;i<v.length;i++){let a=v[i];a.enabled!==!1&&(a.render(e,r,n,t),a.needsSwap!==!1&&(n=r,r=r===s?c:s))}if(p!==e.outputColorSpace||m!==e.toneMapping){p=e.outputColorSpace,m=e.toneMapping,u.defines={},I.getTransfer(p)===`srgb`&&(u.defines.SRGB_TRANSFER=``);let t=Fc[m];t&&(u.defines[t]=``),u.needsUpdate=!0}u.uniforms.tDiffuse.value=n.texture,e.setRenderTarget(_),e.render(d,f),_=null,h=!1},this.isCompositing=function(){return h},this.dispose=function(){o.dispose(),s!==null&&s.dispose(),c!==null&&c.dispose(),l.dispose(),u.dispose()}}var Lc=new Pn,Rc=new ya(1,1),zc=new Rn,Bc=new zn,Vc=new va,Hc=[],Uc=[],Wc=new Float32Array(16),Gc=new Float32Array(9),Kc=new Float32Array(4);function qc(e,t,n){let r=e[0];if(r<=0||r>0)return e;let i=t*n,a=Hc[i];if(a===void 0&&(a=new Float32Array(i),Hc[i]=a),t!==0){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function Jc(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(e[n]!==t[n])return!1;return!0}function Yc(e,t){for(let n=0,r=t.length;n<r;n++)e[n]=t[n]}function Xc(e,t){let n=Uc[t];n===void 0&&(n=new Int32Array(t),Uc[t]=n);for(let r=0;r!==t;++r)n[r]=e.allocateTextureUnit();return n}function Zc(e,t){let n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function Qc(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Jc(n,t))return;e.uniform2fv(this.addr,t),Yc(n,t)}}function $c(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else if(t.r!==void 0)(n[0]!==t.r||n[1]!==t.g||n[2]!==t.b)&&(e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b);else{if(Jc(n,t))return;e.uniform3fv(this.addr,t),Yc(n,t)}}function el(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Jc(n,t))return;e.uniform4fv(this.addr,t),Yc(n,t)}}function tl(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(Jc(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),Yc(n,t)}else{if(Jc(n,r))return;Kc.set(r),e.uniformMatrix2fv(this.addr,!1,Kc),Yc(n,r)}}function nl(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(Jc(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),Yc(n,t)}else{if(Jc(n,r))return;Gc.set(r),e.uniformMatrix3fv(this.addr,!1,Gc),Yc(n,r)}}function rl(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(Jc(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),Yc(n,t)}else{if(Jc(n,r))return;Wc.set(r),e.uniformMatrix4fv(this.addr,!1,Wc),Yc(n,r)}}function il(e,t){let n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function al(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Jc(n,t))return;e.uniform2iv(this.addr,t),Yc(n,t)}}function ol(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(Jc(n,t))return;e.uniform3iv(this.addr,t),Yc(n,t)}}function sl(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Jc(n,t))return;e.uniform4iv(this.addr,t),Yc(n,t)}}function cl(e,t){let n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function ll(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Jc(n,t))return;e.uniform2uiv(this.addr,t),Yc(n,t)}}function ul(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(Jc(n,t))return;e.uniform3uiv(this.addr,t),Yc(n,t)}}function dl(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Jc(n,t))return;e.uniform4uiv(this.addr,t),Yc(n,t)}}function fl(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i);let a;this.type===e.SAMPLER_2D_SHADOW?(Rc.compareFunction=n.isReversedDepthBuffer()?518:515,a=Rc):a=Lc,n.setTexture2D(t||a,i)}function pl(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(t||Bc,i)}function ml(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(t||Vc,i)}function hl(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(t||zc,i)}function gl(e){switch(e){case 5126:return Zc;case 35664:return Qc;case 35665:return $c;case 35666:return el;case 35674:return tl;case 35675:return nl;case 35676:return rl;case 5124:case 35670:return il;case 35667:case 35671:return al;case 35668:case 35672:return ol;case 35669:case 35673:return sl;case 5125:return cl;case 36294:return ll;case 36295:return ul;case 36296:return dl;case 35678:case 36198:case 36298:case 36306:case 35682:return fl;case 35679:case 36299:case 36307:return pl;case 35680:case 36300:case 36308:case 36293:return ml;case 36289:case 36303:case 36311:case 36292:return hl}}function _l(e,t){e.uniform1fv(this.addr,t)}function vl(e,t){let n=qc(t,this.size,2);e.uniform2fv(this.addr,n)}function yl(e,t){let n=qc(t,this.size,3);e.uniform3fv(this.addr,n)}function bl(e,t){let n=qc(t,this.size,4);e.uniform4fv(this.addr,n)}function xl(e,t){let n=qc(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function Sl(e,t){let n=qc(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function Cl(e,t){let n=qc(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function wl(e,t){e.uniform1iv(this.addr,t)}function Tl(e,t){e.uniform2iv(this.addr,t)}function El(e,t){e.uniform3iv(this.addr,t)}function Dl(e,t){e.uniform4iv(this.addr,t)}function Ol(e,t){e.uniform1uiv(this.addr,t)}function kl(e,t){e.uniform2uiv(this.addr,t)}function Al(e,t){e.uniform3uiv(this.addr,t)}function jl(e,t){e.uniform4uiv(this.addr,t)}function Ml(e,t,n){let r=this.cache,i=t.length,a=Xc(n,i);Jc(r,a)||(e.uniform1iv(this.addr,a),Yc(r,a));let o;o=this.type===e.SAMPLER_2D_SHADOW?Rc:Lc;for(let e=0;e!==i;++e)n.setTexture2D(t[e]||o,a[e])}function Nl(e,t,n){let r=this.cache,i=t.length,a=Xc(n,i);Jc(r,a)||(e.uniform1iv(this.addr,a),Yc(r,a));for(let e=0;e!==i;++e)n.setTexture3D(t[e]||Bc,a[e])}function Pl(e,t,n){let r=this.cache,i=t.length,a=Xc(n,i);Jc(r,a)||(e.uniform1iv(this.addr,a),Yc(r,a));for(let e=0;e!==i;++e)n.setTextureCube(t[e]||Vc,a[e])}function Fl(e,t,n){let r=this.cache,i=t.length,a=Xc(n,i);Jc(r,a)||(e.uniform1iv(this.addr,a),Yc(r,a));for(let e=0;e!==i;++e)n.setTexture2DArray(t[e]||zc,a[e])}function Il(e){switch(e){case 5126:return _l;case 35664:return vl;case 35665:return yl;case 35666:return bl;case 35674:return xl;case 35675:return Sl;case 35676:return Cl;case 5124:case 35670:return wl;case 35667:case 35671:return Tl;case 35668:case 35672:return El;case 35669:case 35673:return Dl;case 5125:return Ol;case 36294:return kl;case 36295:return Al;case 36296:return jl;case 35678:case 36198:case 36298:case 36306:case 35682:return Ml;case 35679:case 36299:case 36307:return Nl;case 35680:case 36300:case 36308:case 36293:return Pl;case 36289:case 36303:case 36311:case 36292:return Fl}}var Ll=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=gl(t.type)}},Rl=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=Il(t.type)}},zl=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let r=this.seq;for(let i=0,a=r.length;i!==a;++i){let a=r[i];a.setValue(e,t[a.id],n)}}},Bl=/(\w+)(\])?(\[|\.)?/g;function Vl(e,t){e.seq.push(t),e.map[t.id]=t}function Hl(e,t,n){let r=e.name,i=r.length;for(Bl.lastIndex=0;;){let a=Bl.exec(r),o=Bl.lastIndex,s=a[1],c=a[2]===`]`,l=a[3];if(c&&(s|=0),l===void 0||l===`[`&&o+2===i){Vl(n,l===void 0?new Ll(s,e,t):new Rl(s,e,t));break}{let e=n.map[s];e===void 0&&(e=new zl(s),Vl(n,e)),n=e}}}var Ul=class{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<n;++r){let n=e.getActiveUniform(t,r);Hl(n,e.getUniformLocation(t,n.name),this)}let r=[],i=[];for(let t of this.seq)t.type===e.SAMPLER_2D_SHADOW||t.type===e.SAMPLER_CUBE_SHADOW||t.type===e.SAMPLER_2D_ARRAY_SHADOW?r.push(t):i.push(t);r.length>0&&(this.seq=r.concat(i))}setValue(e,t,n,r){let i=this.map[t];i!==void 0&&i.setValue(e,n,r)}setOptional(e,t,n){let r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let i=0,a=t.length;i!==a;++i){let a=t[i],o=n[a.id];o.needsUpdate!==!1&&a.setValue(e,o.value,r)}}static seqWithValue(e,t){let n=[];for(let r=0,i=e.length;r!==i;++r){let i=e[r];i.id in t&&n.push(i)}return n}};function Wl(e,t,n){let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}var Gl=37297,Kl=0;function ql(e,t){let n=e.split(`
`),r=[],i=Math.max(t-6,0),a=Math.min(t+6,n.length);for(let e=i;e<a;e++){let i=e+1;r.push(`${i===t?`>`:` `} ${i}: ${n[e]}`)}return r.join(`
`)}var Jl=new bn;function Yl(e){I._getMatrix(Jl,I.workingColorSpace,e);let t=`mat3( ${Jl.elements.map(e=>e.toFixed(4))} )`;switch(I.getTransfer(e)){case ht:return[t,`LinearTransferOETF`];case gt:return[t,`sRGBTransferOETF`];default:return M(`WebGLProgram: Unsupported color space: `,e),[t,`LinearTransferOETF`]}}function Xl(e,t,n){let r=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||``).trim();if(r&&i===``)return``;let a=/ERROR: 0:(\d+)/.exec(i);if(a){let r=parseInt(a[1]);return n.toUpperCase()+`
`+i+`
`+ql(e.getShaderSource(t),r)}return i}function Zl(e,t){let n=Yl(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,`}`].join(`
`)}var Ql={1:`Linear`,2:`Reinhard`,3:`Cineon`,4:`ACESFilmic`,6:`AgX`,7:`Neutral`,5:`Custom`};function $l(e,t){let n=Ql[t];return n===void 0?(M(`WebGLProgram: Unsupported toneMapping:`,t),`vec3 `+e+`( vec3 color ) { return LinearToneMapping( color ); }`):`vec3 `+e+`( vec3 color ) { return `+n+`ToneMapping( color ); }`}var eu=new F;function tu(){return I.getLuminanceCoefficients(eu),[`float luminance( const in vec3 rgb ) {`,` const vec3 weights = vec3( ${eu.x.toFixed(4)}, ${eu.y.toFixed(4)}, ${eu.z.toFixed(4)} );`,` return dot( weights, rgb );`,`}`].join(`
`)}function nu(e){return[e.extensionClipCullDistance?`#extension GL_ANGLE_clip_cull_distance : require`:``,e.extensionMultiDraw?`#extension GL_ANGLE_multi_draw : require`:``].filter(au).join(`
`)}function ru(e){let t=[];for(let n in e){let r=e[n];r!==!1&&t.push(`#define `+n+` `+r)}return t.join(`
`)}function iu(e,t){let n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){let r=e.getActiveAttrib(t,i),a=r.name,o=1;r.type===e.FLOAT_MAT2&&(o=2),r.type===e.FLOAT_MAT3&&(o=3),r.type===e.FLOAT_MAT4&&(o=4),n[a]={type:r.type,location:e.getAttribLocation(t,a),locationSize:o}}return n}function au(e){return e!==``}function ou(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_SUN_LIGHTS/g,t.numSunLights).replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_SUN_LIGHT_SHADOWS/g,t.numSunLightShadows).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function su(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var cu=/^[ \t]*#include +<([\w\d./]+)>/gm;function lu(e){return e.replace(cu,du)}var uu=new Map;function du(e,t){let n=Xs[t];if(n===void 0){let e=uu.get(t);if(e!==void 0)n=Xs[e],M(`WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.`,t,e);else throw Error(`THREE.WebGLProgram: Can not resolve #include <`+t+`>`)}return lu(n)}var fu=/#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 pu(e){return e.replace(fu,mu)}function mu(e,t,n,r){let i=``;for(let e=parseInt(t);e<parseInt(n);e++)i+=r.replace(/\[\s*i\s*\]/g,`[ `+e+` ]`).replace(/UNROLLED_LOOP_INDEX/g,e);return i}function hu(e){let t=`precision ${e.precision} float;
precision ${e.precision} int;
precision ${e.precision} sampler2D;
precision ${e.precision} samplerCube;
precision ${e.precision} sampler3D;
precision ${e.precision} sampler2DArray;
precision ${e.precision} sampler2DShadow;
precision ${e.precision} samplerCubeShadow;
precision ${e.precision} sampler2DArrayShadow;
precision ${e.precision} isampler2D;
precision ${e.precision} isampler3D;
precision ${e.precision} isamplerCube;
precision ${e.precision} isampler2DArray;
precision ${e.precision} usampler2D;
precision ${e.precision} usampler3D;
precision ${e.precision} usamplerCube;
precision ${e.precision} usampler2DArray;
`;return e.precision===`highp`?t+=`
#define HIGH_PRECISION`:e.precision===`mediump`?t+=`
#define MEDIUM_PRECISION`:e.precision===`lowp`&&(t+=`
#define LOW_PRECISION`),t}var gu={1:`SHADOWMAP_TYPE_PCF`,3:`SHADOWMAP_TYPE_VSM`};function _u(e){return gu[e.shadowMapType]||`SHADOWMAP_TYPE_BASIC`}var vu={301:`ENVMAP_TYPE_CUBE`,302:`ENVMAP_TYPE_CUBE`,306:`ENVMAP_TYPE_CUBE_UV`};function yu(e){return e.envMap===!1?`ENVMAP_TYPE_CUBE`:vu[e.envMapMode]||`ENVMAP_TYPE_CUBE`}var bu={302:`ENVMAP_MODE_REFRACTION`};function xu(e){return e.envMap===!1?`ENVMAP_MODE_REFLECTION`:bu[e.envMapMode]||`ENVMAP_MODE_REFLECTION`}var Su={0:`ENVMAP_BLENDING_MULTIPLY`,1:`ENVMAP_BLENDING_MIX`,2:`ENVMAP_BLENDING_ADD`};function Cu(e){return e.envMap===!1?`ENVMAP_BLENDING_NONE`:Su[e.combine]||`ENVMAP_BLENDING_NONE`}function wu(e){let t=e.envMapCubeUVHeight;if(t===null)return null;let n=Math.log2(t)-2,r=1/t;return{texelWidth:1/(3*Math.max(2**n,112)),texelHeight:r,maxMip:n}}function Tu(e,t,n,r){let i=e.getContext(),a=n.defines,o=n.vertexShader,s=n.fragmentShader,c=_u(n),l=yu(n),u=xu(n),d=Cu(n),f=wu(n),p=nu(n),m=ru(a),h=i.createProgram(),g,_,v=n.glslVersion?`#version `+n.glslVersion+`
`:``;n.isRawShaderMaterial?(g=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(au).join(`
`),g.length>0&&(g+=`
`),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(au).join(`
`),_.length>0&&(_+=`
`)):(g=[hu(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.extensionClipCullDistance?`#define USE_CLIP_DISTANCE`:``,n.batching?`#define USE_BATCHING`:``,n.batchingColor?`#define USE_BATCHING_COLOR`:``,n.instancing?`#define USE_INSTANCING`:``,n.instancingColor?`#define USE_INSTANCING_COLOR`:``,n.instancingMorph?`#define USE_INSTANCING_MORPH`:``,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.map?`#define USE_MAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+u:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.displacementMap?`#define USE_DISPLACEMENTMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.mapUv?`#define MAP_UV `+n.mapUv:``,n.alphaMapUv?`#define ALPHAMAP_UV `+n.alphaMapUv:``,n.lightMapUv?`#define LIGHTMAP_UV `+n.lightMapUv:``,n.aoMapUv?`#define AOMAP_UV `+n.aoMapUv:``,n.emissiveMapUv?`#define EMISSIVEMAP_UV `+n.emissiveMapUv:``,n.bumpMapUv?`#define BUMPMAP_UV `+n.bumpMapUv:``,n.normalMapUv?`#define NORMALMAP_UV `+n.normalMapUv:``,n.displacementMapUv?`#define DISPLACEMENTMAP_UV `+n.displacementMapUv:``,n.metalnessMapUv?`#define METALNESSMAP_UV `+n.metalnessMapUv:``,n.roughnessMapUv?`#define ROUGHNESSMAP_UV `+n.roughnessMapUv:``,n.anisotropyMapUv?`#define ANISOTROPYMAP_UV `+n.anisotropyMapUv:``,n.clearcoatMapUv?`#define CLEARCOATMAP_UV `+n.clearcoatMapUv:``,n.clearcoatNormalMapUv?`#define CLEARCOAT_NORMALMAP_UV `+n.clearcoatNormalMapUv:``,n.clearcoatRoughnessMapUv?`#define CLEARCOAT_ROUGHNESSMAP_UV `+n.clearcoatRoughnessMapUv:``,n.iridescenceMapUv?`#define IRIDESCENCEMAP_UV `+n.iridescenceMapUv:``,n.iridescenceThicknessMapUv?`#define IRIDESCENCE_THICKNESSMAP_UV `+n.iridescenceThicknessMapUv:``,n.sheenColorMapUv?`#define SHEEN_COLORMAP_UV `+n.sheenColorMapUv:``,n.sheenRoughnessMapUv?`#define SHEEN_ROUGHNESSMAP_UV `+n.sheenRoughnessMapUv:``,n.specularMapUv?`#define SPECULARMAP_UV `+n.specularMapUv:``,n.specularColorMapUv?`#define SPECULAR_COLORMAP_UV `+n.specularColorMapUv:``,n.specularIntensityMapUv?`#define SPECULAR_INTENSITYMAP_UV `+n.specularIntensityMapUv:``,n.transmissionMapUv?`#define TRANSMISSIONMAP_UV `+n.transmissionMapUv:``,n.thicknessMapUv?`#define THICKNESSMAP_UV `+n.thicknessMapUv:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexNormals?`#define HAS_NORMAL`:``,n.vertexColors?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.flatShading?`#define FLAT_SHADED`:``,n.skinning?`#define USE_SKINNING`:``,n.morphTargets?`#define USE_MORPHTARGETS`:``,n.morphNormals&&n.flatShading===!1?`#define USE_MORPHNORMALS`:``,n.morphColors?`#define USE_MORPHCOLORS`:``,n.morphTargetsCount>0?`#define MORPHTARGETS_TEXTURE_STRIDE `+n.morphTextureStride:``,n.morphTargetsCount>0?`#define MORPHTARGETS_COUNT `+n.morphTargetsCount:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.sizeAttenuation?`#define USE_SIZEATTENUATION`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 modelMatrix;`,`uniform mat4 modelViewMatrix;`,`uniform mat4 projectionMatrix;`,`uniform mat4 viewMatrix;`,`uniform mat3 normalMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,`#ifdef USE_INSTANCING`,` 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(au).join(`
`),_=[hu(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.alphaToCoverage?`#define ALPHA_TO_COVERAGE`:``,n.map?`#define USE_MAP`:``,n.matcap?`#define USE_MATCAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+l:``,n.envMap?`#define `+u:``,n.envMap?`#define `+d:``,f?`#define CUBEUV_TEXEL_WIDTH `+f.texelWidth:``,f?`#define CUBEUV_TEXEL_HEIGHT `+f.texelHeight:``,f?`#define CUBEUV_MAX_MIP `+f.maxMip+`.0`:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.packedNormalMap?`#define USE_PACKED_NORMALMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoat?`#define USE_CLEARCOAT`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.dispersion?`#define USE_DISPERSION`:``,n.retroreflection?`#define USE_RETROREFLECTION`:``,n.iridescence?`#define USE_IRIDESCENCE`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaTest?`#define USE_ALPHATEST`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.sheen?`#define USE_SHEEN`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors||n.instancingColor?`#define USE_COLOR`:``,n.vertexAlphas||n.batchingColor?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.gradientMap?`#define USE_GRADIENTMAP`:``,n.flatShading?`#define FLAT_SHADED`:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.premultipliedAlpha?`#define PREMULTIPLIED_ALPHA`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.numLightProbeGrids>0?`#define USE_LIGHT_PROBES_GRID`:``,n.decodeVideoTexture?`#define DECODE_VIDEO_TEXTURE`:``,n.decodeVideoTextureEmissive?`#define DECODE_VIDEO_TEXTURE_EMISSIVE`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 viewMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,n.toneMapping===0?``:`#define TONE_MAPPING`,n.toneMapping===0?``:Xs.tonemapping_pars_fragment,n.toneMapping===0?``:$l(`toneMapping`,n.toneMapping),n.dithering?`#define DITHERING`:``,n.opaque?`#define OPAQUE`:``,Xs.colorspace_pars_fragment,Zl(`linearToOutputTexel`,n.outputColorSpace),tu(),n.useDepthPacking?`#define DEPTH_PACKING `+n.depthPacking:``,`
`].filter(au).join(`
`)),o=lu(o),o=ou(o,n),o=su(o,n),s=lu(s),s=ou(s,n),s=su(s,n),o=pu(o),s=pu(s),n.isRawShaderMaterial!==!0&&(v=`#version 300 es
`,g=[p,`#define attribute in`,`#define varying out`,`#define texture2D texture`].join(`
`)+`
`+g,_=[`#define varying in`,n.glslVersion===`300 es`?``:`layout(location = 0) out highp vec4 pc_fragColor;`,n.glslVersion===`300 es`?``:`#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(`
`)+`
`+_);let y=v+g+o,b=v+_+s,x=Wl(i,i.VERTEX_SHADER,y),S=Wl(i,i.FRAGMENT_SHADER,b);i.attachShader(h,x),i.attachShader(h,S),n.index0AttributeName===void 0?n.hasPositionAttribute===!0&&i.bindAttribLocation(h,0,`position`):i.bindAttribLocation(h,0,n.index0AttributeName),i.linkProgram(h);function C(t){if(e.debug.checkShaderErrors){let n=i.getProgramInfoLog(h)||``,r=i.getShaderInfoLog(x)||``,a=i.getShaderInfoLog(S)||``,o=n.trim(),s=r.trim(),c=a.trim(),l=!0,u=!0;if(i.getProgramParameter(h,i.LINK_STATUS)===!1){if(l=!1,typeof e.debug.onShaderError==`function`)e.debug.onShaderError(i,h,x,S);else{let e=Xl(i,x,`vertex`),n=Xl(i,S,`fragment`);N(`WebGLProgram: Shader Error `+i.getError()+` - VALIDATE_STATUS `+i.getProgramParameter(h,i.VALIDATE_STATUS)+`
Material Name: `+t.name+`
Material Type: `+t.type+`
Program Info Log: `+o+`
`+e+`
`+n)}}else o===``?(s===``||c===``)&&(u=!1):M(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new Ul(i,h),T=iu(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,Gl)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=Kl++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var Eu=0,Du=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,n){let r=this._getShaderCacheForMaterial(e);return r.has(t)===!1&&(r.add(t),t.usedTimes++),r.has(n)===!1&&(r.add(n),n.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new Ou(e),t.set(e,n)),n}},Ou=class{constructor(e){this.id=Eu++,this.code=e,this.usedTimes=0}};function ku(e){return e===1030||e===37490||e===36285}function Au(e,t,n,r,i,a){let o=new Zn,s=new Du,c=new Set,l=[],u=new Map,d=r.logarithmicDepthBuffer,f=r.precision,p={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 m(e){return c.add(e),e===0?`uv`:`uv${e}`}function h(i,o,l,u,h,g){let _=u.fog,v=h.geometry,y=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?u.environment:null,b=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,x=t.get(i.envMap||y,b),S=x&&x.mapping===306?x.image.height:null,C=p[i.type];i.precision!==null&&(f=r.getMaxPrecision(i.precision),f!==i.precision&&M(`WebGLProgram.getParameters:`,i.precision,`not supported, using`,f,`instead.`));let w=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,T=w===void 0?0:w.length,E=0;v.morphAttributes.position!==void 0&&(E=1),v.morphAttributes.normal!==void 0&&(E=2),v.morphAttributes.color!==void 0&&(E=3);let D,O,k,ee;if(C){let e=Zs[C];D=e.vertexShader,O=e.fragmentShader}else{D=i.vertexShader,O=i.fragmentShader;let e=s.getVertexShaderStage(i),t=s.getFragmentShaderStage(i);s.update(i,e,t),k=e.id,ee=t.id}let te=e.getRenderTarget(),ne=e.state.buffers.depth.getReversed(),re=h.isInstancedMesh===!0,ie=h.isBatchedMesh===!0,ae=!!i.map,oe=!!i.matcap,se=!!x,ce=!!i.aoMap,le=!!i.lightMap,ue=!!i.bumpMap&&i.wireframe===!1,de=!!i.normalMap,fe=!!i.displacementMap,pe=!!i.emissiveMap,me=!!i.metalnessMap,he=!!i.roughnessMap,ge=i.anisotropy>0,_e=i.clearcoat>0,ve=i.dispersion>0,ye=i.retroreflectivity>0,be=i.iridescence>0,xe=i.sheen>0,Se=i.transmission>0,Ce=ge&&!!i.anisotropyMap,we=_e&&!!i.clearcoatMap,Te=_e&&!!i.clearcoatNormalMap,Ee=_e&&!!i.clearcoatRoughnessMap,De=be&&!!i.iridescenceMap,Oe=be&&!!i.iridescenceThicknessMap,ke=xe&&!!i.sheenColorMap,Ae=xe&&!!i.sheenRoughnessMap,je=!!i.specularMap,Me=!!i.specularColorMap,Ne=!!i.specularIntensityMap,Pe=Se&&!!i.transmissionMap,Fe=Se&&!!i.thicknessMap,Ie=!!i.gradientMap,Le=!!i.alphaMap,Re=i.alphaTest>0,A=!!i.alphaHash,ze=!!i.extensions,Be=0;i.toneMapped&&(te===null||te.isXRRenderTarget===!0)&&(Be=e.toneMapping);let Ve={shaderID:C,shaderType:i.type,shaderName:i.name,vertexShader:D,fragmentShader:O,defines:i.defines,customVertexShaderID:k,customFragmentShaderID:ee,isRawShaderMaterial:i.isRawShaderMaterial===!0,glslVersion:i.glslVersion,precision:f,batching:ie,batchingColor:ie&&h._colorsTexture!==null,instancing:re,instancingColor:re&&h.instanceColor!==null,instancingMorph:re&&h.morphTexture!==null,outputColorSpace:te===null?e.outputColorSpace:te.isXRRenderTarget===!0?te.texture.colorSpace:I.workingColorSpace,alphaToCoverage:!!i.alphaToCoverage,map:ae,matcap:oe,envMap:se,envMapMode:se&&x.mapping,envMapCubeUVHeight:S,aoMap:ce,lightMap:le,bumpMap:ue,normalMap:de,displacementMap:fe,emissiveMap:pe,normalMapObjectSpace:de&&i.normalMapType===1,normalMapTangentSpace:de&&i.normalMapType===0,packedNormalMap:de&&i.normalMapType===0&&ku(i.normalMap.format),metalnessMap:me,roughnessMap:he,anisotropy:ge,anisotropyMap:Ce,clearcoat:_e,clearcoatMap:we,clearcoatNormalMap:Te,clearcoatRoughnessMap:Ee,dispersion:ve,retroreflection:ye,iridescence:be,iridescenceMap:De,iridescenceThicknessMap:Oe,sheen:xe,sheenColorMap:ke,sheenRoughnessMap:Ae,specularMap:je,specularColorMap:Me,specularIntensityMap:Ne,transmission:Se,transmissionMap:Pe,thicknessMap:Fe,gradientMap:Ie,opaque:i.transparent===!1&&i.blending===1&&i.alphaToCoverage===!1,alphaMap:Le,alphaTest:Re,alphaHash:A,combine:i.combine,mapUv:ae&&m(i.map.channel),aoMapUv:ce&&m(i.aoMap.channel),lightMapUv:le&&m(i.lightMap.channel),bumpMapUv:ue&&m(i.bumpMap.channel),normalMapUv:de&&m(i.normalMap.channel),displacementMapUv:fe&&m(i.displacementMap.channel),emissiveMapUv:pe&&m(i.emissiveMap.channel),metalnessMapUv:me&&m(i.metalnessMap.channel),roughnessMapUv:he&&m(i.roughnessMap.channel),anisotropyMapUv:Ce&&m(i.anisotropyMap.channel),clearcoatMapUv:we&&m(i.clearcoatMap.channel),clearcoatNormalMapUv:Te&&m(i.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ee&&m(i.clearcoatRoughnessMap.channel),iridescenceMapUv:De&&m(i.iridescenceMap.channel),iridescenceThicknessMapUv:Oe&&m(i.iridescenceThicknessMap.channel),sheenColorMapUv:ke&&m(i.sheenColorMap.channel),sheenRoughnessMapUv:Ae&&m(i.sheenRoughnessMap.channel),specularMapUv:je&&m(i.specularMap.channel),specularColorMapUv:Me&&m(i.specularColorMap.channel),specularIntensityMapUv:Ne&&m(i.specularIntensityMap.channel),transmissionMapUv:Pe&&m(i.transmissionMap.channel),thicknessMapUv:Fe&&m(i.thicknessMap.channel),alphaMapUv:Le&&m(i.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(de||ge),vertexNormals:!!v.attributes.normal,vertexColors:i.vertexColors,vertexAlphas:i.vertexColors===!0&&!!v.attributes.color&&v.attributes.color.itemSize===4,pointsUvs:h.isPoints===!0&&!!v.attributes.uv&&(ae||Le),fog:!!_,useFog:i.fog===!0,fogExp2:!!_&&_.isFogExp2,flatShading:i.wireframe===!1&&(i.flatShading===!0||v.attributes.normal===void 0&&de===!1&&(i.isMeshLambertMaterial||i.isMeshPhongMaterial||i.isMeshStandardMaterial||i.isMeshPhysicalMaterial)),sizeAttenuation:i.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ne,skinning:h.isSkinnedMesh===!0,hasPositionAttribute:v.attributes.position!==void 0,morphTargets:v.morphAttributes.position!==void 0,morphNormals:v.morphAttributes.normal!==void 0,morphColors:v.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numSunLights:o.sun.length,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numSunLightShadows:o.sunShadowMap.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numLightProbeGrids:g.length,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&l.length>0,shadowMapType:e.shadowMap.type,toneMapping:Be,decodeVideoTexture:ae&&i.map.isVideoTexture===!0&&I.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:pe&&i.emissiveMap.isVideoTexture===!0&&I.getTransfer(i.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:i.premultipliedAlpha,doubleSided:i.side===2,flipSided:i.side===1,useDepthPacking:i.depthPacking>=0,depthPacking:i.depthPacking||0,index0AttributeName:i.index0AttributeName,extensionClipCullDistance:ze&&i.extensions.clipCullDistance===!0&&n.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(ze&&i.extensions.multiDraw===!0||ie)&&n.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:n.has(`KHR_parallel_shader_compile`),customProgramCacheKey:i.customProgramCacheKey()};return Ve.vertexUv1s=c.has(1),Ve.vertexUv2s=c.has(2),Ve.vertexUv3s=c.has(3),c.clear(),Ve}function g(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(_(n,t),v(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function _(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numSunLights),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numSunLightShadows),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function v(e,t){o.disableAll(),t.instancing&&o.enable(0),t.instancingColor&&o.enable(1),t.instancingMorph&&o.enable(2),t.matcap&&o.enable(3),t.envMap&&o.enable(4),t.normalMapObjectSpace&&o.enable(5),t.normalMapTangentSpace&&o.enable(6),t.clearcoat&&o.enable(7),t.iridescence&&o.enable(8),t.alphaTest&&o.enable(9),t.vertexColors&&o.enable(10),t.vertexAlphas&&o.enable(11),t.vertexUv1s&&o.enable(12),t.vertexUv2s&&o.enable(13),t.vertexUv3s&&o.enable(14),t.vertexTangents&&o.enable(15),t.anisotropy&&o.enable(16),t.alphaHash&&o.enable(17),t.batching&&o.enable(18),t.dispersion&&o.enable(19),t.retroreflection&&o.enable(24),t.batchingColor&&o.enable(20),t.gradientMap&&o.enable(21),t.packedNormalMap&&o.enable(22),t.vertexNormals&&o.enable(23),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.reversedDepthBuffer&&o.enable(4),t.skinning&&o.enable(5),t.morphTargets&&o.enable(6),t.morphNormals&&o.enable(7),t.morphColors&&o.enable(8),t.premultipliedAlpha&&o.enable(9),t.shadowMapEnabled&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.decodeVideoTextureEmissive&&o.enable(20),t.alphaToCoverage&&o.enable(21),t.numLightProbeGrids>0&&o.enable(22),t.hasPositionAttribute&&o.enable(23),e.push(o.mask)}function y(e){let t=p[e.type],n;if(t){let e=Zs[t];n=so.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new Tu(e,n,t,i),l.push(r),u.set(n,r)):++r.usedTimes,r}function x(e){if(--e.usedTimes===0){let t=l.indexOf(e);l[t]=l[l.length-1],l.pop(),u.delete(e.cacheKey),e.destroy()}}function S(e){s.remove(e)}function C(){s.dispose()}return{getParameters:h,getProgramCacheKey:g,getUniforms:y,acquireProgram:b,releaseProgram:x,releaseShaderCache:S,programs:l,dispose:C}}function ju(){let e=new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function Mu(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.materialVariant===t.materialVariant?e.z===t.z?e.id-t.id:e.z-t.z:e.materialVariant-t.materialVariant:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Nu(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Pu(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function s(n,r,i,a,s,c){let l=e[t];return l===void 0?(l={id:n.id,object:n,geometry:r,material:i,materialVariant:o(n),groupOrder:a,renderOrder:n.renderOrder,z:s,group:c},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.materialVariant=o(n),l.groupOrder=a,l.renderOrder=n.renderOrder,l.z=s,l.group=c),t++,l}function c(e,t,a,o,c,l,u){u.reversedDepth===!0&&(c=-c);let d=s(e,t,a,o,c,l);a.transmission>0?r.push(d):a.transparent===!0?i.push(d):n.push(d)}function l(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function u(e,t){n.length>1&&n.sort(e||Mu),r.length>1&&r.sort(t||Nu),i.length>1&&i.sort(t||Nu)}function d(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:c,unshift:l,finish:d,sort:u}}function Fu(){let e=new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new Pu,e.set(t,[i])):n>=r.length?(i=new Pu,r.push(i)):i=r[n],i}function n(){e=new WeakMap}return{get:t,dispose:n}}function Iu(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`SunLight`:case`DirectionalLight`:n={direction:new F,color:new L};break;case`SpotLight`:n={position:new F,direction:new F,color:new L,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new F,color:new L,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new F,skyColor:new L,groundColor:new L};break;case`RectAreaLight`:n={color:new L,position:new F,halfWidth:new F,halfHeight:new F}}return e[t.id]=n,n}}}function Lu(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`SunLight`:case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new P};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new P};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new P,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}var Ru=0;function zu(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function Bu(e){let t=new Iu,n=Lu(),r={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new F);let i=new F,a=new Bn,o=new Bn;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0,y=0,b=0,x=0;i.sort(zu);for(let e=0,S=i.length;e<S;e++){let S=i[e],C=S.color,w=S.intensity,T=S.distance,E=null;if(S.shadow&&S.shadow.map&&(E=S.shadow.map.texture.format===1030?S.shadow.map.texture:S.shadow.map.depthTexture||S.shadow.map.texture),S.isAmbientLight)a+=C.r*w,o+=C.g*w,s+=C.b*w;else if(S.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(S.sh.coefficients[e],w);x++}else if(S.isSunLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize.copy(e.mapSize).multiply(e.getFrameExtents()),r.sunShadow[l]=t,r.sunShadowMap[l]=E;let i=e.getViewportCount();for(let t=0;t<i;t++)r.sunShadowMatrix[u+t]=e.getMatrix(t),r.sunShadowCascade[u+t]=e._cascadeData[t];u+=i,l++}r.sun[c]=e,c++}else if(S.isDirectionalLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[d]=t,r.directionalShadowMap[d]=E,r.directionalShadowMatrix[d]=S.shadow.matrix,g++}r.directional[d]=e,d++}else if(S.isSpotLight){let e=t.get(S);e.position.setFromMatrixPosition(S.matrixWorld),e.color.copy(C).multiplyScalar(w),e.distance=T,e.coneCos=Math.cos(S.angle),e.penumbraCos=Math.cos(S.angle*(1-S.penumbra)),e.decay=S.decay,r.spot[p]=e;let i=S.shadow;if(S.map&&(r.spotLightMap[y]=S.map,y++,i.updateMatrices(S),S.castShadow&&b++),r.spotLightMatrix[p]=i.matrix,S.castShadow){let e=n.get(S);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[p]=e,r.spotShadowMap[p]=E,v++}p++}else if(S.isRectAreaLight){let e=t.get(S);e.color.copy(C).multiplyScalar(w),e.halfWidth.set(S.width*.5,0,0),e.halfHeight.set(0,S.height*.5,0),r.rectArea[m]=e,m++}else if(S.isPointLight){let e=t.get(S);if(e.color.copy(S.color).multiplyScalar(S.intensity),e.distance=S.distance,e.decay=S.decay,S.castShadow){let e=S.shadow,t=n.get(S);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[f]=t,r.pointShadowMap[f]=E,r.pointShadowMatrix[f]=S.shadow.matrix,_++}r.point[f]=e,f++}else if(S.isHemisphereLight){let e=t.get(S);e.skyColor.copy(S.color).multiplyScalar(w),e.groundColor.copy(S.groundColor).multiplyScalar(w),r.hemi[h]=e,h++}}m>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=R.LTC_FLOAT_1,r.rectAreaLTC2=R.LTC_FLOAT_2):(r.rectAreaLTC1=R.LTC_HALF_1,r.rectAreaLTC2=R.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let S=r.hash;(S.sunLength!==c||S.directionalLength!==d||S.pointLength!==f||S.spotLength!==p||S.rectAreaLength!==m||S.hemiLength!==h||S.numSunShadows!==l||S.numDirectionalShadows!==g||S.numPointShadows!==_||S.numSpotShadows!==v||S.numSpotMaps!==y||S.numLightProbes!==x)&&(r.sun.length=c,r.directional.length=d,r.spot.length=p,r.rectArea.length=m,r.point.length=f,r.hemi.length=h,r.sunShadow.length=l,r.sunShadowMap.length=l,r.sunShadowMatrix.length=u,r.sunShadowCascade.length=u,r.directionalShadow.length=g,r.directionalShadowMap.length=g,r.directionalShadowMatrix.length=g,r.pointShadow.length=_,r.pointShadowMap.length=_,r.pointShadowMatrix.length=_,r.spotShadow.length=v,r.spotShadowMap.length=v,r.spotLightMatrix.length=v+y-b,r.spotLightMap.length=y,r.numSpotLightShadowsWithMaps=b,r.numLightProbes=x,S.sunLength=c,S.directionalLength=d,S.pointLength=f,S.spotLength=p,S.rectAreaLength=m,S.hemiLength=h,S.numSunShadows=l,S.numDirectionalShadows=g,S.numPointShadows=_,S.numSpotShadows=v,S.numSpotMaps=y,S.numLightProbes=x,r.version=Ru++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=0,f=t.matrixWorldInverse;for(let t=0,p=e.length;t<p;t++){let p=e[t];if(p.isSunLight){let e=r.sun[n];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(f),n++}else if(p.isDirectionalLight){let e=r.directional[s];e.direction.setFromMatrixPosition(p.matrixWorld),i.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(f),s++}else if(p.isSpotLight){let e=r.spot[l];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),e.direction.setFromMatrixPosition(p.matrixWorld),i.setFromMatrixPosition(p.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(f),l++}else if(p.isRectAreaLight){let e=r.rectArea[u];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),o.identity(),a.copy(p.matrixWorld),a.premultiply(f),o.extractRotation(a),e.halfWidth.set(p.width*.5,0,0),e.halfHeight.set(0,p.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),u++}else if(p.isPointLight){let e=r.point[c];e.position.setFromMatrixPosition(p.matrixWorld),e.position.applyMatrix4(f),c++}else if(p.isHemisphereLight){let e=r.hemi[d];e.direction.setFromMatrixPosition(p.matrixWorld),e.direction.transformDirection(f),d++}}}return{setup:s,setupView:c,state:r}}function Vu(e){let t=new Bu(e),n=[],r=[],i=[];function a(e){d.camera=e,n.length=0,r.length=0,i.length=0}function o(e){n.push(e)}function s(e){r.push(e)}function c(e){i.push(e)}function l(){t.setup(n)}function u(e){t.setupView(n,e)}let d={lightsArray:n,shadowsArray:r,lightProbeGridArray:i,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:a,state:d,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:s,pushLightProbeGrid:c}}function Hu(e){let t=new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new Vu(e),t.set(n,[a])):r>=i.length?(a=new Vu(e),i.push(a)):a=i[r],a}function r(){t=new WeakMap}return{get:n,dispose:r}}var Uu=`void main() {
gl_Position = vec4( position, 1.0 );
}`,Wu=`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 );
}`,Gu=[new F(1,0,0),new F(-1,0,0),new F(0,1,0),new F(0,-1,0),new F(0,0,1),new F(0,0,-1)],Ku=[new F(0,-1,0),new F(0,-1,0),new F(0,0,1),new F(0,0,-1),new F(0,-1,0),new F(0,-1,0)],qu=new Bn,Ju=new F,Yu=new F;function Xu(e,t,n){let r=new ra,i=new P,a=new P,o=new Fn,s=new yo,c=new bo,l={},u=n.maxTextureSize,d={0:1,1:0,2:2},f=new uo({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new P},radius:{value:4}},vertexShader:Uu,fragmentShader:Wu}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new xi;m.setAttribute(`position`,new ai(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new Yi(m,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;this.render=function(t,n,s){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||t.length===0)return;this.type===2&&(M(`WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.`),this.type=1);let c=e.getRenderTarget(),l=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.state;f.setBlending(0),f.buffers.depth.getReversed()===!0?f.buffers.color.setClear(0,0,0,0):f.buffers.color.setClear(1,1,1,1),f.buffers.depth.setTest(!0),f.setScissorTest(!1);let p=_!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let c=0,l=t.length;c<l;c++){let l=t[c],d=l.shadow;if(d===void 0){M(`WebGLShadowMap:`,l,`has no shadow.`);continue}if(d.autoUpdate===!1&&d.needsUpdate===!1)continue;i.copy(d.mapSize);let m=d.getFrameExtents();i.multiply(m),a.copy(d.mapSize),(i.x>u||i.y>u)&&(i.x>u&&(a.x=Math.floor(u/m.x),i.x=a.x*m.x,d.mapSize.x=a.x),i.y>u&&(a.y=Math.floor(u/m.y),i.y=a.y*m.y,d.mapSize.y=a.y));let h=e.state.buffers.depth.getReversed();if(d.camera._reversedDepth=h,d.map===null||p===!0){if(d.map!==null&&(d.map.depthTexture!==null&&(d.map.depthTexture.dispose(),d.map.depthTexture=null),d.map.dispose()),this.type===3){if(l.isPointLight){M(`WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.`);continue}d.map=new Ln(i.x,i.y,{format:xe,type:ce,minFilter:O,magFilter:O,generateMipmaps:!1}),d.map.texture.name=l.name+`.shadowMap`,d.map.depthTexture=new ya(i.x,i.y,se),d.map.depthTexture.name=l.name+`.shadowMapDepth`,d.map.depthTexture.format=_e,d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=T,d.map.depthTexture.magFilter=T}else l.isPointLight?(d.map=new Dc(i.x),d.map.depthTexture=new ba(i.x,oe)):(d.map=new Ln(i.x,i.y),d.map.depthTexture=new ya(i.x,i.y,oe)),d.map.depthTexture.name=l.name+`.shadowMap`,d.map.depthTexture.format=_e,this.type===1?(d.map.depthTexture.compareFunction=h?518:515,d.map.depthTexture.minFilter=O,d.map.depthTexture.magFilter=O):(d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=T,d.map.depthTexture.magFilter=T);d.camera.updateProjectionMatrix()}d.map.isWebGLCubeRenderTarget!==!0&&(d.map.width!==i.x||d.map.height!==i.y)&&d.map.setSize(i.x,i.y);let g=d.map.isWebGLCubeRenderTarget?6:d.getViewportCount();l.isPointLight!==!0&&d.updateMatrices(l,s);for(let t=0;t<g;t++){let i=d.getCamera(t);if(l.isPointLight){let e=d.camera,n=d.matrix,r=l.distance||e.far;r!==e.far&&(e.far=r,e.updateProjectionMatrix()),Ju.setFromMatrixPosition(l.matrixWorld),e.position.copy(Ju),Yu.copy(e.position),Yu.add(Gu[t]),e.up.copy(Ku[t]),e.lookAt(Yu),e.updateMatrixWorld(),n.makeTranslation(-Ju.x,-Ju.y,-Ju.z),qu.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),d._frustum.setFromProjectionMatrix(qu,e.coordinateSystem,e.reversedDepth)}if(d.map.isWebGLCubeRenderTarget)e.setRenderTarget(d.map,t),e.clear();else{t===0&&(e.setRenderTarget(d.map),e.clear());let n=d.getViewport(t);o.set(a.x*n.x,a.y*n.y,a.x*n.z,a.y*n.w),f.viewport(o)}r=d.getFrustum(t),b(n,s,i,l,this.type)}d.isPointLightShadow!==!0&&this.type===3&&v(d,s),d.needsUpdate=!1}_=this.type,g.needsUpdate=!1,e.setRenderTarget(c,l,d)};function v(n,r){let a=t.update(h);f.defines.VSM_SAMPLES!==n.blurSamples&&(f.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,f.needsUpdate=!0,p.needsUpdate=!0),n.mapPass===null?n.mapPass=new Ln(i.x,i.y,{format:xe,type:ce}):(n.mapPass.width!==n.map.width||n.mapPass.height!==n.map.height)&&n.mapPass.setSize(n.map.width,n.map.height),f.uniforms.shadow_pass.value=n.map.depthTexture,f.uniforms.resolution.value.set(n.map.width,n.map.height),f.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,a,f,h,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value.set(n.map.width,n.map.height),p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,a,p,h,null)}function y(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?c:s,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=l[e];r===void 0&&(r={},l[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,x)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?d[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function b(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||n.intersectsFrustum(r))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=y(n,d,o,s);n.onBeforeShadow(e,n,i,a,r,t,u),e.renderBufferDirect(a,null,r,t,n,u),n.onAfterShadow(e,n,i,a,r,t,u)}}}else if(c.visible){let t=y(n,c,o,s);n.onBeforeShadow(e,n,i,a,r,t,null),e.renderBufferDirect(a,null,r,t,n,null),n.onAfterShadow(e,n,i,a,r,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)b(c[e],i,a,o,s)}function x(e){e.target.removeEventListener(`dispose`,x);for(let t in l){let n=l[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}function Zu(e,t){function n(){let t=!1,n=new Fn,r=null,i=new Fn(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?me(e.DEPTH_TEST):he(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=Vt[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(o=t,r&&(t=1-t),e.clearDepth(t))},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?me(e.STENCIL_TEST):he(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=new WeakMap,l=new WeakMap,u={},d={},f={},p=new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new L(0,0,0),T=0,E=!1,D=null,O=null,k=null,ee=null,te=null,ne=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),re=!1,ie=0,ae=e.getParameter(e.VERSION);ae.indexOf(`WebGL`)===-1?ae.indexOf(`OpenGL ES`)!==-1&&(ie=parseFloat(/^OpenGL ES (\d)/.exec(ae)[1]),re=ie>=2):(ie=parseFloat(/^WebGL (\d)/.exec(ae)[1]),re=ie>=1);let oe=null,se={},ce=e.getParameter(e.SCISSOR_BOX),le=e.getParameter(e.VIEWPORT),ue=new Fn().fromArray(ce),de=new Fn().fromArray(le);function fe(t,n,r,i){let a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let pe={};pe[e.TEXTURE_2D]=fe(e.TEXTURE_2D,e.TEXTURE_2D,1),pe[e.TEXTURE_CUBE_MAP]=fe(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),pe[e.TEXTURE_2D_ARRAY]=fe(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),pe[e.TEXTURE_3D]=fe(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),me(e.DEPTH_TEST),o.setFunc(3),Ce(!1),we(1),me(e.CULL_FACE),xe(0);function me(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function he(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function ge(t,n){return f[t]!==n&&(e.bindFramebuffer(t,n),f[t]=n,t===e.DRAW_FRAMEBUFFER&&(f[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(f[e.DRAW_FRAMEBUFFER]=n),!0)}function _e(t,n){let r=m,i=!1;if(t){r=p.get(n),r===void 0&&(r=[],p.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function ve(t){return h!==t&&(e.useProgram(t),h=t,!0)}let ye={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};ye[103]=e.MIN,ye[104]=e.MAX;let be={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function xe(t,n,r,i,a,o,s,c,l,u){if(t===0){g===!0&&(he(e.BLEND),g=!1);return}if(g===!1&&(me(e.BLEND),g=!0),t!==5){if(t!==_||u!==E){if((v!==100||x!==100)&&(e.blendEquation(e.FUNC_ADD),v=100,x=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:N(`WebGLState: Invalid blending: `,t)}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:N(`WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:N(`WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:N(`WebGLState: Invalid blending: `,t)}y=null,b=null,S=null,C=null,w.set(0,0,0),T=0,_=t,E=u}return}a||=n,o||=r,s||=i,(n!==v||a!==x)&&(e.blendEquationSeparate(ye[n],ye[a]),v=n,x=a),(r!==y||i!==b||o!==S||s!==C)&&(e.blendFuncSeparate(be[r],be[i],be[o],be[s]),y=r,b=i,S=o,C=s),(c.equals(w)===!1||l!==T)&&(e.blendColor(c.r,c.g,c.b,l),w.copy(c),T=l),_=t,E=!1}function Se(t,n){t.side===2?he(e.CULL_FACE):me(e.CULL_FACE);let r=t.side===1;n&&(r=!r),Ce(r),t.blending===1&&t.transparent===!1?xe(0):xe(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),Ee(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?me(e.SAMPLE_ALPHA_TO_COVERAGE):he(e.SAMPLE_ALPHA_TO_COVERAGE)}function Ce(t){D!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),D=t)}function we(t){t===0?he(e.CULL_FACE):(me(e.CULL_FACE),t!==O&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),O=t}function Te(t){t!==k&&(re&&e.lineWidth(t),k=t)}function Ee(t,n,r){t?(me(e.POLYGON_OFFSET_FILL),(ee!==n||te!==r)&&(ee=n,te=r,o.getReversed()&&(n=-n),e.polygonOffset(n,r))):he(e.POLYGON_OFFSET_FILL)}function De(t){t?me(e.SCISSOR_TEST):he(e.SCISSOR_TEST)}function Oe(t){t===void 0&&(t=e.TEXTURE0+ne-1),oe!==t&&(e.activeTexture(t),oe=t)}function ke(t,n,r){r===void 0&&(r=oe===null?e.TEXTURE0+ne-1:oe);let i=se[r];i===void 0&&(i={type:void 0,texture:void 0},se[r]=i),(i.type!==t||i.texture!==n)&&(oe!==r&&(e.activeTexture(r),oe=r),e.bindTexture(t,n||pe[t]),i.type=t,i.texture=n)}function Ae(){let t=se[oe];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function je(){try{e.compressedTexImage2D(...arguments)}catch(e){N(`WebGLState:`,e)}}function Me(){try{e.compressedTexImage3D(...arguments)}catch(e){N(`WebGLState:`,e)}}function Ne(){try{e.texSubImage2D(...arguments)}catch(e){N(`WebGLState:`,e)}}function Pe(){try{e.texSubImage3D(...arguments)}catch(e){N(`WebGLState:`,e)}}function Fe(){try{e.compressedTexSubImage2D(...arguments)}catch(e){N(`WebGLState:`,e)}}function Ie(){try{e.compressedTexSubImage3D(...arguments)}catch(e){N(`WebGLState:`,e)}}function Le(){try{e.texStorage2D(...arguments)}catch(e){N(`WebGLState:`,e)}}function Re(){try{e.texStorage3D(...arguments)}catch(e){N(`WebGLState:`,e)}}function A(){try{e.texImage2D(...arguments)}catch(e){N(`WebGLState:`,e)}}function ze(){try{e.texImage3D(...arguments)}catch(e){N(`WebGLState:`,e)}}function Be(t){return d[t]===void 0?e.getParameter(t):d[t]}function Ve(t,n){d[t]!==n&&(e.pixelStorei(t,n),d[t]=n)}function j(t){ue.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),ue.copy(t))}function He(t){de.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),de.copy(t))}function Ue(t,n){let r=l.get(n);r===void 0&&(r=new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function We(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function Ge(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),u={},d={},oe=null,se={},f={},p=new WeakMap,m=[],h=null,g=!1,_=null,v=null,y=null,b=null,x=null,S=null,C=null,w=new L(0,0,0),T=0,E=!1,D=null,O=null,k=null,ee=null,te=null,ue.set(0,0,e.canvas.width,e.canvas.height),de.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:me,disable:he,bindFramebuffer:ge,drawBuffers:_e,useProgram:ve,setBlending:xe,setMaterial:Se,setFlipSided:Ce,setCullFace:we,setLineWidth:Te,setPolygonOffset:Ee,setScissorTest:De,activeTexture:Oe,bindTexture:ke,unbindTexture:Ae,compressedTexImage2D:je,compressedTexImage3D:Me,texImage2D:A,texImage3D:ze,pixelStorei:Ve,getParameter:Be,updateUBOMapping:Ue,uniformBlockBinding:We,texStorage2D:Le,texStorage3D:Re,texSubImage2D:Ne,texSubImage3D:Pe,compressedTexSubImage2D:Fe,compressedTexSubImage3D:Ie,scissor:j,viewport:He,reset:Ge}}function Qu(e,t,n,r,i,a,o){let s=t.has(`WEBGL_multisampled_render_to_texture`)?t.get(`WEBGL_multisampled_render_to_texture`):null,c=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),l=new P,u=new WeakMap,d=new Set,f,p=new WeakMap,m=!1;try{m=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function h(e,t){return m?new OffscreenCanvas(e,t):Nt(`canvas`)}function g(e,t,n){let r=1,i=Be(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);f===void 0&&(f=h(n,a));let o=t?h(n,a):f;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),M(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}return`data`in e&&M(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e}return e}function _(e){return e.generateMipmaps}function v(t){e.generateMipmap(t)}function y(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function b(n,r,i,a,o,s=!1){if(n!==null){if(e[n]!==void 0)return e[n];M(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let c;a&&(c=t.get(`EXT_texture_norm16`),c||M(`WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension`));let l=r;if(r===e.RED&&(i===e.FLOAT&&(l=e.R32F),i===e.HALF_FLOAT&&(l=e.R16F),i===e.UNSIGNED_BYTE&&(l=e.R8),i===e.UNSIGNED_SHORT&&c&&(l=c.R16_EXT),i===e.SHORT&&c&&(l=c.R16_SNORM_EXT)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.R8UI),i===e.UNSIGNED_SHORT&&(l=e.R16UI),i===e.UNSIGNED_INT&&(l=e.R32UI),i===e.BYTE&&(l=e.R8I),i===e.SHORT&&(l=e.R16I),i===e.INT&&(l=e.R32I)),r===e.RG&&(i===e.FLOAT&&(l=e.RG32F),i===e.HALF_FLOAT&&(l=e.RG16F),i===e.UNSIGNED_BYTE&&(l=e.RG8),i===e.UNSIGNED_SHORT&&c&&(l=c.RG16_EXT),i===e.SHORT&&c&&(l=c.RG16_SNORM_EXT)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RG8UI),i===e.UNSIGNED_SHORT&&(l=e.RG16UI),i===e.UNSIGNED_INT&&(l=e.RG32UI),i===e.BYTE&&(l=e.RG8I),i===e.SHORT&&(l=e.RG16I),i===e.INT&&(l=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGB8UI),i===e.UNSIGNED_SHORT&&(l=e.RGB16UI),i===e.UNSIGNED_INT&&(l=e.RGB32UI),i===e.BYTE&&(l=e.RGB8I),i===e.SHORT&&(l=e.RGB16I),i===e.INT&&(l=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(l=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(l=e.RGBA16UI),i===e.UNSIGNED_INT&&(l=e.RGBA32UI),i===e.BYTE&&(l=e.RGBA8I),i===e.SHORT&&(l=e.RGBA16I),i===e.INT&&(l=e.RGBA32I)),r===e.RGB&&(i===e.UNSIGNED_SHORT&&c&&(l=c.RGB16_EXT),i===e.SHORT&&c&&(l=c.RGB16_SNORM_EXT),i===e.UNSIGNED_INT_5_9_9_9_REV&&(l=e.RGB9_E5),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(l=e.R11F_G11F_B10F)),r===e.RGBA){let t=s?ht:I.getTransfer(o);i===e.FLOAT&&(l=e.RGBA32F),i===e.HALF_FLOAT&&(l=e.RGBA16F),i===e.UNSIGNED_BYTE&&(l=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT&&c&&(l=c.RGBA16_EXT),i===e.SHORT&&c&&(l=c.RGBA16_SNORM_EXT),i===e.UNSIGNED_SHORT_4_4_4_4&&(l=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(l=e.RGB5_A1)}return(l===e.R16F||l===e.R32F||l===e.RG16F||l===e.RG32F||l===e.RGBA16F||l===e.RGBA32F)&&t.get(`EXT_color_buffer_float`),l}function x(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,M(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function te(e,t){return _(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function ne(e){let t=e.target;t.removeEventListener(`dispose`,ne),ie(t),t.isVideoTexture&&u.delete(t),t.isHTMLTexture&&d.delete(t)}function re(e){let t=e.target;t.removeEventListener(`dispose`,re),oe(t)}function ie(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=p.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&ae(e),Object.keys(i).length===0&&p.delete(n)}r.remove(e)}function ae(t){let n=r.get(t);e.deleteTexture(n.__webglTexture);let i=t.source,a=p.get(i);delete a[n.__cacheKey],o.memory.textures--}function oe(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r<n.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(n.__webglFramebuffer[t][r]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}let i=t.textures;for(let t=0,n=i.length;t<n;t++){let n=r.get(i[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),o.memory.textures--),r.remove(i[t])}r.remove(t)}let se=0;function ce(){se=0}function le(){return se}function ue(e){se=e}function de(){let e=se;return e>=i.maxTextures&&M(`WebGLTextures: Trying to use `+(e+1)+` texture units while this GPU supports only `+i.maxTextures),se+=1,e}function fe(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function pe(t,i){let a=r.get(t);if(t.isVideoTexture&&A(t),t.isRenderTargetTexture===!1&&t.isExternalTexture!==!0&&t.version>0&&a.__version!==t.version){let e=t.image;if(e===null)M(`WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)M(`WebGLRenderer: Texture marked for update but image is incomplete`);else{Te(a,t,i);return}}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}function me(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){Te(a,t,i);return}t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null),n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i)}function he(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){Te(a,t,i);return}n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)}function ge(t,i){let a=r.get(t);if(t.isCubeDepthTexture!==!0&&t.version>0&&a.__version!==t.version){Ee(a,t,i);return}n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture,e.TEXTURE0+i)}let _e={[S]:e.REPEAT,[C]:e.CLAMP_TO_EDGE,[w]:e.MIRRORED_REPEAT},ye={[T]:e.NEAREST,[E]:e.NEAREST_MIPMAP_NEAREST,[D]:e.NEAREST_MIPMAP_LINEAR,[O]:e.LINEAR,[k]:e.LINEAR_MIPMAP_NEAREST,[ee]:e.LINEAR_MIPMAP_LINEAR},be={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function xe(n,a){if(a.type===1015&&t.has(`OES_texture_float_linear`)===!1&&(a.magFilter===1006||a.magFilter===1007||a.magFilter===1005||a.magFilter===1008||a.minFilter===1006||a.minFilter===1007||a.minFilter===1005||a.minFilter===1008)&&M(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,_e[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,_e[a.wrapT]),(n===e.TEXTURE_3D||n===e.TEXTURE_2D_ARRAY)&&e.texParameteri(n,e.TEXTURE_WRAP_R,_e[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,ye[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,ye[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,be[a.compareFunction])),t.has(`EXT_texture_filter_anisotropic`)===!0){if(a.magFilter===1003||a.minFilter!==1005&&a.minFilter!==1008||a.type===1015&&t.has(`OES_texture_float_linear`)===!1)return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function Se(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,ne));let i=n.source,a=p.get(i);a===void 0&&(a={},p.set(i,a));let s=fe(n);if(s!==t.__cacheKey){a[s]===void 0&&(a[s]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,r=!0),a[s].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&ae(n)),t.__cacheKey=s,t.__webglTexture=a[s].texture}return r}function Ce(e,t,n){return Math.floor(Math.floor(e/n)/t)}function we(t,r,i,a){let o=t.updateRanges;if(o.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,i,a,r.data);else{o.sort((e,t)=>e.start-t.start);let s=0;for(let e=1;e<o.length;e++){let t=o[s],n=o[e],i=t.start+t.count,a=Ce(n.start,r.width,4),c=Ce(t.start,r.width,4);n.start<=i+1&&a===c&&Ce(n.start+n.count-1,r.width,4)===a?t.count=Math.max(t.count,n.start+n.count-t.start):(++s,o[s]=n)}o.length=s+1;let c=n.getParameter(e.UNPACK_ROW_LENGTH),l=n.getParameter(e.UNPACK_SKIP_PIXELS),u=n.getParameter(e.UNPACK_SKIP_ROWS);n.pixelStorei(e.UNPACK_ROW_LENGTH,r.width);for(let t=0,s=o.length;t<s;t++){let s=o[t],c=Math.floor(s.start/4),l=Math.ceil(s.count/4),u=c%r.width,d=Math.floor(c/r.width),f=l;n.pixelStorei(e.UNPACK_SKIP_PIXELS,u),n.pixelStorei(e.UNPACK_SKIP_ROWS,d),n.texSubImage2D(e.TEXTURE_2D,0,u,d,f,1,i,a,r.data)}t.clearUpdateRanges(),n.pixelStorei(e.UNPACK_ROW_LENGTH,c),n.pixelStorei(e.UNPACK_SKIP_PIXELS,l),n.pixelStorei(e.UNPACK_SKIP_ROWS,u)}}function Te(t,o,s){let c=e.TEXTURE_2D;(o.isDataArrayTexture||o.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),o.isData3DTexture&&(c=e.TEXTURE_3D);let l=Se(t,o),u=o.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+s);let f=r.get(u);if(u.version!==f.__version||l===!0){if(n.activeTexture(e.TEXTURE0+s),!(typeof ImageBitmap<`u`&&o.image instanceof ImageBitmap)){let t=I.getPrimaries(I.workingColorSpace),r=o.colorSpace===``?null:I.getPrimaries(o.colorSpace),i=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,i)}n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment);let t=g(o.image,!1,i.maxTextureSize);t=ze(o,t);let r=a.convert(o.format,o.colorSpace),p=a.convert(o.type),m=b(o.internalFormat,r,p,o.normalized,o.colorSpace,o.isVideoTexture);xe(c,o);let h,y=o.mipmaps,S=o.isVideoTexture!==!0,C=f.__version===void 0||l===!0,w=u.dataReady,T=te(o,t);if(o.isDepthTexture)m=x(o.format===ve,o.type),C&&(S?n.texStorage2D(e.TEXTURE_2D,1,m,t.width,t.height):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,null));else if(o.isDataTexture){if(y.length>0){S&&C&&n.texStorage2D(e.TEXTURE_2D,T,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],S?w&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data);o.generateMipmaps=!1}else S?(C&&n.texStorage2D(e.TEXTURE_2D,T,m,t.width,t.height),w&&we(o,t,r,p)):n.texImage2D(e.TEXTURE_2D,0,m,t.width,t.height,0,r,p,t.data)}else if(o.isCompressedTexture){if(o.isCompressedArrayTexture){S&&C&&n.texStorage3D(e.TEXTURE_2D_ARRAY,T,m,y[0].width,y[0].height,t.depth);for(let i=0,a=y.length;i<a;i++)if(h=y[i],o.format!==1023){if(r!==null){if(S){if(w){if(o.layerUpdates.size>0){let t=Ks(h.width,h.height,o.format,o.type);for(let a of o.layerUpdates){let o=h.data.subarray(a*t/h.data.BYTES_PER_ELEMENT,(a+1)*t/h.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,a,h.width,h.height,1,r,o)}}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,h.data)}}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,h.data,0,0)}else M(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`)}else S?w&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,i,0,0,0,h.width,h.height,t.depth,r,p,h.data):n.texImage3D(e.TEXTURE_2D_ARRAY,i,m,h.width,h.height,t.depth,0,r,p,h.data);o.layerUpdates.size>0&&o.clearLayerUpdates()}else{S&&C&&n.texStorage2D(e.TEXTURE_2D,T,m,y[0].width,y[0].height);for(let t=0,i=y.length;t<i;t++)h=y[t],o.format===1023?S?w&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,p,h.data):n.texImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,r,p,h.data):r===null?M(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):S?w&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,h.width,h.height,r,h.data):n.compressedTexImage2D(e.TEXTURE_2D,t,m,h.width,h.height,0,h.data)}}else if(o.isDataArrayTexture){if(S){if(C&&n.texStorage3D(e.TEXTURE_2D_ARRAY,T,m,t.width,t.height,t.depth),w){if(o.layerUpdates.size>0){let i=Ks(t.width,t.height,o.format,o.type);for(let a of o.layerUpdates){let o=t.data.subarray(a*i/t.data.BYTES_PER_ELEMENT,(a+1)*i/t.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,a,t.width,t.height,1,r,p,o)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)}}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,m,t.width,t.height,t.depth,0,r,p,t.data)}else if(o.isData3DTexture)S?(C&&n.texStorage3D(e.TEXTURE_3D,T,m,t.width,t.height,t.depth),w&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,t.width,t.height,t.depth,r,p,t.data)):n.texImage3D(e.TEXTURE_3D,0,m,t.width,t.height,t.depth,0,r,p,t.data);else if(o.isFramebufferTexture){if(C){if(S)n.texStorage2D(e.TEXTURE_2D,T,m,t.width,t.height);else{let i=t.width,a=t.height;for(let t=0;t<T;t++)n.texImage2D(e.TEXTURE_2D,t,m,i,a,0,r,p,null),i>>=1,a>>=1}}}else if(o.isHTMLTexture){if(`texElementImage2D`in e){let n=e.canvas;if(n.hasAttribute(`layoutsubtree`)||n.setAttribute(`layoutsubtree`,`true`),t.parentNode!==n){n.appendChild(t),d.add(o),n.onpaint=e=>{let t=e.changedElements;for(let e of d)t.includes(e.image)&&(e.needsUpdate=!0)},n.requestPaint();return}if(e.texElementImage2D.length===3)e.texElementImage2D(e.TEXTURE_2D,e.RGBA8,t);else{let n=e.RGBA,r=e.RGBA,i=e.UNSIGNED_BYTE;e.texElementImage2D(e.TEXTURE_2D,0,n,r,i,t)}e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}}else if(y.length>0){if(S&&C){let t=Be(y[0]);n.texStorage2D(e.TEXTURE_2D,T,m,t.width,t.height)}for(let t=0,i=y.length;t<i;t++)h=y[t],S?w&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,r,p,h):n.texImage2D(e.TEXTURE_2D,t,m,r,p,h);o.generateMipmaps=!1}else if(S){if(C){let r=Be(t);n.texStorage2D(e.TEXTURE_2D,T,m,r.width,r.height)}w&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,r,p,t)}else n.texImage2D(e.TEXTURE_2D,0,m,r,p,t);_(o)&&v(c),f.__version=u.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function Ee(t,o,s){if(o.image.length!==6)return;let c=Se(t,o),l=o.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);let u=r.get(l);if(l.version!==u.__version||c===!0){n.activeTexture(e.TEXTURE0+s);let t=I.getPrimaries(I.workingColorSpace),r=o.colorSpace===``?null:I.getPrimaries(o.colorSpace),d=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;n.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),n.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),n.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),n.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let f=o.isCompressedTexture||o.image[0].isCompressedTexture,p=o.image[0]&&o.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)!f&&!p?m[e]=g(o.image[e],!0,i.maxCubemapSize):m[e]=p?o.image[e].image:o.image[e],m[e]=ze(o,m[e]);let h=m[0],y=a.convert(o.format,o.colorSpace),x=a.convert(o.type),S=b(o.internalFormat,y,x,o.normalized,o.colorSpace),C=o.isVideoTexture!==!0,w=u.__version===void 0||c===!0,T=l.dataReady,E=te(o,h);xe(e.TEXTURE_CUBE_MAP,o);let D;if(f){C&&w&&n.texStorage2D(e.TEXTURE_CUBE_MAP,E,S,h.width,h.height);for(let t=0;t<6;t++){D=m[t].mipmaps;for(let r=0;r<D.length;r++){let i=D[r];o.format===1023?C?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,S,i.width,i.height,0,y,x,i.data):y===null?M(`WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):C?T&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,y,i.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,S,i.width,i.height,0,i.data)}}}else{if(D=o.mipmaps,C&&w){D.length>0&&E++;let t=Be(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,E,S,t.width,t.height)}for(let t=0;t<6;t++)if(p){C?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,y,x,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,S,m[t].width,m[t].height,0,y,x,m[t].data);for(let r=0;r<D.length;r++){let i=D[r].image[t].image;C?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,i.width,i.height,y,x,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,S,i.width,i.height,0,y,x,i.data)}}else{C?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,y,x,m[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,S,y,x,m[t]);for(let r=0;r<D.length;r++){let i=D[r];C?T&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,y,x,i.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,S,y,x,i.image[t])}}}_(o)&&v(e.TEXTURE_CUBE_MAP),u.__version=l.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function De(t,i,o,c,l,u){let d=a.convert(o.format,o.colorSpace),f=a.convert(o.type),p=b(o.internalFormat,d,f,o.normalized,o.colorSpace),m=r.get(i),h=r.get(o);if(h.__renderTarget=i,!m.__hasExternalTextures){let t=Math.max(1,i.width>>u),r=Math.max(1,i.height>>u);l===e.TEXTURE_3D||l===e.TEXTURE_2D_ARRAY?n.texImage3D(l,u,p,t,r,i.depth,0,d,f,null):n.texImage2D(l,u,p,t,r,0,d,f,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),Re(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,c,l,h.__webglTexture,0,Le(i)):(l===e.TEXTURE_2D||l>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,c,l,h.__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function Oe(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=x(n.stencilBuffer,a),c=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;Re(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Le(n),o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Le(n),o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,c,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i<t.length;i++){let o=t[i],c=a.convert(o.format,o.colorSpace),l=a.convert(o.type),u=b(o.internalFormat,c,l,o.normalized,o.colorSpace);Re(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Le(n),u,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Le(n),u,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,u,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function ke(t,i,o){let c=i.isWebGLCubeRenderTarget===!0;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!(i.depthTexture&&i.depthTexture.isDepthTexture))throw Error(`THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.`);let l=r.get(i.depthTexture);if(l.__renderTarget=i,(!l.__webglTexture||i.depthTexture.image.width!==i.width||i.depthTexture.image.height!==i.height)&&(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),c){if(l.__webglInit===void 0&&(l.__webglInit=!0,i.depthTexture.addEventListener(`dispose`,ne)),l.__webglTexture===void 0){l.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),xe(e.TEXTURE_CUBE_MAP,i.depthTexture);let t=a.convert(i.depthTexture.format),r=a.convert(i.depthTexture.type),o;i.depthTexture.format===1026?o=e.DEPTH_COMPONENT24:i.depthTexture.format===1027&&(o=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,o,i.width,i.height,0,t,r,null)}}else pe(i.depthTexture,0);let u=l.__webglTexture,d=Le(i),f=c?e.TEXTURE_CUBE_MAP_POSITIVE_X+o:e.TEXTURE_2D,p=i.depthTexture.format===1027?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(i.depthTexture.format===1026)Re(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else if(i.depthTexture.format===1027)Re(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,f,u,0,d):e.framebufferTexture2D(e.FRAMEBUFFER,p,f,u,0);else throw Error(`THREE.WebGLTextures: Unknown depthTexture format.`)}function Ae(t){let i=r.get(t),a=t.isWebGLCubeRenderTarget===!0;if(i.__boundDepthTexture!==t.depthTexture){let e=t.depthTexture;if(i.__depthDisposeCallback&&i.__depthDisposeCallback(),e){let t=()=>{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer){if(a)for(let e=0;e<6;e++)ke(i.__webglFramebuffer[e],t,e);else{let e=t.texture.mipmaps;e&&e.length>0?ke(i.__webglFramebuffer[0],t,0):ke(i.__webglFramebuffer,t,0)}}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),Oe(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),Oe(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function je(t,n,i){let a=r.get(t);n!==void 0&&De(a.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),i!==void 0&&Ae(t)}function Me(t){let i=t.texture,s=r.get(t),c=r.get(i);t.addEventListener(`dispose`,re);let l=t.textures,u=t.isWebGLCubeRenderTarget===!0,d=l.length>1;if(d||(c.__webglTexture===void 0&&(c.__webglTexture=e.createTexture()),c.__version=i.version,o.memory.textures++),u){s.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer[t]=[];for(let n=0;n<i.mipmaps.length;n++)s.__webglFramebuffer[t][n]=e.createFramebuffer()}else s.__webglFramebuffer[t]=e.createFramebuffer()}else{if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer=[];for(let t=0;t<i.mipmaps.length;t++)s.__webglFramebuffer[t]=e.createFramebuffer()}else s.__webglFramebuffer=e.createFramebuffer();if(d)for(let t=0,n=l.length;t<n;t++){let n=r.get(l[t]);n.__webglTexture===void 0&&(n.__webglTexture=e.createTexture(),o.memory.textures++)}if(t.samples>0&&Re(t)===!1){s.__webglMultisampledFramebuffer=e.createFramebuffer(),s.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,s.__webglMultisampledFramebuffer);for(let n=0;n<l.length;n++){let r=l[n];s.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,s.__webglColorRenderbuffer[n]);let i=a.convert(r.format,r.colorSpace),o=a.convert(r.type),c=b(r.internalFormat,i,o,r.normalized,r.colorSpace,t.isXRRenderTarget===!0),u=Le(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,u,c,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,s.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(s.__webglDepthRenderbuffer=e.createRenderbuffer(),Oe(s.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(u){n.bindTexture(e.TEXTURE_CUBE_MAP,c.__webglTexture),xe(e.TEXTURE_CUBE_MAP,i);for(let n=0;n<6;n++)if(i.mipmaps&&i.mipmaps.length>0)for(let r=0;r<i.mipmaps.length;r++)De(s.__webglFramebuffer[n][r],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,r);else De(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);_(i)&&v(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(d){for(let i=0,a=l.length;i<a;i++){let a=l[i],o=r.get(a),c=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(c=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(c,o.__webglTexture),xe(c,a),De(s.__webglFramebuffer,t,a,e.COLOR_ATTACHMENT0+i,c,0),_(a)&&v(c)}n.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(r,c.__webglTexture),xe(r,i),i.mipmaps&&i.mipmaps.length>0)for(let n=0;n<i.mipmaps.length;n++)De(s.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,r,n);else De(s.__webglFramebuffer,t,i,e.COLOR_ATTACHMENT0,r,0);_(i)&&v(r),n.unbindTexture()}t.depthBuffer&&Ae(t)}function Ne(e){let t=e.textures;for(let i=0,a=t.length;i<a;i++){let a=t[i];if(_(a)){let t=y(e),i=r.get(a).__webglTexture;n.bindTexture(t,i),v(t),n.unbindTexture()}}}let Pe=[],Fe=[];function Ie(t){if(t.samples>0){if(Re(t)===!1){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=r.get(t),d=i.length>1;if(d)for(let t=0;t<i.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,u.__webglMultisampledFramebuffer);let f=t.texture.mipmaps;f&&f.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let n=0;n<i.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(s|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(s|=e.STENCIL_BUFFER_BIT)),d){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,u.__webglColorRenderbuffer[n]);let t=r.get(i[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,a,o,0,0,a,o,s,e.NEAREST),c===!0&&(Pe.length=0,Fe.length=0,Pe.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&t.storeMultisampledDepthBuffer===!1&&(Pe.push(l),Fe.push(l),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,Fe)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,Pe))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),d)for(let t=0;t<i.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,u.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,u.__webglColorRenderbuffer[t]);let a=r.get(i[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,u.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,a,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&t.storeMultisampledDepthBuffer===!1&&c){let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}}}function Le(e){return Math.min(i.maxSamples,e.samples)}function Re(e){let n=r.get(e);return e.samples>0&&t.has(`WEBGL_multisampled_render_to_texture`)===!0&&n.__useRenderToTexture!==!1}function A(e){let t=o.render.frame;u.get(e)!==t&&(u.set(e,t),e.update())}function ze(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(I.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&M(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):N(`WebGLTextures: Unsupported texture color space:`,n)),t}function Be(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(l.width=e.naturalWidth||e.width,l.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(l.width=e.displayWidth,l.height=e.displayHeight):(l.width=e.width,l.height=e.height),l}this.allocateTextureUnit=de,this.resetTextureUnits=ce,this.getTextureUnits=le,this.setTextureUnits=ue,this.setTexture2D=pe,this.setTexture2DArray=me,this.setTexture3D=he,this.setTextureCube=ge,this.rebindTextures=je,this.setupRenderTarget=Me,this.updateRenderTargetMipmap=Ne,this.updateMultisampleRenderTarget=Ie,this.setupDepthRenderbuffer=Ae,this.setupFrameBufferTexture=De,this.useMultisampledRTT=Re,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function $u(e,t){function n(n,r=``){let i,a=I.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779){if(a===`srgb`){if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null}else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null}if(n===35840||n===35841||n===35842||n===35843){if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null}if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491){if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return i.COMPRESSED_R11_EAC;if(n===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return i.COMPRESSED_RG11_EAC;if(n===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null}if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821){if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null}if(n===36492||n===36494||n===36495){if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null}if(n===36283||n===36284||n===36285||n===36286){if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null}return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var ed=`
void main() {
gl_Position = vec4( position, 1.0 );
}`,td=`
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;
}
}`,nd=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new xa(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){let t=e.cameras[0].viewport,n=new uo({vertexShader:ed,fragmentShader:td,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Yi(new Qa(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},rd=class extends Ht{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=typeof XRWebGLBinding<`u`,h=new nd,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new P,C=null,w=null,T=new cs;T.viewport=new Fn;let E=new cs;E.viewport=new Fn;let D=[T,E],O=new Cs,k=null,ee=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return t===void 0&&(t=new gr,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new gr,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new gr,b[e]=t),t.getHandSpace()};function ne(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=b[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function re(){r.removeEventListener(`select`,ne),r.removeEventListener(`selectstart`,ne),r.removeEventListener(`selectend`,ne),r.removeEventListener(`squeeze`,ne),r.removeEventListener(`squeezestart`,ne),r.removeEventListener(`squeezeend`,ne),r.removeEventListener(`end`,re),r.removeEventListener(`inputsourceschange`,ie);for(let e=0;e<b.length;e++){let t=x[e];t!==null&&(x[e]=null,b[e].disconnect(t))}k=null,ee=null,h.reset();for(let e in g)delete g[e];if(e.setRenderTarget(v),f=null,d=null,u=null,r=null,y=null,me.stop(),n.isPresenting=!1,e.setPixelRatio(C),e.setSize(S.width,S.height,!1),w!==null){let e=w.camera;e.fov=w.fov,e.zoom=w.zoom,e.updateProjectionMatrix(),w=null}n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&M(`WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&M(`WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return d===null?f:d},this.getBinding=function(){return u===null&&m&&(u=new XRWebGLBinding(r,t)),u},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(l){if(r=l,r!==null){if(v=e.getRenderTarget(),r.addEventListener(`select`,ne),r.addEventListener(`selectstart`,ne),r.addEventListener(`selectend`,ne),r.addEventListener(`squeeze`,ne),r.addEventListener(`squeezestart`,ne),r.addEventListener(`squeezeend`,ne),r.addEventListener(`end`,re),r.addEventListener(`inputsourceschange`,ie),_.xrCompatible!==!0&&await t.makeXRCompatible(),C=e.getPixelRatio(),e.getSize(S),m&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;_.depth&&(o=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?ve:_e,a=_.stencil?de:oe);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};u=this.getBinding(),d=u.createProjectionLayer(s),r.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),y=new Ln(d.textureWidth,d.textureHeight,{format:ge,type:te,depthTexture:new ya(d.textureWidth,d.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1,storeMultisampledDepthBuffer:d.ignoreDepthValues===!1,storeMultisampledStencilBuffer:d.ignoreDepthValues===!1})}else{let n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:i};f=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new Ln(f.framebufferWidth,f.framebufferHeight,{format:ge,type:te,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1,storeMultisampledDepthBuffer:f.ignoreDepthValues===!1,storeMultisampledStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),me.setContext(r),me.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return h.getDepthTexture()};function ie(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=x.indexOf(n);r>=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=x.indexOf(n);if(r===-1){for(let e=0;e<b.length;e++)if(e>=x.length){x.push(n),r=e;break}else if(x[e]===null){x[e]=n,r=e;break}if(r===-1)break}let i=b[r];i&&i.connect(n)}}let ae=new F,se=new F;function ce(e,t,n){ae.setFromMatrixPosition(t.matrixWorld),se.setFromMatrixPosition(n.matrixWorld);let r=ae.distanceTo(se),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function le(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;h.texture!==null&&(h.depthNear>0&&(t=h.depthNear),h.depthFar>0&&(n=h.depthFar)),O.near=E.near=T.near=t,O.far=E.far=T.far=n,(k!==O.near||ee!==O.far)&&(r.updateRenderState({depthNear:O.near,depthFar:O.far}),k=O.near,ee=O.far),O.layers.mask=e.layers.mask|6,T.layers.mask=O.layers.mask&-5,E.layers.mask=O.layers.mask&-3;let i=e.parent,a=O.cameras;le(O,i);for(let e=0;e<a.length;e++)le(a[e],i);a.length===2?ce(O,T,E):O.projectionMatrix.copy(T.projectionMatrix),w===null&&e.isPerspectiveCamera&&(w={camera:e,fov:e.fov,zoom:e.zoom}),ue(e,O,i)};function ue(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=Kt*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(d!==null||f!==null)return s},this.setFoveation=function(e){s=e,d!==null&&(d.fixedFoveation=e),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=e)},this.hasDepthSensing=function(){return h.texture!==null},this.getDepthSensingMesh=function(){return h.getMesh(O)},this.getCameraTexture=function(e){return g[e]};let fe=null;function pe(t,i){if(l=i.getViewerPose(c||a),p=i,l!==null){let t=l.views;f!==null&&(e.setRenderTargetFramebuffer(y,f.framebuffer),e.setRenderTarget(y));let i=!1;t.length!==O.cameras.length&&(O.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){let r=t[n],a=null;if(f!==null)a=f.getViewport(r);else{let t=u.getViewSubImage(d,r);a=t.viewport,n===0&&(e.setRenderTargetTextures(y,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(y))}let o=D[n];o===void 0&&(o=new cs,o.layers.enable(n),o.viewport=new Fn,D[n]=o),o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(r.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),n===0&&(O.matrix.copy(o.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),i===!0&&O.cameras.push(o)}let a=r.enabledFeatures;if(a&&a.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&m){u=n.getBinding();let e=u.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&h.init(e,r.renderState)}if(a&&a.includes(`camera-access`)&&m){e.state.unbindTexture(),u=n.getBinding();for(let e=0;e<t.length;e++){let n=t[e].camera;if(n){let e=g[n];e||(e=new xa,g[n]=e);let t=u.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<b.length;e++){let t=x[e],n=b[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}fe&&fe(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),p=null}let me=new Js;me.setAnimationLoop(pe),this.setAnimationLoop=function(e){fe=e},this.dispose=function(){}}},id=new Bn,ad=new bn;ad.set(-1,0,0,0,1,0,0,0,1);function od(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,oo(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isNodeMaterial?t.uniformsNeedUpdate=!1:t.isMeshBasicMaterial?a(e,t):t.isMeshLambertMaterial?(a(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,e.envMapRotation.value.setFromMatrix4(id.makeRotationFromEuler(o)).transpose(),a.isCubeTexture&&a.isRenderTargetTexture===!1&&e.envMapRotation.value.premultiply(ad),e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.retroreflectivity>0&&(e.retroreflectivity.value=t.retroreflectivity),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function sd(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(g(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,v));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return N(`WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let e=0,t=r.length;e<t;e++){let t=r[e];if(Array.isArray(t))for(let n=0,r=t.length;n<r;n++)p(t[n],e,n,a);else p(t,e,0,a)}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(t,n,r,i){if(h(t,n,r,i)===!0){let n=t.__offset,r=t.value;if(Array.isArray(r)){let e=0;for(let n=0;n<r.length;n++){let i=r[n],a=_(i);m(i,t.__data,e),typeof i!=`number`&&typeof i!=`boolean`&&!i.isMatrix3&&!ArrayBuffer.isView(i)&&(e+=a.storage/Float32Array.BYTES_PER_ELEMENT)}}else m(r,t.__data,0);e.bufferSubData(e.UNIFORM_BUFFER,n,t.__data)}}function m(e,t,n){typeof e==`number`||typeof e==`boolean`?t[0]=e:e.isMatrix3?(t[0]=e.elements[0],t[1]=e.elements[1],t[2]=e.elements[2],t[3]=0,t[4]=e.elements[3],t[5]=e.elements[4],t[6]=e.elements[5],t[7]=0,t[8]=e.elements[6],t[9]=e.elements[7],t[10]=e.elements[8],t[11]=0):ArrayBuffer.isView(e)?t.set(new e.constructor(e.buffer,e.byteOffset,t.length)):e.toArray(t,n)}function h(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return r[a]=typeof i==`number`||typeof i==`boolean`?i:ArrayBuffer.isView(i)?i.slice():i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(ArrayBuffer.isView(i))return!0;else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function g(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=_(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function _(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?M(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):ArrayBuffer.isView(e)?(t.boundary=16,t.storage=e.byteLength):M(`WebGLRenderer: Unsupported uniform value type.`,e),t}function v(t){let n=t.target;n.removeEventListener(`dispose`,v);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function y(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:y}}var cd=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]),ld=null;function ud(){return ld===null&&(ld=new Qi(cd,16,16,xe,ce),ld.name=`DFG_LUT`,ld.minFilter=O,ld.magFilter=O,ld.wrapS=C,ld.wrapT=C,ld.generateMipmaps=!1,ld.needsUpdate=!0),ld}var dd=class{constructor(e={}){let{canvas:t=Pt(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:l=`default`,failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=te}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);p=n.getContextAttributes().alpha}else p=a;let m=f,h=new Set([we,Se,be]),g=new Set([te,oe,ie,de,le,ue]),_=new Uint32Array(4),v=new Int32Array(4),y=new F,b=null,x=null,S=[],C=[],w=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let T=this,E=!1,D=null,O=null,k=null,ne=null;this._outputColorSpace=pt;let re=0,ae=0,se=null,fe=-1,pe=null,me=new Fn,he=new Fn,ge=null,_e=new L(0),ve=0,ye=t.width,xe=t.height,Ce=1,Te=null,Ee=null,De=new Fn(0,0,ye,xe),Oe=new Fn(0,0,ye,xe),ke=!1,Ae=new ra,je=!1,Me=!1,Ne=new Bn,Pe=new F,Fe=new Fn,Ie={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Le=!1;function Re(){return se===null?Ce:1}let A=n;function ze(e,n){return t.getContext(e,n)}let Be,Ve,j,He,Ue,We,Ge,Ke,qe,Je,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,at,ot,st;try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r186`),t.addEventListener(`webglcontextlost`,ut,!1),t.addEventListener(`webglcontextrestored`,dt,!1),t.addEventListener(`webglcontextcreationerror`,ft,!1),A===null){let t=`webgl2`;if(A=ze(t,e),A===null)throw ze(t)?Error(`THREE.WebGLRenderer: Error creating WebGL context with your selected attributes.`):Error(`THREE.WebGLRenderer: Error creating WebGL context.`)}ct()}catch(e){throw t.removeEventListener(`webglcontextlost`,ut,!1),t.removeEventListener(`webglcontextrestored`,dt,!1),t.removeEventListener(`webglcontextcreationerror`,ft,!1),N(`WebGLRenderer: `+e.message),e}function ct(){Be=new kc(A),Be.init(),at=new $u(A,Be),Ve=new ic(A,Be,e,at),j=new Zu(A,Be),Ve.reversedDepthBuffer&&d&&j.buffers.depth.setReversed(!0),O=A.createFramebuffer(),k=A.createFramebuffer(),ne=A.createFramebuffer(),He=new Mc(A),Ue=new ju,We=new Qu(A,Be,j,Ue,Ve,at,He),Ge=new Oc(T),Ke=new Ys(A),ot=new nc(A,Ke),qe=new Ac(A,Ke,He,ot),Je=new Pc(A,qe,Ke,ot,He),nt=new Nc(A,Ve,We),$e=new ac(Ue),Ye=new Au(T,Ge,Be,Ve,ot,$e),Xe=new od(T,Ue),Ze=new Fu,Qe=new Hu(Be),tt=new tc(T,Ge,j,Je,p,s),et=new Xu(T,Je,Ve),st=new sd(A,He,Ve,j),rt=new rc(A,Be,He),it=new jc(A,Be,He),He.programs=Ye.programs,T.capabilities=Ve,T.extensions=Be,T.properties=Ue,T.renderLists=Ze,T.shadowMap=et,T.state=j,T.info=He}m!==1009&&(w=new Ic(m,t.width,t.height,o,r,i));let lt=new rd(T,A);this.xr=lt,this.getContext=function(){return A},this.getContextAttributes=function(){return A.getContextAttributes()},this.forceContextLoss=function(){let e=Be.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=Be.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return Ce},this.setPixelRatio=function(e){e!==void 0&&(Ce=e,this.setSize(ye,xe,!1))},this.getSize=function(e){return e.set(ye,xe)},this.setSize=function(e,n,r=!0){if(lt.isPresenting){M(`WebGLRenderer: Can't change size while VR device is presenting.`);return}ye=e,xe=n,t.width=Math.floor(e*Ce),t.height=Math.floor(n*Ce),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),w!==null&&w.setSize(t.width,t.height),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(ye*Ce,xe*Ce).floor()},this.setDrawingBufferSize=function(e,n,r){ye=e,xe=n,Ce=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(m===1009){N(`WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.`);return}if(e){for(let t=0;t<e.length;t++)if(e[t].isOutputPass===!0){M(`WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.`);break}}w.setEffects(e||[])},this.getCurrentViewport=function(e){return e.copy(me)},this.getViewport=function(e){return e.copy(De)},this.setViewport=function(e,t,n,r){e.isVector4?De.set(e.x,e.y,e.z,e.w):De.set(e,t,n,r),j.viewport(me.copy(De).multiplyScalar(Ce).round())},this.getScissor=function(e){return e.copy(Oe)},this.setScissor=function(e,t,n,r){e.isVector4?Oe.set(e.x,e.y,e.z,e.w):Oe.set(e,t,n,r),j.scissor(he.copy(Oe).multiplyScalar(Ce).round())},this.getScissorTest=function(){return ke},this.setScissorTest=function(e){j.setScissorTest(ke=e)},this.setOpaqueSort=function(e){Te=e},this.setTransparentSort=function(e){Ee=e},this.getClearColor=function(e){return e.copy(tt.getClearColor())},this.setClearColor=function(){tt.setClearColor(...arguments)},this.getClearAlpha=function(){return tt.getClearAlpha()},this.setClearAlpha=function(){tt.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(se!==null){let t=se.texture.format;e=h.has(t)}if(e){let e=se.texture.type,t=g.has(e),n=tt.getClearColor(),r=tt.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(_[0]=i,_[1]=a,_[2]=o,_[3]=r,A.clearBufferuiv(A.COLOR,0,_)):(v[0]=i,v[1]=a,v[2]=o,v[3]=r,A.clearBufferiv(A.COLOR,0,v))}else r|=A.COLOR_BUFFER_BIT}t&&(r|=A.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),n&&(r|=A.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),r!==0&&A.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(e){e.setRenderer(this),D=e},this.dispose=function(){t.removeEventListener(`webglcontextlost`,ut,!1),t.removeEventListener(`webglcontextrestored`,dt,!1),t.removeEventListener(`webglcontextcreationerror`,ft,!1),tt.dispose(),Ze.dispose(),Qe.dispose(),Ue.dispose(),Ge.dispose(),Je.dispose(),ot.dispose(),st.dispose(),Ye.dispose(),lt.dispose(),lt.removeEventListener(`sessionstart`,bt),lt.removeEventListener(`sessionend`,xt),St.stop()};function ut(e){e.preventDefault(),It(`WebGLRenderer: Context Lost.`),E=!0}function dt(){It(`WebGLRenderer: Context Restored.`),E=!1;let e=He.autoReset,t=et.enabled,n=et.autoUpdate,r=et.needsUpdate,i=et.type;ct(),He.autoReset=e,et.enabled=t,et.autoUpdate=n,et.needsUpdate=r,et.type=i}function ft(e){N(`WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function mt(e){let t=e.target;t.removeEventListener(`dispose`,mt),ht(t)}function ht(e){gt(e),Ue.remove(e)}function gt(e){let t=Ue.get(e).programs;t!==void 0&&(t.forEach(function(e){Ye.releaseProgram(e)}),e.isShaderMaterial&&Ye.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=Ie);let o=i.isMesh&&i.matrixWorld.determinantAffine()<0,s=Nt(e,t,n,r,i);j.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=qe.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;ot.setup(i,r,s,n,c);let h,g=rt;if(c!==null&&(h=Ke.get(c),g=it,g.setIndex(h)),i.isMesh)r.wireframe===!0?(j.setLineWidth(r.wireframeLinewidth*Re()),g.setMode(A.LINES)):g.setMode(A.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),j.setLineWidth(e*Re()),i.isLineSegments?g.setMode(A.LINES):i.isLineLoop?g.setMode(A.LINE_LOOP):g.setMode(A.LINE_STRIP)}else i.isPoints?g.setMode(A.POINTS):i.isSprite&&g.setMode(A.TRIANGLES);if(i.isBatchedMesh){if(Be.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?Ke.get(c).bytesPerElement:1,o=Ue.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(A,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function _t(e,t,n,r){D!==null&&e.isNodeMaterial&&D.setObject(r,e),je===!0&&$e.setState(e,n,!1),e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,kt(e,t,r),e.side=0,e.needsUpdate=!0,kt(e,t,r),e.side=2):kt(e,t,r)}this.compile=function(e,t,n=null){n===null&&(n=e),D!==null&&D.renderStart(e,t,n),x=Qe.get(n),x.init(t),C.push(x),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),x.setupLights(),D!==null&&D.updateLights(x.state.lightsArray),Me=this.localClippingEnabled,je=$e.init(this.clippingPlanes,Me),je===!0&&$e.setGlobalState(this.clippingPlanes,t),D!==null&&et.render(x.state.shadowsArray,n,t);let r=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let i=e.material;if(i){if(Array.isArray(i))for(let a=0;a<i.length;a++){let o=i[a];_t(o,n,t,e),r.add(o)}else _t(i,n,t,e),r.add(i)}}),x=C.pop(),D!==null&&D.renderEnd(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){let t=Ue.get(e).currentProgram;(t===void 0||t.isReady())&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}Be.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let vt=null;function yt(e){vt&&vt(e)}function bt(){St.stop()}function xt(){St.start()}let St=new Js;St.setAnimationLoop(yt),typeof self<`u`&&St.setContext(self),this.setAnimationLoop=function(e){vt=e,lt.setAnimationLoop(e),e===null?St.stop():St.start()},lt.addEventListener(`sessionstart`,bt),lt.addEventListener(`sessionend`,xt),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){N(`WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(E===!0)return;D!==null&&D.renderStart(e,t);let n=lt.enabled===!0&&lt.isPresenting===!0,r=w!==null&&(se===null||n)&&w.begin(T,se);if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),lt.enabled===!0&&lt.isPresenting===!0&&(w===null||w.isCompositing()===!1)&&(lt.cameraAutoUpdate===!0&&lt.updateCamera(t),t=lt.getCamera()),e.isScene===!0&&e.onBeforeRender(T,e,t,se),x=Qe.get(e,C.length),x.init(t),x.state.textureUnits=We.getTextureUnits(),C.push(x),Ne.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),Ae.setFromProjectionMatrix(Ne,Et,t.reversedDepth),Me=this.localClippingEnabled,je=$e.init(this.clippingPlanes,Me),b=Ze.get(e,S.length),b.init(),S.push(b),lt.enabled===!0&&lt.isPresenting===!0){let e=T.xr.getDepthSensingMesh();e!==null&&Ct(e,t,-1/0,T.sortObjects)}Ct(e,t,0,T.sortObjects),b.finish(),D!==null&&D.updateLights(x.state.lightsArray),T.sortObjects===!0&&b.sort(Te,Ee),Le=lt.enabled===!1||lt.isPresenting===!1||lt.hasDepthSensing()===!1,Le&&tt.addToRenderList(b,e),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),je===!0&&$e.beginShadows();let i=x.state.shadowsArray;if(et.render(i,e,t),je===!0&&$e.endShadows(),(r&&w.hasRenderPass())===!1){let n=b.opaque,r=b.transmissive;if(x.setupLights(),t.isArrayCamera){let i=t.cameras;if(r.length>0)for(let t=0,a=i.length;t<a;t++){let a=i[t];Tt(n,r,e,a)}Le&&tt.render(e);for(let t=0,n=i.length;t<n;t++){let n=i[t];wt(b,e,n,n.viewport)}}else r.length>0&&Tt(n,r,e,t),Le&&tt.render(e),wt(b,e,t)}se!==null&&ae===0&&(We.updateMultisampleRenderTarget(se),We.updateRenderTargetMipmap(se)),r&&w.end(T),e.isScene===!0&&e.onAfterRender(T,e,t),ot.resetDefaultState(),fe=-1,pe=null,C.pop(),C.length>0?(x=C[C.length-1],We.setTextureUnits(x.state.textureUnits),je===!0&&$e.setGlobalState(T.clippingPlanes,x.state.camera)):x=null,S.pop(),b=S.length>0?S[S.length-1]:null,D!==null&&D.renderEnd()};function Ct(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLightProbeGrid)x.pushLightProbeGrid(e);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||e.intersectsFrustum(Ae)){r&&Fe.setFromMatrixPosition(e.matrixWorld).applyMatrix4(Ne);let i=Je.update(e),a=e.material;a.visible&&b.push(e,i,a,n,Fe.z,null,t)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||e.intersectsFrustum(Ae))){let i=Je.update(e),a=e.material;if(r&&(e.boundingSphere===void 0?(i.boundingSphere===null&&i.computeBoundingSphere(),Fe.copy(i.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),Fe.copy(e.boundingSphere.center)),Fe.applyMatrix4(e.matrixWorld).applyMatrix4(Ne)),Array.isArray(a)){let r=i.groups;for(let o=0,s=r.length;o<s;o++){let s=r[o],c=a[s.materialIndex];c&&c.visible&&b.push(e,i,c,n,Fe.z,s,t)}}else a.visible&&b.push(e,i,a,n,Fe.z,null,t)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)Ct(i[e],t,n,r)}function wt(e,t,n,r){let{opaque:i,transmissive:a,transparent:o}=e;x.setupLightsView(n),je===!0&&$e.setGlobalState(T.clippingPlanes,n),r&&j.viewport(me.copy(r)),i.length>0&&Dt(i,t,n),a.length>0&&Dt(a,t,n),o.length>0&&Dt(o,t,n),j.buffers.depth.setTest(!0),j.buffers.depth.setMask(!0),j.buffers.color.setMask(!0),j.setPolygonOffset(!1)}function Tt(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;if(x.state.transmissionRenderTarget[r.id]===void 0){let e=Be.has(`EXT_color_buffer_half_float`)||Be.has(`EXT_color_buffer_float`);x.state.transmissionRenderTarget[r.id]=new Ln(1,1,{generateMipmaps:!0,type:e?ce:te,minFilter:ee,samples:Math.max(4,Ve.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:I.workingColorSpace})}let a=x.state.transmissionRenderTarget[r.id],o=r.viewport||me;a.setSize(o.z*T.transmissionResolutionScale,o.w*T.transmissionResolutionScale);let s=T.getRenderTarget(),c=T.getActiveCubeFace(),l=T.getActiveMipmapLevel();T.setRenderTarget(a),T.getClearColor(_e),ve=T.getClearAlpha(),ve<1&&T.setClearColor(16777215,.5),T.clear(),Le&&tt.render(n);let u=T.toneMapping;T.toneMapping=0;let d=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),x.setupLightsView(r),je===!0&&$e.setGlobalState(T.clippingPlanes,r),Dt(e,n,r),We.updateMultisampleRenderTarget(a),We.updateRenderTargetMipmap(a),Be.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let{object:a,geometry:o,material:s,group:c}=t[i];if(s.side===2&&a.layers.test(r.layers)){let t=s.side;s.side=1,s.needsUpdate=!0,Ot(a,n,r,o,s,c),s.side=t,s.needsUpdate=!0,e=!0}}e===!0&&(We.updateMultisampleRenderTarget(a),We.updateRenderTargetMipmap(a))}T.setRenderTarget(s,c,l),T.setClearColor(_e,ve),d!==void 0&&(r.viewport=d),T.toneMapping=u}function Dt(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],{object:o,geometry:s,group:c}=a,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&&Ot(o,t,n,s,l,c)}}function Ot(e,t,n,r,i,a){D!==null&&i.isNodeMaterial&&D.setObject(e,i),e.onBeforeRender(T,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(T,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,T.renderBufferDirect(n,t,r,i,e,a),i.side=2):T.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(T,t,n,r,i,a)}function kt(e,t,n){t.isScene!==!0&&(t=Ie);let r=Ue.get(e),i=x.state.lights,a=x.state.shadowsArray,o=i.state.version,s=Ye.getParameters(e,i.state,a,t,n,x.state.lightProbeGridArray),c=Ye.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,r.fog=t.fog;let u=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;r.envMap=Ge.get(e.envMap||r.environment,u),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,mt),l=new Map,r.programs=l);let d=l.get(c);if(d!==void 0){if(r.currentProgram===d&&r.lightsStateVersion===o)return jt(e,s),d}else s.uniforms=Ye.getUniforms(e),D!==null&&e.isNodeMaterial&&D.build(e,n,s),e.onBeforeCompile(s,T),d=Ye.acquireProgram(s,c),l.set(c,d),r.uniforms=s.uniforms;let f=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(f.clippingPlanes=$e.uniform),jt(e,s),r.needsLights=Lt(e),r.lightsStateVersion=o,r.needsLights&&(f.ambientLightColor.value=i.state.ambient,f.lightProbe.value=i.state.probe,f.sunLights.value=i.state.sun,f.sunLightShadows.value=i.state.sunShadow,f.directionalLights.value=i.state.directional,f.directionalLightShadows.value=i.state.directionalShadow,f.spotLights.value=i.state.spot,f.spotLightShadows.value=i.state.spotShadow,f.rectAreaLights.value=i.state.rectArea,f.ltc_1.value=i.state.rectAreaLTC1,f.ltc_2.value=i.state.rectAreaLTC2,f.pointLights.value=i.state.point,f.pointLightShadows.value=i.state.pointShadow,f.hemisphereLights.value=i.state.hemi,f.sunShadowMatrix.value=i.state.sunShadowMatrix,f.sunShadowCascade.value=i.state.sunShadowCascade,f.directionalShadowMatrix.value=i.state.directionalShadowMatrix,f.spotLightMatrix.value=i.state.spotLightMatrix,f.spotLightMap.value=i.state.spotLightMap,f.pointShadowMatrix.value=i.state.pointShadowMatrix),r.lightProbeGrid=x.state.lightProbeGridArray.length>0,r.currentProgram=d,r.uniformsList=null,d}function At(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=Ul.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function jt(e,t){let n=Ue.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function Mt(e,t){if(e.length===0)return null;if(e.length===1)return e[0].texture===null?null:e[0];y.setFromMatrixPosition(t.matrixWorld);for(let t=0,n=e.length;t<n;t++){let n=e[t];if(n.texture!==null&&n.boundingBox.containsPoint(y))return n}return null}function Nt(e,t,n,r,i){t.isScene!==!0&&(t=Ie),We.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?t.environment:null,s=se===null?T.outputColorSpace:se.isXRRenderTarget===!0?se.texture.colorSpace:I.workingColorSpace,c=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,l=Ge.get(r.envMap||o,c),u=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,d=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),f=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,m=!!n.morphAttributes.color,h=0;r.toneMapped&&(se===null||se.isXRRenderTarget===!0)&&(h=T.toneMapping);let g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=g===void 0?0:g.length,v=Ue.get(r),y=x.state.lights;if(je===!0&&(Me===!0||e!==pe)){let t=e===pe&&r.id===fe;$e.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version?b=!0:v.outputColorSpace===s?i.isBatchedMesh&&v.batching===!1||!i.isBatchedMesh&&v.batching===!0||i.isBatchedMesh&&v.batchingColor===!0&&i._colorsTexture===null||i.isBatchedMesh&&v.batchingColor===!1&&i._colorsTexture!==null||i.isInstancedMesh&&v.instancing===!1||!i.isInstancedMesh&&v.instancing===!0||i.isSkinnedMesh&&v.skinning===!1||!i.isSkinnedMesh&&v.skinning===!0||i.isInstancedMesh&&v.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&v.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&v.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&v.instancingMorph===!1&&i.morphTexture!==null?b=!0:v.envMap===l?r.fog===!0&&v.fog!==a||v.numClippingPlanes!==void 0&&(v.numClippingPlanes!==$e.numPlanes||v.numIntersection!==$e.numIntersection)?b=!0:v.vertexAlphas===u&&v.vertexTangents===d&&v.morphTargets===f&&v.morphNormals===p&&v.morphColors===m&&v.toneMapping===h&&v.morphTargetsCount===_?!!v.lightProbeGrid!=x.state.lightProbeGridArray.length>0&&(b=!0):b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let S=v.currentProgram;b===!0&&(S=kt(r,t,i),D&&r.isNodeMaterial&&D.onUpdateProgram(r,S,v));let C=!1,w=!1,E=!1,O=S.getUniforms(),k=v.uniforms;if(j.useProgram(S.program)&&(C=!0,w=!0,E=!0),r.id!==fe&&(fe=r.id,w=!0),v.needsLights){let e=Mt(x.state.lightProbeGridArray,i);v.lightProbeGrid!==e&&(v.lightProbeGrid=e,w=!0)}if(C||pe!==e){j.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),O.setValue(A,`projectionMatrix`,e.projectionMatrix),O.setValue(A,`viewMatrix`,e.matrixWorldInverse);let t=O.map.cameraPosition;t!==void 0&&t.setValue(A,Pe.setFromMatrixPosition(e.matrixWorld)),Ve.logarithmicDepthBuffer&&O.setValue(A,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&O.setValue(A,`isOrthographic`,e.isOrthographicCamera===!0),pe!==e&&(pe=e,w=!0,E=!0)}if(v.needsLights&&(y.state.sunShadowMap.length>0&&O.setValue(A,`sunShadowMap`,y.state.sunShadowMap,We),y.state.directionalShadowMap.length>0&&O.setValue(A,`directionalShadowMap`,y.state.directionalShadowMap,We),y.state.spotShadowMap.length>0&&O.setValue(A,`spotShadowMap`,y.state.spotShadowMap,We),y.state.pointShadowMap.length>0&&O.setValue(A,`pointShadowMap`,y.state.pointShadowMap,We)),i.isSkinnedMesh){O.setOptional(A,i,`bindMatrix`),O.setOptional(A,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),O.setValue(A,`boneTexture`,e.boneTexture,We))}i.isBatchedMesh&&(O.setOptional(A,i,`batchingTexture`),O.setValue(A,`batchingTexture`,i._matricesTexture,We),O.setOptional(A,i,`batchingIdTexture`),O.setValue(A,`batchingIdTexture`,i._indirectTexture,We),O.setOptional(A,i,`batchingColorTexture`),i._colorsTexture!==null&&O.setValue(A,`batchingColorTexture`,i._colorsTexture,We));let ee=n.morphAttributes;if((ee.position!==void 0||ee.normal!==void 0||ee.color!==void 0)&&nt.update(i,n,S),(w||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,O.setValue(A,`receiveShadow`,i.receiveShadow)),(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&r.envMap===null&&t.environment!==null&&(k.envMapIntensity.value=t.environmentIntensity),k.dfgLUT!==void 0&&(k.dfgLUT.value=ud()),w){if(O.setValue(A,`toneMappingExposure`,T.toneMappingExposure),v.needsLights&&Ft(k,E),a&&r.fog===!0&&Xe.refreshFogUniforms(k,a),Xe.refreshMaterialUniforms(k,r,Ce,xe,x.state.transmissionRenderTarget[e.id]),v.needsLights&&v.lightProbeGrid){let e=v.lightProbeGrid;k.probesSH.value=e.texture,k.probesMin.value.copy(e.boundingBox.min),k.probesMax.value.copy(e.boundingBox.max),k.probesResolution.value.copy(e.resolution)}Ul.upload(A,At(v),k,We)}if(r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(Ul.upload(A,At(v),k,We),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&O.setValue(A,`center`,i.center),O.setValue(A,`modelViewMatrix`,i.modelViewMatrix),O.setValue(A,`normalMatrix`,i.normalMatrix),O.setValue(A,`modelMatrix`,i.matrixWorld),r.uniformsGroups!==void 0){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];st.update(n,S),st.bind(n,S)}}return S}function Ft(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.sunLights.needsUpdate=t,e.sunLightShadows.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function Lt(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return re},this.getActiveMipmapLevel=function(){return ae},this.getRenderTarget=function(){return se},this.setRenderTargetTextures=function(e,t,n){let r=Ue.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),Ue.get(e.texture).__webglTexture=t,Ue.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=Ue.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0},this.setRenderTarget=function(e,t=0,n=0){se=e,re=t,ae=n;let r=null,i=!1,a=!1;if(e){let o=Ue.get(e);if(o.__useDefaultFramebuffer!==void 0){j.bindFramebuffer(A.FRAMEBUFFER,o.__webglFramebuffer),me.copy(e.viewport),he.copy(e.scissor),ge=e.scissorTest,j.viewport(me),j.scissor(he),j.setScissorTest(ge),fe=-1;return}if(o.__webglFramebuffer===void 0)We.setupRenderTarget(e);else if(o.__hasExternalTextures)We.rebindTextures(e,Ue.get(e.texture).__webglTexture,Ue.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(o.__boundDepthTexture!==t){if(t!==null&&Ue.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.`);We.setupDepthRenderbuffer(e)}}let s=e.texture;(s.isData3DTexture||s.isDataArrayTexture||s.isCompressedArrayTexture)&&(a=!0);let c=Ue.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][n]:c[t],i=!0):r=e.samples>0&&We.useMultisampledRTT(e)===!1?Ue.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,me.copy(e.viewport),he.copy(e.scissor),ge=e.scissorTest}else me.copy(De).multiplyScalar(Ce).floor(),he.copy(Oe).multiplyScalar(Ce).floor(),ge=ke;if(n!==0&&(r=O),j.bindFramebuffer(A.FRAMEBUFFER,r)&&j.drawBuffers(e,r),j.viewport(me),j.scissor(he),j.setScissorTest(ge),i){let r=Ue.get(e.texture);A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){let r=t;for(let t=0;t<e.textures.length;t++){let i=Ue.get(e.textures[t]);A.framebufferTextureLayer(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0+t,i.__webglTexture,n,r)}}else if(e!==null&&n!==0){let t=Ue.get(e.texture);A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_2D,t.__webglTexture,n)}fe=-1};function Rt(e){let t=Ue.get(e);return(t.__readFormat!==e.format||t.__readType!==e.type)&&(t.__readFormat=e.format,t.__readType=e.type,t.__formatReadable=Ve.textureFormatReadable(e.format),t.__typeReadable=Ve.textureTypeReadable(e.type)),t}this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget)){N(`WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let c=Ue.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){j.bindFramebuffer(A.FRAMEBUFFER,c);try{let o=e.textures[s],c=o.format,l=o.type;e.textures.length>1&&A.readBuffer(A.COLOR_ATTACHMENT0+s);let u=Rt(o);if(u.__formatReadable===!1){N(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(u.__typeReadable===!1){N(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&A.readPixels(t,n,r,i,at.convert(c),at.convert(l),a)}finally{let e=se===null?null:Ue.get(se).__webglFramebuffer;j.bindFramebuffer(A.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=Ue.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){j.bindFramebuffer(A.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;e.textures.length>1&&A.readBuffer(A.COLOR_ATTACHMENT0+s);let d=Rt(o);if(d.__formatReadable===!1)throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(d.__typeReadable===!1)throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let f=A.createBuffer();A.bindBuffer(A.PIXEL_PACK_BUFFER,f),A.bufferData(A.PIXEL_PACK_BUFFER,a.byteLength,A.STREAM_READ),A.readPixels(t,n,r,i,at.convert(l),at.convert(u),0),A.bindBuffer(A.PIXEL_PACK_BUFFER,null);let p=se===null?null:Ue.get(se).__webglFramebuffer;j.bindFramebuffer(A.FRAMEBUFFER,p);let m=A.fenceSync(A.SYNC_GPU_COMMANDS_COMPLETE,0);return A.flush(),await Bt(A,m,4),A.bindBuffer(A.PIXEL_PACK_BUFFER,f),A.getBufferSubData(A.PIXEL_PACK_BUFFER,0,a),A.bindBuffer(A.PIXEL_PACK_BUFFER,null),A.deleteBuffer(f),A.deleteSync(m),a}throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)}},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;We.setTexture2D(e,0),A.copyTexSubImage2D(A.TEXTURE_2D,n,0,0,o,s,i,a),j.unbindTexture()},this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=0){let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=at.convert(t.format),_=at.convert(t.type),v;t.isData3DTexture?(We.setTexture3D(t,0),v=A.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(We.setTexture2DArray(t,0),v=A.TEXTURE_2D_ARRAY):(We.setTexture2D(t,0),v=A.TEXTURE_2D),j.activeTexture(A.TEXTURE0),j.pixelStorei(A.UNPACK_FLIP_Y_WEBGL,t.flipY),j.pixelStorei(A.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),j.pixelStorei(A.UNPACK_ALIGNMENT,t.unpackAlignment);let y=j.getParameter(A.UNPACK_ROW_LENGTH),b=j.getParameter(A.UNPACK_IMAGE_HEIGHT),x=j.getParameter(A.UNPACK_SKIP_PIXELS),S=j.getParameter(A.UNPACK_SKIP_ROWS),C=j.getParameter(A.UNPACK_SKIP_IMAGES);j.pixelStorei(A.UNPACK_ROW_LENGTH,h.width),j.pixelStorei(A.UNPACK_IMAGE_HEIGHT,h.height),j.pixelStorei(A.UNPACK_SKIP_PIXELS,l),j.pixelStorei(A.UNPACK_SKIP_ROWS,u),j.pixelStorei(A.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=Ue.get(e),r=Ue.get(t),h=Ue.get(n.__renderTarget),g=Ue.get(r.__renderTarget);j.bindFramebuffer(A.READ_FRAMEBUFFER,h.__webglFramebuffer),j.bindFramebuffer(A.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(A.framebufferTextureLayer(A.READ_FRAMEBUFFER,A.COLOR_ATTACHMENT0,Ue.get(e).__webglTexture,i,d+n),A.framebufferTextureLayer(A.DRAW_FRAMEBUFFER,A.COLOR_ATTACHMENT0,Ue.get(t).__webglTexture,a,m+n)),A.blitFramebuffer(l,u,o,s,f,p,o,s,A.DEPTH_BUFFER_BIT,A.NEAREST);j.bindFramebuffer(A.READ_FRAMEBUFFER,null),j.bindFramebuffer(A.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||Ue.has(e)){let n=Ue.get(e),r=Ue.get(t);j.bindFramebuffer(A.READ_FRAMEBUFFER,k),j.bindFramebuffer(A.DRAW_FRAMEBUFFER,ne);for(let e=0;e<c;e++)w?A.framebufferTextureLayer(A.READ_FRAMEBUFFER,A.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):A.framebufferTexture2D(A.READ_FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_2D,n.__webglTexture,i),T?A.framebufferTextureLayer(A.DRAW_FRAMEBUFFER,A.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):A.framebufferTexture2D(A.DRAW_FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_2D,r.__webglTexture,a),i===0?T?A.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):A.copyTexSubImage2D(v,a,f,p,l,u,o,s):A.blitFramebuffer(l,u,o,s,f,p,o,s,A.COLOR_BUFFER_BIT,A.NEAREST);j.bindFramebuffer(A.READ_FRAMEBUFFER,null),j.bindFramebuffer(A.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?A.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?A.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):A.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?A.texSubImage2D(A.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?A.compressedTexSubImage2D(A.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):A.texSubImage2D(A.TEXTURE_2D,a,f,p,o,s,g,_,h);j.pixelStorei(A.UNPACK_ROW_LENGTH,y),j.pixelStorei(A.UNPACK_IMAGE_HEIGHT,b),j.pixelStorei(A.UNPACK_SKIP_PIXELS,x),j.pixelStorei(A.UNPACK_SKIP_ROWS,S),j.pixelStorei(A.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&A.generateMipmap(v),j.unbindTexture()},this.initRenderTarget=function(e){Ue.get(e).__webglFramebuffer===void 0&&We.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?We.setTextureCube(e,0):e.isData3DTexture?We.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?We.setTexture2DArray(e,0):We.setTexture2D(e,0),j.unbindTexture()},this.resetState=function(){re=0,ae=0,se=null,j.reset(),ot.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return Et}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=I._getDrawingBufferColorSpace(e),t.unpackColorSpace=I._getUnpackColorSpace()}},fd=new Oi,pd=new P,md=new F,hd=new P,gd=new P,_d=new F,vd=new F,yd=new Bn,bd=new F,xd=new F,Sd=null,Cd=null,wd=[],Td={NONE:-1,PAN:0,ROTATE:1},Ed=class extends Gs{constructor(e,t,n=null){super(t,n),this.objects=e,this.recursive=!0,this.transformGroup=!1,this.rotateSpeed=1,this.raycaster=new Bs,this.mouseButtons={LEFT:b.PAN,MIDDLE:b.PAN,RIGHT:b.ROTATE},this.touches={ONE:x.PAN},this._onPointerMove=Dd.bind(this),this._onPointerDown=Od.bind(this),this._onPointerCancel=kd.bind(this),this._onContextMenu=Ad.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){let t=this.domElement.getBoundingClientRect();pd.x=(e.clientX-t.left)/t.width*2-1,pd.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 b.PAN:case x.PAN:this.state=Td.PAN;break;case b.ROTATE:case x.ROTATE:this.state=Td.ROTATE;break;default:this.state=Td.NONE}}};function Dd(e){let t=this.object,n=this.domElement,r=this.raycaster;if(this.enabled!==!1){if(this._updatePointer(e),r.setFromCamera(pd,t),Sd)this.state===Td.PAN?r.ray.intersectPlane(fd,_d)&&(Sd.position.copy(_d.sub(md).applyMatrix4(yd)),this.dispatchEvent({type:`drag`,object:Sd})):this.state===Td.ROTATE&&(hd.subVectors(pd,gd).multiplyScalar(this.rotateSpeed),Sd.rotateOnWorldAxis(bd,hd.x),Sd.rotateOnWorldAxis(xd.normalize(),-hd.y),this.dispatchEvent({type:`drag`,object:Sd})),gd.copy(pd);else if(e.pointerType===`mouse`||e.pointerType===`pen`){if(wd.length=0,r.setFromCamera(pd,t),r.intersectObjects(this.objects,this.recursive,wd),wd.length>0){let e=wd[0].object;fd.setFromNormalAndCoplanarPoint(t.getWorldDirection(fd.normal),vd.setFromMatrixPosition(e.matrixWorld)),Cd!==e&&Cd!==null&&(this.dispatchEvent({type:`hoveroff`,object:Cd}),n.style.cursor=`auto`,Cd=null),Cd!==e&&(this.dispatchEvent({type:`hoveron`,object:e}),n.style.cursor=`pointer`,Cd=e)}else Cd!==null&&(this.dispatchEvent({type:`hoveroff`,object:Cd}),n.style.cursor=`auto`,Cd=null)}gd.copy(pd)}}function Od(e){let t=this.object,n=this.domElement,r=this.raycaster;this.enabled!==!1&&(this._updatePointer(e),this._updateState(e),wd.length=0,r.setFromCamera(pd,t),r.intersectObjects(this.objects,this.recursive,wd),wd.length>0&&(Sd=this.transformGroup===!0?jd(wd[0].object):wd[0].object,fd.setFromNormalAndCoplanarPoint(t.getWorldDirection(fd.normal),vd.setFromMatrixPosition(Sd.matrixWorld)),r.ray.intersectPlane(fd,_d)&&(this.state===Td.PAN?(yd.copy(Sd.parent.matrixWorld).invert(),md.copy(_d).sub(vd.setFromMatrixPosition(Sd.matrixWorld)),n.style.cursor=`move`,this.dispatchEvent({type:`dragstart`,object:Sd})):this.state===Td.ROTATE&&(bd.set(0,1,0).applyQuaternion(t.quaternion).normalize(),xd.set(1,0,0).applyQuaternion(t.quaternion).normalize(),n.style.cursor=`move`,this.dispatchEvent({type:`dragstart`,object:Sd})))),gd.copy(pd))}function kd(){this.enabled!==!1&&(Sd&&=(this.dispatchEvent({type:`dragend`,object:Sd}),null),this.domElement.style.cursor=Cd?`pointer`:`auto`,this.state=Td.NONE)}function Ad(e){this.enabled!==!1&&e.preventDefault()}function jd(e,t=null){return e.isGroup&&(t=e),e.parent===null?t:jd(e.parent,t)}function Md(e){Pd(e);let t=Nd(e);return e.on=t.on,e.off=t.off,e.fire=t.fire,e}function Nd(e){let t=Object.create(null);return{on:function(n,r,i){if(typeof r!=`function`)throw Error(`callback is expected to be a function`);let a=t[n];return a||=t[n]=[],a.push({callback:r,ctx:i}),e},off:function(n,r){if(n===void 0)return t=Object.create(null),e;if(t[n]){if(typeof r!=`function`)delete t[n];else{let e=t[n];for(let t=0;t<e.length;++t)e[t].callback===r&&e.splice(t,1)}}return e},fire:function(n){let r=t[n];if(!r)return e;let i;arguments.length>1&&(i=Array.prototype.slice.call(arguments,1));for(let e=0;e<r.length;++e){let t=r[e];t.callback.apply(t.ctx,i)}return e}}}function Pd(e){if(!e)throw Error(`Eventify cannot use falsy object as events subject`);let t=[`on`,`fire`,`off`];for(let n=0;n<t.length;++n)if(e.hasOwnProperty(t[n]))throw Error(`Subject cannot be eventified, since it already has property '`+t[n]+`'`)}var Fd=Id;function Id(e){if(e||={},`uniqueLinkId`in e&&(console.warn("ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\nUse `multigraph` option instead\n",`
`,`Note: there is also change in default behavior: From now on each graph
is considered to be not a multigraph by default (each edge is unique).`),e.multigraph=e.uniqueLinkId),e.multigraph===void 0&&(e.multigraph=!1),typeof Map!=`function`)throw Error("ngraph.graph requires `Map` to be defined. Please polyfill it before using ngraph");var t=new Map,n=new Map,r={},i=0,a=e.multigraph?b:y,o=[],s=re,c=re,l=re,u=re,d={version:20,addNode:h,addLink:v,removeLink:w,removeNode:_,getNode:g,getNodeCount:x,getLinkCount:S,getEdgeCount:S,getLinksCount:S,getNodesCount:x,getLinks:C,forEachNode:oe,forEachLinkedNode:ee,forEachLink:k,beginUpdate:l,endUpdate:u,clear:O,hasLink:E,hasNode:g,getLink:E,getLinkById:D};return Md(d),f(),d;function f(){var e=d.on;d.on=t;function t(){return d.beginUpdate=l=ie,d.endUpdate=u=ae,s=p,c=m,d.on=e,e.apply(d,arguments)}}function p(e,t){o.push({link:e,changeType:t})}function m(e,t){o.push({node:e,changeType:t})}function h(e,n){if(e===void 0)throw Error(`Invalid node identifier`);l();var r=g(e);return r?(r.data=n,c(r,`update`)):(r=new Ld(e,n),c(r,`add`)),t.set(e,r),u(),r}function g(e){return t.get(e)}function _(e){var n=g(e);if(!n)return!1;l();var r=n.links;return r&&(r.forEach(T),n.links=null),t.delete(e),c(n,`remove`),u(),!0}function v(e,t,r){l();var i=g(e)||h(e),o=g(t)||h(t),c=a(e,t,r),d=n.has(c.id);return n.set(c.id,c),Rd(i,c),e!==t&&Rd(o,c),s(c,d?`update`:`add`),u(),c}function y(e,t,r){var i=Bd(e,t),a=n.get(i);return a?(a.data=r,a):new zd(e,t,r,i)}function b(e,t,n){var i=Bd(e,t),a=r.hasOwnProperty(i);if(a||E(e,t)){a||(r[i]=0);var o=`@`+ ++r[i];i=Bd(e+o,t+o)}return new zd(e,t,n,i)}function x(){return t.size}function S(){return n.size}function C(e){var t=g(e);return t?t.links:null}function w(e,t){return t!==void 0&&(e=E(e,t)),T(e)}function T(e){if(!e||!n.get(e.id))return!1;l(),n.delete(e.id);var t=g(e.fromId),r=g(e.toId);return t&&t.links.delete(e),r&&r.links.delete(e),s(e,`remove`),u(),!0}function E(e,t){if(e!==void 0&&t!==void 0)return n.get(Bd(e,t))}function D(e){if(e!==void 0)return n.get(e)}function O(){l(),oe(function(e){_(e.id)}),u()}function k(e){if(typeof e==`function`)for(var t=n.values(),r=t.next();!r.done;){if(e(r.value))return!0;r=t.next()}}function ee(e,t,n){var r=g(e);if(r&&r.links&&typeof t==`function`)return n?ne(r.links,e,t):te(r.links,e,t)}function te(e,n,r){for(var i,a=e.values(),o=a.next();!o.done;){var s=o.value,c=s.fromId===n?s.toId:s.fromId;if(i=r(t.get(c),s),i)return!0;o=a.next()}}function ne(e,n,r){for(var i,a=e.values(),o=a.next();!o.done;){var s=o.value;if(s.fromId===n&&(i=r(t.get(s.toId),s),i))return!0;o=a.next()}}function re(){}function ie(){i+=1}function ae(){--i,i===0&&o.length>0&&(d.fire(`changed`,o),o.length=0)}function oe(e){if(typeof e!=`function`)throw Error(`Function is expected to iterate over graph nodes. You passed `+e);for(var n=t.values(),r=n.next();!r.done;){if(e(r.value))return!0;r=n.next()}}}function Ld(e,t){this.id=e,this.links=null,this.data=t}function Rd(e,t){e.links?e.links.add(t):e.links=new Set([t])}function zd(e,t,n,r){this.fromId=e,this.toId=t,this.data=n,this.id=r}function Bd(e,t){return e.toString()+`👉 `+t.toString()}var Vd=e(((e,t)=>{t.exports=function(e){return e===0?`x`:e===1?`y`:e===2?`z`:`c`+(e+1)}})),Hd=e(((e,t)=>{var n=Vd();t.exports=function(e){return t;function t(t,r){let i=r&&r.indent||0,a=r&&r.join!==void 0?r.join:`
`,o=Array(i+1).join(` `),s=[];for(let r=0;r<e;++r){let e=n(r),i=r===0?``:o;s.push(i+t.replace(/{var}/g,e))}return s.join(a)}}})),Ud=e(((e,t)=>{var n=Hd();t.exports=r,t.exports.generateCreateBodyFunctionBody=i,t.exports.getVectorCode=o,t.exports.getBodyCode=a;function r(e,t){let n=i(e,t),{Body:r}=Function(n)();return r}function i(e,t){return`
${o(e,t)}
${a(e,t)}
return {Body: Body, Vector: Vector};
`}function a(e){let t=n(e),r=t(`{var}`,{join:`, `});return`
function Body(${r}) {
this.isPinned = false;
this.pos = new Vector(${r});
this.force = new Vector();
this.velocity = new Vector();
this.mass = 1;
this.springCount = 0;
this.springLength = 0;
}
Body.prototype.reset = function() {
this.force.reset();
this.springCount = 0;
this.springLength = 0;
}
Body.prototype.setPosition = function (${r}) {
${t(`this.pos.{var} = {var} || 0;`,{indent:2})}
};`}function o(e,t){let r=n(e),i=``;return t&&(i=`${r(`
var v{var};
Object.defineProperty(this, '{var}', {
set: function(v) {
if (!Number.isFinite(v)) throw new Error('Cannot set non-numbers to {var}');
v{var} = v;
},
get: function() { return v{var}; }
});`)}`),`function Vector(${r(`{var}`,{join:`, `})}) {
${i}
if (typeof arguments[0] === 'object') {
// could be another vector
let v = arguments[0];
${r(`if (!Number.isFinite(v.{var})) throw new Error("Expected value is not a finite number at Vector constructor ({var})");`,{indent:4})}
${r(`this.{var} = v.{var};`,{indent:4})}
} else {
${r(`this.{var} = typeof {var} === "number" ? {var} : 0;`,{indent:4})}
}
}
Vector.prototype.reset = function () {
${r(`this.{var} = `,{join:``})}0;
};`}})),Wd=e(((e,t)=>{var n=Hd(),r=Vd();t.exports=i,t.exports.generateQuadTreeFunctionBody=a,t.exports.getInsertStackCode=u,t.exports.getQuadNodeCode=l,t.exports.isSamePosition=o,t.exports.getChildBodyCode=c,t.exports.setChildBodyCode=s;function i(e){let t=a(e);return Function(t)()}function a(e){let t=n(e),i=2**e;return`
${u()}
${l(e)}
${o(e)}
${c(e)}
${s(e)}
function createQuadTree(options, random) {
options = options || {};
options.gravity = typeof options.gravity === 'number' ? options.gravity : -1;
options.theta = typeof options.theta === 'number' ? options.theta : 0.8;
var gravity = options.gravity;
var updateQueue = [];
var insertStack = new InsertStack();
var theta = options.theta;
var nodesCache = [];
var currentInCache = 0;
var root = newNode();
return {
insertBodies: insertBodies,
/**
* Gets root node if it is present
*/
getRoot: function() {
return root;
},
updateBodyForce: update,
options: function(newOptions) {
if (newOptions) {
if (typeof newOptions.gravity === 'number') {
gravity = newOptions.gravity;
}
if (typeof newOptions.theta === 'number') {
theta = newOptions.theta;
}
return this;
}
return {
gravity: gravity,
theta: theta
};
}
};
function newNode() {
// To avoid pressure on GC we reuse nodes.
var node = nodesCache[currentInCache];
if (node) {
${f(` node.`)}
node.body = null;
node.mass = ${t(`node.mass_{var} = `,{join:``})}0;
${t(`node.min_{var} = node.max_{var} = `,{join:``})}0;
} else {
node = new QuadNode();
nodesCache[currentInCache] = node;
}
++currentInCache;
return node;
}
function update(sourceBody) {
var queue = updateQueue;
var v;
${t(`var d{var};`,{indent:4})}
var r;
${t(`var f{var} = 0;`,{indent:4})}
var queueLength = 1;
var shiftIdx = 0;
var pushIdx = 1;
queue[0] = root;
while (queueLength) {
var node = queue[shiftIdx];
var body = node.body;
queueLength -= 1;
shiftIdx += 1;
var differentBody = (body !== sourceBody);
if (body && differentBody) {
// If the current node is a leaf node (and it is not source body),
// calculate the force exerted by the current node on body, and add this
// amount to body's net force.
${t(`d{var} = body.pos.{var} - sourceBody.pos.{var};`,{indent:8})}
r = Math.sqrt(${t(`d{var} * d{var}`,{join:` + `})});
if (r === 0) {
// Poor man's protection against zero distance.
${t(`d{var} = (random.nextDouble() - 0.5) / 50;`,{indent:10})}
r = Math.sqrt(${t(`d{var} * d{var}`,{join:` + `})});
}
// This is standard gravitation force calculation but we divide
// by r^3 to save two operations when normalizing force vector.
v = gravity * body.mass * sourceBody.mass / (r * r * r);
${t(`f{var} += v * d{var};`,{indent:8})}
} else if (differentBody) {
// Otherwise, calculate the ratio s / r, where s is the width of the region
// represented by the internal node, and r is the distance between the body
// and the node's center-of-mass
${t(`d{var} = node.mass_{var} / node.mass - sourceBody.pos.{var};`,{indent:8})}
r = Math.sqrt(${t(`d{var} * d{var}`,{join:` + `})});
if (r === 0) {
// Sorry about code duplication. I don't want to create many functions
// right away. Just want to see performance first.
${t(`d{var} = (random.nextDouble() - 0.5) / 50;`,{indent:10})}
r = Math.sqrt(${t(`d{var} * d{var}`,{join:` + `})});
}
// If s / r < θ, treat this internal node as a single body, and calculate the
// force it exerts on sourceBody, and add this amount to sourceBody's net force.
if ((node.max_${r(0)} - node.min_${r(0)}) / r < theta) {
// in the if statement above we consider node's width only
// because the region was made into square during tree creation.
// Thus there is no difference between using width or height.
v = gravity * node.mass * sourceBody.mass / (r * r * r);
${t(`f{var} += v * d{var};`,{indent:10})}
} else {
// Otherwise, run the procedure recursively on each of the current node's children.
// I intentionally unfolded this loop, to save several CPU cycles.
${d()}
}
}
}
${t(`sourceBody.force.{var} += f{var};`,{indent:4})}
}
function insertBodies(bodies) {
${t(`var {var}min = Number.MAX_VALUE;`,{indent:4})}
${t(`var {var}max = Number.MIN_VALUE;`,{indent:4})}
var i = bodies.length;
// To reduce quad tree depth we are looking for exact bounding box of all particles.
while (i--) {
var pos = bodies[i].pos;
${t(`if (pos.{var} < {var}min) {var}min = pos.{var};`,{indent:6})}
${t(`if (pos.{var} > {var}max) {var}max = pos.{var};`,{indent:6})}
}
// Makes the bounds square.
var maxSideLength = -Infinity;
${t(`if ({var}max - {var}min > maxSideLength) maxSideLength = {var}max - {var}min ;`,{indent:4})}
currentInCache = 0;
root = newNode();
${t(`root.min_{var} = {var}min;`,{indent:4})}
${t(`root.max_{var} = {var}min + maxSideLength;`,{indent:4})}
i = bodies.length - 1;
if (i >= 0) {
root.body = bodies[i];
}
while (i--) {
insert(bodies[i], root);
}
}
function insert(newBody) {
insertStack.reset();
insertStack.push(root, newBody);
while (!insertStack.isEmpty()) {
var stackItem = insertStack.pop();
var node = stackItem.node;
var body = stackItem.body;
if (!node.body) {
// This is internal node. Update the total mass of the node and center-of-mass.
${t(`var {var} = body.pos.{var};`,{indent:8})}
node.mass += body.mass;
${t(`node.mass_{var} += body.mass * {var};`,{indent:8})}
// Recursively insert the body in the appropriate quadrant.
// But first find the appropriate quadrant.
var quadIdx = 0; // Assume we are in the 0's quad.
${t(`var min_{var} = node.min_{var};`,{indent:8})}
${t(`var max_{var} = (min_{var} + node.max_{var}) / 2;`,{indent:8})}
${a(8)}
var child = getChild(node, quadIdx);
if (!child) {
// The node is internal but this quadrant is not taken. Add
// subnode to it.
child = newNode();
${t(`child.min_{var} = min_{var};`,{indent:10})}
${t(`child.max_{var} = max_{var};`,{indent:10})}
child.body = body;
setChild(node, quadIdx, child);
} else {
// continue searching in this quadrant.
insertStack.push(child, body);
}
} else {
// We are trying to add to the leaf node.
// We have to convert current leaf into internal node
// and continue adding two nodes.
var oldBody = node.body;
node.body = null; // internal nodes do not cary bodies
if (isSamePosition(oldBody.pos, body.pos)) {
// Prevent infinite subdivision by bumping one node
// anywhere in this quadrant
var retriesCount = 3;
do {
var offset = random.nextDouble();
${t(`var d{var} = (node.max_{var} - node.min_{var}) * offset;`,{indent:12})}
${t(`oldBody.pos.{var} = node.min_{var} + d{var};`,{indent:12})}
retriesCount -= 1;
// Make sure we don't bump it out of the box. If we do, next iteration should fix it
} while (retriesCount > 0 && isSamePosition(oldBody.pos, body.pos));
if (retriesCount === 0 && isSamePosition(oldBody.pos, body.pos)) {
// This is very bad, we ran out of precision.
// if we do not return from the method we'll get into
// infinite loop here. So we sacrifice correctness of layout, and keep the app running
// Next layout iteration should get larger bounding box in the first step and fix this
return;
}
}
// Next iteration should subdivide node further.
insertStack.push(node, oldBody);
insertStack.push(node, body);
}
}
}
}
return createQuadTree;
`;function a(t){let n=[],i=Array(t+1).join(` `);for(let t=0;t<e;++t)n.push(i+`if (${r(t)} > max_${r(t)}) {`),n.push(i+` quadIdx = quadIdx + ${2**t};`),n.push(i+` min_${r(t)} = max_${r(t)};`),n.push(i+` max_${r(t)} = node.max_${r(t)};`),n.push(i+`}`);return n.join(`
`)}function d(){let e=Array(11).join(` `),t=[];for(let n=0;n<i;++n)t.push(e+`if (node.quad${n}) {`),t.push(e+` queue[pushIdx] = node.quad${n};`),t.push(e+` queueLength += 1;`),t.push(e+` pushIdx += 1;`),t.push(e+`}`);return t.join(`
`)}function f(e){let t=[];for(let n=0;n<i;++n)t.push(`${e}quad${n} = null;`);return t.join(`
`)}}function o(e){let t=n(e);return`
function isSamePosition(point1, point2) {
${t(`var d{var} = Math.abs(point1.{var} - point2.{var});`,{indent:2})}
return ${t(`d{var} < 1e-8`,{join:` && `})};
}
`}function s(e){var t=2**e;return`
function setChild(node, idx, child) {
${n()}
}`;function n(){let e=[];for(let n=0;n<t;++n){let t=n===0?` `:` else `;e.push(`${t}if (idx === ${n}) node.quad${n} = child;`)}return e.join(`
`)}}function c(e){return`function getChild(node, idx) {
${t()}
return null;
}`;function t(){let t=[],n=2**e;for(let e=0;e<n;++e)t.push(` if (idx === ${e}) return node.quad${e};`);return t.join(`
`)}}function l(e){let t=n(e),r=2**e;return`
function QuadNode() {
// body stored inside this node. In quad tree only leaf nodes (by construction)
// contain bodies:
this.body = null;
// Child nodes are stored in quads. Each quad is presented by number:
// 0 | 1
// -----
// 2 | 3
${i(` this.`)}
// Total mass of current node
this.mass = 0;
// Center of mass coordinates
${t(`this.mass_{var} = 0;`,{indent:2})}
// bounding box coordinates
${t(`this.min_{var} = 0;`,{indent:2})}
${t(`this.max_{var} = 0;`,{indent:2})}
}
`;function i(e){let t=[];for(let n=0;n<r;++n)t.push(`${e}quad${n} = null;`);return t.join(`
`)}}function u(){return`
/**
* Our implementation of QuadTree is non-recursive to avoid GC hit
* This data structure represent stack of elements
* which we are trying to insert into quad tree.
*/
function InsertStack () {
this.stack = [];
this.popIdx = 0;
}
InsertStack.prototype = {
isEmpty: function() {
return this.popIdx === 0;
},
push: function (node, body) {
var item = this.stack[this.popIdx];
if (!item) {
// we are trying to avoid memory pressure: create new element
// only when absolutely necessary
this.stack[this.popIdx] = new InsertStackElement(node, body);
} else {
item.node = node;
item.body = body;
}
++this.popIdx;
},
pop: function () {
if (this.popIdx > 0) {
return this.stack[--this.popIdx];
}
},
reset: function () {
this.popIdx = 0;
}
};
function InsertStackElement(node, body) {
this.node = node; // QuadTree node
this.body = body; // physical body which needs to be inserted to node
}
`}})),Gd=e(((e,t)=>{t.exports=r,t.exports.generateFunctionBody=i;var n=Hd();function r(e){let t=i(e);return Function(`bodies`,`settings`,`random`,t)}function i(e){let t=n(e);return`
var boundingBox = {
${t(`min_{var}: 0, max_{var}: 0,`,{indent:4})}
};
return {
box: boundingBox,
update: updateBoundingBox,
reset: resetBoundingBox,
getBestNewPosition: function (neighbors) {
var ${t(`base_{var} = 0`,{join:`, `})};
if (neighbors.length) {
for (var i = 0; i < neighbors.length; ++i) {
let neighborPos = neighbors[i].pos;
${t(`base_{var} += neighborPos.{var};`,{indent:10})}
}
${t(`base_{var} /= neighbors.length;`,{indent:8})}
} else {
${t(`base_{var} = (boundingBox.min_{var} + boundingBox.max_{var}) / 2;`,{indent:8})}
}
var springLength = settings.springLength;
return {
${t(`{var}: base_{var} + (random.nextDouble() - 0.5) * springLength,`,{indent:8})}
};
}
};
function updateBoundingBox() {
var i = bodies.length;
if (i === 0) return; // No bodies - no borders.
${t(`var max_{var} = -Infinity;`,{indent:4})}
${t(`var min_{var} = Infinity;`,{indent:4})}
while(i--) {
// this is O(n), it could be done faster with quadtree, if we check the root node bounds
var bodyPos = bodies[i].pos;
${t(`if (bodyPos.{var} < min_{var}) min_{var} = bodyPos.{var};`,{indent:6})}
${t(`if (bodyPos.{var} > max_{var}) max_{var} = bodyPos.{var};`,{indent:6})}
}
${t(`boundingBox.min_{var} = min_{var};`,{indent:4})}
${t(`boundingBox.max_{var} = max_{var};`,{indent:4})}
}
function resetBoundingBox() {
${t(`boundingBox.min_{var} = boundingBox.max_{var} = 0;`,{indent:4})}
}
`}})),Kd=e(((e,t)=>{var n=Hd();t.exports=r,t.exports.generateCreateDragForceFunctionBody=i;function r(e){let t=i(e);return Function(`options`,t)}function i(e){return`
if (!Number.isFinite(options.dragCoefficient)) throw new Error('dragCoefficient is not a finite number');
return {
update: function(body) {
${n(e)(`body.force.{var} -= options.dragCoefficient * body.velocity.{var};`,{indent:6})}
}
};
`}})),qd=e(((e,t)=>{var n=Hd();t.exports=r,t.exports.generateCreateSpringForceFunctionBody=i;function r(e){let t=i(e);return Function(`options`,`random`,t)}function i(e){let t=n(e);return`
if (!Number.isFinite(options.springCoefficient)) throw new Error('Spring coefficient is not a number');
if (!Number.isFinite(options.springLength)) throw new Error('Spring length is not a number');
return {
/**
* Updates forces acting on a spring
*/
update: function (spring) {
var body1 = spring.from;
var body2 = spring.to;
var length = spring.length < 0 ? options.springLength : spring.length;
${t(`var d{var} = body2.pos.{var} - body1.pos.{var};`,{indent:6})}
var r = Math.sqrt(${t(`d{var} * d{var}`,{join:` + `})});
if (r === 0) {
${t(`d{var} = (random.nextDouble() - 0.5) / 50;`,{indent:8})}
r = Math.sqrt(${t(`d{var} * d{var}`,{join:` + `})});
}
var d = r - length;
var coefficient = ((spring.coefficient > 0) ? spring.coefficient : options.springCoefficient) * d / r;
${t(`body1.force.{var} += coefficient * d{var}`,{indent:6})};
body1.springCount += 1;
body1.springLength += r;
${t(`body2.force.{var} -= coefficient * d{var}`,{indent:6})};
body2.springCount += 1;
body2.springLength += r;
}
};
`}})),Jd=e(((e,t)=>{var n=Hd();t.exports=r,t.exports.generateIntegratorFunctionBody=i;function r(e){let t=i(e);return Function(`bodies`,`timeStep`,`adaptiveTimeStepWeight`,t)}function i(e){let t=n(e);return`
var length = bodies.length;
if (length === 0) return 0;
${t(`var d{var} = 0, t{var} = 0;`,{indent:2})}
for (var i = 0; i < length; ++i) {
var body = bodies[i];
if (body.isPinned) continue;
if (adaptiveTimeStepWeight && body.springCount) {
timeStep = (adaptiveTimeStepWeight * body.springLength/body.springCount);
}
var coeff = timeStep / body.mass;
${t(`body.velocity.{var} += coeff * body.force.{var};`,{indent:4})}
${t(`var v{var} = body.velocity.{var};`,{indent:4})}
var v = Math.sqrt(${t(`v{var} * v{var}`,{join:` + `})});
if (v > 1) {
// We normalize it so that we move within timeStep range.
// for the case when v <= 1 - we let velocity to fade out.
${t(`body.velocity.{var} = v{var} / v;`,{indent:6})}
}
${t(`d{var} = timeStep * body.velocity.{var};`,{indent:4})}
${t(`body.pos.{var} += d{var};`,{indent:4})}
${t(`t{var} += Math.abs(d{var});`,{indent:4})}
}
return (${t(`t{var} * t{var}`,{join:` + `})})/length;
`}})),Yd=e(((e,t)=>{t.exports=n;function n(e,t,n,r){this.from=e,this.to=t,this.length=n,this.coefficient=r}})),Xd=e(((e,t)=>{t.exports=n;function n(e,t){var r;if(e||={},t){for(r in t)if(t.hasOwnProperty(r)){var i=e.hasOwnProperty(r),a=typeof t[r];!i||typeof e[r]!==a?e[r]=t[r]:a===`object`&&(e[r]=n(e[r],t[r]))}}return e}})),Zd=e(((e,t)=>{function n(e){i(e);let t=r(e);return e.on=t.on,e.off=t.off,e.fire=t.fire,e}function r(e){let t=Object.create(null);return{on:function(n,r,i){if(typeof r!=`function`)throw Error(`callback is expected to be a function`);let a=t[n];return a||=t[n]=[],a.push({callback:r,ctx:i}),e},off:function(n,r){if(typeof n>`u`)return t=Object.create(null),e;if(t[n]){if(typeof r!=`function`)delete t[n];else{let e=t[n];for(let t=0;t<e.length;++t)e[t].callback===r&&e.splice(t,1)}}return e},fire:function(n){let r=t[n];if(!r)return e;let i;arguments.length>1&&(i=Array.prototype.slice.call(arguments,1));for(let e=0;e<r.length;++e){let t=r[e];t.callback.apply(t.ctx,i)}return e}}}function i(e){if(!e)throw Error(`Eventify cannot use falsy object as events subject`);let t=[`on`,`fire`,`off`];for(let n=0;n<t.length;++n)if(e.hasOwnProperty(t[n]))throw Error(`Subject cannot be eventified, since it already has property '`+t[n]+`'`)}t.exports=n})),Qd=e(((e,t)=>{t.exports=n,t.exports.random=n,t.exports.randomIterator=l;function n(e){return new r(typeof e==`number`?e:+new Date)}function r(e){this.seed=e}r.prototype.next=c,r.prototype.nextDouble=s,r.prototype.uniform=s,r.prototype.gaussian=i,r.prototype.random=s;function i(){var e,t,n;do t=this.nextDouble()*2-1,n=this.nextDouble()*2-1,e=t*t+n*n;while(e>=1||e===0);return t*Math.sqrt(-2*Math.log(e)/e)}r.prototype.levy=a;function a(){var e=3/2,t=(o(1+e)*Math.sin(Math.PI*e/2)/(o((1+e)/2)*e*2**((e-1)/2)))**(1/e);return this.gaussian()*t/Math.abs(this.gaussian())**(1/e)}function o(e){return Math.sqrt(2*Math.PI/e)*(1/Math.E*(e+1/(12*e-1/(10*e))))**e}function s(){var e=this.seed;return e=e+2127912214+(e<<12)&4294967295,e=(e^3345072700^e>>>19)&4294967295,e=e+374761393+(e<<5)&4294967295,e=(e+3550635116^e<<9)&4294967295,e=e+4251993797+(e<<3)&4294967295,e=(e^3042594569^e>>>16)&4294967295,this.seed=e,(e&268435455)/268435456}function c(e){return Math.floor(this.nextDouble()*e)}function l(e,t){var r=t||n();if(typeof r.next!=`function`)throw Error(`customRandom does not match expected API: next() function is missing`);return{forEach:a,shuffle:i};function i(){for(var t=e.length-1,n,i;t>0;--t)n=r.next(t+1),i=e[n],e[n]=e[t],e[t]=i;return e}function a(t){for(var n=e.length-1,i,a;n>0;--n)i=r.next(n+1),a=e[i],e[i]=e[n],e[n]=a,t(a);e.length&&t(e[0])}}})),$d=e(((e,t)=>{t.exports=l;var n=Ud(),r=Wd(),i=Gd(),a=Kd(),o=qd(),s=Jd(),c={};function l(e){var t=Yd(),l=Xd(),d=Zd();if(e){if(e.springCoeff!==void 0)throw Error(`springCoeff was renamed to springCoefficient`);if(e.dragCoeff!==void 0)throw Error(`dragCoeff was renamed to dragCoefficient`)}e=l(e,{springLength:10,springCoefficient:.8,gravity:-12,theta:.8,dragCoefficient:.9,timeStep:.5,adaptiveTimeStepWeight:0,dimensions:2,debug:!1});var f=c[e.dimensions];if(!f){var p=e.dimensions;f={Body:n(p,e.debug),createQuadTree:r(p),createBounds:i(p),createDragForce:a(p),createSpringForce:o(p),integrate:s(p)},c[p]=f}var m=f.Body,h=f.createQuadTree,g=f.createBounds,_=f.createDragForce,v=f.createSpringForce,y=f.integrate,b=e=>new m(e),x=Qd().random(42),S=[],C=[],w=h(e,x),T=g(S,e,x),E=v(e,x),D=_(e),O=0,k=[],ee=new Map,te=0;ie(`nbody`,se),ie(`spring`,ce);var ne={bodies:S,quadTree:w,springs:C,settings:e,addForce:ie,removeForce:ae,getForces:oe,step:function(){for(var t=0;t<k.length;++t)k[t](te);var n=y(S,e.timeStep,e.adaptiveTimeStepWeight);return te+=1,n},addBody:function(e){if(!e)throw Error(`Body is required`);return S.push(e),e},addBodyAt:function(e){if(!e)throw Error(`Body position is required`);var t=b(e);return S.push(t),t},removeBody:function(e){if(e){var t=S.indexOf(e);if(!(t<0))return S.splice(t,1),S.length===0&&T.reset(),!0}},addSpring:function(e,n,r,i){if(!e||!n)throw Error(`Cannot add null spring to force simulator`);typeof r!=`number`&&(r=-1);var a=new t(e,n,r,i>=0?i:-1);return C.push(a),a},getTotalMovement:function(){return O},removeSpring:function(e){if(e){var t=C.indexOf(e);if(t>-1)return C.splice(t,1),!0}},getBestNewBodyPosition:function(e){return T.getBestNewPosition(e)},getBBox:re,getBoundingBox:re,invalidateBBox:function(){console.warn("invalidateBBox() is deprecated, bounds always recomputed on `getBBox()` call")},gravity:function(t){return t===void 0?e.gravity:(e.gravity=t,w.options({gravity:t}),this)},theta:function(t){return t===void 0?e.theta:(e.theta=t,w.options({theta:t}),this)},random:x};return u(e,ne),d(ne),ne;function re(){return T.update(),T.box}function ie(e,t){if(ee.has(e))throw Error(`Force `+e+` is already added`);ee.set(e,t),k.push(t)}function ae(e){var t=k.indexOf(ee.get(e));t<0||(k.splice(t,1),ee.delete(e))}function oe(){return ee}function se(){if(S.length!==0){w.insertBodies(S);for(var e=S.length;e--;){var t=S[e];t.isPinned||(t.reset(),w.updateBodyForce(t),D.update(t))}}}function ce(){for(var e=C.length;e--;)E.update(C[e])}}function u(e,t){for(var n in e)d(e,t,n)}function d(e,t,n){e.hasOwnProperty(n)&&typeof t[n]!=`function`&&(t[n]=Number.isFinite(e[n])?function(r){if(r!==void 0){if(!Number.isFinite(r))throw Error(`Value of `+n+` should be a valid number.`);return e[n]=r,t}return e[n]}:function(r){return r===void 0?e[n]:(e[n]=r,t)})}})),ef=t(e(((e,t)=>{t.exports=r,t.exports.simulator=$d();var n=Zd();function r(e,t){if(!e)throw Error(`Graph structure cannot be undefined`);var r=(t&&t.createSimulator||$d())(t);if(Array.isArray(t))throw Error(`Physics settings is expected to be an object`);var a=e.version>19?ee:k;t&&typeof t.nodeMass==`function`&&(a=t.nodeMass);var o=new Map,s={},c=0,l=r.settings.springTransform||i;b(),_();var u=!1,d={step:function(){if(c===0)return f(!0),!0;var e=r.step();d.lastMove=e,d.fire(`step`);var t=e/c<=.01;return f(t),t},getNodePosition:function(e){return O(e).pos},setNodePosition:function(e){var t=O(e);t.setPosition.apply(t,Array.prototype.slice.call(arguments,1))},getLinkPosition:function(e){var t=s[e];if(t)return{from:t.from.pos,to:t.to.pos}},getGraphRect:function(){return r.getBBox()},forEachBody:p,pinNode:function(e,t){var n=O(e.id);n.isPinned=!!t},isNodePinned:function(e){return O(e.id).isPinned},dispose:function(){e.off(`changed`,y),d.fire(`disposed`)},getBody:g,getSpring:h,getForceVectorLength:m,simulator:r,graph:e,lastMove:0};return n(d),d;function f(e){u!==e&&(u=e,v(e))}function p(e){o.forEach(e)}function m(){var e=0,t=0;return p(function(n){e+=Math.abs(n.force.x),t+=Math.abs(n.force.y)}),Math.sqrt(e*e+t*t)}function h(t,n){var r;if(n===void 0)r=typeof t==`object`?t.id:t;else{var i=e.hasLink(t,n);if(!i)return;r=i.id}return s[r]}function g(e){return o.get(e)}function _(){e.on(`changed`,y)}function v(e){d.fire(`stable`,e)}function y(t){for(var n=0;n<t.length;++n){var r=t[n];r.changeType===`add`?(r.node&&x(r.node.id),r.link&&C(r.link)):r.changeType===`remove`&&(r.node&&S(r.node),r.link&&w(r.link))}c=e.getNodesCount()}function b(){c=0,e.forEachNode(function(e){x(e.id),c+=1}),e.forEachLink(C)}function x(t){var n=o.get(t);if(!n){var i=e.getNode(t);if(!i)throw Error(`initBody() was called with unknown node id`);var a=i.position;if(!a){var s=T(i);a=r.getBestNewBodyPosition(s)}n=r.addBodyAt(a),n.id=t,o.set(t,n),E(t),D(i)&&(n.isPinned=!0)}}function S(e){var t=e.id,n=o.get(t);n&&(o.delete(t),r.removeBody(n))}function C(e){E(e.fromId),E(e.toId);var t=o.get(e.fromId),n=o.get(e.toId),i=r.addSpring(t,n,e.length);l(e,i),s[e.id]=i}function w(t){var n=s[t.id];if(n){var i=e.getNode(t.fromId),a=e.getNode(t.toId);i&&E(i.id),a&&E(a.id),delete s[t.id],r.removeSpring(n)}}function T(e){var t=[];if(!e.links)return t;for(var n=Math.min(e.links.length,2),r=0;r<n;++r){var i=e.links[r],a=i.fromId===e.id?o.get(i.toId):o.get(i.fromId);a&&a.pos&&t.push(a)}return t}function E(e){var t=o.get(e);if(t.mass=a(e),Number.isNaN(t.mass))throw Error(`Node mass should be a number`)}function D(e){return e&&(e.isPinned||e.data&&e.data.isPinned)}function O(e){var t=o.get(e);return t||=(x(e),o.get(e)),t}function k(t){var n=e.getLinks(t);return n?1+n.length/3:1}function ee(t){var n=e.getLinks(t);return n?1+n.size/3:1}}function i(){}}))(),1);function tf(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function nf(e){if(Array.isArray(e))return e}function rf(e){if(Array.isArray(e))return tf(e)}function af(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}function of(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function sf(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function cf(e,t){return e.get(af(e,t))}function lf(e,t,n){of(e,t),t.set(e,n)}function uf(e,t,n){return e.set(af(e,t),n),n}function df(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,bf(r.key),r)}}function ff(e,t,n){return t&&df(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function pf(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function mf(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function hf(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function gf(){throw TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _f(e,t){return nf(e)||mf(e,t)||xf(e,t)||hf()}function vf(e){return rf(e)||pf(e)||xf(e)||gf()}function yf(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return String(e)}function bf(e){var t=yf(e,`string`);return typeof t==`symbol`?t:t+``}function xf(e,t){if(e){if(typeof e==`string`)return tf(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?tf(e,t):void 0}}var Sf=new WeakMap,Cf=new WeakMap,wf=new WeakMap,Tf=new WeakMap,Ef=new WeakMap,Df=new WeakMap,Of=function(){function e(){sf(this,e),lf(this,Sf,new Map),lf(this,Cf,new Map),lf(this,wf,function(e){return e}),lf(this,Tf,function(){return{}}),lf(this,Ef,function(){}),lf(this,Df,function(){})}return ff(e,[{key:`getObj`,value:function(e){return cf(Sf,this).get(cf(wf,this).call(this,e))}},{key:`getData`,value:function(e){return cf(Cf,this).get(e)}},{key:`entries`,value:function(){return vf(cf(Cf,this).entries()).map(function(e){var t=_f(e,2),n=t[0];return[t[1],n]})}},{key:`id`,value:function(e){return uf(wf,this,a(e)),this}},{key:`onCreateObj`,value:function(e){return uf(Tf,this,e),this}},{key:`onUpdateObj`,value:function(e){return uf(Ef,this,e),this}},{key:`onRemoveObj`,value:function(e){return uf(Df,this,e),this}},{key:`digest`,value:function(e){var t=this;e.filter(function(e){return!cf(Sf,t).has(cf(wf,t).call(t,e))}).forEach(function(e){var n=cf(Tf,t).call(t,e);cf(Sf,t).set(cf(wf,t).call(t,e),n),cf(Cf,t).set(n,e)});var n=new Map(e.map(function(e){return[cf(wf,t).call(t,e),e]}));return cf(Sf,this).forEach(function(e,r){n.has(r)?cf(Ef,t).call(t,e,n.get(r)):(cf(Df,t).call(t,e,r),cf(Sf,t).delete(r),cf(Cf,t).delete(e))}),this}},{key:`clear`,value:function(){return this.digest([]),this}}])}();function kf(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Af(e){if(Array.isArray(e))return e}function jf(e){if(Array.isArray(e))return kf(e)}function Mf(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}function Nf(e){if(e===void 0)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return e}function Pf(e,t,n){return t=Gf(t),ep(e,qf()?Reflect.construct(t,n||[],Gf(e).constructor):t.apply(e,n))}function Ff(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function If(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function Lf(e,t){return e.get(Mf(e,t))}function Rf(e,t,n){Ff(e,t),t.set(e,n)}function zf(e,t,n){return e.set(Mf(e,t),n),n}function Bf(e,t,n){if(qf())return Reflect.construct.apply(null,arguments);var r=[null];return r.push.apply(r,t),new(e.bind.apply(e,r))}function Vf(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,sp(r.key),r)}}function Hf(e,t,n){return t&&Vf(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Uf(e,t,n){return(t=sp(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Wf(){return Wf=typeof Reflect<`u`&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=rp(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}},Wf.apply(null,arguments)}function Gf(e){return Gf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Gf(e)}function Kf(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Super expression must either be null or a function`);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&tp(e,t)}function qf(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(qf=function(){return!!e})()}function Jf(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function Yf(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Xf(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Zf(){throw TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Qf(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $f(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Qf(Object(n),!0).forEach(function(t){Uf(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Qf(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ep(e,t){if(t&&(typeof t==`object`||typeof t==`function`))return t;if(t!==void 0)throw TypeError(`Derived constructors may only return object or undefined`);return Nf(e)}function tp(e,t){return tp=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},tp(e,t)}function np(e,t){return Af(e)||Yf(e,t)||lp(e,t)||Xf()}function rp(e,t){for(;!{}.hasOwnProperty.call(e,t)&&(e=Gf(e))!==null;);return e}function ip(e,t,n,r){var i=Wf(Gf(e.prototype),t,n);return typeof i==`function`?function(e){return i.apply(n,e)}:i}function ap(e){return jf(e)||Jf(e)||lp(e)||Zf()}function op(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function sp(e){var t=op(e,`string`);return typeof t==`symbol`?t:t+``}function cp(e){"@babel/helpers - typeof";return cp=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},cp(e)}function lp(e,t){if(e){if(typeof e==`string`)return kf(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?kf(e,t):void 0}}var up=function(e){e instanceof Array?e.forEach(up):(e.map&&e.map.dispose(),e.dispose())},dp=function(e){e.geometry&&e.geometry.dispose(),e.material&&up(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(dp)},fp=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),dp(t)}},pp=new WeakMap,mp=new WeakMap,hp=function(e){function t(e){var n,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=r.dataBindAttr,a=i===void 0?`__data`:i,o=r.objBindAttr,s=o===void 0?`__threeObj`:o;return If(this,t),n=Pf(this,t),Uf(n,`scene`,void 0),Rf(n,pp,void 0),Rf(n,mp,void 0),n.scene=e,zf(pp,n,a),zf(mp,n,s),n.onRemoveObj(function(){}),n}return Kf(t,e),Hf(t,[{key:`onCreateObj`,value:function(e){var n=this;return ip(t,`onCreateObj`,this)([function(t){var r=e(t);return t[Lf(mp,n)]=r,r[Lf(pp,n)]=t,n.scene.add(r),r}]),this}},{key:`onRemoveObj`,value:function(e){var n=this;return ip(t,`onRemoveObj`,this)([function(r,i){var a=ip(t,`getData`,n)([r]);e(r,i),n.scene.remove(r),dp(r),delete a[Lf(mp,n)]}]),this}}])}(Of),gp=function(e){return isNaN(e)?parseInt(p(e).toHex(),16):e},_p=function(e){return isNaN(e)?p(e).getAlpha():1},vp=i(g);function yp(e,t,n){t&&typeof n==`string`&&e.filter(function(e){return!e[n]}).forEach(function(e){e[n]=vp(t(e))})}function bp(e,t){var n=e.nodes,r=e.links,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},a=i.nodeFilter,o=a===void 0?function(){return!0}:a,s=i.onLoopError,c=s===void 0?function(e){throw`Invalid DAG structure! Found cycle in node path: ${e.join(` -> `)}.`}:s,l={};n.forEach(function(e){return l[t(e)]={data:e,out:[],depth:-1,skip:!o(e)}}),r.forEach(function(e){var n=e.source,r=e.target,i=c(n),a=c(r);if(!l.hasOwnProperty(i))throw`Missing source node with id: ${i}`;if(!l.hasOwnProperty(a))throw`Missing target node with id: ${a}`;var o=l[i],s=l[a];o.out.push(s);function c(e){return cp(e)===`object`?t(e):e}});var u=[];return d(Object.values(l)),Object.assign.apply(Object,[{}].concat(ap(Object.entries(l).filter(function(e){return!np(e,2)[1].skip}).map(function(e){var t=np(e,2),n=t[0],r=t[1];return Uf({},n,r.depth)}))));function d(e){for(var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=function(){var i=e[a];if(n.indexOf(i)!==-1){var o=[].concat(ap(n.slice(n.indexOf(i))),[i]).map(function(e){return t(e.data)});return u.some(function(e){return e.length===o.length&&e.every(function(e,t){return e===o[t]})})||(u.push(o),c(o)),1}r>i.depth&&(i.depth=r,d(i.out,[].concat(ap(n),[i]),r+ +!i.skip))},a=0,o=e.length;a<o;a++)if(i())continue}}var xp=window.THREE?window.THREE:{Group:mr,Mesh:Yi,MeshLambertMaterial:vo,Color:L,BufferGeometry:xi,BufferAttribute:ai,Matrix4:Bn,Vector3:F,SphereGeometry:$a,CylinderGeometry:Ca,TubeGeometry:eo,ConeGeometry:wa,Line:ma,LineBasicMaterial:oa,QuadraticBezierCurve3:Xa,CubicBezierCurve3:Ka,Box3:Lr},Sp={graph:Fd,forcelayout:ef.default},Cp=2,wp=new xp.BufferGeometry().setAttribute?`setAttribute`:`addAttribute`,Tp=new xp.BufferGeometry().applyMatrix4?`applyMatrix4`:`applyMatrix`,Ep=o({props:{jsonUrl:{onChange:function(e,t){var n=this;e&&!t.fetchingJson&&(t.fetchingJson=!0,t.onLoading(),fetch(e).then(function(e){return e.json()}).then(function(e){t.fetchingJson=!1,t.onFinishLoading(e),n.graphData(e)}))},triggerUpdate:!1},graphData:{default:{nodes:[],links:[]},onChange:function(e,t){t.engineRunning=!1}},numDimensions:{default:3,onChange:function(e,t){var n=t.d3ForceLayout.force(`charge`);n&&n.strength(e>2?-60:-30),e<3&&r(t.graphData.nodes,`z`),e<2&&r(t.graphData.nodes,`y`);function r(e,t){e.forEach(function(e){delete e[t],delete e[`v${t}`]})}}},dagMode:{onChange:function(e,t){!e&&t.forceEngine===`d3`&&(t.graphData.nodes||[]).forEach(function(e){e.fx=e.fy=e.fz=void 0})}},dagLevelDistance:{},dagNodeFilter:{default:function(e){return!0}},onDagError:{triggerUpdate:!1},nodeRelSize:{default:4},nodeId:{default:`id`},nodeVal:{default:`val`},nodeResolution:{default:8},nodeColor:{default:`color`},nodeAutoColorBy:{},nodeOpacity:{default:.75},nodeVisibility:{default:!0},nodeThreeObject:{},nodeThreeObjectExtend:{default:!1},nodePositionUpdate:{triggerUpdate:!1},linkSource:{default:`source`},linkTarget:{default:`target`},linkVisibility:{default:!0},linkColor:{default:`color`},linkAutoColorBy:{},linkOpacity:{default:.2},linkWidth:{},linkResolution:{default:6},linkCurvature:{default:0,triggerUpdate:!1},linkCurveRotation:{default:0,triggerUpdate:!1},linkMaterial:{},linkThreeObject:{},linkThreeObjectExtend:{default:!1},linkPositionUpdate:{triggerUpdate:!1},linkDirectionalArrowLength:{default:0},linkDirectionalArrowColor:{},linkDirectionalArrowRelPos:{default:.5,triggerUpdate:!1},linkDirectionalArrowResolution:{default:8},linkDirectionalParticles:{default:0},linkDirectionalParticleSpeed:{default:.01,triggerUpdate:!1},linkDirectionalParticleOffset:{default:0,triggerUpdate:!1},linkDirectionalParticleWidth:{default:.5},linkDirectionalParticleColor:{},linkDirectionalParticleResolution:{default:4},linkDirectionalParticleThreeObject:{},forceEngine:{default:`d3`},d3AlphaMin:{default:0},d3AlphaDecay:{default:.0228,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaDecay(e)}},d3AlphaTarget:{default:0,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaTarget(e)}},d3VelocityDecay:{default:.4,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.velocityDecay(e)}},ngraphPhysics:{default:{timeStep:20,gravity:-1.2,theta:.8,springLength:30,springCoefficient:8e-4,dragCoefficient:.02}},warmupTicks:{default:0,triggerUpdate:!1},cooldownTicks:{default:1/0,triggerUpdate:!1},cooldownTime:{default:15e3,triggerUpdate:!1},onLoading:{default:function(){},triggerUpdate:!1},onFinishLoading:{default:function(){},triggerUpdate:!1},onUpdate:{default:function(){},triggerUpdate:!1},onFinishUpdate:{default:function(){},triggerUpdate:!1},onEngineTick:{default:function(){},triggerUpdate:!1},onEngineStop:{default:function(){},triggerUpdate:!1}},methods:{refresh:function(e){return e._flushObjects=!0,e._rerender(),this},d3Force:function(e,t,n){return 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(),r(),i(),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 n=a(e.nodeThreeObjectExtend);e.nodeDataMapper.entries().forEach(function(r){var i=np(r,2),a=i[0],o=i[1];if(o){var s=t?a:e.layout.getNodePosition(a[e.nodeId]),c=n(a);(!e.nodePositionUpdate||!e.nodePositionUpdate(c?o.children[0]:o,{x:s.x,y:s.y,z:s.z},a)||c)&&(o.position.x=s.x,o.position.y=s.y||0,o.position.z=s.z||0)}});var r=a(e.linkWidth),i=a(e.linkCurvature),o=a(e.linkCurveRotation),s=a(e.linkThreeObjectExtend);e.linkDataMapper.entries().forEach(function(n){var i=np(n,2),a=i[0],o=i[1];if(o){var l=t?a:e.layout.getLinkPosition(e.layout.graph.getLink(a.source,a.target).id),u=l[t?`source`:`from`],d=l[t?`target`:`to`];if(u&&d&&u.hasOwnProperty(`x`)&&d.hasOwnProperty(`x`)){c(a);var f=s(a);if(!(e.linkPositionUpdate&&e.linkPositionUpdate(f?o.children[1]:o,{start:{x:u.x,y:u.y,z:u.z},end:{x:d.x,y:d.y,z:d.z}},a)&&!f)){var p=30,m=a.__curve,h=o.children.length?o.children[0]:o;if(h.type===`Line`){if(m){var g=m.getPoints(p);h.geometry.getAttribute(`position`).array.length!==g.length*3&&h.geometry[wp](`position`,new xp.BufferAttribute(new Float32Array(g.length*3),3)),h.geometry.setFromPoints(g)}else{var _=h.geometry.getAttribute(`position`);(!_||!_.array||_.array.length!==6)&&h.geometry[wp](`position`,_=new xp.BufferAttribute(new Float32Array(6),3)),_.array[0]=u.x,_.array[1]=u.y||0,_.array[2]=u.z||0,_.array[3]=d.x,_.array[4]=d.y||0,_.array[5]=d.z||0,_.needsUpdate=!0}h.geometry.computeBoundingSphere()}else if(h.type===`Mesh`){if(m){h.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(h.position.set(0,0,0),h.rotation.set(0,0,0),h.scale.set(1,1,1));var v=Math.ceil(r(a)*10)/10/2,y=new xp.TubeGeometry(m,p,v,e.linkResolution,!1);h.geometry.dispose(),h.geometry=y}else{if(!h.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var b=Math.ceil(r(a)*10)/10/2,x=new xp.CylinderGeometry(b,b,1,e.linkResolution,1,!1);x[Tp](new xp.Matrix4().makeTranslation(0,1/2,0)),x[Tp](new xp.Matrix4().makeRotationX(Math.PI/2)),h.geometry.dispose(),h.geometry=x}var S=new xp.Vector3(u.x,u.y||0,u.z||0),C=new xp.Vector3(d.x,d.y||0,d.z||0),w=S.distanceTo(C);h.position.x=S.x,h.position.y=S.y,h.position.z=S.z,h.scale.z=w,h.parent.localToWorld(C),h.lookAt(C)}}}}}});function c(n){var r=t?n:e.layout.getLinkPosition(e.layout.graph.getLink(n.source,n.target).id),a=r[t?`source`:`from`],s=r[t?`target`:`to`];if(a&&s&&a.hasOwnProperty(`x`)&&s.hasOwnProperty(`x`)){var c=i(n);if(!c)n.__curve=null;else{var l=new xp.Vector3(a.x,a.y||0,a.z||0),u=new xp.Vector3(s.x,s.y||0,s.z||0),d=l.distanceTo(u),f,p=o(n);if(d>0){var m=s.x-a.x,h=s.y-a.y||0,g=new xp.Vector3().subVectors(u,l),_=g.clone().multiplyScalar(c).cross(m!==0||h!==0?new xp.Vector3(0,0,1):new xp.Vector3(0,1,0)).applyAxisAngle(g.normalize(),p).add(new xp.Vector3().addVectors(l,u).divideScalar(2));f=new xp.QuadraticBezierCurve3(l,_,u)}else{var v=c*70,y=-p,b=y+Math.PI/2;f=new xp.CubicBezierCurve3(l,new xp.Vector3(v*Math.cos(b),v*Math.sin(b),0).add(l),new xp.Vector3(v*Math.cos(y),v*Math.sin(y),0).add(l),u)}n.__curve=f}}}}function r(){var n=a(e.linkDirectionalArrowRelPos),r=a(e.linkDirectionalArrowLength),i=a(e.nodeVal);e.arrowDataMapper.entries().forEach(function(a){var o=np(a,2),s=o[0],c=o[1];if(c){var l=t?s:e.layout.getLinkPosition(e.layout.graph.getLink(s.source,s.target).id),u=l[t?`source`:`from`],d=l[t?`target`:`to`];if(u&&d&&u.hasOwnProperty(`x`)&&d.hasOwnProperty(`x`)){var f=Math.cbrt(Math.max(0,i(u)||1))*e.nodeRelSize,p=Math.cbrt(Math.max(0,i(d)||1))*e.nodeRelSize,m=r(s),h=n(s),g=s.__curve?function(e){return s.__curve.getPoint(e)}:function(e){var t=function(e,t,n,r){return t[e]+(n[e]-t[e])*r||0};return{x:t(`x`,u,d,e),y:t(`y`,u,d,e),z:t(`z`,u,d,e)}},_=s.__curve?s.__curve.getLength():Math.sqrt([`x`,`y`,`z`].map(function(e){return((d[e]||0)-(u[e]||0))**2}).reduce(function(e,t){return e+t},0)),v=f+m+(_-f-p-m)*h,y=g(v/_),b=g((v-m)/_);[`x`,`y`,`z`].forEach(function(e){return c.position[e]=b[e]});var x=Bf(xp.Vector3,ap([`x`,`y`,`z`].map(function(e){return y[e]})));c.parent.localToWorld(x),c.lookAt(x)}}})}function i(){var n=a(e.linkDirectionalParticleSpeed),r=a(e.linkDirectionalParticleOffset);e.graphData.links.forEach(function(i){var a=e.particlesDataMapper.getObj(i),o=a&&a.children,s=i.__singleHopPhotonsObj&&i.__singleHopPhotonsObj.children;if(s&&s.length||o&&o.length){var c=t?i:e.layout.getLinkPosition(e.layout.graph.getLink(i.source,i.target).id),l=c[t?`source`:`from`],u=c[t?`target`:`to`];if(l&&u&&l.hasOwnProperty(`x`)&&u.hasOwnProperty(`x`)){var d=n(i),f=Math.abs(r(i)),p=i.__curve?function(e){return i.__curve.getPoint(e)}:function(e){var t=function(e,t,n,r){return t[e]+(n[e]-t[e])*r||0};return{x:t(`x`,l,u,e),y:t(`y`,l,u,e),z:t(`z`,l,u,e)}};[].concat(ap(o||[]),ap(s||[])).forEach(function(e,t){var n=e.parent.__linkThreeObjType===`singleHopPhotons`;if(e.hasOwnProperty(`__progressRatio`)||(e.__progressRatio=n?+(d<0):(t+f)/o.length),e.__progressRatio+=d,e.__progressRatio>=1||e.__progressRatio<0){if(!n)e.__progressRatio%=1,e.__progressRatio<0&&e.__progressRatio++;else{e.parent.remove(e),fp(e);return}}var r=e.__progressRatio,i=p(r);e.geometry.type!==`SphereGeometry`&&e.lookAt(i.x,i.y,i.z),[`x`,`y`,`z`].forEach(function(t){return e.position[t]=i[t]})})}}})}},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){var n=new xp.Group;n.__linkThreeObjType=`singleHopPhotons`,t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var r=a(e.linkDirectionalParticleThreeObject)(t);if(r&&e.linkDirectionalParticleThreeObject===r&&(r=r.clone()),!r){var i=a(e.linkDirectionalParticleWidth),o=Math.ceil(i(t)*10)/10/2,s=e.linkDirectionalParticleResolution,c=new xp.SphereGeometry(o,s,s),l=a(e.linkColor),u=a(e.linkDirectionalParticleColor)(t)||l(t)||`#f0f0f0`,d=new xp.Color(gp(u)),f=e.linkOpacity*3,p=new xp.MeshLambertMaterial({color:d,transparent:!0,opacity:f});r=new xp.Mesh(c,p)}t.__singleHopPhotonsObj.add(r)}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 e(n){var r=[];if(n.geometry){n.geometry.computeBoundingBox();var i=new xp.Box3;i.copy(n.geometry.boundingBox).applyMatrix4(n.matrixWorld),r.push(i)}return r.concat.apply(r,ap((n.children||[]).filter(function(e){return!e.hasOwnProperty(`__graphObjType`)||e.__graphObjType===`node`&&t(e.__data)}).map(e)))}(e.graphScene);return n.length?Object.assign.apply(Object,ap([`x`,`y`,`z`].map(function(e){return Uf({},e,[u(n,function(t){return t.min[e]}),v(n,function(t){return t.max[e]})])}))):null}},stateInit:function(){return{d3ForceLayout:c().force(`link`,s()).force(`charge`,d()).force(`center`,n()).force(`dagRadial`,null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new hp(e,{objBindAttr:`__threeObj`}),t.linkDataMapper=new hp(e,{objBindAttr:`__lineObj`}),t.arrowDataMapper=new hp(e,{objBindAttr:`__arrowObj`}),t.particlesDataMapper=new hp(e,{objBindAttr:`__photonsObj`})},update:function(e,t){var n=function(e){return e.some(function(e){return t.hasOwnProperty(e)})};if(e.engineRunning=!1,typeof e.onUpdate==`function`&&e.onUpdate(),e.nodeAutoColorBy!==null&&n([`nodeAutoColorBy`,`graphData`,`nodeColor`])&&yp(e.graphData.nodes,a(e.nodeAutoColorBy),e.nodeColor),e.linkAutoColorBy!==null&&n([`linkAutoColorBy`,`graphData`,`linkColor`])&&yp(e.graphData.links,a(e.linkAutoColorBy),e.linkColor),e._flushObjects||n([`graphData`,`nodeThreeObject`,`nodeThreeObjectExtend`,`nodeVal`,`nodeColor`,`nodeVisibility`,`nodeRelSize`,`nodeResolution`,`nodeOpacity`])){var r=a(e.nodeThreeObject),i=a(e.nodeThreeObjectExtend),o=a(e.nodeVal),s=a(e.nodeColor),c=a(e.nodeVisibility),l={},u={};(e._flushObjects||n([`nodeThreeObject`,`nodeThreeObjectExtend`]))&&e.nodeDataMapper.clear(),e.nodeDataMapper.onCreateObj(function(t){var n=r(t),a=i(t);n&&e.nodeThreeObject===n&&(n=n.clone());var o;return n&&!a?o=n:(o=new xp.Mesh,o.__graphDefaultObj=!0,n&&a&&o.add(n)),o.__graphObjType=`node`,o}).onUpdateObj(function(t,n){if(t.__graphDefaultObj){var r=o(n)||1,i=Math.cbrt(r)*e.nodeRelSize,a=e.nodeResolution;(!t.geometry.type.match(/^Sphere(Buffer)?Geometry$/)||t.geometry.parameters.radius!==i||t.geometry.parameters.widthSegments!==a)&&(l.hasOwnProperty(r)||(l[r]=new xp.SphereGeometry(i,a,a)),t.geometry.dispose(),t.geometry=l[r]);var c=s(n),d=new xp.Color(gp(c||`#ffffaa`)),f=e.nodeOpacity*_p(c);(t.material.type!==`MeshLambertMaterial`||!t.material.color.equals(d)||t.material.opacity!==f)&&(u.hasOwnProperty(c)||(u[c]=new xp.MeshLambertMaterial({color:d,transparent:!0,opacity:f})),t.material.dispose(),t.material=u[c])}}).digest(e.graphData.nodes.filter(c))}if(e._flushObjects||n([`graphData`,`linkThreeObject`,`linkThreeObjectExtend`,`linkMaterial`,`linkColor`,`linkWidth`,`linkVisibility`,`linkResolution`,`linkOpacity`,`linkDirectionalArrowLength`,`linkDirectionalArrowColor`,`linkDirectionalArrowResolution`,`linkDirectionalParticles`,`linkDirectionalParticleWidth`,`linkDirectionalParticleColor`,`linkDirectionalParticleResolution`,`linkDirectionalParticleThreeObject`])){var d=a(e.linkThreeObject),f=a(e.linkThreeObjectExtend),p=a(e.linkMaterial),h=a(e.linkVisibility),g=a(e.linkColor),_=a(e.linkWidth),v={},y={},b={},x=e.graphData.links.filter(h);if((e._flushObjects||n([`linkThreeObject`,`linkThreeObjectExtend`,`linkWidth`]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj(function(e){var t=e.__data&&e.__data.__singleHopPhotonsObj;t&&(t.parent.remove(t),fp(t),delete e.__data.__singleHopPhotonsObj)}).onCreateObj(function(t){var n=d(t),r=f(t);n&&e.linkThreeObject===n&&(n=n.clone());var i;if(!n||r){if(_(t))i=new xp.Mesh;else{var a=new xp.BufferGeometry;a[wp](`position`,new xp.BufferAttribute(new Float32Array(6),3)),i=new xp.Line(a)}}var o;return n?r?(o=new xp.Group,o.__graphDefaultObj=!0,o.add(i),o.add(n)):o=n:(o=i,o.__graphDefaultObj=!0),o.renderOrder=10,o.__graphObjType=`link`,o}).onUpdateObj(function(t,n){if(t.__graphDefaultObj){var r=t.children.length?t.children[0]:t,i=Math.ceil(_(n)*10)/10,a=!!i;if(a){var o=i/2,s=e.linkResolution;if(!r.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||r.geometry.parameters.radiusTop!==o||r.geometry.parameters.radialSegments!==s){if(!v.hasOwnProperty(i)){var c=new xp.CylinderGeometry(o,o,1,s,1,!1);c[Tp](new xp.Matrix4().makeTranslation(0,1/2,0)),c[Tp](new xp.Matrix4().makeRotationX(Math.PI/2)),v[i]=c}r.geometry.dispose(),r.geometry=v[i]}}var l=p(n);if(l)r.material=l;else{var u=g(n),d=new xp.Color(gp(u||`#f0f0f0`)),f=e.linkOpacity*_p(u),m=a?`MeshLambertMaterial`:`LineBasicMaterial`;if(r.material.type!==m||!r.material.color.equals(d)||r.material.opacity!==f){var h=a?y:b;h.hasOwnProperty(u)||(h[u]=new xp[m]({color:d,transparent:f<1,opacity:f,depthWrite:f>=1})),r.material.dispose(),r.material=h[u]}}}}).digest(x),e.linkDirectionalArrowLength||t.hasOwnProperty(`linkDirectionalArrowLength`)){var S=a(e.linkDirectionalArrowLength),C=a(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj(function(){var e=new xp.Mesh(void 0,new xp.MeshLambertMaterial({transparent:!0}));return e.__linkThreeObjType=`arrow`,e}).onUpdateObj(function(t,n){var r=S(n),i=e.linkDirectionalArrowResolution;if(!t.geometry.type.match(/^Cone(Buffer)?Geometry$/)||t.geometry.parameters.height!==r||t.geometry.parameters.radialSegments!==i){var a=new xp.ConeGeometry(r*.25,r,i);a.translate(0,r/2,0),a.rotateX(Math.PI/2),t.geometry.dispose(),t.geometry=a}var o=C(n)||g(n)||`#f0f0f0`;t.material.color=new xp.Color(gp(o)),t.material.opacity=e.linkOpacity*3*_p(o)}).digest(x.filter(S))}if(e.linkDirectionalParticles||t.hasOwnProperty(`linkDirectionalParticles`)){var w=a(e.linkDirectionalParticles),T=a(e.linkDirectionalParticleWidth),E=a(e.linkDirectionalParticleColor),D=a(e.linkDirectionalParticleThreeObject),O={},k={};e.particlesDataMapper.onCreateObj(function(){var e=new xp.Group;return e.__linkThreeObjType=`photons`,e.__photonDataMapper=new hp(e),e}).onUpdateObj(function(t,n){var r=!!t.children.length&&t.children[0],i=D(n),a,o;if(i)a=i.geometry,o=i.material;else{var s=Math.ceil(T(n)*10)/10/2,c=e.linkDirectionalParticleResolution;r&&r.geometry.parameters.radius===s&&r.geometry.parameters.widthSegments===c?a=r.geometry:(k.hasOwnProperty(s)||(k[s]=new xp.SphereGeometry(s,c,c)),a=k[s]);var l=E(n)||g(n)||`#f0f0f0`,u=new xp.Color(gp(l)),d=e.linkOpacity*3;r&&r.material.color.equals(u)&&r.material.opacity===d?o=r.material:(O.hasOwnProperty(l)||(O[l]=new xp.MeshLambertMaterial({color:u,transparent:!0,opacity:d})),o=O[l])}r&&(r.geometry!==a&&r.geometry.dispose(),r.material!==o&&r.material.dispose());var f=Math.round(Math.abs(w(n)));t.__photonDataMapper.id(function(e){return e.idx}).onCreateObj(function(){return new xp.Mesh(a,o)}).onUpdateObj(function(e){e.geometry=a,e.material=o}).digest(ap(Array(f)).map(function(e,t){return{idx:t}}))}).digest(x.filter(w))}}if(e._flushObjects=!1,n([`graphData`,`nodeId`,`linkSource`,`linkTarget`,`numDimensions`,`forceEngine`,`dagMode`,`dagNodeFilter`,`dagLevelDistance`])){e.engineRunning=!1,e.graphData.links.forEach(function(t){t.source=t[e.linkSource],t.target=t[e.linkTarget]});var ee=e.forceEngine!==`ngraph`,te;if(ee){(te=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);var ne=e.d3ForceLayout.force(`link`);ne&&ne.id(function(t){return t[e.nodeId]}).links(e.graphData.links);var re=e.dagMode&&bp(e.graphData,function(t){return t[e.nodeId]},{nodeFilter:e.dagNodeFilter,onLoopError:e.onDagError||void 0}),ie=Math.max.apply(Math,ap(Object.values(re||[]))),ae=e.dagLevelDistance||e.graphData.nodes.length/(ie||1)*Cp*([`radialin`,`radialout`].indexOf(e.dagMode)===-1?1:.7);if([`lr`,`rl`,`td`,`bu`,`zin`,`zout`].includes(t.dagMode)){var oe=[`lr`,`rl`].includes(t.dagMode)?`fx`:[`td`,`bu`].includes(t.dagMode)?`fy`:`fz`;e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(e){return delete e[oe]})}if([`lr`,`rl`,`td`,`bu`,`zin`,`zout`].includes(e.dagMode)){var se=[`rl`,`td`,`zout`].includes(e.dagMode),ce=function(t){return(re[t[e.nodeId]]-ie/2)*ae*(se?-1:1)},le=[`lr`,`rl`].includes(e.dagMode)?`fx`:[`td`,`bu`].includes(e.dagMode)?`fy`:`fz`;e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(e){return e[le]=ce(e)})}e.d3ForceLayout.force(`dagRadial`,[`radialin`,`radialout`].indexOf(e.dagMode)===-1?null:m(function(t){var n=re[t[e.nodeId]]||-1;return(e.dagMode===`radialin`?ie-n:n)*ae}).strength(function(t){return+!!e.dagNodeFilter(t)}))}else{var ue=Sp.graph();e.graphData.nodes.forEach(function(t){ue.addNode(t[e.nodeId])}),e.graphData.links.forEach(function(e){ue.addLink(e.source,e.target)}),te=Sp.forcelayout(ue,$f({dimensions:e.numDimensions},e.ngraphPhysics)),te.graph=ue}for(var de=0;de<e.warmupTicks&&!(ee&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin);de++)te[ee?`tick`:`step`]();e.layout=te,this.resetCountdown()}e.engineRunning=!0,e.onFinishUpdate()}});function Dp(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Object,n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=function(t){function r(){var t;If(this,r);var i=[...arguments];return t=Pf(this,r,[].concat(i)),t.__kapsuleInstance=Bf(e,[].concat(ap(n?[t]:[]),i)),t}return Kf(r,t),Hf(r)}(t);return Object.keys(e()).forEach(function(e){return r.prototype[e]=function(){var t,n=(t=this.__kapsuleInstance)[e].apply(t,arguments);return n===this.__kapsuleInstance?this:n}}),r}var Op=Dp(Ep,(window.THREE?window.THREE:{Group:mr}).Group,!0),kp=`alphaMap.alphaTest.anisotropy.anisotropyMap.anisotropyRotation.aoMap.aoMapIntensity.attenuationColor.attenuationDistance.bumpMap.bumpScale.clearcoat.clearcoatMap.clearcoatNormalMap.clearcoatNormalScale.clearcoatRoughness.color.dashOffset.dashSize.dispersion.displacementBias.displacementMap.displacementScale.emissive.emissiveIntensity.emissiveMap.envMap.envMapIntensity.envMapRotation.gapSize.gradientMap.ior.iridescence.iridescenceIOR.iridescenceMap.iridescenceThickness.iridescenceThicknessMap.lightMap.lightMapIntensity.linewidth.map.matcap.metalness.metalnessMap.normalMap.normalScale.opacity.reflectivity.retroreflectivity.rotation.roughness.roughnessMap.scale.sheen.sheenColor.sheenColorMap.sheenRoughness.sheenRoughnessMap.shininess.size.specular.specularColor.specularColorMap.specularIntensity.specularIntensityMap.specularMap.steps.thickness.transmission.transmissionMap`.split(`.`),Ap=new WeakMap,jp=new WeakMap,Mp=new WeakMap,Np=new WeakMap,Pp=class{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=e.object.isSkinnedMesh===!0,this.refreshUniforms=kp,this.renderId=0}firstInitialization(e){return this.renderObjects.has(e)===!1&&(this.getRenderObjectData(e),!0)}hasDynamicInstancing(e){return e.isInstancedMesh===!0&&(e.instanceMatrix.usage===35048||e.instanceColor!==null&&e.instanceColor.usage===35048)}needsVelocity(e){let t=e.getMRT();return t!==null&&t.has(`velocity`)}getRenderObjectData(e){let t=this.renderObjects.get(e);if(t===void 0){let{geometry:n,object:r}=e;if(t={geometryId:n.id,geometryVersion:this.getGeometryData(n)._version,materialVersion:this.getMaterialData(e.material)._version,worldMatrix:r.matrixWorld.clone()},r.center&&(t.center=r.center.clone()),r.morphTargetInfluences&&(t.morphTargetInfluences=r.morphTargetInfluences.slice()),r.isInstancedMesh===!0&&(t.instanceMatrixVersion=r.instanceMatrix.version,t.instanceColorVersion=r.instanceColor===null?null:r.instanceColor.version,t.morphTextureVersion=r.morphTexture===null?null:r.morphTexture.version),r.isBatchedMesh===!0&&(t.matricesTextureVersion=r._matricesTexture.version,t.colorsTextureVersion=r._colorsTexture===null?null:r._colorsTexture.version,t.indirectTextureVersion=r._indirectTexture.version),e.bundle!==null&&(t.version=e.bundle.version),e.material.transmission>0){let{width:n,height:r}=e.context;t.bufferWidth=n,t.bufferHeight=r}let{environmentIntensity:i,environmentRotation:a}=e.scene;t.environmentIntensity=i,t.environmentRotation=a.clone(),t.lights=this.getLightsData(e.lightsNode.getBuiltinLights(),[]),this.renderObjects.set(e,t)}return t}getAttributesData(e){let t={};for(let n in e){let r=e[n];t[n]={id:r.isInterleavedBufferAttribute?r.data.uuid:r.id,version:r.isInterleavedBufferAttribute?r.data.version:r.version}}return t}containsNode(e){let t=e.material;for(let e in t)if(t[e]&&t[e].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getGeometryData(e){let t=Mp.get(e);return t===void 0&&(t={_renderId:-1,_version:0,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},e.addEventListener(`dispose`,()=>{t._version++}),Mp.set(e,t)),t}getTextureData(e){let t=Np.get(e);if(t===void 0){t={_version:0};let n=()=>{t._version++};e.renderTarget===null?e.addEventListener(`dispose`,n):e.renderTarget.addEventListener(`dispose`,n),Np.set(e,t)}return t}getMaterialData(e){let t=jp.get(e);if(t===void 0){t={_renderId:-1,_version:0};for(let n of this.refreshUniforms){let r=e[n];r!==void 0&&(r===null?t[n]=null:typeof r==`object`&&r.clone!==void 0?r.isTexture===!0?t[n]={id:r.id,version:0,cacheVersion:this.getTextureData(r)._version}:t[n]=r.clone():t[n]=r)}jp.set(e,t)}return t}equals(e,t,n){let{object:r,material:i,geometry:a}=e,o=this.getRenderObjectData(e);if(o.worldMatrix.equals(r.matrixWorld)!==!0)return o.worldMatrix.copy(r.matrixWorld),!1;let s=this.getMaterialData(e.material);if(s._renderId!==n){s._renderId=n;let e=!1;for(let t in s){let n=s[t],r=i[t];if(t!==`_renderId`&&t!==`_version`){if(n===null||r==null)n!==(r===void 0?null:r)&&(s[t]=r==null?null:r.isTexture===!0?{id:r.id,version:r.version,cacheVersion:this.getTextureData(r)._version}:typeof r==`object`&&r.clone!==void 0?r.clone():r,e=!0);else if(n.equals!==void 0)n.equals(r)===!1&&(n.copy(r),e=!0);else if(r.isTexture===!0){let t=this.getTextureData(r);(n.id!==r.id||n.version!==r.version||n.cacheVersion!==t._version)&&(n.id=r.id,n.version=r.version,n.cacheVersion=t._version,e=!0)}else n!==r&&(s[t]=r,e=!0)}}e===!0&&s._version++}if(o.materialVersion!==s._version)return o.materialVersion=s._version,!1;if(s.transmission>0){let{width:t,height:n}=e.context;if(o.bufferWidth!==t||o.bufferHeight!==n)return o.bufferWidth=t,o.bufferHeight=n,!1}if(o.geometryId!==a.id)return o.geometryId=a.id,o.geometryVersion=this.getGeometryData(a)._version,!1;let c=this.getGeometryData(e.geometry);if(c._renderId!==n){c._renderId=n;let e=!1,t=a.attributes,r=c.attributes,i=0,o=0;for(let e in t)i++;for(let n in r){o++;let i=r[n],a=t[n];if(a===void 0){delete r[n],e=!0;continue}let s=a.isInterleavedBufferAttribute?a.data.uuid:a.id,c=a.isInterleavedBufferAttribute?a.data.version:a.version;(i.id!==s||i.version!==c)&&(i.id=s,i.version=c,e=!0)}o!==i&&(c.attributes=this.getAttributesData(t),e=!0);let s=a.index,l=s?s.id:null,u=s?s.version:null;(c.indexId!==l||c.indexVersion!==u)&&(c.indexId=l,c.indexVersion=u,e=!0),(c.drawRange.start!==a.drawRange.start||c.drawRange.count!==a.drawRange.count)&&(c.drawRange.start=a.drawRange.start,c.drawRange.count=a.drawRange.count,e=!0),e===!0&&c._version++}if(o.geometryVersion!==c._version)return o.geometryVersion=c._version,!1;if(o.morphTargetInfluences){let e=!1;for(let t=0;t<o.morphTargetInfluences.length;t++)o.morphTargetInfluences[t]!==r.morphTargetInfluences[t]&&(o.morphTargetInfluences[t]=r.morphTargetInfluences[t],e=!0);if(e)return!1}if(r.isInstancedMesh===!0){let e=r.instanceColor===null?null:r.instanceColor.version,t=r.morphTexture===null?null:r.morphTexture.version;if(o.instanceMatrixVersion!==r.instanceMatrix.version||o.instanceColorVersion!==e||o.morphTextureVersion!==t)return o.instanceMatrixVersion=r.instanceMatrix.version,o.instanceColorVersion=e,o.morphTextureVersion=t,!1}if(r.isBatchedMesh===!0){let e=r._colorsTexture===null?null:r._colorsTexture.version;if(o.matricesTextureVersion!==r._matricesTexture.version||o.colorsTextureVersion!==e||o.indirectTextureVersion!==r._indirectTexture.version)return o.matricesTextureVersion=r._matricesTexture.version,o.colorsTextureVersion=e,o.indirectTextureVersion=r._indirectTexture.version,!1}if(o.lights)for(let e=0;e<t.length;e++){let n=o.lights[e],r=t[e];if(n.map!==r.map||n.cacheVersion!==r.cacheVersion||n.shadowMapWidth!==r.shadowMapWidth||n.shadowMapHeight!==r.shadowMapHeight)return n.map=r.map,n.cacheVersion=r.cacheVersion,n.shadowMapWidth=r.shadowMapWidth,n.shadowMapHeight=r.shadowMapHeight,!1}let l=e.scene;return l.environment!==null&&i.envMap===null&&(o.environmentIntensity!==l.environmentIntensity||o.environmentRotation.equals(l.environmentRotation)===!1)?(o.environmentIntensity=l.environmentIntensity,o.environmentRotation.copy(l.environmentRotation),!1):o.center&&o.center.equals(r.center)===!1?(o.center.copy(r.center),!1):(e.bundle!==null&&(o.version=e.bundle.version),!0)}getLightsData(e,t){t.length=0;for(let n of e){let e=null;n.isSpotLight===!0&&n.map!==null&&(e={map:n.map.version,cacheVersion:this.getTextureData(n.map)._version}),n.castShadow===!0&&n.shadow!==void 0&&(e===null&&(e={}),e.shadowMapWidth=n.shadow.mapSize.width,e.shadowMapHeight=n.shadow.mapSize.height),e!==null&&t.push(e)}return t}getLights(e,t){let n=Ap.get(e);return n===void 0&&(n={renderId:-1,lightsData:[]},Ap.set(e,n)),n.renderId===t?n.lightsData:(n.renderId=t,this.getLightsData(e.getBuiltinLights(),n.lightsData),n.lightsData)}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.hasDynamicInstancing(e.object)||this.firstInitialization(e)||this.needsVelocity(t.renderer))return At.FULL;let{renderId:n}=t,r=At.NONE;this.renderId!==n&&(this.renderId=n,r=At.SHARED);let i=e.object.static===!0,a=e.bundle!==null&&e.bundle.static===!0&&this.getRenderObjectData(e).version===e.bundle.version;if(i||a)return r;let o=this.getLights(e.lightsNode,n);return this.equals(e,o,n)===!1&&(r=At.FULL),r}},Fp=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];function Ip(e){let t=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return e.split(`
`).map(e=>{let n=e.match(t);if(!n)return null;let r=n[1]||n[2]||``,i=n[3].split(`?`)[0],a=parseInt(n[4],10),o=parseInt(n[5],10);return{fn:r,file:i.split(`/`).pop(),line:a,column:o}}).filter(e=>e&&!Fp.some(t=>t.test(e.file)))}var Lp=class{constructor(e=null){this.isStackTrace=!0,this.stack=Ip(e||Error().stack)}getLocation(){if(this.stack.length===0)return`[Unknown location]`;let e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:``}"${e.file}:${e.line}"`}getError(e){return this.stack.length===0?e:`${e}\n${this.stack.map(e=>{let t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join(`
`)}`}};function Rp(e,t=0){let n=3735928559^t,r=1103547991^t;if(Array.isArray(e))for(let t=0,i;t<e.length;t++)i=e[t],n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677);else for(let t=0,i;t<e.length;t++)i=e.charCodeAt(t),n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677);return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}var zp=e=>Rp(e),Bp=e=>Rp(e),Vp=(...e)=>Rp(e),Hp=new Map([[1,`float`],[2,`vec2`],[3,`vec3`],[4,`vec4`],[9,`mat3`],[16,`mat4`]]),Up=new WeakMap;function Wp(e){return Hp.get(e)}function Gp(e){if(e==null)return null;let t=typeof e;return e.isNode===!0?`node`:t===`number`?`float`:t===`boolean`?`bool`:t===`string`?`string`:t===`function`?`shader`:e.isVector2===!0?`vec2`:e.isVector3===!0?`vec3`:e.isVector4===!0?`vec4`:e.isMatrix2===!0?`mat2`:e.isMatrix3===!0?`mat3`:e.isMatrix4===!0?`mat4`:e.isColor===!0?`color`:e instanceof ArrayBuffer?`ArrayBuffer`:null}function Kp(e){if(e.isDepthTexture===!0)return`float`;let t=e.format,n;n=t===1028||t===1029||t===1026||t===1027||t===1021?1:t===1030||t===1031?2:t===1022||t===1032?3:4;let r;if(r=e.type===1014?`uint`:e.type===1013?`int`:`float`,n===1)return r;let i=Wp(n);return r!==`float`&&(i=r[0]+i),i}function qp(e,...t){let n=e?e.slice(-4):void 0;return t.length===1&&(n===`vec2`?t=[t[0],t[0]]:n===`vec3`?t=[t[0],t[0],t[0]]:n===`vec4`&&(t=[t[0],t[0],t[0],t[0]])),e===`color`?new L(...t):n===`vec2`?new P(...t):n===`vec3`?new F(...t):n===`vec4`?new Fn(...t):n===`mat2`?new Ws(...t):n===`mat3`?new bn(...t):n===`mat4`?new Bn(...t):e===`bool`?t[0]||!1:e===`float`||e===`int`||e===`uint`?t[0]||0:e===`string`?t[0]||``:e===`ArrayBuffer`?Xp(t[0]):null}function Jp(e){let t=Up.get(e);return t===void 0&&(t={},Up.set(e,t)),t}function Yp(e){let t=``,n=new Uint8Array(e);for(let e=0;e<n.length;e++)t+=String.fromCharCode(n[e]);return btoa(t)}function Xp(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0)).buffer}function Zp(e){return e[0]!==void 0&&e[0]!==null&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)}var Qp={VERTEX:`vertex`,FRAGMENT:`fragment`},$p={NONE:`none`,FRAME:`frame`,RENDER:`render`,OBJECT:`object`},em={READ_ONLY:`readOnly`,WRITE_ONLY:`writeOnly`,READ_WRITE:`readWrite`},tm=[`fragment`,`vertex`],nm=[`setup`,`analyze`,`generate`],rm=[...tm,`compute`],im=[`x`,`y`,`z`,`w`],am={analyze:`setup`,generate:`analyze`},om=0,z=class e extends Ht{static get type(){return`Node`}constructor(t=null){super(),this.nodeType=t,this.updateType=$p.NONE,this.updateBeforeType=$p.NONE,this.updateAfterType=$p.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=om++,this.stackTrace=null,e.captureStackTrace===!0&&(this.stackTrace=new Lp)}set needsUpdate(e){e===!0&&this.version++}get uuid(){return this._uuid===null&&(this._uuid=gn.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,$p.FRAME)}onRenderUpdate(e){return this.onUpdate(e,$p.RENDER)}onObjectUpdate(e){return this.onUpdate(e,$p.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(let{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:`dispose`})}traverse(e){e(this);for(let t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){let t=[];e.add(this);for(let n of Object.getOwnPropertyNames(this)){let r=this[n];if(!(n.startsWith(`_`)===!0||e.has(r))){if(Array.isArray(r)===!0)for(let e=0;e<r.length;e++){let i=r[e];i&&i.isNode===!0&&t.push({property:n,index:e,childNode:i})}else if(r&&r.isNode===!0)t.push({property:n,childNode:r});else if(r&&Object.getPrototypeOf(r)===Object.prototype)for(let e in r){if(e.startsWith(`_`)===!0)continue;let i=r[e];i&&i.isNode===!0&&t.push({property:n,index:e,childNode:i})}}}return t}getCacheKey(e=!1,t=null){if(e||=this.version!==this._cacheKeyVersion,e===!0||this._cacheKey===null){t===null&&(t=new Set);let n=[];for(let{property:r,childNode:i}of this._getChildren(t))n.push(zp(r.slice(0,-4)),i.getCacheKey(e,t));this._cacheKey=Vp(Bp(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){let t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return`void`}getNodeType(e,t=null){let n=e.getDataFromNode(this),r;return t===null?(r=n.type,r===void 0&&(r=this.generateNodeType(e),n.type=r)):(n.typeFromOutput=n.typeFromOutput||{},r=n.typeFromOutput[t],r===void 0&&(r=this.generateNodeType(e,t),n.typeFromOutput[t]=r)),r}generateNodeType(e,t=null){let n=e.getNodeProperties(this);return n.outputNode?n.outputNode.getNodeType(e,t):this.nodeType}getShared(e){let t=this.getHash(e),n=e.getNodeFromHash(t),r=null;if(n&&n!==this)r=n;else if(e.context.overrideNodes){let t=e.context.overrideNodes.get(this);if(t){let n=e.getDataFromNode(this);n.isOverwritten===!0?r=n.sharedNode:(n.isOverwritten=!0,r=t(e).overrideNode(this,null),n.sharedNode=r)}}return r||this}getArrayCount(){return null}setup(e){let t=e.getNodeProperties(this),n=0;for(let e of this.getChildren())t[`node`+n++]=e;return t.outputNode||null}analyze(e,t=null){let n=e.increaseUsage(this);if(this.parents===!0){let n=e.getDataFromNode(this,`any`);n.stages=n.stages||{},n.stages[e.shaderStage]=n.stages[e.shaderStage]||[],n.stages[e.shaderStage].push(t)}if(n===1){let t=e.getNodeProperties(this);for(let n of Object.values(t))n&&n.isNode===!0&&n.build(e,this)}}generate(e,t){let{outputNode:n}=e.getNodeProperties(this);if(n&&n.isNode===!0)return n.build(e,t)}updateBefore(){M(`Abstract function.`)}updateAfter(){M(`Abstract function.`)}update(){M(`Abstract function.`)}before(e){return this._beforeNodes===null&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){let n=this.getShared(e);if(this!==n)return n.build(e,t);if(this._beforeNodes!==null){let n=this._beforeNodes;this._beforeNodes=null;for(let r of n)r.build(e,t);this._beforeNodes=n}let r=e.getDataFromNode(this);r.buildStages=r.buildStages||{},r.buildStages[e.buildStage]=!0;let i=am[e.buildStage];if(i&&r.buildStages[i]!==!0){let t=e.getBuildStage();e.setBuildStage(i),this.build(e),e.setBuildStage(t)}e.addChain(this);let a=null,o=e.getBuildStage();if(o===`setup`){e.addNode(this),this.updateReference(e);let t=e.getNodeProperties(this);if(t.initialized!==!0){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(let n of Object.values(t))if(n&&n.isNode===!0){if(n.parents===!0){let t=e.getNodeProperties(n);t.parents=t.parents||[],t.parents.push(this)}n.build(e)}e.addSequentialNode(this)}a=t.outputNode}else if(o===`analyze`)this.analyze(e,t);else if(o===`generate`){if(this.generate.length<2){let n=this.getNodeType(e),r=e.getDataFromNode(this);a=r.snippet,a===void 0?r.generated===void 0?(r.generated=!0,a=this.generate(e)||``,r.snippet=a):(M(`Node: Recursion detected.`,this),a=`/* Recursion detected. */`):r.flowCodes!==void 0&&e.context.nodeBlock!==void 0&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),a=e.format(a,n,t)}else a=this.generate(e,t)||``;a===``&&t!==null&&t!==`void`&&t!==`OutputType`&&(N(`TSL: Invalid generated code, expected a "${t}".`),a=e.generateConst(t))}return e.removeChain(this),a}getSerializeChildren(){return this._getChildren()}serialize(e){let t=this.getSerializeChildren(),n={};for(let{property:r,index:i,childNode:a}of t)i===void 0?n[r]=a.toJSON(e.meta).uuid:(n[r]===void 0&&(n[r]=Number.isInteger(i)?[]:{}),n[r][i]=a.toJSON(e.meta).uuid);Object.keys(n).length>0&&(e.inputNodes=n)}deserialize(e){if(e.inputNodes!==void 0){let t=e.meta.nodes;for(let n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){let r=[];for(let i of e.inputNodes[n])r.push(t[i]);this[n]=r}else if(typeof e.inputNodes[n]==`object`){let r={};for(let i in e.inputNodes[n])r[i]=t[e.inputNodes[n][i]];this[n]=r}else{let r=e.inputNodes[n];this[n]=t[r]}}}toJSON(e){let{uuid:t,type:n}=this,r=e===void 0||typeof e==`string`;r&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];i===void 0&&(i={uuid:t,type:n,meta:e,metadata:{version:4.7,type:`Node`,generator:`Node.toJSON`}},r!==!0&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta);function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(r){let t=a(e.textures),n=a(e.images),r=a(e.nodes);t.length>0&&(i.textures=t),n.length>0&&(i.images=n),r.length>0&&(i.nodes=r)}return i}};z.captureStackTrace=!1;var sm=class extends z{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){let t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:`uint`)} ]`}},cm=class extends z{static get type(){return`ConvertNode`}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){let t=this.node.getNodeType(e),n=null;for(let r of this.convertTo.split(`|`))(n===null||e.getTypeLength(t)===e.getTypeLength(r))&&(n=r);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){let n=this.node,r=this.getNodeType(e),i=n.build(e,r);return e.format(i,r,t)}},lm=class extends z{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`){let n=e.getVectorType(this.getNodeType(e,t)),r=e.getDataFromNode(this);if(r.propertyName!==void 0)return e.format(r.propertyName,n,t);if(n!==`void`&&t!==`void`&&this.hasDependencies(e)){let i=super.build(e,n),a=e.getVarFromNode(this,null,n),o=e.getPropertyName(a);return e.addLineFlowCode(`${o} = ${i}`,this),r.snippet=i,r.propertyName=o,e.format(r.propertyName,n,t)}}return super.build(e,t)}},um=class extends lm{static get type(){return`JoinNode`}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(e){return this.nodeType===null?e.getTypeFromLength(this.nodes.reduce((t,n)=>t+e.getTypeLength(n.getNodeType(e)),0)):e.getVectorType(this.nodeType)}generate(e,t){let n=this.getNodeType(e),r=e.getTypeLength(n),i=this.nodes,a=e.getComponentType(n),o=[],s=0;for(let t of i){if(s>=r){N(`TSL: Length of parameters exceeds maximum length of function '${n}()' type.`,this.stackTrace);break}let i=t.getNodeType(e),c=e.getTypeLength(i),l;if(s+c>r&&(N(`TSL: Length of '${n}()' data exceeds maximum length of output type.`,this.stackTrace),c=r-s,i=e.getTypeFromLength(c)),s+=c,l=t.build(e,i),e.getComponentType(i)!==a){let t=e.getTypeFromLength(c,a);l=e.format(l,i,t)}o.push(l)}let c=`${e.getType(n)}( ${o.join(`, `)} )`;return e.format(c,n,t)}},dm=im.join(``),fm=class extends z{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(let t of this.components)e=Math.max(im.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){let n=this.node,r=e.getTypeLength(n.getNodeType(e)),i=null;if(r>1){let a=null;this.getVectorLength()>=r&&(a=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));let o=n.build(e,a);i=this.components.length===r&&this.components===dm.slice(0,this.components.length)?e.format(o,a,t):e.format(`${o}.${this.components}`,this.getNodeType(e),t)}else i=n.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}},pm=class extends lm{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){let{sourceNode:t,components:n,targetNode:r}=this,i=this.getNodeType(e),a=e.getComponentType(r.getNodeType(e)),o=e.getTypeFromLength(n.length,a),s=r.build(e,o),c=t.build(e,i),l=e.getTypeLength(i),u=[];for(let e=0;e<l;e++){let t=im[e];t===n[0]?(u.push(s),e+=n.length-1):u.push(c+`.`+t)}return`${e.getType(i)}( ${u.join(`, `)} )`}},mm=class extends lm{static get type(){return`FlipNode`}constructor(e,t){super(),this.sourceNode=e,this.components=t}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){let{components:t,sourceNode:n}=this,r=this.getNodeType(e),i=n.build(e),a=e.getVarFromNode(this),o=e.getPropertyName(a);e.addLineFlowCode(o+` = `+i,this);let s=e.getTypeLength(r),c=[],l=0;for(let e=0;e<s;e++){let n=im[e];n===t[l]?(c.push(`1.0 - `+(o+`.`+n)),l++):c.push(o+`.`+n)}return`${e.getType(r)}( ${c.join(`, `)} )`}},hm=class extends z{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?Gp(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=Gp(this.value),e.nodeType=this.nodeType,e.valueType===`ArrayBuffer`&&(e.value=Yp(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?qp(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){M(`Abstract function.`)}},gm=/float|u?int/,_m=class extends hm{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){let n=this.getNodeType(e);return gm.test(n)&&gm.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),n,t)}},vm=class extends z{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`;let n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}generate(e){if(this.hasMember(e)===!1){M(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);let t=this.getNodeType(e);return e.generateConst(t)}return this.structNode.build(e)+`.`+this.property}},ym=null,bm=new Map;function B(e,t){if(bm.has(e)){M(`TSL: Redefinition of method chaining '${e}'.`);return}if(typeof t!=`function`)throw Error(`THREE.TSL: Node element ${e} is not a function`);bm.set(e,t),e!==`assign`&&(z.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},z.prototype[e+`Assign`]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}var xm=e=>e.replace(/r|s/g,`x`).replace(/g|t/g,`y`).replace(/b|p/g,`z`).replace(/a|q/g,`w`),Sm=e=>xm(e).split(``).sort().join(``);z.prototype.assign=function(...e){if(this.isStackNode!==!0)return ym===null?N(`TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().`,new Lp):ym.assign(this,...e),this;{let t=bm.get(`assign`);return this.addToStack(t(...e))}},z.prototype.toVarIntent=function(){return this},z.prototype.get=function(e){return new vm(this,e)};var Cm={};function wm(e,t,n){Cm[e]=Cm[t]=Cm[n]={get(){this._cache=this._cache||{};let t=this._cache[e];return t===void 0&&(t=new fm(this,e),this._cache[e]=t),t},set(t){this[e].assign(V(t))}};let r=e.toUpperCase(),i=t.toUpperCase(),a=n.toUpperCase();z.prototype[`set`+r]=z.prototype[`set`+i]=z.prototype[`set`+a]=function(t){let n=Sm(e);return new pm(this,n,V(t))},z.prototype[`flip`+r]=z.prototype[`flip`+i]=z.prototype[`flip`+a]=function(){let t=Sm(e);return new mm(this,t)}}var Tm=[`x`,`y`,`z`,`w`],Em=[`r`,`g`,`b`,`a`],Dm=[`s`,`t`,`p`,`q`];for(let e=0;e<4;e++){let t=Tm[e],n=Em[e],r=Dm[e];wm(t,n,r);for(let i=0;i<4;i++){t=Tm[e]+Tm[i],n=Em[e]+Em[i],r=Dm[e]+Dm[i],wm(t,n,r);for(let a=0;a<4;a++){t=Tm[e]+Tm[i]+Tm[a],n=Em[e]+Em[i]+Em[a],r=Dm[e]+Dm[i]+Dm[a],wm(t,n,r);for(let o=0;o<4;o++)t=Tm[e]+Tm[i]+Tm[a]+Tm[o],n=Em[e]+Em[i]+Em[a]+Em[o],r=Dm[e]+Dm[i]+Dm[a]+Dm[o],wm(t,n,r)}}}for(let e=0;e<32;e++)Cm[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return t===void 0&&(t=new sm(this,new _m(e,`uint`)),this._cache[e]=t),t},set(t){this[e].assign(V(t))}};Object.defineProperties(z.prototype,Cm);var Om=function(e,t=null){let n=Gp(e);return n===`node`?e:t===null&&(n===`float`||n===`boolean`)||n&&n!==`shader`&&n!==`string`?V(qm(e,t)):n===`shader`?e.isFn?e:W(e):e},km=function(e,t=null){for(let n in e)e[n]=V(e[n],t);return e},Am=function(e,t=null){let n=e.length;for(let r=0;r<n;r++)e[r]=V(e[r],t);return e},jm=function(e,t=null,n=null,r=null){function i(e){return r===null?e=V(e):(e=V(Object.assign(e,r)),r.intent===!0&&(e=e.toVarIntent())),e}let a,o=t,s,c;function l(t){let n;return n=o?/[a-z]/i.test(o)?o+`()`:o:e.type,s!==void 0&&t.length<s?(N(`TSL: "${n}" parameter length is less than minimum required.`,new Lp),t.concat(Array(s-t.length).fill(0))):c!==void 0&&t.length>c?(N(`TSL: "${n}" parameter length exceeds limit.`,new Lp),t.slice(0,c)):t}return t===null?a=(...t)=>i(new e(...eh(l(t)))):n===null?a=(...n)=>i(new e(t,...eh(l(n)))):(n=V(n),a=(...r)=>i(new e(t,...eh(l(r)),n))),a.setParameterLength=(...e)=>(e.length===1?s=c=e[0]:e.length===2&&([s,c]=e),a),a.setName=e=>(o=e,a),a},Mm=function(e,...t){return new e(...eh(t))},Nm=class extends z{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){let{shaderNode:t,rawInputs:n}=this,r=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||``,a=i||`default`;if(r[a])return r[a];let o=e.subBuildFn,s=e.fnCall;e.subBuildFn=i,e.fnCall=this;let c=null;if(t.layout){if(n){let r=t.layout.inputs;if(Zp(n)){let t=n;for(let n=0;n<r.length;n++){let r=t[n];r&&r.isNode&&r.build(e)}}else{let t=n[0];for(let n of r){let r=t[n.name];r&&r.isNode&&r.build(e)}}}let r=e.buildFunctionNode(t);e.addInclude(r);let i=n?Pm(n):null;c=r.call(i)}else{let r=new Proxy(e,{get:(e,t,n)=>{let r;return r=Symbol.iterator===t?function*(){yield void 0}:Reflect.get(e,t,n),r}}),i=n?Fm(n):null,a=Array.isArray(n)?n.length>0:n!==null,o=t.jsFunc;c=V(a||o.length>1?o(i,r):o(r))}return e.subBuildFn=o,e.fnCall=s,t.once&&(r[a]=c),c}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){let 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,r=e.getBuildStage(),i=e.getNodeProperties(this),a=e.getSubBuildOutput(this),o=this.getOutputNode(e),s=e.fnCall;if(e.fnCall=this,r===`setup`){let t=e.getSubBuildProperty(`initialized`,this);if(i[t]!==!0&&(i[t]=!0,i[a]=this.getOutputNode(e),i[a].build(e),this.shaderNode.subBuilds))for(let t of e.chaining){let n=e.getDataFromNode(t,`any`);n.subBuilds=n.subBuilds||new Set;for(let e of this.shaderNode.subBuilds)n.subBuilds.add(e)}n=i[a]}else r===`analyze`?o.build(e,t):r===`generate`&&(n=o.build(e,t)||``);return e.fnCall=s,n}};function Pm(e){let t;return $m(e),t=Zp(e)?[...e]:e[0],t}function Fm(e){let t=0;return $m(e),new Proxy(e,{get:(n,r,i)=>{let a;if(r===`length`)return a=e.length,a;if(Symbol.iterator===r)a=function*(){for(let t of e)yield V(t)};else{if(e.length>0){if(Object.getPrototypeOf(e[0])===Object.prototype){let n=e[0];a=n[r]===void 0?n[t++]:Reflect.get(n,r,i)}else e[0]instanceof z&&(a=e[r]===void 0?e[t++]:Reflect.get(e,r,i))}else a=Reflect.get(n,r,i);a=V(a)}return a}})}var Im=class extends z{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 Nm(this,e)}setup(){return this.call()}},Lm=[!1,!0],Rm=[0,1,2,3],zm=[-1,-2],Bm=[.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],Vm=new Map;for(let e of Lm)Vm.set(e,new _m(e));var Hm=new Map;for(let e of Rm)Hm.set(e,new _m(e,`uint`));var Um=new Map([...Hm].map(e=>new _m(e.value,`int`)));for(let e of zm)Um.set(e,new _m(e,`int`));var Wm=new Map([...Um].map(e=>new _m(e.value)));for(let e of Bm)Wm.set(e,new _m(e));for(let e of Bm)Wm.set(-e,new _m(-e));var Gm={bool:Vm,uint:Hm,ints:Um,float:Wm},Km=new Map([...Vm,...Wm]),qm=(e,t)=>Km.has(e)?Km.get(e):e.isNode===!0?e:new _m(e,t),Jm=function(e,t=null){return(...n)=>{for(let t of n)if(t===void 0)return N(`TSL: Invalid parameter for the type "${e}".`,new Lp),new _m(0,e);if((n.length===0||![`bool`,`float`,`int`,`uint`].includes(e)&&n.every(e=>{let t=typeof e;return t!==`object`&&t!==`function`}))&&(n=[qp(e,...n)]),n.length===1&&t!==null&&t.has(n[0]))return Qm(t.get(n[0]));if(n.length===1){let t=qm(n[0],e);return t.nodeType===e?Qm(t):Qm(new cm(t,e))}return Qm(new um(n.map(e=>qm(e)),e))}};function Ym(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),!!e}var Xm=e=>e==null?null:e.nodeType||e.convertTo||(typeof e==`string`?e:null);function Zm(e,t){return new Im(e,t)}var V=(e,t=null)=>Om(e,t),Qm=(e,t=null)=>V(e,t).toVarIntent(),$m=(e,t=null)=>new km(e,t),eh=(e,t=null)=>new Am(e,t),th=(e,t=null,n=null,r=null)=>new jm(e,t,n,r),H=(e,...t)=>new Mm(e,...t),U=(e,t=null,n=null,r={})=>new jm(e,t,n,{...r,intent:!0}),nh=0,rh=class extends z{constructor(e,t=null){super();let n=null;t!==null&&(typeof t==`object`?n=t.return:(typeof t==`string`?n=t:N(`TSL: Invalid layout type.`,new Lp),t=null)),this.shaderNode=new Zm(e,n),t!==null&&this.setLayout(t),this.isFn=!0}setLayout(e){let t=this.shaderNode.nodeType;if(typeof e.inputs!=`object`){let n={name:`fn`+nh++,type:t,inputs:[]};for(let t in e)t!==`return`&&n.inputs.push({name:t,type:e[t]});e=n}return this.shaderNode.setLayout(e),this}generateNodeType(e){return this.shaderNode.getNodeType(e)||`float`}call(...e){let 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){let t=this.getNodeType(e);return N(`TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".`,this.stackTrace),e.generateConst(t)}};function W(e,t=null){let n=new rh(e,t);return new Proxy(()=>{},{apply(e,t,r){return n.call(...r)},get(e,t,r){return Reflect.get(n,t,r)},set(e,t,r,i){return Reflect.set(n,t,r,i)}})}var ih=e=>{ym=e},ah=()=>ym,oh=(...e)=>ym.If(...e);function sh(e){return ym&&ym.addToStack(e),e}B(`toStack`,sh);var ch=new Jm(`color`),G=new Jm(`float`,Gm.float),lh=new Jm(`int`,Gm.ints),uh=new Jm(`uint`,Gm.uint),dh=new Jm(`bool`,Gm.bool),fh=new Jm(`vec2`),ph=new Jm(`ivec2`),mh=new Jm(`uvec2`),hh=new Jm(`bvec2`),K=new Jm(`vec3`),gh=new Jm(`ivec3`),_h=new Jm(`uvec3`),vh=new Jm(`bvec3`),q=new Jm(`vec4`),yh=new Jm(`ivec4`),bh=new Jm(`uvec4`),xh=new Jm(`bvec4`),Sh=new Jm(`mat2`),Ch=new Jm(`mat3`),wh=new Jm(`mat4`);B(`toColor`,ch),B(`toFloat`,G),B(`toInt`,lh),B(`toUint`,uh),B(`toBool`,dh),B(`toVec2`,fh),B(`toIVec2`,ph),B(`toUVec2`,mh),B(`toBVec2`,hh),B(`toVec3`,K),B(`toIVec3`,gh),B(`toUVec3`,_h),B(`toBVec3`,vh),B(`toVec4`,q),B(`toIVec4`,yh),B(`toUVec4`,bh),B(`toBVec4`,xh),B(`toMat2`,Sh),B(`toMat3`,Ch),B(`toMat4`,wh),B(`element`,th(sm).setParameterLength(2)),B(`convert`,(e,t)=>new cm(V(e),t));var Th=class extends z{static get type(){return`PropertyNode`}constructor(e,t=null,n=!1,r=null){super(e),this.name=t,this.varying=n,this.placeholderNode=V(r),this.isPropertyNode=!0,this.global=!0}getNodeType(e){let t=super.getNodeType(e);return t===`output`?e.getOutputType():t}customCacheKey(){return zp(this.type+`:`+(this.name||``)+`:`+(this.varying?`1`:`0`))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;if(this.varying===!0)t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0;else if(t=e.getVarFromNode(this,this.name),this.placeholderNode!==null&&e.hasWriteUsage(this)===!1){let n=this.placeholderNode.build(e,this.getNodeType(e));e.addLineFlowCode(`${e.getPropertyName(t)} = ${n}`,this)}return e.getPropertyName(t)}},Eh=(e,t,n=null)=>new Th(e,t,!1,n),Dh=(e,t,n=null)=>new Th(e,t,!0,n),Oh=H(Th,`vec4`,`DiffuseColor`),kh=H(Th,`vec3`,`DiffuseContribution`),Ah=H(Th,`vec3`,`EmissiveColor`),jh=H(Th,`float`,`Roughness`),Mh=H(Th,`float`,`Metalness`),Nh=H(Th,`float`,`Clearcoat`),Ph=H(Th,`float`,`ClearcoatRoughness`),Fh=H(Th,`vec3`,`Sheen`),Ih=H(Th,`float`,`SheenRoughness`),Lh=H(Th,`float`,`Iridescence`),Rh=H(Th,`float`,`IridescenceIOR`),zh=H(Th,`float`,`IridescenceThickness`),Bh=H(Th,`float`,`AlphaT`),Vh=H(Th,`float`,`Anisotropy`),Hh=H(Th,`vec3`,`AnisotropyT`),Uh=H(Th,`vec3`,`AnisotropyB`),Wh=H(Th,`color`,`SpecularColor`),Gh=H(Th,`color`,`SpecularColorBlended`),Kh=H(Th,`float`,`SpecularF90`),qh=H(Th,`float`,`Shininess`),Jh=H(Th,`output`,`Output`),Yh=H(Th,`float`,`dashSize`),Xh=H(Th,`float`,`gapSize`),Zh=H(Th,`float`,`IOR`),Qh=H(Th,`float`,`Transmission`),$h=H(Th,`float`,`Thickness`),eg=H(Th,`float`,`AttenuationDistance`),tg=H(Th,`color`,`AttenuationColor`),ng=H(Th,`float`,`Dispersion`),rg=H(Th,`float`,`Retroreflectivity`),ig=H(Th,`float`,`AmbientOcclusion`,!1,1),ag=class extends z{static get type(){return`UniformGroupNode`}constructor(e,t=!1,n=1,r=null){super(`string`),this.name=e,this.shared=t,this.order=n,this.updateType=r,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}},og=(e,t=1,n=null)=>new ag(e,!1,t,n),sg=(e,t=0,n=null)=>new ag(e,!0,t,n);$p.FRAME;var J=sg(`render`,0,$p.RENDER),cg=og(`object`,1,$p.OBJECT),lg=class extends hm{static get type(){return`UniformNode`}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name=``,this.groupNode=cg}setName(e){return this.name=e,this}label(e){return M(`TSL: "label()" has been deprecated. Use "setName()" instead.`,new Lp),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}getSharedNode(e){let t=this.getUniformHash(e),n=e.getNodeFromHash(t);return n===void 0&&(e.setHashNode(this,t),n=this),n}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{let n=e(t,this);n!==void 0&&(this.value=n)},t)}getInputType(e){let t=super.getInputType(e);return t===`bool`&&(t=`uint`),t}generate(e,t){let n=this.getNodeType(e),r=this.getSharedNode(e),i=r.getInputType(e),a=e.getUniformFromNode(r,i,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);e.context.nodeName!==void 0&&delete e.context.nodeName;let s=o;if(n===`bool`){let t=e.getDataFromNode(this),r=t.propertyName;if(r===void 0){let a=e.getVarFromNode(this,null,`bool`);r=e.getPropertyName(a),t.propertyName=r,s=e.format(o,i,n),e.addLineFlowCode(`${r} = ${s}`,this)}s=r}return e.format(s,n,t)}},Y=(e,t)=>{let n=Xm(t||e);if(n===e&&(e=qp(n)),e&&e.isNode===!0){let t=e.value;e.traverse(e=>{e.isConstNode===!0&&(t=e.value)}),e=t}return new lg(e,n)},ug=class extends lm{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){let t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}},dg=(...e)=>{let t;if(e.length===1){let n=e[0].map(e=>V(e));t=new ug(null,n.length,n)}else{let n=e[0],r=e[1];t=new ug(n,r)}return t};B(`toArray`,(e,t)=>dg(Array(t).fill(e))),B(`assign`,th(class extends lm{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`?`void`:this.targetNode.getNodeType(e)}needsSplitAssign(e){let{targetNode:t}=this;if(e.isAvailable(`swizzleAssign`)===!1&&t.isSplitNode&&t.components.length>1){let n=e.getTypeLength(t.node.getNodeType(e));return im.join(``).slice(0,n)!==t.components}return!1}setup(e){let{targetNode:t,sourceNode:n}=this,r=t.getScope(),i=e.getDataFromNode(r);i.assign=!0;let a=e.getNodeProperties(this);a.sourceNode=n,a.targetNode=t.context({assign:!0})}generate(e,t){let{targetNode:n,sourceNode:r}=e.getNodeProperties(this),i=this.needsSplitAssign(e),a=n.build(e),o=n.getNodeType(e),s=r.build(e,o),c=r.getNodeType(e),l=e.getDataFromNode(this),u;if(l.initialized===!0)t!==`void`&&(u=a);else if(i){let r=e.getVarFromNode(this,null,o),i=e.getPropertyName(r);e.addLineFlowCode(`${i} = ${s}`,this);let c=n.node,l=c.node.context({assign:!0}).build(e);for(let t=0;t<c.components.length;t++){let n=c.components[t];e.addLineFlowCode(`${l}.${n} = ${i}[ ${t} ]`,this)}t!==`void`&&(u=a)}else u=`${a} = ${s}`,(t===`void`||c===`void`)&&(e.addLineFlowCode(u,this),t!==`void`&&(u=a));return l.initialized=!0,e.format(u,o,t)}}).setParameterLength(2));var fg=class extends lm{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){let t=[],n=this.functionNode,r=n.getInputs(e),i=this.parameters,a=(t,n)=>{let r=n.type,i=r===`pointer`,a;return a=i?`&`+t.build(e):t.build(e,r),a};if(Array.isArray(i)){if(i.length>r.length)N(`TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'.`),i.length=r.length;else if(i.length<r.length)for(N(`TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.`);i.length<r.length;)i.push(G(0));for(let e=0;e<i.length;e++)t.push(a(i[e],r[e]))}else for(let e of r){let n=i[e.name];n===void 0?(N(`TSL: Input '${e.name}' not found in \'Fn()\'.`),t.push(a(G(0),e))):t.push(a(n,e))}return`${n.build(e,`property`)}( ${t.join(`, `)} )`}};B(`call`,(e,...t)=>(t=t.length>1||t[0]&&t[0].isNode===!0?eh(t):$m(t[0]),new fg(V(e),t)));var pg={"==":`equal`,"!=":`notEqual`,"<":`lessThan`,">":`greaterThan`,"<=":`lessThanEqual`,">=":`greaterThanEqual`,"%":`mod`},mg=class e extends lm{static get type(){return`OperatorNode`}constructor(t,n,r,...i){if(super(),i.length>0){let a=new e(t,n,r);for(let n=0;n<i.length-1;n++)a=new e(t,a,i[n]);n=a,r=i[i.length-1]}this.op=t,this.aNode=n,this.bNode=r,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(pg[this.op],t)}generateNodeType(e,t=null){let n=this.op,r=this.aNode,i=this.bNode,a=r.getNodeType(e),o=i?i.getNodeType(e):null;if(a===`void`||o===`void`)return t||`void`;if(n===`%`)return a;if(n===`~`||n===`&`||n===`|`||n===`^`||n===`>>`||n===`<<`)return e.getIntegerType(a);if(n===`&&`||n===`||`||n===`^^`)return`bool`;if(n===`!`){let t=e.getTypeLength(a);return t>1?`bvec${t}`:`bool`}if(n===`==`||n===`!=`||n===`<`||n===`>`||n===`<=`||n===`>=`){let t=Math.max(e.getTypeLength(a),e.getTypeLength(o));return t>1?`bvec${t}`:`bool`}if(e.isMatrix(a)){if(o===`float`)return a;if(e.isVector(o))return e.getVectorFromMatrix(a);if(e.isMatrix(o))return a}else if(e.isMatrix(o)){if(a===`float`)return o;if(e.isVector(a))return e.getVectorFromMatrix(o)}return e.getTypeLength(o)>e.getTypeLength(a)?o:a}generate(e,t){let n=this.op,{aNode:r,bNode:i}=this,a=this.getNodeType(e,t),o=null,s=null;a===`void`?o=s=a:(o=r.getNodeType(e),s=i?i.getNodeType(e):null,n===`<`||n===`>`||n===`<=`||n===`>=`||n===`==`||n===`!=`?e.isVector(o)?s=o:e.isVector(s)?o=s:o!==s&&(o=s=`float`):n===`>>`||n===`<<`?(o=a,s=e.changeComponentType(s,`uint`)):n===`%`?(o=a,s=e.isInteger(o)&&e.isInteger(s)?s:o):e.isMatrix(o)?s===`float`?s=`float`:e.isVector(s)?s=e.getVectorFromMatrix(o):e.isMatrix(s)||(o=s=a):o=e.isMatrix(s)?o===`float`?`float`:e.isVector(o)?e.getVectorFromMatrix(s):s=a:s=a);let c=r.build(e,o),l=i?i.build(e,s):null,u=e.getFunctionOperator(n);if(t!==`void`){let r=e.renderer.coordinateSystem===Et;if(n===`==`||n===`!=`||n===`<`||n===`>`||n===`<=`||n===`>=`)return r&&e.isVector(o)?e.format(`${this.getOperatorMethod(e,t)}( ${c}, ${l} )`,a,t):e.format(`( ${c} ${n} ${l} )`,a,t);if(n===`%`)return e.isInteger(s)?e.format(`( ${c} % ${l} )`,a,t):e.format(`${this.getOperatorMethod(e,a)}( ${c}, ${l} )`,a,t);if(n===`!`)return r&&e.isVector(o)?e.format(`not( ${c} )`,t):e.format(`( ${n} ${c} )`,o,t);if(n===`~`)return e.format(`( ${n} ${c} )`,o,t);if(u)return e.format(`${u}( ${c}, ${l} )`,a,t);if(e.isMatrix(o)&&s===`float`)return e.format(`( ${l} ${n} ${c} )`,a,t);if(o===`float`&&e.isMatrix(s))return e.format(`${c} ${n} ${l}`,a,t);{let i=`( ${c} ${n} ${l} )`;return!r&&a===`bool`&&e.isVector(o)&&e.isVector(s)&&(i=`all${i}`),e.format(i,a,t)}}if(o!==`void`)return u?e.format(`${u}( ${c}, ${l} )`,a,t):e.isMatrix(o)&&s===`float`?e.format(`${l} ${n} ${c}`,a,t):e.format(`${c} ${n} ${l}`,a,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}},hg=U(mg,`+`).setParameterLength(2,1/0).setName(`add`),gg=U(mg,`-`).setParameterLength(2,1/0).setName(`sub`),_g=U(mg,`*`).setParameterLength(2,1/0).setName(`mul`),vg=U(mg,`/`).setParameterLength(2,1/0).setName(`div`),yg=U(mg,`%`).setParameterLength(2).setName(`mod`),bg=U(mg,`==`).setParameterLength(2).setName(`equal`),xg=U(mg,`!=`).setParameterLength(2).setName(`notEqual`),Sg=U(mg,`<`).setParameterLength(2).setName(`lessThan`),Cg=U(mg,`>`).setParameterLength(2).setName(`greaterThan`),wg=U(mg,`<=`).setParameterLength(2).setName(`lessThanEqual`),Tg=U(mg,`>=`).setParameterLength(2).setName(`greaterThanEqual`),Eg=U(mg,`&&`).setParameterLength(2,1/0).setName(`and`),Dg=U(mg,`||`).setParameterLength(2,1/0).setName(`or`),Og=U(mg,`!`).setParameterLength(1).setName(`not`),kg=U(mg,`^^`).setParameterLength(2).setName(`xor`),Ag=U(mg,`&`).setParameterLength(2).setName(`bitAnd`),jg=U(mg,`~`).setParameterLength(1).setName(`bitNot`),Mg=U(mg,`|`).setParameterLength(2).setName(`bitOr`),Ng=U(mg,`^`).setParameterLength(2).setName(`bitXor`),Pg=U(mg,`<<`).setParameterLength(2).setName(`shiftLeft`),Fg=U(mg,`>>`).setParameterLength(2).setName(`shiftRight`),Ig=W(([e])=>(e.addAssign(1),e)),Lg=W(([e])=>(e.subAssign(1),e)),Rg=W(([e])=>{let t=lh(e).toConst();return e.addAssign(1),t}),zg=W(([e])=>{let t=lh(e).toConst();return e.subAssign(1),t});B(`add`,hg),B(`sub`,gg),B(`mul`,_g),B(`div`,vg),B(`mod`,yg),B(`equal`,bg),B(`notEqual`,xg),B(`lessThan`,Sg),B(`greaterThan`,Cg),B(`lessThanEqual`,wg),B(`greaterThanEqual`,Tg),B(`and`,Eg),B(`or`,Dg),B(`not`,Og),B(`xor`,kg),B(`bitAnd`,Ag),B(`bitNot`,jg),B(`bitOr`,Mg),B(`bitXor`,Ng),B(`shiftLeft`,Pg),B(`shiftRight`,Fg),B(`incrementBefore`,Ig),B(`decrementBefore`,Lg),B(`increment`,Rg),B(`decrement`,zg);var X=class e extends lm{static get type(){return`MathNode`}constructor(t,n,r=null,i=null){if(super(),(t===e.MAX||t===e.MIN)&&arguments.length>3){let a=new e(t,n,r);for(let n=3;n<arguments.length-1;n++)a=new e(t,a,arguments[n]);n=a,r=arguments[arguments.length-1],i=null}this.method=t,this.aNode=n,this.bNode=r,this.cNode=i,this.isMathNode=!0}getInputType(e){let t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,r=this.cNode?this.cNode.getNodeType(e):null,i=e.isMatrix(t)?0:e.getTypeLength(t),a=e.isMatrix(n)?0:e.getTypeLength(n),o=e.isMatrix(r)?0:e.getTypeLength(r);return i>a&&i>o?t:a>o?n:o>i?r:t}generateNodeType(t){let n=this.method;return n===e.LENGTH||n===e.DISTANCE||n===e.DOT||n===e.DETERMINANT?`float`:n===e.CROSS?`vec3`:n===e.ALL||n===e.ANY?`bool`:n===e.EQUALS?t.changeComponentType(this.aNode.getNodeType(t),`bool`):this.getInputType(t)}setup(t){let{aNode:n,bNode:r,method:i}=this,a=null;if(i===e.ONE_MINUS)a=gg(1,n);else if(i===e.RECIPROCAL)a=vg(1,n);else if(i===e.DIFFERENCE)a=m_(gg(n,r));else if(i===e.TRANSFORM_DIRECTION){let e,i;t.isMatrix(n.getNodeType(t))?(e=n,i=r):(e=r,i=n),a=e_(_g(e,q(K(i),0)).xyz)}return a===null?super.setup(t):a}generate(t,n){if(t.getNodeProperties(this).outputNode)return super.generate(t,n);let r=this.method,i=this.getNodeType(t),a=this.getInputType(t),o=this.aNode,s=this.bNode,c=this.cNode,l=t.renderer.coordinateSystem;if(r===e.NEGATE)return t.format(`( - `+o.build(t,a)+` )`,i,n);{let u=[];return r===e.CROSS?u.push(o.build(t,i),s.build(t,i)):l===2e3&&r===e.STEP?u.push(o.build(t,t.getTypeLength(o.getNodeType(t))===1?`float`:a),s.build(t,a)):l===2e3&&(r===e.MIN||r===e.MAX)?u.push(o.build(t,a),s.build(t,t.getTypeLength(s.getNodeType(t))===1?t.getComponentType(a):a)):r===e.REFRACT?u.push(o.build(t,a),s.build(t,a),c.build(t,`float`)):r===e.MIX?u.push(o.build(t,a),s.build(t,a),c.build(t,t.getTypeLength(c.getNodeType(t))===1?`float`:a)):(l===2001&&r===e.ATAN&&s!==null&&(r=`atan2`),t.shaderStage!==`fragment`&&(r===e.DFDX||r===e.DFDY)&&(N(`TSL: '${r}' is not supported in the ${t.shaderStage} stage.`,this.stackTrace),r=`/*`+r+`*/`),u.push(o.build(t,a)),s!==null&&u.push(s.build(t,a)),c!==null&&u.push(c.build(t,a))),t.format(`${t.getMethod(r,i)}( ${u.join(`, `)} )`,i,n)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}};X.ALL=`all`,X.ANY=`any`,X.RADIANS=`radians`,X.DEGREES=`degrees`,X.EXP=`exp`,X.EXP2=`exp2`,X.LOG=`log`,X.LOG2=`log2`,X.SQRT=`sqrt`,X.INVERSE_SQRT=`inversesqrt`,X.FLOOR=`floor`,X.CEIL=`ceil`,X.NORMALIZE=`normalize`,X.FRACT=`fract`,X.SIN=`sin`,X.SINH=`sinh`,X.COS=`cos`,X.COSH=`cosh`,X.TAN=`tan`,X.TANH=`tanh`,X.ASIN=`asin`,X.ASINH=`asinh`,X.ACOS=`acos`,X.ACOSH=`acosh`,X.ATAN=`atan`,X.ATANH=`atanh`,X.ABS=`abs`,X.SIGN=`sign`,X.LENGTH=`length`,X.NEGATE=`negate`,X.ONE_MINUS=`oneMinus`,X.DFDX=`dFdx`,X.DFDY=`dFdy`,X.ROUND=`round`,X.RECIPROCAL=`reciprocal`,X.TRUNC=`trunc`,X.FWIDTH=`fwidth`,X.TRANSPOSE=`transpose`,X.DETERMINANT=`determinant`,X.INVERSE=`inverse`,X.EQUALS=`equals`,X.MIN=`min`,X.MAX=`max`,X.STEP=`step`,X.REFLECT=`reflect`,X.DISTANCE=`distance`,X.DIFFERENCE=`difference`,X.DOT=`dot`,X.CROSS=`cross`,X.POW=`pow`,X.TRANSFORM_DIRECTION=`transformDirection`,X.MIX=`mix`,X.CLAMP=`clamp`,X.REFRACT=`refract`,X.SMOOTHSTEP=`smoothstep`,X.FACEFORWARD=`faceforward`;var Bg=G(1e-6),Vg=G(Math.PI);Math.PI*2,Math.PI*2,Math.PI*.5;var Hg=U(X,X.ALL).setParameterLength(1),Ug=U(X,X.ANY).setParameterLength(1),Wg=U(X,X.RADIANS).setParameterLength(1),Gg=U(X,X.DEGREES).setParameterLength(1),Kg=U(X,X.EXP).setParameterLength(1),qg=U(X,X.EXP2).setParameterLength(1),Jg=U(X,X.LOG).setParameterLength(1),Yg=U(X,X.LOG2).setParameterLength(1),Xg=U(X,X.SQRT).setParameterLength(1),Zg=U(X,X.INVERSE_SQRT).setParameterLength(1),Qg=U(X,X.FLOOR).setParameterLength(1),$g=U(X,X.CEIL).setParameterLength(1),e_=U(X,X.NORMALIZE).setParameterLength(1),t_=U(X,X.FRACT).setParameterLength(1),n_=U(X,X.SIN).setParameterLength(1),r_=U(X,X.SINH).setParameterLength(1),i_=U(X,X.COS).setParameterLength(1),a_=U(X,X.COSH).setParameterLength(1),o_=U(X,X.TAN).setParameterLength(1),s_=U(X,X.TANH).setParameterLength(1),c_=U(X,X.ASIN).setParameterLength(1),l_=U(X,X.ASINH).setParameterLength(1),u_=U(X,X.ACOS).setParameterLength(1),d_=U(X,X.ACOSH).setParameterLength(1),f_=U(X,X.ATAN).setParameterLength(1,2),p_=U(X,X.ATANH).setParameterLength(1),m_=U(X,X.ABS).setParameterLength(1),h_=U(X,X.SIGN).setParameterLength(1),g_=U(X,X.LENGTH).setParameterLength(1),__=U(X,X.NEGATE).setParameterLength(1),v_=U(X,X.ONE_MINUS).setParameterLength(1),y_=U(X,X.DFDX).setParameterLength(1),b_=U(X,X.DFDY).setParameterLength(1),x_=U(X,X.ROUND).setParameterLength(1),S_=U(X,X.RECIPROCAL).setParameterLength(1),C_=U(X,X.TRUNC).setParameterLength(1),w_=U(X,X.FWIDTH).setParameterLength(1),T_=U(X,X.TRANSPOSE).setParameterLength(1),E_=U(X,X.DETERMINANT).setParameterLength(1),D_=U(X,X.INVERSE).setParameterLength(1),O_=U(X,X.MIN).setParameterLength(2,1/0),k_=U(X,X.MAX).setParameterLength(2,1/0),A_=U(X,X.STEP).setParameterLength(2),j_=U(X,X.REFLECT).setParameterLength(2),M_=U(X,X.DISTANCE).setParameterLength(2),N_=U(X,X.DIFFERENCE).setParameterLength(2),P_=U(X,X.DOT).setParameterLength(2),F_=U(X,X.CROSS).setParameterLength(2),I_=U(X,X.POW).setParameterLength(2),L_=e=>_g(e,e),R_=e=>_g(e,e,e),z_=e=>_g(e,e,e,e),B_=U(X,X.TRANSFORM_DIRECTION).setParameterLength(2),V_=(e,t)=>e_(_g(t,q(K(e),0)).xyz),H_=(e,t)=>e_(q(K(e),0).mul(t).xyz),U_=e=>_g(h_(e),I_(m_(e),1/3)),W_=e=>P_(e,e),G_=U(X,X.MIX).setParameterLength(3),K_=(e,t=0,n=1)=>new X(X.CLAMP,V(e),V(t),V(n)),q_=e=>K_(e),J_=U(X,X.REFRACT).setParameterLength(3),Y_=U(X,X.SMOOTHSTEP).setParameterLength(3),X_=U(X,X.FACEFORWARD).setParameterLength(3),Z_=W(([e])=>t_(n_(yg(P_(e.xy,fh(12.9898,78.233)),Vg)).mul(43758.5453)));B(`all`,Hg),B(`any`,Ug),B(`radians`,Wg),B(`degrees`,Gg),B(`exp`,Kg),B(`exp2`,qg),B(`log`,Jg),B(`log2`,Yg),B(`sqrt`,Xg),B(`inverseSqrt`,Zg),B(`floor`,Qg),B(`ceil`,$g),B(`normalize`,e_),B(`fract`,t_),B(`sin`,n_),B(`sinh`,r_),B(`cos`,i_),B(`cosh`,a_),B(`tan`,o_),B(`tanh`,s_),B(`asin`,c_),B(`asinh`,l_),B(`acos`,u_),B(`acosh`,d_),B(`atan`,f_),B(`atanh`,p_),B(`abs`,m_),B(`sign`,h_),B(`length`,g_),B(`lengthSq`,W_),B(`negate`,__),B(`oneMinus`,v_),B(`dFdx`,y_),B(`dFdy`,b_),B(`round`,x_),B(`reciprocal`,S_),B(`trunc`,C_),B(`fwidth`,w_),B(`min`,O_),B(`max`,k_),B(`step`,(e,t)=>A_(t,e)),B(`reflect`,j_),B(`distance`,M_),B(`dot`,P_),B(`cross`,F_),B(`pow`,I_),B(`pow2`,L_),B(`pow3`,R_),B(`pow4`,z_),B(`transformDirection`,B_),B(`transformNormalByViewMatrix`,V_),B(`transformNormalByInverseViewMatrix`,H_),B(`mix`,(e,t,n)=>G_(t,n,e)),B(`clamp`,K_),B(`refract`,J_),B(`smoothstep`,(e,t,n)=>Y_(t,n,e)),B(`faceForward`,X_),B(`difference`,N_),B(`saturate`,q_),B(`cbrt`,U_),B(`transpose`,T_),B(`determinant`,E_),B(`inverse`,D_),B(`rand`,Z_);var Q_=th(class extends z{static get type(){return`ConditionalNode`}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}generateNodeType(e){let{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(t===void 0)return e.flowBuildStage(this,`setup`),this.getNodeType(e);let r=t.getNodeType(e);if(n!==null){let t=n.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(r))return t}return r}setup(e){let t=this.condNode,n=this.ifNode.isolate(),r=this.elseNode?this.elseNode.isolate():null,i=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=i,r!==null&&(e.getDataFromNode(r).parentNodeBlock=i);let a=e.context.uniformFlow,o=e.getNodeProperties(this);o.condNode=t,o.ifNode=a?n:n.context({nodeBlock:n}),o.elseNode=r?a?r:r.context({nodeBlock:r}):null}generate(e,t){let n=this.getNodeType(e),r=e.getDataFromNode(this);if(r.nodeProperty!==void 0)return r.nodeProperty;let{condNode:i,ifNode:a,elseNode:o}=e.getNodeProperties(this),s=e.currentFunctionNode,c=t!==`void`,l=c?Eh(n).build(e):``;r.nodeProperty=l;let u=i.build(e,`bool`);if(e.context.uniformFlow&&o!==null){let r=a.build(e,n),i=o.build(e,n),s=e.getTernary(u,r,i);return e.format(s,n,t)}e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let d=a.build(e,n);if(d&&(c?d=l+` = `+d+`;`:(d=`return `+d+`;`,s===null&&(M(`TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.`,this.stackTrace),d=`// `+d))),e.removeFlowTab().addFlowCode(e.tab+` `+d+`
`+e.tab+`}`),o!==null){e.addFlowCode(` else {
`).addFlowTab();let t=o.build(e,n);t&&(c?t=l+` = `+t+`;`:(t=`return `+t+`;`,s===null&&(M(`TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.`,this.stackTrace),t=`// `+t))),e.removeFlowTab().addFlowCode(e.tab+` `+t+`
`+e.tab+`}
`)}else e.addFlowCode(`
`);return e.format(l,n,t)}}).setParameterLength(2,3);B(`select`,Q_);var $_=class extends z{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(){let 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){if(e.increaseUsage(this)===1){let t=e.addContext(this.value);this.node.build(e,this),e.setContext(t)}}setup(e){let t=e.addContext(this.value),n=this.node.build(e);return e.setContext(t),n}generate(e,t){let n=e.addContext(this.value),r=this.node.build(e,t);return e.setContext(n),r}},ev=(e=null,t={})=>{let n=e;return(n===null||n.isNode!==!0)&&(t=n||t,n=null),new $_(n,t)},tv=e=>ev(e,{uniformFlow:!0}),nv=(e,t)=>ev(e,{nodeName:t});function rv(e,t,n=null){return ev(n,{getShadow:({light:n,shadowColorNode:r})=>t===n?r.mul(e):r})}function iv(e,t=null){return ev(t,{getAO:(t,{material:n})=>n.transparent===!0?t:t===null?e:t.mul(e)})}function av(e,t,n=null){let r=e.max(.001);return ev(n,{getAO:(e,{material:t})=>t.transparent===!0?e:e===null?r:e.mul(r),getGI:(e,{material:n})=>{if(n.transparent===!0)return e;let i=t.div(r);return e===null?i:e.add(i)}})}function ov(e,t){return M(`TSL: "label()" has been deprecated. Use "setName()" instead.`),nv(e,t)}B(`context`,ev),B(`label`,ov),B(`uniformFlow`,tv),B(`setName`,nv),B(`builtinShadowContext`,(e,t,n)=>rv(t,n,e)),B(`builtinAOContext`,(e,t)=>iv(t,e)),B(`builtinGIContext`,(e,t,n)=>av(t,n,e));var sv=class extends z{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&&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){let t=e[0],n=this.getShared(t);if(this!==n)return n.build(...e);if(this._hasStack(t)===!1&&t.buildStage===`setup`&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&this.node.shaderNode.getLayout()===null&&t.fnCall&&t.fnCall.shaderNode&&t.getDataFromNode(this.node.shaderNode).hasLoop){let n=t.getDataFromNode(this);n.forceDeclaration=!0,e=!0}let n=t.getBaseStack();e?n.addToStackBefore(this):n.addToStack(this)}return this.isIntent(t)&&this.isAssign(t)!==!0?this.node.build(...e):super.build(...e)}generate(e){let{node:t,name:n,readOnly:r}=this,{renderer:i}=e,a=i.backend.isWebGPUBackend===!0,o=!1,s=!1;r&&(o=e.isDeterministic(t),s=a?r:o);let c=this.getNodeType(e);if(c==`void`)return this.isIntent(e)!==!0&&N(`TSL: ".toVar()" can not be used with void type.`,this.stackTrace),t.build(e);let l=e.getVectorType(c),u=t.build(e,l),d=e.getVarFromNode(this,n,l,void 0,s),f=e.getPropertyName(d),p=f;if(s){if(a)p=o?`const ${f}`:`let ${f}`;else{let n=t.getArrayCount(e);p=`const ${e.getVar(d.type,f,n)}`}}return e.addLineFlowCode(`${p} = ${u}`,this),f}_hasStack(e){return e.getDataFromNode(this).stack!==void 0}},cv=th(sv);B(`toVar`,(e,t=null)=>cv(e,t).toStack()),B(`toConst`,(e,t=null)=>cv(e,t,!0).toStack()),B(`toVarIntent`,e=>cv(e).setIntent(!0).toStack());var lv=class extends z{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);let t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);let n=this.node.build(e,...t);return e.removeSubBuild(),n}},uv=(e,t,n=null)=>new lv(V(e),t,n),dv=th(class extends z{static get type(){return`VaryingNode`}constructor(e,t=null){super(),this.node=uv(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){let t=e.getNodeProperties(this),n=t.varying;if(n===void 0){let r=this.name,i=this.getNodeType(e),a=this.interpolationType,o=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,r,i,a,o),t.node=uv(this.node,`VERTEX`)}return n.needsInterpolation||(n.needsInterpolation=e.shaderStage===`fragment`),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Qp.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Qp.VERTEX,this.node)}generate(e){let t=e.getSubBuildProperty(`property`,e.currentStack),n=e.getNodeProperties(this),r=this.setupVarying(e);if(n[t]===void 0){let i=this.getNodeType(e),a=e.getPropertyName(r,Qp.VERTEX);if(e.shaderStage===Qp.VERTEX){let t=n.node.build(e,i);e.addLineFlowCode(`${a} = ${t}`,this)}else e.flowNodeFromShaderStage(Qp.VERTEX,n.node,i,a);n[t]=a}return e.getPropertyName(r)}}).setParameterLength(1,2);B(`toVarying`,dv),B(`toVertexStage`,e=>dv(e));var fv=W(([e])=>G_(e.mul(.9478672986).add(.0521327014).pow(2.4),e.mul(.0773993808),e.lessThanEqual(.04045))).setLayout({name:`sRGBTransferEOTF`,type:`vec3`,inputs:[{name:`color`,type:`vec3`}]}),pv=W(([e])=>G_(e.pow(.41666).mul(1.055).sub(.055),e.mul(12.92),e.lessThanEqual(.0031308))).setLayout({name:`sRGBTransferOETF`,type:`vec3`,inputs:[{name:`color`,type:`vec3`}]}),mv=`WorkingColorSpace`,hv=`OutputColorSpace`,gv=class extends lm{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===mv?I.workingColorSpace:t===hv?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){let{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),r=this.resolveColorSpace(e,this.target),i=t;return I.enabled===!1||n===r||!n||!r?i:(I.getTransfer(n)===`srgb`&&(i=q(fv(i.rgb),i.a)),I.getPrimaries(n)!==I.getPrimaries(r)&&(i=q(Ch(I._getMatrix(new bn,n,r)).mul(i.rgb),i.a)),I.getTransfer(r)===`srgb`&&(i=q(pv(i.rgb),i.a)),i)}},_v=(e,t)=>new gv(V(e),mv,t),vv=(e,t)=>new gv(V(e),t,mv);B(`workingToColorSpace`,_v),B(`colorSpaceToWorking`,vv);var yv=class extends sm{static get type(){return`ReferenceElementNode`}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){let t=super.generate(e),n=this.referenceNode.getNodeType(e),r=this.getNodeType(e);return e.format(t,n,r)}},bv=class extends z{static get type(){return`ReferenceBaseNode`}constructor(e,t,n=null,r=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=r,this.properties=e.split(`.`),this.reference=n,this.node=null,this.group=null,this.updateType=$p.OBJECT}setGroup(e){return this.group=e,this}element(e){return new yv(this,V(e))}setNodeType(e){let t=Y(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){let{properties:t}=this,n=e[t[0]];for(let e=1;e<t.length;e++)n=n[t[e]];return n}updateReference(e){return this.reference=this.object===null?e.object:this.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);let e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}},xv=(e,t,n)=>new bv(e,t,n),Sv=class extends bv{static get type(){return`RendererReferenceNode`}constructor(e,t,n=null){super(e,t,n),this.renderer=n,this.setGroup(J)}updateReference(e){return this.reference=this.renderer===null?e.renderer:this.renderer,this.reference}},Cv=(e,t,n=null)=>new Sv(e,t,n),wv=class extends lm{static get type(){return`ToneMappingNode`}constructor(e,t=Ev,n=null){super(`vec3`),this._toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return Vp(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){let t=this.colorNode||e.context.color,n=this._toneMapping;if(n===0)return t;let r=null,i=e.renderer.library.getToneMappingFunction(n);return i===null?(N(`ToneMappingNode: Unsupported Tone Mapping configuration.`,n),r=t):r=q(i(t.rgb,this.exposureNode),t.a),r}},Tv=(e,t,n)=>new wv(e,V(t),V(n)),Ev=Cv(`toneMappingExposure`,`float`);B(`toneMapping`,(e,t,n)=>Tv(t,n,e));var Dv=new WeakMap;function Ov(e,t){let n=Dv.get(e);return n===void 0&&(n=new Si(e,t),Dv.set(e,n)),n}var kv=class extends hm{static get type(){return`BufferAttributeNode`}constructor(e,t=null,n=0,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=r,this.usage=wt,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;let t=this.getNodeType(e),n=e.getTypeLength(t),r=this.value,i=this.bufferStride||n,a=this.bufferOffset,o;o=r.isInterleavedBuffer===!0?r:r.isBufferAttribute===!0?Ov(r.array,i):Ov(r,i);let s=new wi(o,n,a);o.setUsage(this.usage),this.attribute=s,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){let t=this.getNodeType(e),n=e.context.nodeName;n!==void 0&&delete e.context.nodeName;let r=e.getBufferAttributeFromNode(this,t,n),i=e.getPropertyName(r),a=null;if(e.shaderStage===`vertex`||e.shaderStage===`compute`)this.name=i,a=i;else{let r;n&&(r=n+`Varying`),a=dv(this,r).build(e,t)}return a}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 Av(e,t=null,n=0,r=0,i=wt,a=!1){return t===`mat3`||t===null&&e.itemSize===9?Ch(new kv(e,`vec3`,9,0).setUsage(i).setInstanced(a),new kv(e,`vec3`,9,3).setUsage(i).setInstanced(a),new kv(e,`vec3`,9,6).setUsage(i).setInstanced(a)):t===`mat4`||t===null&&e.itemSize===16?wh(new kv(e,`vec4`,16,0).setUsage(i).setInstanced(a),new kv(e,`vec4`,16,4).setUsage(i).setInstanced(a),new kv(e,`vec4`,16,8).setUsage(i).setInstanced(a),new kv(e,`vec4`,16,12).setUsage(i).setInstanced(a)):new kv(e,t,n,r).setUsage(i)}var jv=(e,t=null,n=0,r=0)=>Av(e,t,n,r),Mv=(e,t=null,n=0,r=0)=>Av(e,t,n,r,wt,!0),Nv=(e,t=null,n=0,r=0)=>Av(e,t,n,r,Tt,!0);B(`toAttribute`,e=>jv(e.value,e.bufferType));var Pv=class e extends z{static get type(){return`IndexNode`}constructor(e){super(`uint`),this.scope=e,this.isIndexNode=!0}generate(t){let n=this.getNodeType(t),r=this.scope,i;if(r===e.VERTEX)i=t.getVertexIndex();else if(r===e.INSTANCE)i=t.getInstanceIndex();else if(r===e.DRAW)i=t.getDrawIndex();else if(r===e.INVOCATION_LOCAL)i=t.getInvocationLocalIndex();else if(r===e.INVOCATION_SUBGROUP)i=t.getInvocationSubgroupIndex();else if(r===e.SUBGROUP)i=t.getSubgroupIndex();else throw Error(`THREE.IndexNode: Unknown scope: `+r);let a;return a=t.shaderStage===`vertex`||t.shaderStage===`compute`?i:dv(this).build(t,n),a}};Pv.VERTEX=`vertex`,Pv.INSTANCE=`instance`,Pv.SUBGROUP=`subgroup`,Pv.INVOCATION_LOCAL=`invocationLocal`,Pv.INVOCATION_SUBGROUP=`invocationSubgroup`,Pv.DRAW=`draw`;var Fv=H(Pv,Pv.VERTEX),Iv=H(Pv,Pv.INSTANCE);Pv.SUBGROUP,Pv.INVOCATION_SUBGROUP,Pv.INVOCATION_LOCAL;var Lv=H(Pv,Pv.DRAW),Rv=class extends z{static get type(){return`ComputeNode`}constructor(e,t){super(`void`),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name=``,this.onInitFunction=null,this.countNode=null,this.updateBeforeType=$p.FRAME}setName(e){return this.name=e,this}label(e){return M(`TSL: "label()" has been deprecated. Use "setName()" instead.`,new Lp),this.setName(e)}onInit(e){return this.onInitFunction=e,this}getUpdateBeforeType(e){return e.compute===this?$p.NONE:this.updateBeforeType}updateBefore({renderer:e}){e.compute(this)}setup(e){this.count!==null&&this.countNode===null&&(this.countNode=Y(this.count,`uint`).onObjectUpdate(()=>this.count));let t=this.computeNode.build(e);if(t){let n=e.getNodeProperties(this);n.outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){let{shaderStage:n}=e;if(n===`compute`){let t=this.computeNode.build(e,`void`);if(t!==``&&e.addLineFlowCode(t,this),this.count!==null&&e.allowEarlyReturns===!0){let t=this.countNode.build(e,`uint`),n=Iv.build(e,`uint`);e.flow.code=`${e.tab}if ( ${n} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{let n=e.getNodeProperties(this).outputComputeNode;if(n)return n.build(e,t)}}},zv=(e,t=[64])=>{(t.length===0||t.length>3)&&N(`TSL: compute() workgroupSize must have 1, 2, or 3 elements`,new Lp);for(let e=0;e<t.length;e++){let n=t[e];(typeof n!=`number`||n<=0||!Number.isInteger(n))&&N(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`,new Lp)}for(;t.length<3;)t.push(1);return new Rv(V(e),t)};B(`compute`,(e,t,n)=>{let r=zv(e,n);return typeof t==`number`?r.count=t:r.dispatchSize=t,r}),B(`computeKernel`,zv);var Bv=class extends z{static get type(){return`IsolateNode`}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}generateNodeType(e){let t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);let r=this.node.getNodeType(e);return e.setCache(t),r}build(e,...t){let n=e.getCache(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);let i=this.node.build(e,...t);return e.setCache(n),i}setParent(e){return this.parent=e,this}getParent(){return this.parent}},Vv=e=>new Bv(V(e));function Hv(e,t=!0){return M(`TSL: "cache()" has been deprecated. Use "isolate()" instead.`),Vv(e).setParent(t)}B(`cache`,Hv),B(`isolate`,Vv),B(`bypass`,th(class extends z{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){let t=this.callNode.build(e,`void`);return t!==``&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}).setParameterLength(2));var Uv=W(([e,t,n,r=G(0),i=G(1),a=dh(!1)])=>{let o=e.sub(t).div(n.sub(t));return Ym(a)&&(o=o.clamp()),o.mul(i.sub(r)).add(r)});function Wv(e,t,n,r=G(0),i=G(1)){return Uv(e,t,n,r,i,!0)}B(`remap`,Uv),B(`remapClamp`,Wv);var Gv=class extends z{static get type(){return`ExpressionNode`}constructor(e=``,t=`void`){super(t),this.snippet=e}generate(e,t){let n=this.getNodeType(e),r=this.snippet;if(n===`void`)e.addLineFlowCode(r,this);else return e.format(r,n,t)}},Kv=th(Gv).setParameterLength(1,2);B(`discard`,e=>(e?Q_(e,Kv(`discard`)):Kv(`discard`)).toStack());var qv=W(([e])=>q(e.rgb.mul(e.a),e.a),{color:`vec4`,return:`vec4`}),Jv=W(([e])=>e.a.equal(0).select(q(0),q(e.rgb.div(e.a),e.a)),{color:`vec4`,return:`vec4`}),Yv=class extends lm{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;t=q(t.rgb,t.a.clamp(0,1)),t=Jv(t);let n=(this._toneMapping===null?e.toneMapping:this._toneMapping)||0,r=(this.outputColorSpace===null?e.outputColorSpace:this.outputColorSpace)||``;return n!==0&&(t=t.toneMapping(n)),r!==``&&r!==I.workingColorSpace&&(t=t.workingToColorSpace(r)),t=qv(t),t}},Xv=(e,t=null,n=null)=>new Yv(V(e),t,n);B(`renderOutput`,Xv);var Zv=class extends lm{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){let t=this.callback,n=this.node.build(e);if(t!==null)t(e,n);else{let t=`--- TSL debug - `+e.shaderStage+` shader ---`,r=`-`.repeat(t.length),i=``;i+=`// #`+t+`#
`,i+=e.flow.code.replace(/^\t/gm,``)+`
`,i+=`/* ... */ `+n+` /* ... */
`,i+=`// #`+r+`#
`,It(i)}return n}};B(`debug`,(e,t=null)=>new Zv(V(e),t).toStack());var Qv=class extends Ht{constructor(){super(),this._renderer=null,this.currentFrame=null,this.isRunning=!1,this.enabled=!0}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}begin(){this.isRunning=!0}finish(){this.isRunning=!1}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}dispose(){this.isRunning===!0&&this.finish(),this.dispatchEvent({type:`dispose`})}},$v=class extends z{static get type(){return`InspectorNode`}constructor(e,t=``,n=null){super(),this.node=e,this.name=t,this.callback=n,this.updateType=$p.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!==Qv&&Rt(`TSL: ".toInspector()" is only available with WebGPU.`),t}};function ey(e,t=``,n=null){return e=V(e),e.before(new $v(e,t,n))}B(`toInspector`,ey);var ty=class extends z{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){let n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){let r=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(r)}else t=`float`}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){let t=this.getAttributeName(e),n=this.getNodeType(e);if(e.hasGeometryAttribute(t)===!0){let r=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(r),a=e.getAttribute(t,i);return e.shaderStage===`vertex`?e.format(a.name,i,n):dv(this).build(e,n)}return M(`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}},ny=(e,t=null)=>new ty(e,t),ry=(e=0)=>ny(`uv`+(e>0?e:``),`vec2`),iy=th(class extends z{static get type(){return`TextureSizeNode`}constructor(e,t=null){super(`uvec2`),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e){let t=this.textureNode.build(e,`property`),n=this.levelNode===null?`0`:this.levelNode.build(e,`int`),r=e.generateTextureSize(this.textureNode.value,t,n);return e.format(r,this.getNodeType(e))}}).setParameterLength(1,2),ay=th(class extends lg{static get type(){return`MaxMipLevelNode`}constructor(e){super(0),this._textureNode=e,this.updateType=$p.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){let 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){let{width:e,height:t}=n;this.value=Math.log2(Math.max(e,t))}}}).setParameterLength(1),oy=class extends Error{constructor(e,t=null){super(e),this.name=`NodeError`,this.stackTrace=t}},sy=new Pn,cy=class extends lg{static get type(){return`TextureNode`}constructor(e=sy,t=null,n=null,r=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=r,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.gatherNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=$p.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this._samplerComparison=!1,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.gatherNode===null?Kp(this.value):`vec4`}getInputType(){return`texture`}getDefaultUV(){return ry(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._matrixUniform===null&&(this._matrixUniform=Y(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=Y(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(lh(iy(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){let t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;let n=this.value;if(!n||n.isTexture!==!0)throw new oy("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);let r=W(()=>{let t=this.uvNode;return(t===null||e.context.forceUVContext===!0)&&e.context.getUV&&(t=e.context.getUV(this,e)),t||=this.getDefaultUV(),this.updateMatrix===!0&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=this._matrixUniform!==null||this._flipYUniform!==null?$p.OBJECT:$p.NONE,t})(),i=this.levelNode;i===null&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this));let a=null,o=null;if(this.compareNode!==null){if(e.renderer.hasCompatibility(kt.TEXTURE_COMPARE))a=this.compareNode;else{let e=n.compareFunction;e===null||e===513||e===515||e===516||e===518?o=this.compareNode:(a=this.compareNode,Rt(`TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.`))}}t.uvNode=r,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=a,t.compareStepNode=o,t.gradNode=this.gradNode,t.gatherNode=this.gatherNode,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,r,i,a,o,s,c,l,u){let d=this.value,f;return f=i?e.generateTextureBias(d,t,n,i,a,l):s?e.generateTextureGrad(d,t,n,s,a,l):c?o?e.generateTextureGatherCompare(d,t,n,o,a,l,u):e.generateTextureGather(d,t,n,c,a,l,u):o?e.generateTextureCompare(d,t,n,o,a,l):this.sampler===!1?e.generateTextureLoad(d,t,n,r,a,l):r?e.generateTextureLevel(d,t,n,r,a,l):e.generateTexture(d,t,n,a,l),f}generate(e,t){let n=this.value,r=e.getNodeProperties(this),i=super.generate(e,`property`);if(/^sampler/.test(t)){if(t===`samplerComparison`){this._samplerComparison=!0;let t=this.getSharedNode(e);t._samplerComparison=!0}return i+`_sampler`}if(e.isReference(t))return i;{let a=e.getDataFromNode(this),o=this.getNodeType(e),s=a.propertyName;if(s===void 0){let{uvNode:t,levelNode:c,biasNode:l,compareNode:u,compareStepNode:d,depthNode:f,gradNode:p,gatherNode:m,offsetNode:h}=r,g=this.generateUV(e,t),_=c?c.build(e,`float`):null,v=l?l.build(e,`float`):null,y=f?f.build(e,`int`):null,b=u?u.build(e,`float`):null,x=d?d.build(e,`float`):null,S=p?[p[0].build(e,`vec2`),p[1].build(e,`vec2`)]:null,C=m?m.build(e,`int`):null,w=h?this.generateOffset(e,h):null,T=this._flipYUniform?this._flipYUniform.build(e,`bool`):null,E=y;E===null&&n.isArrayTexture&&this.isTexture3DNode!==!0&&(E=`0`);let D=e.getVarFromNode(this);s=e.getPropertyName(D);let O=this.generateSnippet(e,i,g,_,v,E,b,S,C,w,T),k;if(k=n.isDepthTexture===!0&&C===null?`float`:n.type===1014?`uvec4`:n.type===1013?`ivec4`:`vec4`,O=e.format(O,k,o),x!==null){let t=n.compareFunction;O=t===516||t===518?A_(Kv(O,o),Kv(x,`float`)).build(e,o):A_(Kv(x,`float`),Kv(O,o)).build(e,o)}e.addLineFlowCode(`${s} = ${O}`,this),a.snippet=O,a.propertyName=s}let c=s;return e.needsToWorkingColorSpace(n)&&(c=vv(Kv(c,o),n.colorSpace).setup(e).build(e,o)),e.format(c,o,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){let t=this.clone();return t.uvNode=V(e),t.referenceNode=this.getBase(),V(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){let t=this.clone();t.biasNode=V(e).mul(ay(t)),t.referenceNode=this.getBase();let n=t.value;return t.generateMipmaps===!1&&(n&&n.generateMipmaps===!1||n.minFilter===1003||n.magFilter===1003)&&(M(`TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.`),t.biasNode=null),V(t)}level(e){let t=this.clone();return t.levelNode=V(e),t.referenceNode=this.getBase(),V(t)}size(e){return iy(this,e)}bias(e){let t=this.clone();return t.biasNode=V(e),t.referenceNode=this.getBase(),V(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){let t=this.clone();return t.compareNode=V(e),t.referenceNode=this.getBase(),V(t)}grad(e,t){let n=this.clone();return n.gradNode=[V(e),V(t)],n.referenceNode=this.getBase(),V(n)}gather(e=0){let t=this.clone();return t.gatherNode=V(e),t.referenceNode=this.getBase(),V(t)}isSampleCompare(){return this.compareNode!==null||this._samplerComparison===!0}depth(e){let t=this.clone();return t.depthNode=V(e),t.referenceNode=this.getBase(),V(t)}offset(e){let t=this.clone();return t.offsetNode=V(e),t.referenceNode=this.getBase(),V(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(){let e=this.value,t=this._matrixUniform;t!==null&&(t.value=e.matrix),e.matrixAutoUpdate===!0&&e.updateMatrix();let n=this._flipYUniform;n!==null&&(n.value=e.image instanceof ImageBitmap&&e.flipY===!0||e.isRenderTargetTexture===!0||e.isFramebufferTexture===!0||e.isDepthTexture===!0)}clone(){let e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e}},ly=th(cy).setParameterLength(1,4).setName(`texture`),uy=(e=sy,t=null,n=null,r=null)=>{let i;return e&&e.isTextureNode===!0?(i=V(e.clone()),i.referenceNode=e.getBase(),t!==null&&(i.uvNode=V(t)),n!==null&&(i.levelNode=V(n)),r!==null&&(i.biasNode=V(r))):i=ly(e,t,n,r),i},dy=(...e)=>uy(...e).setSampler(!1),fy=class extends lg{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`}},py=(e,t,n)=>new fy(e,t,n),my=class extends sm{static get type(){return`UniformArrayElementNode`}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){let t=super.generate(e),n=this.getNodeType(e),r=this.node.getPaddedType();return e.format(t,r,n)}},hy=class extends fy{static get type(){return`UniformArrayNode`}constructor(e,t=null){super(null),this.array=e,this.elementType=t===null?Gp(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=$p.RENDER,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){let e=this.elementType,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(){this.updateBuffer()}onUpdate(e,t){return e=e.bind(this),super.onUpdate((t,n)=>{e(t,n),this.updateBuffer()},t)}updateBuffer(){let{array:e,value:t}=this,n=this.elementType;if(n===`float`||n===`int`||n===`uint`)for(let n=0;n<e.length;n++){let r=n*4;t[r]=e[n]}else if(n===`color`)for(let n=0;n<e.length;n++){let r=n*4,i=e[n];t[r]=i.r,t[r+1]=i.g,t[r+2]=i.b||0}else if(n===`mat2`)for(let n=0;n<e.length;n++){let r=n*4,i=e[n];t[r]=i.elements[0],t[r+1]=i.elements[1],t[r+2]=i.elements[2],t[r+3]=i.elements[3]}else if(n===`mat3`)for(let n=0;n<e.length;n++){let r=n*16,i=e[n];t[r]=i.elements[0],t[r+1]=i.elements[1],t[r+2]=i.elements[2],t[r+4]=i.elements[3],t[r+5]=i.elements[4],t[r+6]=i.elements[5],t[r+8]=i.elements[6],t[r+9]=i.elements[7],t[r+10]=i.elements[8],t[r+15]=1}else if(n===`mat4`)for(let n=0;n<e.length;n++){let r=n*16,i=e[n];for(let e=0;e<i.elements.length;e++)t[r+e]=i.elements[e]}else for(let n=0;n<e.length;n++){let r=n*4,i=e[n];t[r]=i.x,t[r+1]=i.y,t[r+2]=i.z||0,t[r+3]=i.w||0}}setup(e){let t=this.array.length,n=this.elementType,r=Float32Array,i=this.paddedType,a=e.getTypeLength(i);return n.charAt(0)===`i`&&(r=Int32Array),n.charAt(0)===`u`&&(r=Uint32Array),this.value=new r(t*a),this.bufferCount=t,this.bufferType=i,this.updateBuffer(),super.setup(e)}element(e){return new my(this,V(e))}},gy=(e,t)=>new hy(e,t),_y=th(class extends z{constructor(e){super(`float`),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1),vy,yy,by=class e extends z{static get type(){return`ScreenNode`}constructor(e){super(),this.scope=e,this.isViewportNode=!0}generateNodeType(){return this.scope===e.VIEWPORT?`vec4`:`vec2`}update({renderer:t}){let n=t.getRenderTarget();this.scope===e.VIEWPORT?n===null?(t.getViewport(yy),yy.multiplyScalar(t.getPixelRatio())):yy.copy(n.viewport):n===null?t.getDrawingBufferSize(vy):(vy.width=n.width,vy.height=n.height)}setup(){let t=this.scope,n=null;n=t===e.SIZE?Y(vy||=new P).setGroup(J):t===e.VIEWPORT?Y(yy||=new Fn).setGroup(J):fh(wy.div(Cy));let r=$p.NONE;return(this.scope===e.SIZE||this.scope===e.VIEWPORT)&&(r=$p.RENDER),this.updateType=r,n}generate(t){if(this.scope===e.COORDINATE){let e=t.getFragCoord();if(t.isFlipY()){let n=t.getNodeProperties(Cy).outputNode.build(t);e=`${t.getType(`vec2`)}( ${e}.x, ${n}.y - ${e}.y )`}return e}return super.generate(t)}};by.COORDINATE=`coordinate`,by.VIEWPORT=`viewport`,by.SIZE=`size`,by.UV=`uv`;var xy=Y(1).setGroup(J).onRenderUpdate(({renderer:e})=>e.getPixelRatio()),Sy=H(by,by.UV),Cy=H(by,by.SIZE),wy=H(by,by.COORDINATE),Ty=H(by,by.VIEWPORT),Ey=Ty.zw;Ty.xy;var Dy=null,Oy=null,ky=null,Ay=null,jy=null,My=null,Ny=null,Py=null,Fy=null,Iy=null,Ly=null,Ry=null,zy=Y(0,`uint`).setName(`u_cameraIndex`).setGroup(sg(`cameraIndex`)).toVarying(`v_cameraIndex`),By=Y(`float`).setName(`cameraNear`).setGroup(J).onRenderUpdate(({camera:e})=>e.near),Vy=Y(`float`).setName(`cameraFar`).setGroup(J).onRenderUpdate(({camera:e})=>e.far),Hy=W(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t of e.cameras)n.push(t.projectionMatrix);Oy===null?Oy=gy(n).setGroup(J).setName(`cameraProjectionMatrices`):Oy.array=n,t=Oy.element(e.isMultiViewCamera?_y(`gl_ViewID_OVR`):zy)}else Dy===null&&(Dy=Y(e.projectionMatrix).setName(`cameraProjectionMatrix`).setGroup(J).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=Dy;return t}).once()(),Uy=W(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t of e.cameras)n.push(t.projectionMatrixInverse);Ay===null?Ay=gy(n).setGroup(J).setName(`cameraProjectionMatricesInverse`):Ay.array=n,t=Ay.element(e.isMultiViewCamera?_y(`gl_ViewID_OVR`):zy)}else ky===null&&(ky=Y(e.projectionMatrixInverse).setName(`cameraProjectionMatrixInverse`).setGroup(J).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=ky;return t}).once()(),Wy=W(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t of e.cameras)n.push(t.matrixWorldInverse);My===null?My=gy(n).setGroup(J).setName(`cameraViewMatrices`):My.array=n,t=My.element(e.isMultiViewCamera?_y(`gl_ViewID_OVR`):zy)}else jy===null&&(jy=Y(e.matrixWorldInverse).setName(`cameraViewMatrix`).setGroup(J).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=jy;return t}).once()(),Gy=W(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t of e.cameras)n.push(t.matrixWorld);Py===null?Py=gy(n).setGroup(J).setName(`cameraWorldMatrices`):Py.array=n,t=Py.element(e.isMultiViewCamera?_y(`gl_ViewID_OVR`):zy)}else Ny===null&&(Ny=Y(e.matrixWorld).setName(`cameraWorldMatrix`).setGroup(J).onRenderUpdate(({camera:e})=>e.matrixWorld)),t=Ny;return t}).once()(),Ky=W(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t=0,r=e.cameras.length;t<r;t++)n.push(new F);Iy===null?Iy=gy(n).setGroup(J).setName(`cameraPositions`).onRenderUpdate(({camera:e},t)=>{let n=e.cameras,r=t.array;for(let e=0,t=n.length;e<t;e++)r[e].setFromMatrixPosition(n[e].matrixWorld)}):Iy.array=n,t=Iy.element(e.isMultiViewCamera?_y(`gl_ViewID_OVR`):zy)}else Fy===null&&(Fy=Y(new F).setName(`cameraPosition`).setGroup(J).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),t=Fy;return t}).once()(),qy=W(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){let n=[];for(let t of e.cameras)n.push(t.viewport);Ry===null?Ry=gy(n,`vec4`).setGroup(J).setName(`cameraViewports`):Ry.array=n,t=Ry.element(zy)}else Ly===null&&(Ly=q(0,0,Cy.x,Cy.y).toConst(`cameraViewport`)),t=Ly;return t}).once()(),Jy=new pi,Yy=class e extends z{static get type(){return`Object3DNode`}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=$p.OBJECT,this.uniformNode=new lg(null)}generateNodeType(){let t=this.scope;if(t===e.WORLD_MATRIX)return`mat4`;if(t===e.POSITION||t===e.VIEW_POSITION||t===e.DIRECTION||t===e.SCALE)return`vec3`;if(t===e.RADIUS)return`float`}update(t){let n=this.object3d,r=this.uniformNode,i=this.scope;if(i===e.WORLD_MATRIX)r.value=n.matrixWorld;else if(i===e.POSITION)r.value=r.value||new F,r.value.setFromMatrixPosition(n.matrixWorld);else if(i===e.SCALE)r.value=r.value||new F,r.value.setFromMatrixScale(n.matrixWorld);else if(i===e.DIRECTION)r.value=r.value||new F,n.getWorldDirection(r.value);else if(i===e.VIEW_POSITION){let e=t.camera;r.value=r.value||new F,r.value.setFromMatrixPosition(n.matrixWorld),r.value.applyMatrix4(e.matrixWorldInverse)}else if(i===e.RADIUS){let e=t.object.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),Jy.copy(e.boundingSphere).applyMatrix4(n.matrixWorld),r.value=Jy.radius}}generate(t){let n=this.scope;return n===e.WORLD_MATRIX?this.uniformNode.nodeType=`mat4`:n===e.POSITION||n===e.VIEW_POSITION||n===e.DIRECTION||n===e.SCALE?this.uniformNode.nodeType=`vec3`:n===e.RADIUS&&(this.uniformNode.nodeType=`float`),this.uniformNode.build(t)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}};Yy.WORLD_MATRIX=`worldMatrix`,Yy.POSITION=`position`,Yy.SCALE=`scale`,Yy.VIEW_POSITION=`viewPosition`,Yy.DIRECTION=`direction`,Yy.RADIUS=`radius`;var Xy=new Bn,Zy=class extends Yy{static get type(){return`ModelNode`}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}};Zy.DIRECTION;var Qy=H(Zy,Zy.WORLD_MATRIX);Zy.POSITION,Zy.SCALE,Zy.VIEW_POSITION,Zy.RADIUS;var $y=Y(new bn).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),eb=W(e=>e.context.modelViewMatrix||tb).once()().toVar(`modelViewMatrix`),tb=Wy.mul(Qy),nb=W(e=>{e.context.isHighPrecisionModelViewMatrix=!0;let t=e.camera,n;if(t.isArrayCamera&&t.cameras.length>0){let e=[];for(let n=0;n<t.cameras.length;n++)e.push(new Bn);n=gy(e).onObjectUpdate(({object:e,camera:t},n)=>{let r=t.cameras,i=n.array;for(let t=0,n=r.length;t<n;t++)i[t].multiplyMatrices(r[t].matrixWorldInverse,e.matrixWorld)}).element(t.isMultiViewCamera?_y(`gl_ViewID_OVR`):zy)}else n=Y(`mat4`).onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld));return n}).once()().toVar(`highpModelViewMatrix`),rb=W(e=>{let t=e.context.isHighPrecisionModelViewMatrix,n=e.camera,r;if(n.isArrayCamera&&n.cameras.length>0){let e=[];for(let t=0;t<n.cameras.length;t++)e.push(new bn);r=gy(e).onObjectUpdate(({object:e,camera:t},n)=>{let r=t.cameras,i=n.array;for(let t=0,n=r.length;t<n;t++)Xy.multiplyMatrices(r[t].matrixWorldInverse,e.matrixWorld),i[t].getNormalMatrix(Xy)}).element(n.isMultiViewCamera?_y(`gl_ViewID_OVR`):zy)}else r=Y(`mat3`).onObjectUpdate(({object:e,camera:n})=>(t!==!0&&e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)));return r}).once()().toVar(`highpModelNormalViewMatrix`),ib=W(e=>e.shaderStage===`fragment`?e.context.clipSpace.toVarying(`v_clipSpace`):(Rt("TSL: `clipSpace` is only available in fragment stage."),q())).once()(),ab=ny(`position`,`vec3`),ob=ab.toVarying(`positionLocal`),sb=ab.toVarying(`positionPrevious`),cb=W(e=>Qy.mul(ob).xyz.toVarying(e.getSubBuildProperty(`v_positionWorld`)),`vec3`).once([`POSITION`])(),lb=W(()=>ob.transformDirection(Qy).toVarying(`v_positionWorldDirection`).normalize().toVar(`positionWorldDirection`),`vec3`).once([`POSITION`])(),ub=W(e=>{if(e.shaderStage===`fragment`&&e.material.vertexNode){let e=Uy.mul(ib);return e.xyz.div(e.w).toVar(`positionView`)}return e.context.setupPositionView().toVarying(`v_positionView`)},`vec3`).once([`POSITION`,`VERTEX`])(),db=W(e=>{let t;return t=e.camera.isOrthographicCamera?K(0,0,1):ub.negate().toVarying(`v_positionViewDirection`).normalize(),t.toVar(`positionViewDirection`)},`vec3`).once([`POSITION`])(),fb=G(H(class extends z{static get type(){return`FrontFacingNode`}constructor(){super(`bool`),this.isFrontFacingNode=!0}generate(e){if(e.shaderStage!==`fragment`)return`true`;let{material:t}=e;return t.side===1?`false`:e.getFrontFacing()}})).mul(2).sub(1),pb=W(([e],{material:t})=>{let n=t.side;return n===1?e=e.mul(-1):n===2&&(e=e.mul(fb)),e}),mb=ny(`normal`,`vec3`),hb=W(e=>e.geometry.hasAttribute(`normal`)===!1?(M(`TSL: Vertex attribute "normal" not found on geometry.`),K(0,1,0)):mb,`vec3`).once()().toVar(`normalLocal`),gb=ub.dFdx().cross(ub.dFdy()).normalize().toVar(`normalFlat`),_b=W(e=>{let t;return t=e.isFlatShading()?gb:Cb(hb).toVarying(`v_normalViewGeometry`).normalize(),t},`vec3`).once()().toVar(`normalViewGeometry`),vb=W(e=>{let t=_b.transformNormalByInverseViewMatrix(Wy);return e.isFlatShading()!==!0&&(t=t.toVarying(`v_normalWorldGeometry`)),t.normalize().toVar(`normalWorldGeometry`)},`vec3`).once()(),yb=W(e=>{let t;return e.subBuildFn===`NORMAL`||e.subBuildFn===`VERTEX`?(t=_b,e.isFlatShading()!==!0&&(t=pb(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},`vec3`).once([`NORMAL`,`VERTEX`])().toVar(`normalView`),bb=yb.transformNormalByInverseViewMatrix(Wy).toVar(`normalWorld`),xb=W(({subBuildFn:e,context:t})=>{let n;return n=e===`NORMAL`||e===`VERTEX`?yb:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),n},`vec3`).once([`NORMAL`,`VERTEX`])().toVar(`clearcoatNormalView`),Sb=W(([e,t=Qy])=>Ch(t).inverse().transpose().mul(e).normalize());B(`transformNormal`,Sb);var Cb=W(([e],t)=>{let n=t.context.modelNormalViewMatrix;return n?e.transformNormalByViewMatrix(n):$y.mul(e).transformNormalByViewMatrix(Wy)});W(()=>(M(`TSL: "transformedNormalView" is deprecated. Use "normalView" instead.`),yb)).once([`NORMAL`,`VERTEX`])(),W(()=>(M(`TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.`),bb)).once([`NORMAL`,`VERTEX`])(),W(()=>(M(`TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.`),xb)).once([`NORMAL`,`VERTEX`])();var wb=new Bn,Tb=Y(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Eb=Y(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Db=Y(new Bn).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){let n=(t.environment!==null||t.environmentNode&&t.environmentNode.isNode)&&e.envMap===null?t.environmentRotation:e.envMapRotation;return n?wb.makeRotationFromEuler(n).transpose():wb.identity(),wb}),Ob=db.negate().reflect(yb),kb=db.negate().refract(yb,Tb),Ab=Ob.transformDirection(Gy).toVar(`reflectVector`),jb=kb.transformDirection(Gy).toVar(`refractVector`),Mb=new va,Nb=th(class extends cy{static get type(){return`CubeTextureNode`}constructor(e,t=null,n=null,r=null){super(e,t,n,r),this.isCubeTextureNode=!0}getInputType(){return this.value.isDepthTexture===!0?`cubeDepthTexture`:`cubeTexture`}getDefaultUV(){let e=this.value;return e.mapping===301?Ab:e.mapping===302?jb:(N(`CubeTextureNode: Mapping "%s" not supported.`,e.mapping),K(0,0,0))}setUpdateMatrix(){}setupUV(e,t){let n=this.value;return n.isDepthTexture===!0?e.renderer.coordinateSystem===2001?K(t.x,t.y.negate(),t.z):t:(t=Db.mul(t),(e.renderer.coordinateSystem===2001||!n.isRenderTargetTexture)&&(t=K(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,this.sampler===!0?`vec3`:`ivec3`)}}).setParameterLength(1,4).setName(`cubeTexture`),Pb=(e=Mb,t=null,n=null,r=null)=>{let i;return e&&e.isCubeTextureNode===!0?(i=V(e.clone()),i.referenceNode=e,t!==null&&(i.uvNode=V(t)),n!==null&&(i.levelNode=V(n)),r!==null&&(i.biasNode=V(r))):i=Nb(e,t,n,r),i},Fb=class extends z{static get type(){return`ReferenceNode`}constructor(e,t,n=null,r=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=r,this.properties=e.split(`.`),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=$p.OBJECT}element(e){return new yv(this,V(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return M(`TSL: "label()" has been deprecated. Use "setName()" instead.`),this.setName(e)}setNodeType(e){let t=null;this.count===null?Array.isArray(this.getValueFromReference())?(t=gy(null,e),t.updateType=$p.OBJECT):t=e===`texture`?uy(null):e===`cubeTexture`?Pb(null):Y(null,e):t=py(null,e,this.count),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){let{properties:t}=this,n=e[t[0]];for(let e=1;e<t.length;e++)n=n[t[e]];return n}updateReference(e){return this.reference=this.object===null?e.object:this.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);let e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}},Ib=(e,t,n)=>new Fb(e,t,n),Lb=(e,t,n,r)=>new Fb(e,t,r,n),Rb=class extends Fb{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?e.material:this.material,this.reference}},zb=(e,t,n=null)=>new Rb(e,t,n),Bb=ry(),Vb=ub.dFdx(),Hb=ub.dFdy(),Ub=Bb.dFdx(),Wb=Bb.dFdy(),Gb=yb,Kb=Hb.cross(Gb),qb=Gb.cross(Vb),Jb=Kb.mul(Ub.x).add(qb.mul(Wb.x)),Yb=Kb.mul(Ub.y).add(qb.mul(Wb.y)),Xb=Jb.dot(Jb).max(Yb.dot(Yb)),Zb=Xb.equal(0).select(0,Xb.inverseSqrt()),Qb=Jb.mul(Zb).toVar(`tangentViewFrame`),$b=Yb.mul(Zb).toVar(`bitangentViewFrame`),ex=ny(`tangent`,`vec4`),tx=ex.xyz.toVar(`tangentLocal`),nx=W(e=>{let t;return t=e.subBuildFn===`VERTEX`||e.geometry.hasAttribute(`tangent`)?eb.mul(q(tx,0)).xyz.toVarying(`v_tangentView`).normalize():Qb,e.isFlatShading()!==!0&&(t=pb(t)),t},`vec3`).once([`NORMAL`,`VERTEX`])().toVar(`tangentView`),rx=W(([e,t],n)=>{let r=e.mul(ex.w).xyz;return n.subBuildFn===`NORMAL`&&n.isFlatShading()!==!0&&(r=r.toVarying(t)),r}).once([`NORMAL`]),ix=Ch(nx,W(e=>{let t;return t=e.subBuildFn===`VERTEX`||e.geometry.hasAttribute(`tangent`)?rx(yb.cross(nx),`v_bitangentView`).normalize():$b,e.isFlatShading()!==!0&&(t=pb(t)),t},`vec3`).once([`NORMAL`,`VERTEX`])().toVar(`bitangentView`),yb).toVar(`TBNViewMatrix`),ax=W(()=>{let e=Uh.cross(db);return e=e.cross(Uh).normalize(),e=G_(e,yb,Vh.mul(jh.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),ox=e=>V(e).mul(.5).add(.5),sx=e=>K(e,Xg(q_(G(1).sub(P_(e,e))))),cx=th(class extends lm{static get type(){return`NormalMapNode`}constructor(e,t=null){super(`vec3`),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=``}setup(e){let{normalMapType:t,scaleNode:n,unpackNormalMode:r}=this,i=this.node.mul(2).sub(1);if(t===0?r===`rg`?i=sx(i.xy):r===`ga`?i=sx(i.yw):r!==``&&N(`THREE.NodeMaterial: Unexpected unpack normal mode: ${r}`):r!==``&&N(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${r}'`),n!==null){let t=n;e.isFlatShading()===!0&&(t=pb(t)),i=K(i.xy.mul(t),i.z)}let a=null;return t===1?a=Cb(i):t===0?a=ix.mul(i).normalize():(N(`NodeMaterial: Unsupported normal map type: ${t}`),a=yb),a}}).setParameterLength(1,2),lx=W(({textureNode:e,bumpScale:t})=>{let n=t=>e.isolate().context({getUV:e=>t(e.uvNode||ry()),forceUVContext:!0}),r=G(n(e=>e));return fh(G(n(e=>e.add(e.dFdx()))).sub(r),G(n(e=>e.add(e.dFdy()))).sub(r)).mul(t)}),ux=W(e=>{let{surf_pos:t,surf_norm:n,dHdxy:r}=e,i=t.dFdx().normalize(),a=t.dFdy().normalize(),o=n,s=a.cross(o),c=o.cross(i),l=i.dot(s).mul(fb),u=l.sign().mul(r.x.mul(s).add(r.y.mul(c)));return l.abs().mul(n).sub(u).normalize()}),dx=th(class extends lm{static get type(){return`BumpMapNode`}constructor(e,t=null){super(`vec3`),this.textureNode=e,this.scaleNode=t}setup(e){if(e.material.wireframe===!0)return yb;let t=this.scaleNode===null?1:this.scaleNode;return ux({surf_pos:ub,surf_norm:yb,dHdxy:lx({textureNode:this.textureNode,bumpScale:t})})}}).setParameterLength(1,2),fx=new Map,Z=class e extends z{static get type(){return`MaterialNode`}constructor(e){super(),this.scope=e}getCache(e,t){let n=fx.get(e);return n===void 0&&(n=zb(e,t),fx.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(t){let n=t.context.material,r=this.scope,i=null;if(r===e.COLOR){let e=n.color===void 0?K():this.getColor(r);i=n.map&&n.map.isTexture===!0?e.mul(this.getTexture(`map`)):e}else if(r===e.OPACITY){let e=this.getFloat(r);i=n.alphaMap&&n.alphaMap.isTexture===!0?e.mul(this.getTexture(`alpha`)):e}else if(r===e.SPECULAR_STRENGTH)i=n.specularMap&&n.specularMap.isTexture===!0?this.getTexture(`specular`).r:G(1);else if(r===e.SPECULAR_INTENSITY){let e=this.getFloat(r);i=n.specularIntensityMap&&n.specularIntensityMap.isTexture===!0?e.mul(this.getTexture(r).a):e}else if(r===e.SPECULAR_COLOR){let e=this.getColor(r);i=n.specularColorMap&&n.specularColorMap.isTexture===!0?e.mul(this.getTexture(r).rgb):e}else if(r===e.ROUGHNESS){let e=this.getFloat(r);i=n.roughnessMap&&n.roughnessMap.isTexture===!0?e.mul(this.getTexture(r).g):e}else if(r===e.METALNESS){let e=this.getFloat(r);i=n.metalnessMap&&n.metalnessMap.isTexture===!0?e.mul(this.getTexture(r).b):e}else if(r===e.EMISSIVE){let e=this.getFloat(`emissiveIntensity`),t=this.getColor(r).mul(e);i=n.emissiveMap&&n.emissiveMap.isTexture===!0?t.mul(this.getTexture(r)):t}else if(r===e.NORMAL)n.normalMap?(i=cx(this.getTexture(`normal`),this.getCache(`normalScale`,`vec2`)),i.normalMapType=n.normalMapType,(n.normalMap.format==1030||n.normalMap.format==36285||n.normalMap.format==37490)&&(i.unpackNormalMode=`rg`)):i=n.bumpMap?dx(this.getTexture(`bump`).r,this.getFloat(`bumpScale`)):yb;else if(r===e.CLEARCOAT){let e=this.getFloat(r);i=n.clearcoatMap&&n.clearcoatMap.isTexture===!0?e.mul(this.getTexture(r).r):e}else if(r===e.CLEARCOAT_ROUGHNESS){let e=this.getFloat(r);i=n.clearcoatRoughnessMap&&n.clearcoatRoughnessMap.isTexture===!0?e.mul(this.getTexture(r).r):e}else if(r===e.CLEARCOAT_NORMAL)i=n.clearcoatNormalMap?cx(this.getTexture(r),this.getCache(r+`Scale`,`vec2`)):yb;else if(r===e.SHEEN){let e=this.getColor(`sheenColor`).mul(this.getFloat(`sheen`));i=n.sheenColorMap&&n.sheenColorMap.isTexture===!0?e.mul(this.getTexture(`sheenColor`).rgb):e}else if(r===e.SHEEN_ROUGHNESS){let e=this.getFloat(r);i=n.sheenRoughnessMap&&n.sheenRoughnessMap.isTexture===!0?e.mul(this.getTexture(r).a):e,i=i.clamp(1e-4,1)}else if(r===e.ANISOTROPY){if(n.anisotropyMap&&n.anisotropyMap.isTexture===!0){let e=this.getTexture(r);i=Sh(Zx.x,Zx.y,Zx.y.negate(),Zx.x).mul(e.rg.mul(2).sub(fh(1)).normalize().mul(e.b))}else i=Zx}else if(r===e.IRIDESCENCE_THICKNESS){let e=Ib(`1`,`float`,n.iridescenceThicknessRange);if(n.iridescenceThicknessMap){let t=Ib(`0`,`float`,n.iridescenceThicknessRange);i=e.sub(t).mul(this.getTexture(r).g).add(t)}else i=e}else if(r===e.TRANSMISSION){let e=this.getFloat(r);i=n.transmissionMap?e.mul(this.getTexture(r).r):e}else if(r===e.THICKNESS){let e=this.getFloat(r);i=n.thicknessMap?e.mul(this.getTexture(r).g):e}else if(r===e.IOR)i=this.getFloat(r);else if(r===e.LIGHT_MAP)i=n.lightMap?this.getTexture(r).rgb.mul(this.getFloat(`lightMapIntensity`)):K(0);else if(r===e.AO)i=n.aoMap?this.getTexture(r).r.sub(1).mul(this.getFloat(`aoMapIntensity`)).add(1):G(1);else if(r===e.LINE_DASH_OFFSET)i=n.dashOffset?this.getFloat(r):G(0);else{let e=this.getNodeType(t);i=this.getCache(r,e)}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.RETROREFLECTIVITY=`retroreflectivity`,Z.LIGHT_MAP=`light`,Z.AO=`ao`;var px=H(Z,Z.ALPHA_TEST),mx=H(Z,Z.COLOR),hx=H(Z,Z.SHININESS),gx=H(Z,Z.EMISSIVE),_x=H(Z,Z.OPACITY),vx=H(Z,Z.SPECULAR),yx=H(Z,Z.SPECULAR_INTENSITY),bx=H(Z,Z.SPECULAR_COLOR),xx=H(Z,Z.SPECULAR_STRENGTH),Sx=H(Z,Z.REFLECTIVITY),Cx=H(Z,Z.ROUGHNESS),wx=H(Z,Z.METALNESS),Tx=H(Z,Z.NORMAL),Ex=H(Z,Z.CLEARCOAT),Dx=H(Z,Z.CLEARCOAT_ROUGHNESS),Ox=H(Z,Z.CLEARCOAT_NORMAL),kx=H(Z,Z.ROTATION),Ax=H(Z,Z.SHEEN),jx=H(Z,Z.SHEEN_ROUGHNESS),Mx=H(Z,Z.ANISOTROPY),Nx=H(Z,Z.IRIDESCENCE),Px=H(Z,Z.IRIDESCENCE_IOR),Fx=H(Z,Z.IRIDESCENCE_THICKNESS),Ix=H(Z,Z.TRANSMISSION),Lx=H(Z,Z.THICKNESS),Rx=H(Z,Z.IOR),zx=H(Z,Z.ATTENUATION_DISTANCE),Bx=H(Z,Z.ATTENUATION_COLOR),Vx=H(Z,Z.LINE_SCALE),Hx=H(Z,Z.LINE_DASH_SIZE),Ux=H(Z,Z.LINE_GAP_SIZE),Wx=H(Z,Z.LINE_WIDTH),Gx=H(Z,Z.LINE_DASH_OFFSET),Kx=H(Z,Z.POINT_SIZE),qx=H(Z,Z.DISPERSION),Jx=H(Z,Z.RETROREFLECTIVITY),Yx=H(Z,Z.LIGHT_MAP),Xx=H(Z,Z.AO),Zx=Y(new P).onReference(function(e){return e.material}).onRenderUpdate(function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))}),Qx=W(e=>e.context.setupModelViewProjection(),`vec4`).once()().toVarying(`v_modelViewProjection`),$x=class e extends z{static get type(){return`EventNode`}constructor(t,n){super(`void`),this.eventType=t,this.callback=n,t===e.OBJECT?this.updateType=$p.OBJECT:t===e.MATERIAL?this.updateType=$p.RENDER:t===e.FRAME?this.updateType=$p.FRAME:t===e.AFTER_OBJECT?this.updateAfterType=$p.OBJECT:t===e.BEFORE_OBJECT?this.updateBeforeType=$p.OBJECT:t===e.BEFORE_MATERIAL?this.updateBeforeType=$p.RENDER:t===e.BEFORE_FRAME&&(this.updateBeforeType=$p.FRAME)}setup(t){let{eventType:n,callback:r}=this;if(n===e.BEFORE_RENDER_PIPELINE){let e=t.context.onBeforePipelineCallbacks;e&&e.push(r)}else if(n===e.AFTER_RENDER_PIPELINE){let e=t.context.onAfterPipelineCallbacks;e&&e.push(r)}return super.setup(t)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}updateAfter(e){this.callback(e)}};$x.OBJECT=`object`,$x.MATERIAL=`material`,$x.FRAME=`frame`,$x.AFTER_OBJECT=`afterObject`,$x.BEFORE_OBJECT=`beforeObject`,$x.BEFORE_MATERIAL=`beforeMaterial`,$x.BEFORE_FRAME=`beforeFrame`,$x.BEFORE_RENDER_PIPELINE=`beforeRenderPipeline`,$x.AFTER_RENDER_PIPELINE=`afterRenderPipeline`;var eS=(e,t)=>new $x(e,t).toStack(),tS=e=>eS($x.OBJECT,e),nS=e=>eS($x.AFTER_OBJECT,e),rS=e=>eS($x.BEFORE_FRAME,e),iS=th(class extends sm{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){let 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,r=e.isContextAssign();if(n=e.isAvailable(`storageBuffer`)===!1?this.node.isPBO===!0&&r!==!0&&(this.node.value.isInstancedBufferAttribute||e.shaderStage!==`compute`)?e.generatePBO(this):this.node.build(e):super.generate(e),r!==!0){let r=this.getNodeType(e);n=e.format(n,r,t)}return n}}).setParameterLength(2),aS=class extends fy{static get type(){return`StorageBufferNode`}constructor(e,t=null,n=0){let r,i=null;t&&t.isStructTypeNode?(r=`struct`,i=t,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(n=e.count)):t===null&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(r=Wp(e.itemSize),n=e.count):r=t,super(e,r,n),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=em.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 iS(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(em.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return this._attribute===null&&(this._attribute=jv(this.value),this._varying=dv(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);let{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return this.structTypeNode===null?`void`:this.structTypeNode.getMemberType(e,t)}generate(e){if(this.structTypeNode!==null&&this.structTypeNode.build(e),e.isAvailable(`storageBuffer`)||e.isAvailable(`indirectStorageBuffer`))return super.generate(e);let{attribute:t,varying:n}=this.getAttributeData(),r=n.build(e);return e.registerTransform(r,t),r}},oS=(e,t=null,n=0)=>new aS(e,t,n),sS=new WeakMap,cS=new WeakMap,lS=new WeakMap;function uS(e,t){let n,r=Math.max(t.count,1);if(t.isStorageInstancedBufferAttribute===!0)n=oS(t,`mat4`,r).element(Iv);else if(r*16*4<=e.getUniformBufferLimit())n=py(t.array,`mat4`,r).element(Iv);else{let e=sS.get(t);e||(e=new Rs(t.array,16,1),sS.set(t,e));let r=t.usage===35048?Nv:Mv;n=wh(r(e,`vec4`,16,0),r(e,`vec4`,16,4),r(e,`vec4`,16,8),r(e,`vec4`,16,12))}return n}function dS(e,t,n){let r=lS.get(e);if(r===void 0){let i=t.clone();r={previousInstanceMatrix:i,node:uS(n,i)},lS.set(e,r)}return r.node}var fS=Dh(`vec3`,`vInstanceColor`),pS=W(([e,t=null],n)=>{let r=e.isStorageInstancedBufferAttribute===!0,i=t&&t.isStorageInstancedBufferAttribute===!0,a=uS(n,e),o=null;r||Math.max(e.count,1)*16*4>n.getUniformBufferLimit()&&(o=sS.get(e));let s=null,c=null;if(t){if(i)s=oS(t,`vec3`,Math.max(t.count,1)).element(Iv);else{let e=cS.get(t);e||(e=new $i(t.array,3),cS.set(t,e)),c=e,s=K((t.usage===35048?Nv:Mv)(e,`vec3`,3,0))}}(o!==null||c!==null)&&rS(()=>{o!==null&&o.version!==e.version&&(o.clearUpdateRanges(),o.updateRanges.push(...e.updateRanges),e.clearUpdateRanges(),o.version=e.version),t&&c!==null&&c.version!==t.version&&(c.clearUpdateRanges(),c.updateRanges.push(...t.updateRanges),t.clearUpdateRanges(),c.version=t.version)});let l=a.mul(ob).xyz;if(ob.assign(l),n.needsPreviousData()){let t=n.object;nS(({object:t})=>{let{previousInstanceMatrix:n}=lS.get(t);n.array.set(e.array),n.version=e.version;let r=sS.get(n);r!==void 0&&(r.version=e.version)});let r=dS(t,e,n);sb.assign(r.mul(sb).xyz)}if(n.hasGeometryAttribute(`normal`)){let e=Sb(hb,a);hb.assign(e)}s!==null&&fS.assign(s)},`void`),mS=W(([e])=>{let{instanceMatrix:t,instanceColor:n}=e;pS(t,n)},`void`),hS=new WeakMap,gS=W(([e,t])=>{let n=lh(iy(dy(e),0).x).toConst(),r=lh(t);return dy(e,ph(r.mod(n).toConst(),r.div(n).toConst()))}),_S=W(([e,t])=>{let n=lh(iy(dy(e),0).x).toConst();return dy(e,ph(lh(t).mod(n).toConst(),lh(t).div(n).toConst())).x});function vS(e,t){let n=lh(iy(dy(e),0).x).toConst(),r=G(t).mul(4).toInt().toConst(),i=r.mod(n).toConst(),a=r.div(n).toConst();return wh(dy(e,ph(i,a)),dy(e,ph(i.add(1),a)),dy(e,ph(i.add(2),a)),dy(e,ph(i.add(3),a)))}function yS(e,t){let n=hS.get(e);if(n===void 0){let{image:r,format:i,type:a}=e._matricesTexture,o=new Qi(r.data.slice(),r.width,r.height,i,a);n={previousMatricesTexture:o,node:vS(o,t)},hS.set(e,n)}return n.node}var bS=Dh(`vec4`,`vBatchColor`),xS=Dh(`uint`,`vBatchIndirectId`),SS=W(([e],t)=>{let n=t.getDrawIndex()===null?Iv:Lv,r=_S(e._indirectTexture,lh(n));xS.assign(r);let i=vS(e._matricesTexture,r),a=e._colorsTexture;if(a!==null){let e=gS(a,r);bS.assign(e)}let o=Ch(i);if(ob.assign(i.mul(ob)),t.needsPreviousData()){nS(({object:e})=>{let t=hS.get(e);t.previousMatricesTexture.image.data.set(e._matricesTexture.image.data),t.previousMatricesTexture.needsUpdate=!0});let t=yS(e,r);sb.assign(t.mul(sb).xyz)}let s=hb.div(K(o[0].dot(o[0]),o[1].dot(o[1]),o[2].dot(o[2]))),c=o.mul(s).xyz;hb.assign(c),t.hasGeometryAttribute(`tangent`)&&tx.mulAssign(o)},`void`),CS=new WeakMap,wS=new WeakMap;function TS(e){return{element:t=>{let n=lh(iy(e).x).toConst(),r=lh(t).mul(4).toConst(),i=r.div(n).toConst(),a=r.sub(i.mul(n)).toConst();return wh(e.load(ph(a,i)),e.load(ph(a.add(1),i)),e.load(ph(a.add(2),i)),e.load(ph(a.add(3),i)))}}}function ES(e,t){let n;if(t.bones.length*16*4<=e.getUniformBufferLimit())n=Lb(`skeleton.boneMatrices`,`mat4`,t.bones.length);else{t.boneTexture===null&&t.computeBoneTexture();let e=uy(t.boneTexture);tS(({object:t})=>{let n=t.skeleton;n.boneTexture===null&&n.computeBoneTexture(),e.value=n.boneTexture}),n=TS(e)}return n}function DS(e,t,n,r,i,a){let o=e.element(i.x),s=e.element(i.y),c=e.element(i.z),l=e.element(i.w),u=n.mul(t),d=hg(o.mul(a.x).mul(u),s.mul(a.y).mul(u),c.mul(a.z).mul(u),l.mul(a.w).mul(u));return r.mul(d).xyz}function OS(e,t,n,r,i,a,o){let s=e.element(a.x),c=e.element(a.y),l=e.element(a.z),u=e.element(a.w),d=hg(o.x.mul(s),o.y.mul(c),o.z.mul(l),o.w.mul(u));d=i.mul(d).mul(r);let f=Ch(d);return{skinNormal:f.mul(t),skinTangent:f.mul(n)}}function kS(e,t,n,r,i,a){let o=t.skeleton,s=wS.get(o);if(s===void 0){if(o.update(),o.bones.length*16*4<=e.getUniformBufferLimit()){let e=new Float32Array(o.boneMatrices);s={previousBoneMatrices:e,previousBoneTexture:null,node:py(e,`mat4`,o.bones.length)}}else{o.boneTexture===null&&o.computeBoneTexture();let{width:e,height:t}=o.boneTexture.image,n=new Float32Array(o.boneMatrices),r=new Qi(n,e,t,ge,se);r.needsUpdate=!0,s={previousBoneMatrices:n,previousBoneTexture:r,node:TS(uy(r))}}wS.set(o,s)}return DS(s.node,sb,n,r,i,a)}var AS=W(([e],t)=>{let n=ny(`skinIndex`,`uvec4`),r=ny(`skinWeight`,`vec4`),i=Ib(`bindMatrix`,`mat4`),a=Ib(`bindMatrixInverse`,`mat4`),o=ES(t,e.skeleton);if(tS(({object:e,frameId:t})=>{let n=e.skeleton;if(CS.get(n)!==t){CS.set(n,t);let e=wS.get(n);e!==void 0&&(e.previousBoneMatrices.set(n.boneMatrices),e.previousBoneTexture!==null&&(e.previousBoneTexture.needsUpdate=!0)),n.update()}}),t.needsPreviousData()){let o=kS(t,e,i,a,n,r);sb.assign(o)}let s=DS(o,ob,i,a,n,r);if(ob.assign(s),t.hasGeometryAttribute(`normal`)){let{skinNormal:e,skinTangent:s}=OS(o,hb,tx,i,a,n,r);hb.assign(e),t.hasGeometryAttribute(`tangent`)&&tx.assign(s)}},`void`),jS=class extends z{static get type(){return`LoopNode`}constructor(e=[]){super(`void`),this.params=e}getVarName(e){return String.fromCharCode(105+e)}getProperties(e){let t=e.getNodeProperties(this);if(t.stackNode!==void 0)return t;let n={},r=this._getInternalParams();for(let e=0,t=r.length-1;e<t;e++){let t=r[e],i=t.isNode!==!0&&t.name||this.getVarName(e);n[i]=Kv(i,t.isNode!==!0&&t.type||`int`)}let i=e.addStack(),a=r[r.length-1](n);t.returnsNode=a.context({nodeLoop:a}),t.stackNode=i;let o=r[0];if(o.isNode!==!0&&typeof o.update==`function`){let e=W(o.update)(n);t.updateNode=e.context({nodeLoop:e})}return e.removeStack(),t}_getInternalParams(){let e=this.params;return typeof e[0]==`function`?[dh(!0),e[0]]:e}setup(e){if(this.getProperties(e),e.fnCall){let t=e.getDataFromNode(e.fnCall.shaderNode);t.hasLoop=!0}}generate(e){let t=this.getProperties(e),n=this._getInternalParams(),r=t.stackNode;for(let r=0,i=n.length-1;r<i;r++){let i=n[r],a=!1,o=null,s=null,c=null,l=null,u=null,d=null;i.isNode?i.getNodeType(e)===`bool`?(a=!0,l=`bool`,s=i.build(e,l)):(l=`int`,c=this.getVarName(r),o=`0`,s=i.build(e,l),u=`<`):(l=i.type||`int`,c=i.name||this.getVarName(r),o=i.start,s=i.end,u=i.condition,d=i.update,typeof o==`number`?o=e.generateConst(l,o):o&&o.isNode&&(o=o.build(e,l)),typeof s==`number`?s=e.generateConst(l,s):s&&s.isNode&&(s=s.build(e,l)),o!==void 0&&s===void 0?(o+=` - 1`,s=`0`,u=`>=`):s!==void 0&&o===void 0&&(o=`0`,u=`<`),u===void 0&&(u=Number(o)>Number(s)?`>=`:`<`));let f;if(a)f=`while ( ${s} )`;else{let n={start:o,end:s},r=n.start,i=n.end,a,p=()=>u.includes(`<`)?`+=`:`-=`;if(d!=null)switch(typeof d){case`function`:a=e.flowStagesNode(t.updateNode,`void`).code.replace(/\t|;/g,``);break;case`number`:a=c+` `+p()+` `+e.generateConst(l,d);break;case`string`:a=c+` `+d;break;default:d.isNode?a=c+` `+p()+` `+d.build(e):(N(`TSL: 'Loop( { update: ... } )' is not a function, string or number.`,this.stackTrace),a=`break /* invalid update */`)}else d=l===`int`||l===`uint`?u.includes(`<`)?`++`:`--`:p()+` 1.`,a=c+` `+d;f=`for ( ${e.getVar(l,c)+` = `+r}; ${c+` `+u+` `+i}; ${a} )`}e.addFlowCode((r===0?`
`:``)+e.tab+f+` {
`).addFlowTab()}let i=r.build(e,`void`);t.returnsNode.build(e,`void`),e.removeFlowTab().addFlowCode(`
`+e.tab+i);for(let t=0,r=n.length-1;t<r;t++)e.addFlowCode((t===0?``:e.tab)+`}
`).removeFlowTab();e.addFlowTab()}},MS=(...e)=>new jS(eh(e,`int`)).toStack(),NS=new WeakMap,PS=new Fn,FS=new WeakMap,IS=W(({bufferMap:e,influence:t,stride:n,width:r,depth:i,offset:a})=>{let o=lh(Fv).mul(n).add(a),s=o.div(r);return dy(e,ph(o.sub(s.mul(r)),s)).depth(i).xyz.mul(t)});function LS(e){let t=e.morphAttributes.position!==void 0,n=e.morphAttributes.normal!==void 0,r=e.morphAttributes.color!==void 0,i=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,a=i===void 0?0:i.length,o=NS.get(e);if(o===void 0||o.count!==a){o!==void 0&&o.texture.dispose();let i=e.morphAttributes.position||[],s=e.morphAttributes.normal||[],c=e.morphAttributes.color||[],l=0;t===!0&&(l=1),n===!0&&(l=2),r===!0&&(l=3);let u=e.attributes.position.count*l,d=1,f=4096;u>f&&(d=Math.ceil(u/f),u=f);let p=new Float32Array(u*d*4*a),m=new Rn(p,u,d,a);m.type=se,m.needsUpdate=!0;let h=l*4;for(let e=0;e<a;e++){let a=i[e],o=s[e],l=c[e],f=u*d*4*e;for(let e=0;e<a.count;e++){let i=e*h;t===!0&&(PS.fromBufferAttribute(a,e),p[f+i+0]=PS.x,p[f+i+1]=PS.y,p[f+i+2]=PS.z,p[f+i+3]=0),n===!0&&(PS.fromBufferAttribute(o,e),p[f+i+4]=PS.x,p[f+i+5]=PS.y,p[f+i+6]=PS.z,p[f+i+7]=0),r===!0&&(PS.fromBufferAttribute(l,e),p[f+i+8]=PS.x,p[f+i+9]=PS.y,p[f+i+10]=PS.z,p[f+i+11]=l.itemSize===4?PS.w:1)}}o={count:a,texture:m,stride:l,size:new P(u,d)},NS.set(e,o);function g(){m.dispose(),NS.delete(e),e.removeEventListener(`dispose`,g)}e.addEventListener(`dispose`,g)}return o}var RS=W(([e])=>{let{geometry:t}=e,n=t.morphAttributes.position!==void 0,r=t.hasAttribute(`normal`)&&t.morphAttributes.normal!==void 0,i=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,a=i===void 0?0:i.length;if(a===0)return;let o=FS.get(e);(o===void 0||o.count!==a)&&(o={base:Y(1),influences:e.morphTargetInfluences?gy(e.morphTargetInfluences,`float`):null,count:a},FS.set(e,o));let{base:s,influences:c}=o,{texture:l,stride:u,size:d}=LS(t);n===!0&&ob.mulAssign(s),r===!0&&hb.mulAssign(s);let f=lh(d.width);MS(a,({i:t})=>{let i=G(0).toVar();e.count>1&&e.morphTexture!==null&&e.morphTexture!==void 0?i.assign(dy(e.morphTexture,ph(lh(t).add(1),lh(Iv))).r):i.assign(c.element(t).toVar()),oh(i.notEqual(0),()=>{n===!0&&ob.addAssign(IS({bufferMap:l,influence:i,stride:u,width:f,depth:t,offset:lh(0)})),r===!0&&hb.addAssign(IS({bufferMap:l,influence:i,stride:u,width:f,depth:t,offset:lh(1)}))})}),tS(({object:e})=>{let{base:t,influences:n}=o;t.value=e.geometry.morphTargetsRelative?1:1-e.morphTargetInfluences.reduce((e,t)=>e+t,0),n&&(n.array=e.morphTargetInfluences,n.update())})},`void`),zS=class extends z{static get type(){return`LightingNode`}constructor(){super(`vec3`),this.isLightingNode=!0}},BS=class extends zS{static get type(){return`AONode`}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}},VS=th(class extends $_{static get type(){return`LightingContextNode`}constructor(e,t=null,n=[],r=null,i=null){super(e),this.lightingModel=t,this.materialLightings=n,this.backdropNode=r,this.backdropAlphaNode=i,this._value=null}getContext(){let{materialLightings:e,backdropNode:t,backdropAlphaNode:n}=this,r={directDiffuse:K().toVar(`directDiffuse`),directSpecular:K().toVar(`directSpecular`),indirectDiffuse:K().toVar(`indirectDiffuse`),indirectSpecular:K().toVar(`indirectSpecular`)};return{radiance:K().toVar(`radiance`),irradiance:K().toVar(`irradiance`),iblIrradiance:K().toVar(`iblIrradiance`),ambientOcclusion:G(1).toVar(`ambientOcclusion`),reflectedLight:r,materialLightings:e,backdrop:t,backdropAlpha:n}}setup(e){return this.value=this._value||=this.getContext(),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}),HS=class extends zS{static get type(){return`IrradianceNode`}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}},US=new P,WS=class extends cy{static get type(){return`ViewportTextureNode`}constructor(e=Sy,t=null,n=null){let r=null;n===null?(r=new _a,r.minFilter=ee,n=r):r=n,super(n,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=r,this.isOutputTextureNode=!0,this.updateBeforeType=$p.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){let r=t.clone();n.set(e,r)}return n.get(e)}updateReference(e){let t=e.renderer,n=t.getRenderTarget(),r=t.getCanvasTarget(),i=n||r;return this.value=this.getTextureForReference(i),this.value}updateBefore(e){let t=e.renderer,n=t.getRenderTarget(),r=t.getCanvasTarget(),i=n||r;i===null?t.getDrawingBufferSize(US):i.getDrawingBufferSize?i.getDrawingBufferSize(US):US.set(i.width,i.height);let a=this.getTextureForReference(i);(a.image.width!==US.width||a.image.height!==US.height)&&(a.image.width=US.width,a.image.height=US.height,a.needsUpdate=!0);let o=a.generateMipmaps;a.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(a),a.generateMipmaps=o}clone(){let e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}},GS=th(WS,null,null,{generateMipmaps:!0}).setParameterLength(0,3),KS=GS(),qS=(e=Sy,t=null)=>KS.sample(e,t),JS=null,YS=th(class extends WS{static get type(){return`ViewportDepthTextureNode`}constructor(e=Sy,t=null,n=null){n===null&&(JS===null&&(JS=new ya),n=JS),super(e,t,n)}}).setParameterLength(0,3),XS=class e extends z{static get type(){return`ViewportDepthNode`}constructor(e,t=null){super(`float`),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(t){let{scope:n}=this;return n===e.DEPTH_BASE?t.getFragDepth():super.generate(t)}setup({camera:t}){let{scope:n}=this,r=this.valueNode,i=null;return n===e.DEPTH_BASE?r!==null&&(i=rC().assign(r)):n===e.DEPTH?i=t.isPerspectiveCamera?$S(ub.z,By,Vy):ZS(ub.z,By,Vy):n===e.LINEAR_DEPTH&&(i=r===null?ZS(ub.z,By,Vy):t.isPerspectiveCamera?ZS(tC(r,By,Vy),By,Vy):r),i}};XS.DEPTH_BASE=`depthBase`,XS.DEPTH=`depth`,XS.LINEAR_DEPTH=`linearDepth`;var ZS=(e,t,n)=>e.add(t).div(t.sub(n)),QS=W(([e,t,n],r)=>r.renderer.reversedDepthBuffer===!0?n.sub(t).mul(e).sub(n):t.sub(n).mul(e).sub(t)),$S=(e,t,n)=>t.add(e).mul(n).div(n.sub(t).mul(e)),eC=(e,t,n)=>t.mul(e.add(n)).div(e.mul(t.sub(n))),tC=W(([e,t,n],r)=>r.renderer.reversedDepthBuffer===!0?t.mul(n).div(t.sub(n).mul(e).sub(t)):t.mul(n).div(n.sub(t).mul(e).sub(n))),nC=(e,t,n)=>{t=t.max(1e-6).toVar();let r=Yg(e.negate().div(t)),i=Yg(n.div(t));return r.div(i)},rC=th(XS,XS.DEPTH_BASE),iC=H(XS,XS.DEPTH);YS(),iC.assign=e=>rC(e);var aC=class e extends z{static get type(){return`ClippingNode`}constructor(t=e.DEFAULT){super(),this.scope=t}setup(t){super.setup(t);let{intersectionPlanes:n,unionPlanes:r}=t.clippingContext;return this.hardwareClipping=t.hardwareClipping,this.scope===e.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,r):this.scope===e.HARDWARE?this.setupHardwareClipping(r,t):this.setupDefault(n,r)}setupAlphaToCoverage(e,t){return W(()=>{let n=G().toVar(`distanceToPlane`),r=G().toVar(`distanceToGradient`),i=G(1).toVar(`clipOpacity`),a=t.length;if(this.hardwareClipping===!1&&a>0){let e=gy(t).setGroup(J);MS(a,({i:t})=>{let a=e.element(t);n.assign(ub.dot(a.xyz).negate().add(a.w)),r.assign(n.fwidth().div(2)),i.mulAssign(Y_(r.negate(),r,n))})}let o=e.length;if(o>0){let t=gy(e).setGroup(J),a=G(1).toVar(`intersectionClipOpacity`);MS(o,({i:e})=>{let i=t.element(e);n.assign(ub.dot(i.xyz).negate().add(i.w)),r.assign(n.fwidth().div(2)),a.mulAssign(Y_(r.negate(),r,n).oneMinus())}),i.mulAssign(a.oneMinus())}Oh.a.mulAssign(i),Oh.a.equal(0).discard()})()}setupDefault(e,t){return W(()=>{let n=t.length;if(this.hardwareClipping===!1&&n>0){let e=gy(t).setGroup(J);MS(n,({i:t})=>{let n=e.element(t);ub.dot(n.xyz).greaterThan(n.w).discard()})}let r=e.length;if(r>0){let t=gy(e).setGroup(J),n=dh(!0).toVar(`clipped`);MS(r,({i:e})=>{let r=t.element(e);n.assign(ub.dot(r.xyz).greaterThan(r.w).and(n))}),n.discard()}})()}setupHardwareClipping(e,t){let n=e.length;return t.enableHardwareClipping(n),W(()=>{let r=gy(e).setGroup(J),i=_y(t.getClipDistance());MS(n,({i:e})=>{let t=r.element(e),n=ub.dot(t.xyz).sub(t.w).negate();i.element(e).assign(n)})})()}};aC.ALPHA_TO_COVERAGE=`alphaToCoverage`,aC.DEFAULT=`default`,aC.HARDWARE=`hardware`;var oC=()=>new aC,sC=()=>new aC(aC.ALPHA_TO_COVERAGE),cC=()=>new aC(aC.HARDWARE),lC=.05,uC=W(([e])=>t_(_g(1e4,n_(_g(17,e.x).add(_g(.1,e.y)))).mul(hg(.1,m_(n_(_g(13,e.y).add(e.x))))))),dC=W(([e])=>uC(fh(uC(e.xy),e.z))),fC=W(([e])=>{let t=k_(g_(y_(e.xyz)),g_(b_(e.xyz))),n=G(1).div(G(lC).mul(t)).toVar(`pixScale`),r=fh(qg(Qg(Yg(n))),qg($g(Yg(n)))),i=fh(dC(Qg(r.x.mul(e.xyz))),dC(Qg(r.y.mul(e.xyz)))),a=t_(Yg(n)),o=hg(_g(a.oneMinus(),i.x),_g(a,i.y)),s=O_(a,a.oneMinus()),c=K(o.mul(o).div(_g(2,s).mul(gg(1,s))),o.sub(_g(.5,s)).div(gg(1,s)),gg(1,gg(1,o).mul(gg(1,o)).div(_g(2,s).mul(gg(1,s)))));return K_(o.lessThan(s.oneMinus()).select(o.lessThan(s).select(c.x,c.y),c.z),1e-6,1)}).setLayout({name:`getAlphaHashThreshold`,type:`float`,inputs:[{name:`position`,type:`vec3`}]}),pC=class extends ty{static get type(){return`VertexColorNode`}constructor(e){super(null,`vec4`),this.isVertexColorNode=!0,this.index=e}getAttributeName(){let e=this.index;return`color`+(e>0?e:``)}generate(e){let t=this.getAttributeName(e),n=e.hasGeometryAttribute(t),r;return r=n===!0?super.generate(e):e.generateConst(this.nodeType,new Fn(1,1,1,1)),r}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}},mC=(e=0)=>new pC(e),hC=class extends Ai{static get type(){return`NodeMaterial`}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){let e=[];for(let t of Object.getOwnPropertyNames(this)){if(t.startsWith(`_`)===!0)continue;let n=this[t];n&&n.isNode===!0&&e.push({property:t,childNode:n})}return e}customProgramCacheKey(){let e=[];for(let{property:t,childNode:n}of this._getNodeChildren())e.push(zp(t.slice(0,-4)),n.getCacheKey());return this.type+Bp(e)}build(e){this.setup(e)}setupObserver(e){return new Pp(e)}setup(e){e.context.setupNormal=()=>uv(this.setupNormal(e),`NORMAL`,`vec3`),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);let t=e.renderer,n=t.getRenderTarget();e.addStack();let r=this.setupVertex(e),i=uv(this.vertexNode||r,`VERTEX`);e.context.clipSpace=i,e.stack.outputNode=i,this.setupHardwareClipping(e),this.geometryNode!==null&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow(`vertex`,e.removeStack()),e.addStack();let a,o=this.setupClipping(e);if((this.depthWrite===!0||this.depthTest===!0)&&(n===null?t.depth===!0&&this.setupDepth(e):n.depthBuffer===!0&&this.setupDepth(e)),this.fragmentNode===null){this.setupDiffuseColor(e),this.setupAmbientOcclusion(e),this.setupVariants(e);let r=this.setupLighting(e);o!==null&&e.stack.addToStack(o);let i=q(r,Oh.a).max(0);a=this.setupOutput(e,i),Jh.assign(a);let s=this.outputNode!==null;if(s&&(a=this.outputNode),e.context.getOutput&&(a=e.context.getOutput(a,e)),n!==null){let e=t.getMRT(),n=this.mrtNode;e===null?n!==null&&(a=n):(s&&Jh.assign(a),a=e,n!==null&&(a=e.merge(n)))}}else{let t=this.fragmentNode;t.isOutputStructNode!==!0&&(t=t.convert(e.getOutputType())),a=this.setupOutput(e,t)}e.stack.outputNode=a,e.addFlow(`fragment`,e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(e.clippingContext===null)return null;let{unionPlanes:t,intersectionPlanes:n}=e.clippingContext,r=null;if(t.length>0||n.length>0){let t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?r=sC():e.stack.addToStack(oC())}return r}setupHardwareClipping(e){if(e.hardwareClipping=!1,e.clippingContext===null)return;let t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable(`clipDistance`)&&(e.stack.addToStack(cC()),e.hardwareClipping=!0)}setupDepth(e){let{renderer:t,camera:n}=e,r=this.depthNode;if(r===null){let e=t.getMRT();e&&e.has(`depth`)?r=e.get(`depth`):t.logarithmicDepthBuffer===!0&&(r=n.isPerspectiveCamera?nC(ub.z,By,Vy):ZS(ub.z,By,Vy))}r!==null&&iC.assign(r).toStack()}setupPositionView(){return eb.mul(ob).xyz}setupModelViewProjection(){return Hy.mul(ub)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),Qx}setupPosition(e){let{object:t,geometry:n}=e;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&RS(t),t.isSkinnedMesh===!0&&AS(t),this.displacementMap){let e=zb(`displacementMap`,`texture`),t=zb(`displacementScale`,`float`),n=zb(`displacementBias`,`float`);ob.addAssign(hb.normalize().mul(e.x.mul(t).add(n)))}return t.isBatchedMesh&&SS(t),t.isInstancedMesh&&t.instanceMatrix&&t.instanceMatrix.isInstancedBufferAttribute===!0&&mS(t),this.positionNode!==null&&ob.assign(uv(this.positionNode,`POSITION`,`vec3`)),ob}setupDiffuseColor(e){let{object:t,geometry:n}=e;this.maskNode!==null&&dh(this.maskNode).not().discard();let r=this.colorNode?q(this.colorNode):mx;this.vertexColors===!0&&n.hasAttribute(`color`)&&(r=r.mul(mC())),t.instanceColor&&(r=fS.mul(r)),t.isBatchedMesh&&t._colorsTexture&&(r=bS.mul(r)),Oh.assign(r);let i=this.opacityNode?G(this.opacityNode):_x;Oh.a.assign(Oh.a.mul(i));let a=null;(this.alphaTestNode!==null||this.alphaTest>0)&&(a=this.alphaTestNode===null?px:G(this.alphaTestNode),this.alphaToCoverage===!0?(Oh.a=Y_(a,a.add(w_(Oh.a)),Oh.a),Oh.a.lessThanEqual(0).discard()):Oh.a.lessThanEqual(a).discard()),this.alphaHash===!0&&Oh.a.lessThan(fC(ob)).discard(),e.isOpaque()&&Oh.a.assign(1)}setupVariants(){}setupOutgoingLight(){return this.lights===!0?K(0):Oh.rgb}setupNormal(){return this.normalNode?K(this.normalNode):Tx}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?zb(`envMap`,`cubeTexture`):zb(`envMap`,`texture`)),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new HS(Yx)),t}setupMaterialLightings(e){let t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);let r=this.setupLightMap(e);if(r&&r.isLightingNode&&t.push(r),e.context.ambientOcclusion&&t.push(new BS(e.context.ambientOcclusion)),e.context.getGI){let n=e.context.getGI(null,e);n!==null&&t.push(new HS(n))}return t}setupAmbientOcclusion(e){let t=this.aoNode;t===null&&e.material.aoMap&&(t=Xx),e.context.getAO&&(t=e.context.getAO(t,e)),t!==null&&(ig.assign(t),e.context.ambientOcclusion=ig)}setupLightingModel(){}setupLighting(e){let{material:t}=e,{backdropNode:n,backdropAlphaNode:r,emissiveNode:i}=this,a=this.lights===!0&&e.renderer.lighting.enabled,o=a||this.lightsNode!==null,s=a?this.setupMaterialLightings(e):[],c=o?this.lightsNode||e.lightsNode:null,l=this.setupOutgoingLight(e);return c&&(s.length>0||c.getScope().hasLights)?l=VS(c,this.setupLightingModel(e)||null,s,n,r):n!==null&&(l=K(r===null?n:G_(l,n,r))),(i&&i.isNode===!0||t.emissive&&t.emissive.isColor===!0)&&(Ah.assign(K(i||gx)),l=l.add(Ah)),l}setupFog(e,t){let n=e.fogNode;return n&&(Jh.assign(t),t=q(n.toVar())),t}setupPremultipliedAlpha(e,t){return qv(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(let t in e){let n=e[t];this[t]===void 0&&(this[t]=n,n&&n.clone&&(this[t]=n.clone()))}let t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(let e in t)Object.getOwnPropertyDescriptor(this.constructor.prototype,e)===void 0&&t[e].get!==void 0&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{},nodes:{}});let n=Ai.prototype.toJSON.call(this,e);n.inputNodes={};for(let{property:t,childNode:r}of this._getNodeChildren())n.inputNodes[t]=r.toJSON(e).uuid;function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images),a=r(e.nodes);t.length>0&&(n.textures=t),i.length>0&&(n.images=i),a.length>0&&(n.nodes=a)}return n}copy(e){let t=Object.getOwnPropertyDescriptors(this.constructor.prototype);for(let n in t)if(t[n].set!==void 0&&e[n]!==void 0){let t=e[n];this[n]&&this[n].copy!==void 0?this[n].copy(t):this[n]=t}for(let t in this)if(!/^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPlanes)$/.test(t)&&this[t]!==void 0&&e[t]!==void 0){let n=e[t];this[t]&&this[t].copy!==void 0?this[t].copy(n):this[t]=n}return this.clippingPlanes=e.clippingPlanes?e.clippingPlanes.map(e=>e.clone()):null,this.userData=JSON.parse(JSON.stringify(e.userData)),this}},gC=new oa,_C=class extends hC{static get type(){return`LineBasicNodeMaterial`}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(gC),this.setValues(e)}},vC=new So,yC=class extends hC{static get type(){return`LineDashedNodeMaterial`}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(vC),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){let e=this.offsetNode?G(this.offsetNode):Gx,t=this.dashScaleNode?G(this.dashScaleNode):Vx,n=this.dashSizeNode?G(this.dashSizeNode):Hx,r=this.gapSizeNode?G(this.gapSizeNode):Ux;Yh.assign(n),Xh.assign(r);let i=dv(ny(`lineDistance`).mul(t));(e?i.add(e):i).mod(Yh.add(Xh)).greaterThan(Yh).discard()}},bC=Dh(`vec3`,`worldStart`),xC=Dh(`vec3`,`worldEnd`),SC=Dh(`float`,`lineDistance`),CC=Dh(`vec4`,`worldPos`),wC=W(({start:e,end:t})=>{let n=Hy.element(2).element(2),r=Hy.element(3).element(2);return n.greaterThan(0).select(r.negate().div(n.add(1)),r.mul(-.5).div(n)).sub(e.z).div(t.z.sub(e.z))},{start:`vec4`,end:`vec4`,return:`float`}),TC=W(({p1:e,p2:t,p3:n,p4:r})=>{let i=e.sub(n),a=r.sub(n),o=t.sub(e),s=i.dot(a),c=a.dot(o),l=i.dot(o),u=a.dot(a),d=o.dot(o).mul(u).sub(c.mul(c)),f=s.mul(c).sub(l.mul(u)).div(d).clamp();return fh(f,s.add(c.mul(f)).div(u).clamp())},{p1:`vec3`,p2:`vec3`,p3:`vec3`,p4:`vec3`,return:`vec2`});W(({material:e})=>{let t=e._useDash,n=e._useWorldUnits,r=ny(`instanceStart`),i=ny(`instanceEnd`),a=q(eb.mul(q(r,1))).toVar(`start`),o=q(eb.mul(q(i,1))).toVar(`end`),s,c;t&&(s=G(ny(`instanceDistanceStart`)).toVar(`distanceStart`),c=G(ny(`instanceDistanceEnd`)).toVar(`distanceEnd`)),n&&(bC.assign(a.xyz),xC.assign(o.xyz));let l=Ty.z.div(Ty.w);if(oh(Hy.element(2).element(3).equal(-1),()=>{oh(a.z.lessThan(0).and(o.z.greaterThan(0)),()=>{let e=wC({start:a,end:o});o.assign(q(G_(a.xyz,o.xyz,e),o.w)),t&&c.assign(G_(s,c,e))}).ElseIf(o.z.lessThan(0).and(a.z.greaterThanEqual(0)),()=>{let e=wC({start:o,end:a});a.assign(q(G_(o.xyz,a.xyz,e),a.w)),t&&s.assign(G_(c,s,e))})}),t){let t=e.dashScaleNode?G(e.dashScaleNode):Vx,n=e.offsetNode?G(e.offsetNode):Gx,r=ab.y.lessThan(.5).select(t.mul(s),t.mul(c));r=r.add(n),SC.assign(r)}let u=Hy.mul(a),d=Hy.mul(o),f=u.xyz.div(u.w),p=d.xyz.div(d.w),m=p.xy.sub(f.xy).toVar();m.x.assign(m.x.mul(l)),m.assign(m.normalize());let h=q().toVar();if(n){let e=o.xyz.sub(a.xyz).normalize(),n=G_(a.xyz,o.xyz,.5).normalize(),r=e.cross(n).normalize(),i=e.cross(r);CC.assign(ab.y.lessThan(.5).select(a,o));let s=Wx.mul(.5);CC.addAssign(q(ab.x.lessThan(0).select(r.mul(s),r.mul(s).negate()),0)),t||(CC.addAssign(q(ab.y.lessThan(.5).select(e.mul(s).negate(),e.mul(s)),0)),CC.addAssign(q(i.mul(s),0)),oh(ab.y.greaterThan(1).or(ab.y.lessThan(0)),()=>{CC.subAssign(q(i.mul(2).mul(s),0))})),h.assign(Hy.mul(CC));let c=K().toVar();c.assign(ab.y.lessThan(.5).select(f,p)),h.z.assign(c.z.mul(h.w))}else{let e=fh(m.y,m.x.negate()).toVar(`offset`);m.x.assign(m.x.div(l)),e.x.assign(e.x.div(l)),e.assign(ab.x.lessThan(0).select(e.negate(),e)),oh(ab.y.lessThan(0),()=>{e.assign(e.sub(m))}).ElseIf(ab.y.greaterThan(1),()=>{e.assign(e.add(m))}),e.assign(e.mul(Wx)),e.assign(e.div(Ty.w.div(xy))),h.assign(ab.y.lessThan(.5).select(u,d)),e.assign(e.mul(h.w)),h.assign(h.add(q(e,0,0)))}return h})(),W(({material:e,renderer:t})=>{let n=e._useAlphaToCoverage,r=e._useDash,i=e._useWorldUnits,a=ry();if(r){let t=e.dashSizeNode?G(e.dashSizeNode):Hx,n=e.gapSizeNode?G(e.gapSizeNode):Ux;Yh.assign(t),Xh.assign(n),a.y.lessThan(-1).or(a.y.greaterThan(1)).discard(),SC.mod(Yh.add(Xh)).greaterThan(Yh).discard()}let o=G(1).toVar(`alpha`);if(i){let e=CC.xyz.normalize().mul(1e5),i=xC.sub(bC),a=TC({p1:bC,p2:xC,p3:K(0,0,0),p4:e}),s=bC.add(i.mul(a.x)),c=e.mul(a.y),l=s.sub(c).length().div(Wx);if(!r){if(n&&t.currentSamples>0){let e=l.fwidth();o.assign(Y_(e.negate().add(.5),e.add(.5),l).oneMinus())}else l.greaterThan(.5).discard()}}else if(n&&t.currentSamples>0){let e=a.x,t=a.y.greaterThan(0).select(a.y.sub(1),a.y.add(1)),n=e.mul(e).add(t.mul(t)),r=G(n.fwidth()).toVar(`dlen`);oh(a.y.abs().greaterThan(1),()=>{o.assign(Y_(r.oneMinus(),r.add(1),n).oneMinus())})}else oh(a.y.abs().greaterThan(1),()=>{let e=a.x,t=a.y.greaterThan(0).select(a.y.sub(1),a.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()});return o})();var EC=new _o,DC=class extends hC{static get type(){return`MeshNormalNodeMaterial`}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(EC),this.setValues(e)}setupDiffuseColor(){let e=this.opacityNode?G(this.opacityNode):_x;Oh.assign(vv(q(ox(yb),e),pt))}},OC=W(([e=lb])=>fh(e.z.atan(e.x).mul(1/(Math.PI*2)).add(.5),e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5))),kC=W(([e=ry()])=>{let t=e.x.sub(.5).mul(Math.PI*2),n=e.y.sub(.5).mul(Math.PI),r=n.cos();return K(r.mul(t.cos()),n.sin(),r.mul(t.sin()))}),AC=class extends In{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;let n={width:e,height:e,depth:1},r=[n,n,n,n,n,n];this.texture=new va(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){let n=t.minFilter,r=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let i=new Sa(5,5,5),a=OC(lb),o=new hC;o.colorNode=uy(t,a,0),o.side=1,o.blending=0;let s=new Yi(i,o),c=new Sr;c.add(s),t.minFilter===1008&&(t.minFilter=O);let l=new Ss(1,10,this),u=e.getMRT();return e.setMRT(null),l.update(e,c),e.setMRT(u),t.minFilter=n,t.generateMipmaps=r,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}},jC=new WeakMap,MC=class extends lm{static get type(){return`CubeMapNode`}constructor(e){super(`vec3`),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Pb(null);let t=new va;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=$p.RENDER}updateBefore(e){let{renderer:t,material:n}=e,r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){let e=r.isTextureNode?r.value:n[r.property];if(e&&e.isTexture){let n=e.mapping;if(n===303||n===304){if(jC.has(e)){let t=jC.get(e);FC(t,e.mapping),this._cubeTexture=t}else{let n=e.image;if(NC(n)){let r=new AC(n.height);r.fromEquirectangularTexture(t,e),FC(r.texture,e.mapping),this._cubeTexture=r.texture,jC.set(e,r.texture),e.addEventListener(`dispose`,PC)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}};function NC(e){return e!=null&&e.height>0}function PC(e){let t=e.target;t.removeEventListener(`dispose`,PC);let n=jC.get(t);n!==void 0&&(jC.delete(t),n.dispose())}function FC(e,t){t===303?e.mapping=301:t===304&&(e.mapping=302)}var IC=th(MC).setParameterLength(1),LC=class extends zS{static get type(){return`BasicEnvironmentNode`}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=IC(this.envNode)}},RC=class extends zS{static get type(){return`BasicLightMapNode`}constructor(e=null){super(),this.lightMapNode=e}setup(e){let t=G(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}},zC=class{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}},BC=class extends zC{constructor(){super()}indirect({context:e}){let t=e.ambientOcclusion,n=e.reflectedLight,r=e.irradianceLightMap;n.indirectDiffuse.assign(q(0)),r?n.indirectDiffuse.addAssign(r):n.indirectDiffuse.addAssign(q(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(Oh.rgb)}finish(e){let{material:t,context:n}=e,r=n.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case 0:r.rgb.assign(G_(r.rgb,r.rgb.mul(i.rgb),xx.mul(Sx)));break;case 1:r.rgb.assign(G_(r.rgb,i.rgb,xx.mul(Sx)));break;case 2:r.rgb.addAssign(i.rgb.mul(xx.mul(Sx)));break;default:M(`BasicLightingModel: Unsupported .combine value:`,t.combine)}}},VC=new Li,HC=class extends hC{static get type(){return`MeshBasicNodeMaterial`}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(VC),this.setValues(e)}setupNormal(){return pb(_b)}setupEnvironment(e){let t=super.setupEnvironment(e);return t?new LC(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new RC(Yx)),t}setupOutgoingLight(){return Oh.rgb}setupLightingModel(){return new BC}},UC=W(({f0:e,f90:t,dotVH:n})=>{let r=n.mul(-5.55473).sub(6.98316).mul(n).exp2();return e.mul(r.oneMinus()).add(t.mul(r))}),WC=W(e=>e.diffuseColor.mul(1/Math.PI)),GC=()=>G(.25),KC=W(({dotNH:e})=>qh.mul(G(.5)).add(1).mul(G(1/Math.PI)).mul(e.pow(qh))),qC=W(({lightDirection:e})=>{let t=e.add(db).normalize(),n=yb.dot(t).clamp(),r=UC({f0:Wh,f90:1,dotVH:db.dot(t).clamp()}),i=GC(),a=KC({dotNH:n});return r.mul(i).mul(a)}),JC=class extends BC{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){let r=yb.dot(e).clamp().mul(t);n.directDiffuse.addAssign(r.mul(WC({diffuseColor:Oh.rgb}))),this.specular===!0&&n.directSpecular.addAssign(r.mul(qC({lightDirection:e})).mul(xx))}indirect(e){let{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(WC({diffuseColor:Oh}))),r.indirectDiffuse.mulAssign(t)}},YC=new vo,XC=class extends hC{static get type(){return`MeshLambertNodeMaterial`}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(YC),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t?new LC(t):null}setupLightingModel(){return new JC(!1)}},ZC=new ho,QC=class extends hC{static get type(){return`MeshPhongNodeMaterial`}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(ZC),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t?new LC(t):null}setupLightingModel(){return new JC}setupVariants(){let e=(this.shininessNode?G(this.shininessNode):hx).max(1e-4);qh.assign(e);let t=this.specularNode||vx;Wh.assign(t)}},$C=W(e=>{if(e.geometry.hasAttribute(`normal`)===!1)return G(0);let t=_b.dFdx().abs().max(_b.dFdy().abs());return t.x.max(t.y).max(t.z)}),ew=W(e=>{let{roughness:t}=e,n=$C(),r=t.max(.0525);return r=r.add(n),r=r.min(1),r}),tw=W(({alpha:e,dotNL:t,dotNV:n})=>{let r=e.pow2(),i=t.mul(r.add(r.oneMinus().mul(n.pow2())).sqrt()),a=n.mul(r.add(r.oneMinus().mul(t.pow2())).sqrt());return vg(.5,i.add(a).max(Bg))}).setLayout({name:`V_GGX_SmithCorrelated`,type:`float`,inputs:[{name:`alpha`,type:`float`},{name:`dotNL`,type:`float`},{name:`dotNV`,type:`float`}]}),nw=W(({alphaT:e,alphaB:t,dotTV:n,dotBV:r,dotTL:i,dotBL:a,dotNV:o,dotNL:s})=>{let c=s.mul(K(e.mul(n),t.mul(r),o).length()),l=o.mul(K(e.mul(i),t.mul(a),s).length());return vg(.5,c.add(l).max(Bg))}).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`}]}),rw=W(({alpha:e,dotNH:t})=>{let n=e.pow2(),r=t.pow2().mul(n.oneMinus()).oneMinus();return n.div(r.pow2()).mul(1/Math.PI)}).setLayout({name:`D_GGX`,type:`float`,inputs:[{name:`alpha`,type:`float`},{name:`dotNH`,type:`float`}]}),iw=G(1/Math.PI),aw=W(({alphaT:e,alphaB:t,dotNH:n,dotTH:r,dotBH:i})=>{let a=e.mul(t),o=K(t.mul(r),e.mul(i),a.mul(n)),s=o.dot(o),c=a.div(s);return iw.mul(a.mul(c.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`}]}),ow=W(({lightDirection:e,f0:t,f90:n,roughness:r,f:i,normalView:a=yb,viewDirection:o=db,USE_IRIDESCENCE:s,USE_ANISOTROPY:c})=>{let l=r.pow2(),u=e.add(o).normalize(),d=a.dot(e).clamp(),f=a.dot(o).clamp(),p=a.dot(u).clamp(),m=UC({f0:t,f90:n,dotVH:o.dot(u).clamp()}),h,g;if(Ym(s)&&(m=Lh.mix(m,i)),Ym(c)){let t=Hh.dot(e),n=Hh.dot(o),r=Hh.dot(u),i=Uh.dot(e),a=Uh.dot(o),s=Uh.dot(u);h=nw({alphaT:Bh,alphaB:l,dotTV:n,dotBV:a,dotTL:t,dotBL:i,dotNV:f,dotNL:d}),g=aw({alphaT:Bh,alphaB:l,dotNH:p,dotTH:r,dotBH:s})}else h=tw({alpha:l,dotNL:d,dotNV:f}),g=rw({alpha:l,dotNH:p});return m.mul(h).mul(g)}),sw=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]),cw=null,lw=W(({roughness:e,dotNV:t})=>{cw===null&&(cw=new Qi(sw,16,16,xe,ce),cw.name=`DFG_LUT`,cw.minFilter=O,cw.magFilter=O,cw.wrapS=C,cw.wrapT=C,cw.generateMipmaps=!1,cw.needsUpdate=!0);let n=fh(e,t);return uy(cw,n).rg}),uw=W(e=>{let{dotNV:t,specularColor:n,specularF90:r,roughness:i}=e,a=lw({dotNV:t,roughness:i});return n.mul(a.x).add(r.mul(a.y))}),dw=W(({f:e,f90:t,dotVH:n})=>{let r=n.oneMinus().saturate(),i=r.mul(r),a=r.mul(i,i).clamp(0,.9999);return e.sub(K(t).mul(a)).div(a.oneMinus())}).setLayout({name:`Schlick_to_F0`,type:`vec3`,inputs:[{name:`f`,type:`vec3`},{name:`f90`,type:`float`},{name:`dotVH`,type:`float`}]}),fw=W(({roughness:e,dotNH:t})=>{let n=e.pow2(),r=G(1).div(n),i=t.pow2().oneMinus().max(.0078125);return G(2).add(r).mul(i.pow(r.mul(.5))).div(2*Math.PI)}).setLayout({name:`D_Charlie`,type:`float`,inputs:[{name:`roughness`,type:`float`},{name:`dotNH`,type:`float`}]}),pw=W(({dotNV:e,dotNL:t})=>G(1).div(G(4).mul(t.add(e).sub(t.mul(e)))).clamp()).setLayout({name:`V_Neubelt`,type:`float`,inputs:[{name:`dotNV`,type:`float`},{name:`dotNL`,type:`float`}]}),mw=W(({lightDirection:e})=>{let t=e.add(db).normalize(),n=yb.dot(e).clamp(),r=yb.dot(db).clamp(),i=fw({roughness:Ih,dotNH:yb.dot(t).clamp()}),a=pw({dotNV:r,dotNL:n});return Fh.mul(i).mul(a)}),hw=W(({N:e,V:t,roughness:n})=>{let r=fh(n,e.dot(t).saturate().oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r}).setLayout({name:`LTC_Uv`,type:`vec2`,inputs:[{name:`N`,type:`vec3`},{name:`V`,type:`vec3`},{name:`roughness`,type:`float`}]}),gw=W(({f:e})=>{let t=e.length();return k_(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:`LTC_ClippedSphereFormFactor`,type:`float`,inputs:[{name:`f`,type:`vec3`}]}),_w=W(({v1:e,v2:t})=>{let n=e.dot(t),r=n.abs().toVar(),i=r.mul(.0145206).add(.4965155).mul(r).add(.8543985).toVar(),a=r.add(4.1616724).mul(r).add(3.417594).toVar(),o=i.div(a),s=n.greaterThan(0).select(o,k_(n.mul(n).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return e.cross(t).mul(s)}).setLayout({name:`LTC_EdgeVectorFormFactor`,type:`vec3`,inputs:[{name:`v1`,type:`vec3`},{name:`v2`,type:`vec3`}]}),vw=W(({N:e,V:t,P:n,mInv:r,p0:i,p1:a,p2:o,p3:s})=>{let c=a.sub(i).toVar(),l=s.sub(i).toVar(),u=c.cross(l),d=K().toVar();return oh(u.dot(n.sub(i)).greaterThanEqual(0),()=>{let c=t.sub(e.mul(t.dot(e))).normalize(),l=e.cross(c).negate(),u=r.mul(Ch(c,l,e).transpose()).toVar(),f=u.mul(i.sub(n)).normalize().toVar(),p=u.mul(a.sub(n)).normalize().toVar(),m=u.mul(o.sub(n)).normalize().toVar(),h=u.mul(s.sub(n)).normalize().toVar(),g=K(0).toVar();g.addAssign(_w({v1:f,v2:p})),g.addAssign(_w({v1:p,v2:m})),g.addAssign(_w({v1:m,v2:h})),g.addAssign(_w({v1:h,v2:f})),d.assign(K(gw({f:g})))}),d}).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`}]}),yw=1/6,bw=e=>_g(yw,_g(e,_g(e,e.negate().add(3)).sub(3)).add(1)),xw=e=>_g(yw,_g(e,_g(e,_g(3,e).sub(6))).add(4)),Sw=e=>_g(yw,_g(e,_g(e,_g(-3,e).add(3)).add(3)).add(1)),Cw=e=>_g(yw,I_(e,3)),ww=e=>bw(e).add(xw(e)),Tw=e=>Sw(e).add(Cw(e)),Ew=e=>hg(-1,xw(e).div(bw(e).add(xw(e)))),Dw=e=>hg(1,Cw(e).div(Sw(e).add(Cw(e)))),Ow=(e,t,n)=>{let r=e.uvNode,i=_g(r,t.zw).add(.5),a=Qg(i),o=t_(i),s=ww(o.x),c=Tw(o.x),l=Ew(o.x),u=Dw(o.x),d=Ew(o.y),f=Dw(o.y),p=fh(a.x.add(l),a.y.add(d)).sub(.5).mul(t.xy),m=fh(a.x.add(u),a.y.add(d)).sub(.5).mul(t.xy),h=fh(a.x.add(l),a.y.add(f)).sub(.5).mul(t.xy),g=fh(a.x.add(u),a.y.add(f)).sub(.5).mul(t.xy),_=ww(o.y).mul(hg(s.mul(e.sample(p).level(n)),c.mul(e.sample(m).level(n)))),v=Tw(o.y).mul(hg(s.mul(e.sample(h).level(n)),c.mul(e.sample(g).level(n))));return _.add(v)},kw=W(([e,t])=>{let n=fh(e.size(lh(t))),r=fh(e.size(lh(t.add(1)))),i=vg(1,n),a=vg(1,r),o=Ow(e,q(i,n),Qg(t)),s=Ow(e,q(a,r),$g(t));return t_(t).mix(o,s)}),Aw=W(([e,t,n,r,i])=>{let a=K(J_(t.negate(),e_(e),vg(1,r))),o=K(g_(i[0].xyz),g_(i[1].xyz),g_(i[2].xyz));return e_(a).mul(n.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`}]}),jw=W(([e,t])=>e.mul(K_(t.mul(2).sub(2),0,1))).setLayout({name:`applyIorToRoughness`,type:`float`,inputs:[{name:`roughness`,type:`float`},{name:`ior`,type:`float`}]}),Mw=GS(),Nw=qS(),Pw=W(([e,t,n],{material:r})=>kw((r.side===1?Mw:Nw).sample(e.mul(qy.zw).add(qy.xy).div(Cy)),Yg(qy.z).mul(jw(t,n)))),Fw=W(([e,t,n])=>(oh(n.notEqual(0),()=>Kg(Jg(t).negate().div(n).negate().mul(e))),K(1))).setLayout({name:`volumeAttenuation`,type:`vec3`,inputs:[{name:`transmissionDistance`,type:`float`},{name:`attenuationColor`,type:`vec3`},{name:`attenuationDistance`,type:`float`}]}),Iw=W(([e,t,n,r,i,a,o,s,c,l,u,d,f,p,m])=>{let h,g;if(m){h=q().toVar(),g=K().toVar();let i=u.sub(1).mul(m.mul(.025)),a=K(u.sub(i),u,u.add(i));MS({start:0,end:3},({i})=>{let u=a.element(i),m=Aw(e,t,d,u,s),_=o.add(m),v=l.mul(c.mul(q(_,1))),y=fh(v.xy.div(v.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(fh(y.x,y.y.oneMinus()));let b=Pw(y,n,u);h.element(i).assign(b.element(i)),h.a.addAssign(b.a),g.element(i).assign(r.element(i).mul(Fw(g_(m),f,p).element(i)))}),h.a.divAssign(3)}else{let i=Aw(e,t,d,u,s),a=o.add(i),m=l.mul(c.mul(q(a,1))),_=fh(m.xy.div(m.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(fh(_.x,_.y.oneMinus())),h=Pw(_,n,u),g=r.mul(Fw(g_(i),f,p))}let _=g.rgb.mul(h.rgb),v=K(uw({dotNV:e.dot(t).clamp(),specularColor:i,specularF90:a,roughness:n})),y=g.r.add(g.g,g.b).div(3);return q(v.oneMinus().mul(_),h.a.oneMinus().mul(y).oneMinus())}),Lw=Ch(3.2404542,-1.5371385,-.4985314,-.969266,1.8760108,.041556,.0556434,-.2040259,1.0572252),Rw=e=>{let t=e.sqrt();return K(1).add(t).div(K(1).sub(t))},zw=(e,t)=>e.sub(t).div(e.add(t)).pow2(),Bw=(e,t)=>{let n=e.mul(2*Math.PI*1e-9),r=K(54856e-17,44201e-17,52481e-17),i=K(1681e3,1795300,2208400),a=K(43278e5,93046e5,66121e5),o=G(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(n.mul(2239900).add(t.x).cos()).mul(n.pow2().mul(-45282e5).exp()),s=r.mul(a.mul(2*Math.PI).sqrt()).mul(i.mul(n).add(t).cos()).mul(n.pow2().negate().mul(a).exp());return s=K(s.x.add(o),s.y,s.z).div(1.0685e-7),Lw.mul(s)},Vw=W(({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:r,baseF0:i})=>{let a=G_(e,t,Y_(0,.03,r)),o=e.div(a).pow2().mul(n.pow2().oneMinus()).oneMinus();oh(o.lessThan(0),()=>K(1));let s=o.sqrt(),c=UC({f0:zw(a,e),f90:1,dotVH:n}),l=c.oneMinus(),u=a.lessThan(e).select(Math.PI,0),d=G(Math.PI).sub(u),f=Rw(i.clamp(0,.9999)),p=UC({f0:zw(f,a.toVec3()),f90:1,dotVH:s}),m=K(f.x.lessThan(a).select(Math.PI,0),f.y.lessThan(a).select(Math.PI,0),f.z.lessThan(a).select(Math.PI,0)),h=a.mul(r,s,2),g=K(d).add(m),_=c.mul(p).clamp(1e-5,.9999),v=_.sqrt(),y=l.pow2().mul(p).div(K(1).sub(_)),b=c.add(y).toVar(),x=y.sub(l).toVar();return MS({start:1,end:2,condition:`<=`,name:`m`},({m:e})=>{x.mulAssign(v);let t=Bw(G(e).mul(h),G(e).mul(g)).mul(2);b.addAssign(x.mul(t))}),b.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`}]}),Hw=W(({normal:e,viewDir:t,roughness:n})=>{let r=e.dot(t).saturate(),i=n.mul(n),a=n.add(.1).reciprocal(),o=G(-1.9362).add(n.mul(1.0678)).add(i.mul(.4573)).sub(a.mul(.8469)),s=G(-.6014).add(n.mul(.5538)).sub(i.mul(.467)).sub(a.mul(.1255));return o.mul(r).add(s).exp().saturate()}),Uw=K(.04),Ww=G(1),Gw=class extends zC{constructor(e=!1,t=!1,n=!1,r=!1,i=!1,a=!1,o=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=r,this.transmission=i,this.dispersion=a,this.retroreflection=o,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null,this.dfg=null,this.multiScatteringCompensation=null}start(e){if(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){let e=yb.dot(db).clamp(),t=Vw({outsideIOR:G(1),eta2:Rh,cosTheta1:e,thinFilmThickness:zh,baseF0:Wh}),n=Vw({outsideIOR:G(1),eta2:Rh,cosTheta1:e,thinFilmThickness:zh,baseF0:Oh.rgb});this.iridescenceFresnel=G_(t,n,Mh),this.iridescenceF0Dielectric=dw({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=dw({f:n,f90:1,dotVH:e})}if(this.transmission===!0){let t=cb,n=Ky.sub(cb).normalize(),r=bb,i=e.context;i.backdrop=Iw(r,n,jh,kh,Gh,Kh,t,Qy,Wy,Hy,Zh,$h,tg,eg,this.dispersion?ng:null),i.backdropAlpha=Qh,Oh.a.mulAssign(G_(1,i.backdrop.a,Qh))}let t=yb.dot(db).clamp();this.dfg=lw({roughness:jh,dotNV:t}).toConst(`dfg`);let n=this.dfg.x.add(this.dfg.y);this.multiScatteringCompensation=Gh.mul(n.reciprocal().sub(1)).add(1).toConst(`multiScatteringCompensation`),super.start(e)}computeMultiscattering(e,t,n,r,i=null){let a=this.dfg,o=i?Lh.mix(r,i):r,s=o.mul(a.x).add(n.mul(a.y)),c=a.x.add(a.y).oneMinus(),l=o.add(o.oneMinus().mul(.047619)),u=s.mul(l).div(c.mul(l).oneMinus());e.addAssign(s),t.addAssign(u.mul(c))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){let r=yb.dot(e).clamp().mul(t).toVar();if(this.sheen===!0){this.sheenSpecularDirect.addAssign(r.mul(mw({lightDirection:e})));let t=Hw({normal:yb,viewDir:db,roughness:Ih}),n=Hw({normal:yb,viewDir:e,roughness:Ih}),i=Fh.r.max(Fh.g).max(Fh.b).mul(t.max(n)).oneMinus();r.mulAssign(i)}if(this.clearcoat===!0){let n=xb.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(ow({lightDirection:e,f0:Uw,f90:Ww,roughness:Ph,normalView:xb})))}let i=e.add(db).normalize(),a=UC({f0:Wh,f90:Kh,dotVH:db.dot(i).clamp()}),o=ow({lightDirection:e,f0:Gh,f90:1,roughness:jh,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});if(this.retroreflection===!0){let t=db.negate().reflect(yb),n=e.add(t).normalize(),r=UC({f0:Wh,f90:Kh,dotVH:t.dot(n).clamp()}),i=ow({lightDirection:e,viewDirection:t,f0:Gh,f90:1,roughness:jh,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});a=G_(a,r,rg.clamp()),o=G_(o,i,rg.clamp())}n.directDiffuse.addAssign(r.mul(WC({diffuseColor:kh})).mul(a.oneMinus())),n.directSpecular.addAssign(r.mul(o).mul(this.multiScatteringCompensation))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:r,reflectedLight:i,ltc_1:a,ltc_2:o}){let s=t.add(n).sub(r),c=t.sub(n).sub(r),l=t.sub(n).add(r),u=t.add(n).add(r),d=yb,f=db,p=ub.toVar(),m=hw({N:d,V:f,roughness:jh}),h=a.sample(m).toVar(),g=o.sample(m).toVar(),_=Ch(K(h.x,0,h.y),K(0,1,0),K(h.z,0,h.w)).toVar(),v=Gh.mul(g.x).add(Kh.sub(Gh).mul(g.y)).toVar();if(i.directSpecular.addAssign(e.mul(v).mul(vw({N:d,V:f,P:p,mInv:_,p0:s,p1:c,p2:l,p3:u}))),i.directDiffuse.addAssign(e.mul(kh).mul(vw({N:d,V:f,P:p,mInv:Ch(1,0,0,0,1,0,0,0,1),p0:s,p1:c,p2:l,p3:u}))),this.clearcoat===!0){let t=xb,n=hw({N:t,V:f,roughness:Ph}),r=a.sample(n),i=o.sample(n),d=Ch(K(r.x,0,r.y),K(0,1,0),K(r.z,0,r.w)),m=Uw.mul(i.x).add(Ww.sub(Uw).mul(i.y));this.clearcoatSpecularDirect.addAssign(e.mul(m).mul(vw({N:t,V:f,P:p,mInv:d,p0:s,p1:c,p2:l,p3:u})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){let{irradiance:t,reflectedLight:n}=e.context,r=K().toVar(),i=K().toVar();this.computeMultiscattering(r,i,Kh,Wh,this.iridescenceF0Dielectric);let a=t.mul(WC({diffuseColor:kh})).mul(r.add(i).oneMinus()).toVar();if(this.sheen===!0){let e=Hw({normal:yb,viewDir:db,roughness:Ih});this.sheenSpecularIndirect.addAssign(t.mul(Fh,e,1/Math.PI));let n=Fh.r.max(Fh.g).max(Fh.b).mul(e).oneMinus();a.mulAssign(n)}n.indirectDiffuse.addAssign(a)}indirectSpecular(e){let{radiance:t,iblIrradiance:n,reflectedLight:r}=e.context;if(this.sheen===!0&&this.sheenSpecularIndirect.addAssign(n.mul(Fh,Hw({normal:yb,viewDir:db,roughness:Ih}),1/Math.PI)),this.clearcoat===!0){let e=uw({dotNV:xb.dot(db).clamp(),specularColor:Uw,specularF90:Ww,roughness:Ph});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(e))}let i=K().toVar(`singleScatteringDielectric`),a=K().toVar(`multiScatteringDielectric`),o=K().toVar(`singleScatteringMetallic`),s=K().toVar(`multiScatteringMetallic`);this.computeMultiscattering(i,a,Kh,Wh,this.iridescenceF0Dielectric),this.computeMultiscattering(o,s,Kh,Oh.rgb,this.iridescenceF0Metallic);let c=G_(i,o,Mh),l=G_(a,s,Mh),u=i.add(a),d=kh.mul(u.oneMinus()),f=n.mul(1/Math.PI),p=t.mul(c).add(l.mul(f)).toVar(),m=d.mul(f).toVar();if(this.sheen===!0){let e=Hw({normal:yb,viewDir:db,roughness:Ih}),t=Fh.r.max(Fh.g).max(Fh.b).mul(e).oneMinus();p.mulAssign(t),m.mulAssign(t)}r.indirectSpecular.addAssign(p),r.indirectDiffuse.addAssign(m)}ambientOcclusion(e){let{ambientOcclusion:t,reflectedLight:n}=e.context,r=yb.dot(db).clamp().add(t),i=jh.mul(-16).oneMinus().negate().exp2(),a=t.sub(r.pow(i).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}){let{outgoingLight:t}=e;if(this.clearcoat===!0){let e=UC({dotVH:xb.dot(db).clamp(),f0:Uw,f90:Ww}),n=t.mul(Nh.mul(e).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Nh));t.assign(n)}if(this.sheen===!0){let e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(e)}}},Kw=2.399963229728653,qw=G(1),Jw=G(-2),Yw=G(.8),Xw=G(-1),Zw=G(.4),Qw=G(2),$w=G(.305),eT=G(3),tT=G(.21),nT=G(4),rT=G(4),iT=G(16),aT=W(([e])=>{let t=K(m_(e)).toVar(),n=G(-1).toVar();return oh(t.x.greaterThan(t.z),()=>{oh(t.x.greaterThan(t.y),()=>{n.assign(Q_(e.x.greaterThan(0),0,3))}).Else(()=>{n.assign(Q_(e.y.greaterThan(0),1,4))})}).Else(()=>{oh(t.z.greaterThan(t.y),()=>{n.assign(Q_(e.z.greaterThan(0),2,5))}).Else(()=>{n.assign(Q_(e.y.greaterThan(0),1,4))})}),n}).setLayout({name:`getFace`,type:`float`,inputs:[{name:`direction`,type:`vec3`}]}),oT=W(([e,t])=>{let n=fh().toVar();return oh(t.equal(0),()=>{n.assign(fh(e.z,e.y).div(m_(e.x)))}).ElseIf(t.equal(1),()=>{n.assign(fh(e.x.negate(),e.z.negate()).div(m_(e.y)))}).ElseIf(t.equal(2),()=>{n.assign(fh(e.x.negate(),e.y).div(m_(e.z)))}).ElseIf(t.equal(3),()=>{n.assign(fh(e.z.negate(),e.y).div(m_(e.x)))}).ElseIf(t.equal(4),()=>{n.assign(fh(e.x.negate(),e.z).div(m_(e.y)))}).Else(()=>{n.assign(fh(e.x,e.y).div(m_(e.z)))}),_g(.5,n.add(1))}).setLayout({name:`getUV`,type:`vec2`,inputs:[{name:`direction`,type:`vec3`},{name:`face`,type:`float`}]}),sT=W(([e])=>{let t=G(0).toVar();return oh(e.greaterThanEqual(Yw),()=>{t.assign(qw.sub(e).mul(Xw.sub(Jw)).div(qw.sub(Yw)).add(Jw))}).ElseIf(e.greaterThanEqual(Zw),()=>{t.assign(Yw.sub(e).mul(Qw.sub(Xw)).div(Yw.sub(Zw)).add(Xw))}).ElseIf(e.greaterThanEqual($w),()=>{t.assign(Zw.sub(e).mul(eT.sub(Qw)).div(Zw.sub($w)).add(Qw))}).ElseIf(e.greaterThanEqual(tT),()=>{t.assign($w.sub(e).mul(nT.sub(eT)).div($w.sub(tT)).add(eT))}).Else(()=>{t.assign(G(-2).mul(Yg(_g(1.16,e))))}),t}).setLayout({name:`roughnessToMip`,type:`float`,inputs:[{name:`roughness`,type:`float`}]}),cT=W(([e,t,n,r,i,a])=>{let o=G(n),s=K(t),c=K_(sT(o),Jw,a),l=t_(c),u=Qg(c),d=K(lT(e,s,u,r,i,a)).toVar();return oh(l.notEqual(0),()=>{let t=K(lT(e,s,u.add(1),r,i,a)).toVar();d.assign(G_(d,t,l))}),d}),lT=W(([e,t,n,r,i,a])=>{let o=G(n).toVar(),s=K(t),c=G(aT(s)).toVar(),l=G(k_(rT.sub(o),0)).toVar();o.assign(k_(o,rT));let u=G(qg(o)).toVar(),d=fh(oT(s,c).mul(u.sub(2)).add(1)).toVar();return oh(c.greaterThan(2),()=>{d.y.addAssign(u),c.subAssign(3)}),d.x.addAssign(c.mul(u)),d.x.addAssign(l.mul(_g(3,iT))),d.y.addAssign(_g(4,qg(a).sub(u))),d.x.mulAssign(r),d.y.mulAssign(i),e.sample(d).grad(fh(),fh())}),uT=W(({SAMPLES:e,sigma:t,outputDirection:n,mipInt:r,envMap:i,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:s})=>{let c=K(0).toVar();return oh(t.equal(0),()=>{c.assign(lT(i,n,r,a,o,s))}).Else(()=>{let l=e_(F_(Q_(m_(n.z).lessThan(.999),K(0,0,1),K(1,0,0)),n)).toVar(),u=F_(n,l).toVar(),d=O_(t.mul(3),Math.PI),f=Kg(d.mul(d).mul(-.5).div(t.mul(t))).oneMinus().toVar(),p=G(0).toVar();MS({start:lh(0),end:e},({i:d})=>{let m=G(d).add(.5).div(G(e)),h=t.mul(Xg(Jg(m.mul(f).oneMinus()).mul(-2))).toVar(),g=G(d).mul(Kw).toVar(),_=l.mul(i_(g)).add(u.mul(n_(g))),v=n.mul(i_(h)).add(_.mul(n_(h))),y=n_(h).div(h).toVar();c.addAssign(lT(i,v,r,a,o,s).mul(y)),p.addAssign(y)}),c.divAssign(p)}),q(c,1)}),dT=W(([e])=>{let t=uh(e).toVar();return t.assign(t.shiftLeft(uh(16)).bitOr(t.shiftRight(uh(16)))),t.assign(t.bitAnd(uh(1431655765)).shiftLeft(uh(1)).bitOr(t.bitAnd(uh(2863311530)).shiftRight(uh(1)))),t.assign(t.bitAnd(uh(858993459)).shiftLeft(uh(2)).bitOr(t.bitAnd(uh(3435973836)).shiftRight(uh(2)))),t.assign(t.bitAnd(uh(252645135)).shiftLeft(uh(4)).bitOr(t.bitAnd(uh(4042322160)).shiftRight(uh(4)))),t.assign(t.bitAnd(uh(16711935)).shiftLeft(uh(8)).bitOr(t.bitAnd(uh(4278255360)).shiftRight(uh(8)))),G(t).mul(23283064365386963e-26)}),fT=W(([e,t])=>fh(G(e).div(G(t)),dT(e))),pT=W(([e,t,n])=>{let r=n.mul(n).toConst(),i=K(1,0,0).toConst(),a=F_(t,i).toConst(),o=Xg(e.x).toConst(),s=_g(2,3.14159265359).mul(e.y).toConst(),c=o.mul(i_(s)).toConst(),l=o.mul(n_(s)).toVar(),u=_g(.5,t.z.add(1)).toConst();l.assign(u.oneMinus().mul(Xg(c.mul(c).oneMinus())).add(u.mul(l)));let d=i.mul(c).add(a.mul(l)).add(t.mul(Xg(k_(0,c.mul(c).add(l.mul(l)).oneMinus()))));return e_(K(r.mul(d.x),r.mul(d.y),k_(0,d.z)))}),mT=W(({roughness:e,mipInt:t,envMap:n,N_immutable:r,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:s})=>{let c=K(r).toVar(),l=K(0).toVar(),u=G(0).toVar();return oh(e.lessThan(.001),()=>{l.assign(lT(n,c,t,a,o,s))}).Else(()=>{let r=e_(F_(Q_(m_(c.z).lessThan(.999),K(0,0,1),K(1,0,0)),c)).toVar(),d=F_(c,r).toVar();MS({start:uh(0),end:i},({i:f})=>{let p=pT(fT(f,i),K(0,0,1),e),m=e_(r.mul(p.x).add(d.mul(p.y)).add(c.mul(p.z))),h=e_(m.mul(P_(c,m).mul(2)).sub(c)),g=k_(P_(c,h),0);oh(g.greaterThan(0),()=>{let e=lT(n,h,t,a,o,s);l.addAssign(e.mul(g)),u.addAssign(g)})}),oh(u.greaterThan(0),()=>{l.assign(l.div(u))})}),q(l,1)}),hT=4,gT=6,_T=20,vT=256,yT=new ps(-1,1,1,-1,0,1),bT=new cs(90,1),xT=new L,ST=null,CT=0,wT=0,TT=new F,ET=new F,DT=new WeakMap,OT=[3,1,5,0,4,2],kT=ny(`outputDirection`).normalize(),AT=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=TT,renderTarget:s=null}=i;if(this._setSize(a),this._hasInitialized===!1)throw Error(`THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Use "await renderer.init();" before using this method.`);ST=this._renderer.getRenderTarget(),CT=this._renderer.getActiveCubeFace(),wT=this._renderer.getActiveMipmapLevel();let c=s||this._allocateTarget(!0);return this._init(c),this._sceneToCubeUV(e,n,r,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}async fromSceneAsync(e,t=0,n=.1,r=100,i={}){return Rt(`PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.`),await this._renderer.init(),this.fromScene(e,t,n,r,i)}fromEquirectangular(e,t=null){if(this._hasInitialized===!1)throw Error(`THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Use "await renderer.init();" before using this method.`);return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Rt(`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)throw Error(`THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Use "await renderer.init();" before using this method.`);return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Rt(`PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.`),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=IT(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=LT(),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===301||e.mapping===302?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=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(ST,CT,wT),e.scissorTest=!1,this._setViewport(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),ST=this._renderer.getRenderTarget(),CT=this._renderer.getActiveCubeFace(),wT=this._renderer.getActiveMipmapLevel();let n=t||this._allocateTarget(!1);return this._init(n),this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTarget(e){return MT(3*Math.max(this._cubeSize,112),4*this._cubeSize,e)}_init(e){if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=MT(e.width,e.height);let{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=jT(t)),this._blurMaterial=PT(t,e.width,e.height),this._ggxMaterial=FT(t,e.width,e.height)}}async _compileMaterial(e){let t=new Yi(new xi,e);await this._renderer.compile(t,yT)}_sceneToCubeUV(e,t,n,r,i){let a=bT;a.near=t,a.far=n;let o=[1,1,1,1,-1,1],s=[1,-1,1,-1,1,-1],c=this._renderer,l=c.autoClear;c.getClearColor(xT),c.autoClear=!1,this._backgroundBox===null&&(this._backgroundBox=new Yi(new Sa,new Li({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1})));let u=this._backgroundBox,d=u.material,f=!1,p=e.background;p?p.isColor&&(d.color.copy(p),e.background=null,f=!0):(d.color.copy(xT),f=!0),c.setRenderTarget(r),c.clear(),f&&c.render(u,a);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;this._setViewport(r,n*l,t>2?l:0,l,l),c.render(e,a)}c.autoClear=l,e.background=p}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?this._cubemapMaterial===null&&(this._cubemapMaterial=IT(e)):this._equirectMaterial===null&&(this._equirectMaterial=LT(e));let i=r?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;let a=this._lodMeshes[0];a.material=i;let o=this._cubeSize;this._setViewport(t,0,0,3*o,2*o),n.setRenderTarget(t),n.render(a,yT)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;t<r;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){let r=this._renderer,i=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;let s=DT.get(a),c=n/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(c*c-l*l)*(c*1.25),{_lodMax:d}=this,f=this._sizeLods[n],p=3*f*(n>d-hT?n-d+hT:0),m=4*(this._cubeSize-f);e.texture.frame=(e.texture.frame||0)+1,s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,this._setViewport(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,yT),i.texture.frame=(i.texture.frame||0)+1,s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,this._setViewport(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,yT)}_blur(e,t,n,r){let i=this._pingPongRenderTarget,a=Math.min(r,Math.PI)/Math.SQRT2;this._blurPass(e,i,t,n,a),this._blurPass(i,e,n,n,a)}_blurPass(e,t,n,r,i){let a=this._renderer,o=this._blurMaterial,s=this._lodMeshes[r];s.material=o;let c=DT.get(o);e.texture.frame=(e.texture.frame||0)+1,c.envMap.value=e.texture,c.sigma.value=i,c.mipInt.value=this._lodMax-n;let l=this._sizeLods[r],u=3*l*(r>this._lodMax-hT?r-this._lodMax+hT:0),d=4*(this._cubeSize-l);this._setViewport(t,u,d,3*l,2*l),a.setRenderTarget(t),a.render(s,yT)}_setViewport(e,t,n,r,i){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-i-n,r,i),e.scissor.set(t,e.height-i-n,r,i)):(e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i))}};function jT(e){let t=[],n=[],r=e,i=e-hT+1+gT;for(let e=0;e<i;e++){let e=2**r;t.push(e);let i=1/(e-2),a=-i,o=1+i,s=[a,a,o,a,o,o,a,a,o,o,a,o],c=new Float32Array(108),l=new Float32Array(108);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0],i=OT[e];c.set(r,18*i);for(let e=0;e<6;e++){let t=s[e*2]*2-1,n=s[e*2+1]*2-1;i===0?ET.set(1,n,t):i===1?ET.set(-t,1,-n):i===2?ET.set(-t,n,1):i===3?ET.set(-1,n,-t):i===4?ET.set(-t,-1,n):ET.set(t,n,-1),ET.toArray(l,(i*6+e)*3)}}let u=new xi;u.setAttribute(`position`,new ai(c,3)),u.setAttribute(`outputDirection`,new ai(l,3)),n.push(new Yi(u,null)),r>hT&&r--}return{lodMeshes:n,sizeLods:t}}function MT(e,t,n){let r=new In(e,t,{magFilter:O,minFilter:O,generateMipmaps:!1,type:ce,format:ge,colorSpace:mt,depthBuffer:n});return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.texture.isPMREMTexture=!0,r.scissorTest=!0,r}function NT(e){let t=new hC;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function PT(e,t,n){let r={envMap:uy(),sigma:Y(0),mipInt:Y(0),CUBEUV_TEXEL_WIDTH:G(1/t),CUBEUV_TEXEL_HEIGHT:G(1/n),CUBEUV_MAX_MIP:G(e)},i=NT(`blur`);return i.fragmentNode=uT({...r,outputDirection:kT,SAMPLES:lh(_T)}),DT.set(i,r),i}function FT(e,t,n){let r={envMap:uy(),roughness:Y(0),mipInt:Y(0),CUBEUV_TEXEL_WIDTH:G(1/t),CUBEUV_TEXEL_HEIGHT:G(1/n),CUBEUV_MAX_MIP:G(e)},i=NT(`ggx`);return i.fragmentNode=mT({...r,N_immutable:kT,GGX_SAMPLES:uh(vT)}),DT.set(i,r),i}function IT(e){let t=NT(`cubemap`);return t.fragmentNode=Pb(e,kT),t}function LT(e){let t=NT(`equirect`);return t.fragmentNode=uy(e,OC(kT),0),t}var RT=new WeakMap;function zT(e){let t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(2**t,112)),texelHeight:n,maxMip:t}}function BT(e,t,n){let r=VT(t),i=r.get(e);if((i===void 0?-1:i.pmremVersion)!==e.pmremVersion){let t=e.image;if(e.isCubeTexture){if(UT(t))i=n.fromCubemap(e,i);else return null}else if(WT(t))i=n.fromEquirectangular(e,i);else return null;if(i.pmremVersion=e.pmremVersion,r.has(e)===!1){let t=()=>{e.removeEventListener(`dispose`,t);let n=r.get(e);n!==void 0&&(n.dispose(),r.delete(e))};e.addEventListener(`dispose`,t)}r.set(e,i)}return i.texture}function VT(e){let t=RT.get(e);return t===void 0&&(t=new WeakMap,RT.set(e,t)),t}var HT=class extends lm{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;let r=new Pn;r.isRenderTargetTexture=!0,this._texture=uy(r),this._width=Y(0),this._height=Y(0),this._maxMip=Y(0),this.updateBeforeType=$p.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){let t=zT(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,n=t?t.pmremVersion:-1,r=this._value;n!==r.pmremVersion&&(t=r.isPMREMTexture===!0||r.mapping===306?r:BT(r,e.renderer,this._generator),t!==null&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){this._generator===null&&(this._generator=new AT(e.renderer)),this.updateBefore(e);let t=this.uvNode;t===null&&e.context.getUV&&(t=e.context.getUV(this,e)),t=this._pmrem===null||this._pmrem.isRenderTargetTexture?Db.mul(K(t.x,t.y.negate(),t.z)):Db.mul(t);let n=this.levelNode;return n===null&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),cT(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),this._generator!==null&&this._generator.dispose()}};function UT(e){if(e==null)return!1;let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}function WT(e){return e!=null&&e.height>0}var GT=th(HT).setParameterLength(1,3),KT=new WeakMap,qT=class extends zS{static get type(){return`EnvironmentNode`}constructor(e=null){super(),this.envNode=e}setup(e){let{material:t}=e,n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){let r=n.isTextureNode?n.value:t[n.property],i=this._getPMREMNodeCache(e.renderer),a=i.get(r);a===void 0&&(a=GT(r),i.set(r,a)),n=a}let r=t.useAnisotropy===!0||t.anisotropy>0?ax:yb,i=Vv(n.context(JT(jh,r)).mul(Eb));if(t.useRetroreflection===!0||t.retroreflectivity>0){let e=Vv(n.context(YT(jh,r)).mul(Eb));i=rg.clamp().mix(i,e)}let a=Vv(n.context(XT(bb)).mul(Math.PI).mul(Eb));e.context.radiance.addAssign(i),e.context.iblIrradiance.addAssign(a);let o=e.context.lightingModel.clearcoatRadiance;if(o){let e=Vv(n.context(JT(Ph,xb)).mul(Eb));o.addAssign(e)}}_getPMREMNodeCache(e){let t=KT.get(e);return t===void 0&&(t=new WeakMap,KT.set(e,t)),t}},JT=(e,t)=>{let n=null;return{getUV:()=>(n===null&&(n=db.negate().reflect(t),n=z_(e).mix(n,t).normalize(),n=n.transformDirection(Gy)),n),getTextureLevel:()=>e}},YT=(e,t)=>{let n=null;return{getUV:()=>(n===null&&(n=z_(e).mix(db,t).normalize(),n=n.transformDirection(Gy)),n),getTextureLevel:()=>e}},XT=e=>({getUV:()=>e,getTextureLevel:()=>G(1)}),ZT=new po,QT=class extends hC{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(ZT),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t===null&&e.environmentNode&&(t=e.environmentNode),t?new qT(t):null}setupLightingModel(){return new Gw}setupSpecular(){let e=G_(K(.04),Oh.rgb,Mh);Wh.assign(K(.04)),Gh.assign(e),Kh.assign(1)}setupVariants(){let e=this.metalnessNode?G(this.metalnessNode):wx;Mh.assign(e);let t=this.roughnessNode?G(this.roughnessNode):Cx;t=ew({roughness:t}),jh.assign(t),this.setupSpecular(),kh.assign(Oh.rgb.mul(e.oneMinus()))}},$T=new mo,eE=class extends QT{static get type(){return`MeshPhysicalNodeMaterial`}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.retroreflectivityNode=null,this.anisotropyNode=null,this.setDefaultValues($T),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}get useRetroreflection(){return this.retroreflectivity>0||this.retroreflectivityNode!==null}setupSpecular(){let e=this.iorNode?G(this.iorNode):Rx,t=this.specularColorNode?K(this.specularColorNode):bx,n=this.specularIntensityNode?G(this.specularIntensityNode):yx;Zh.assign(e),Wh.assign(O_(L_(Zh.sub(1).div(Zh.add(1))).mul(t),K(1)).mul(n)),Gh.assign(G_(Wh,Oh.rgb,Mh)),Kh.assign(G_(n,1,Mh))}setupLightingModel(){return new Gw(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useRetroreflection)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){let e=this.clearcoatNode?G(this.clearcoatNode):Ex,t=this.clearcoatRoughnessNode?G(this.clearcoatRoughnessNode):Dx;Nh.assign(e),Ph.assign(ew({roughness:t}))}if(this.useSheen){let e=this.sheenNode?K(this.sheenNode):Ax,t=this.sheenRoughnessNode?G(this.sheenRoughnessNode):jx;Fh.assign(e),Ih.assign(t)}if(this.useRetroreflection){let e=this.retroreflectivityNode?G(this.retroreflectivityNode):Jx;rg.assign(e)}if(this.useIridescence){let e=this.iridescenceNode?G(this.iridescenceNode):Nx,t=this.iridescenceIORNode?G(this.iridescenceIORNode):Px,n=this.iridescenceThicknessNode?G(this.iridescenceThicknessNode):Fx;Lh.assign(e),Rh.assign(t),zh.assign(n)}if(this.useAnisotropy){let e=(this.anisotropyNode?fh(this.anisotropyNode):Mx).toVar();Vh.assign(e.length()),oh(Vh.equal(0),()=>{e.assign(fh(1,0))}).Else(()=>{e.divAssign(fh(Vh)),Vh.assign(Vh.saturate())}),Bh.assign(Vh.pow2().mix(jh.pow2(),1)),Hh.assign(ix[0].mul(e.x).add(ix[1].mul(e.y))),Uh.assign(ix[1].mul(e.x).sub(ix[0].mul(e.y)))}if(this.useTransmission){let e=this.transmissionNode?G(this.transmissionNode):Ix,t=this.thicknessNode?G(this.thicknessNode):Lx,n=this.attenuationDistanceNode?G(this.attenuationDistanceNode):zx,r=this.attenuationColorNode?K(this.attenuationColorNode):Bx;if(Qh.assign(e),$h.assign(t),eg.assign(n),tg.assign(r),this.useDispersion){let e=this.dispersionNode?G(this.dispersionNode):qx;ng.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?K(this.clearcoatNormalNode):Ox}setup(e){e.context.setupClearcoatNormal=()=>uv(this.setupClearcoatNormal(e),`NORMAL`,`vec3`),super.setup(e)}},tE=W(({normal:e,lightDirection:t,builder:n})=>{let r=fh(e.dot(t).mul(.5).add(.5),0);if(n.material.gradientMap)return K(zb(`gradientMap`,`texture`).context({getUV:()=>r}).r);{let e=r.fwidth().mul(.5);return G_(K(.7),K(1),Y_(G(.7).sub(e.x),G(.7).add(e.x),r.x))}}),nE=class extends zC{direct({lightDirection:e,lightColor:t,reflectedLight:n},r){let i=tE({normal:yb,lightDirection:e,builder:r}).mul(t);n.directDiffuse.addAssign(i.mul(WC({diffuseColor:Oh.rgb})))}indirect(e){let{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(WC({diffuseColor:Oh}))),r.indirectDiffuse.mulAssign(t)}},rE=new go,iE=class extends hC{static get type(){return`MeshToonNodeMaterial`}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(rE),this.setValues(e)}setupLightingModel(){return new nE}},aE=W(()=>{let e=K(db.z,0,db.x.negate()).normalize(),t=db.cross(e);return fh(e.dot(yb),t.dot(yb)).mul(.495).add(.5)}).once([`NORMAL`,`VERTEX`])().toVar(`matcapUV`),oE=new xo,sE=class extends hC{static get type(){return`MeshMatcapNodeMaterial`}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(oE),this.setValues(e)}setupVariants(e){let t=aE,n;n=e.material.matcap?zb(`matcap`,`texture`).context({getUV:()=>t}):K(G_(.2,.8,t.y)),Oh.rgb.mulAssign(n.rgb)}},cE=th(class extends lm{static get type(){return`RotateNode`}constructor(e,t,n=`XYZ`){super(),this.positionNode=e,this.rotationNode=t,this._order=n}customCacheKey(){return zp(this._order)}setOrder(e){return this._order=e,this}getOrder(){return this._order}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){let{rotationNode:t,positionNode:n}=this;if(this.getNodeType(e)===`vec2`){let e=t.cos(),r=t.sin();return Sh(e,r,r.negate(),e).mul(n)}{let e=t,r=this._order,i={X:wh(q(1,0,0,0),q(0,i_(e.x),n_(e.x),0),q(0,n_(e.x).negate(),i_(e.x),0),q(0,0,0,1)),Y:wh(q(i_(e.y),0,n_(e.y).negate(),0),q(0,1,0,0),q(n_(e.y),0,i_(e.y),0),q(0,0,0,1)),Z:wh(q(i_(e.z),n_(e.z),0,0),q(n_(e.z).negate(),i_(e.z),0,0),q(0,0,1,0),q(0,0,0,1))};return i[r.charAt(0)].mul(i[r.charAt(1)]).mul(i[r.charAt(2)]).mul(q(n,1)).xyz}}serialize(e){super.serialize(e),e.order=this._order}deserialize(e){super.deserialize(e),this._order=e.order}}).setParameterLength(2,3),lE=new ji,uE=class extends hC{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(lE),this.setValues(e)}setupPositionView(e){let{object:t,camera:n}=e,{positionNode:r,rotationNode:i,scaleNode:a,sizeAttenuation:o}=this,s=eb.mul(K(r||0)),c=fh(Qy[0].xyz.length(),Qy[1].xyz.length());a!==null&&(c=c.mul(fh(a))),n.isPerspectiveCamera&&o===!1&&(c=c.mul(s.z.negate()));let l=ab.xy;if(t.center&&t.center.isVector2===!0){let e=xv(`center`,`vec2`,t);l=l.sub(e.sub(.5))}l=l.mul(c);let u=G(i||kx),d=cE(l,u);return q(s.xy.add(d),s.zw)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}},dE=new ga,fE=new P,pE=class extends uE{static get type(){return`PointsNodeMaterial`}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(dE),this.setValues(e)}setupPositionView(){let{positionNode:e}=this;return eb.mul(K(e||ob)).xyz}setupVertexSprite(e){let{material:t,camera:n}=e,{rotationNode:r,scaleNode:i,sizeNode:a,sizeAttenuation:o}=this,s=super.setupVertex(e);if(t.isNodeMaterial!==!0)return s;let c=a===null?Kx:fh(a);c=c.mul(xy),n.isPerspectiveCamera&&o===!0&&(c=c.mul(mE.div(ub.z.negate()))),i&&i.isNode&&(c=c.mul(fh(i)));let l=ab.xy;if(r&&r.isNode){let e=G(r);l=cE(l,e)}return l=l.mul(c),l=l.div(Ey.div(2)),l=l.mul(s.w),s=s.add(q(l,0,0)),s}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)}},mE=Y(1).setGroup(J).onRenderUpdate(function({renderer:e}){let t=e.getSize(fE);this.value=.5*t.y}),hE=class extends zC{constructor(){super(),this.shadowNode=G(1).toVar(`shadowMask`)}direct({lightNode:e}){e.shadowNode!==null&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Oh.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Oh.rgb)}},gE=new to,_E=class extends hC{static get type(){return`ShadowNodeMaterial`}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(gE),this.setValues(e)}setupLightingModel(){return new hE}};Eh(`vec3`),Eh(`vec3`),Eh(`vec3`);var vE=class{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(){let e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),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)};e()}stop(){this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),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()}},yE=class{constructor(){this.weakMaps={}}_getWeakMap(e){let t=e.length,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 t=0;t<e.length-1;t++){let r=e[t];n.has(r)===!1&&n.set(r,new WeakMap),n=n.get(r)}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])}},bE=0,xE=new WeakMap;function SE(e){let t=Object.keys(e),n=xE.get(e.constructor);if(n===void 0){n=[];let t=Object.getPrototypeOf(e);for(;t;){let e=Object.getOwnPropertyDescriptors(t);for(let t in e){let r=e[t];r&&typeof r.get==`function`&&n.push(t)}t=Object.getPrototypeOf(t)}xE.set(e.constructor,n)}for(let e=0;e<n.length;e++)t.push(n[e]);return t}var CE=class{constructor(e,t,n,r,i,a,o,s,c,l){this.id=bE++,this._nodes=e,this._geometries=t,this.renderer=n,this.object=r,this.material=i,this.scene=a,this.camera=o,this.lightsNode=s,this.context=c,this.geometry=r.geometry,this.version=i.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=l,this.clippingContextCacheKey=l===null?``:l.cacheKey,this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this._sourceMaterial=n._currentSourceMaterial,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.onObjectDispose=()=>{this.dispose()},this.object.addEventListener(`dispose`,this.onObjectDispose),this.material.addEventListener(`dispose`,this.onMaterialDispose),this.geometry.addEventListener(`dispose`,this.onGeometryDispose),this._sourceMaterial!==null&&this._sourceMaterial.addEventListener(`dispose`,this.onMaterialDispose)}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.getNodeBuilderState().hardwareClipping===!0?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||=this._nodes.getForRender(this)}getMonitor(){return this._monitor||=this.getNodeBuilderState().observer}getBindings(){return this._bindings||=this.getNodeBuilderState().createBindings()}getBindingGroup(e){for(let 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;let e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],r=new Set,i={};for(let a of e){let e;if(a.node&&a.node.attribute?e=a.node.attribute:(e=t.getAttribute(a.name),e!==void 0&&(e.isInterleavedBufferAttribute?i[a.name]=e.data.uuid:i[a.name]=e.id)),e===void 0)continue;n.push(e);let o=e.isInterleavedBufferAttribute?e.data:e;r.add(o)}return this.attributes=n,this.attributesId=i,this.vertexBuffers=Array.from(r.values()),n}getVertexBuffers(){return this.vertexBuffers===null&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){let{object:e,material:t,geometry:n,group:r,drawRange:i}=this,a=this.drawParams||={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0},o=this.getIndex(),s=o!==null,c=1;if(n.isInstancedBufferGeometry===!0?c=n.instanceCount:e.count!==void 0&&(c=Math.max(0,e.count)),c===0)return null;if(a.instanceCount=c,e.isBatchedMesh===!0)return a;let l=1;t.wireframe===!0&&!e.isPoints&&!e.isLineSegments&&!e.isLine&&!e.isLineLoop&&(l=2);let u=i.start*l,d=(i.start+i.count)*l;r!==null&&(u=Math.max(u,r.start*l),d=Math.min(d,(r.start+r.count)*l));let f=n.attributes.position,p=1/0;s?p=o.count:f!=null&&(p=f.count),u=Math.max(u,0),d=Math.min(d,p);let m=d-u;return m<0||m===1/0?null:(a.vertexCount=m,a.firstVertex=u,a)}getGeometryCacheKey(){let{geometry:e}=this,t=``;for(let n of Object.keys(e.attributes).sort()){let r=e.attributes[n];t+=n+`,`,r.data&&(t+=r.data.stride+`,`),r.offset&&(t+=r.offset+`,`),r.itemSize&&(t+=r.itemSize+`,`),r.normalized&&(t+=`n,`)}for(let n of Object.keys(e.morphAttributes).sort()){let r=e.morphAttributes[n];t+=`morph-`+n+`,`;for(let e=0,n=r.length;e<n;e++){let n=r[e];t+=n.id+`,`}}return e.index&&(t+=`index,`),t}getMaterialCacheKey(){let{object:e,material:t,renderer:n}=this,r=t.customProgramCacheKey();for(let e of SE(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;let i=t[e],a;if(i!==null){let t=typeof i;t===`number`?a=e===`side`?String(i):i===0?`0`:`1`:t===`object`?(a=`{`,i.isTexture&&(a+=i.mapping,n.backend.isWebGPUBackend===!0&&(a+=i.magFilter,a+=i.minFilter,a+=i.wrapS,a+=i.wrapT,a+=i.wrapR)),a+=`}`):a=String(i)}else a=String(i);r+=a+`,`}return r+=this.clippingContextCacheKey+`,`,e.geometry&&(r+=this.getGeometryCacheKey()),e.skeleton&&(r+=e.skeleton.bones.length+`,`),e.isBatchedMesh&&(r+=e._matricesTexture.uuid+`,`,e._colorsTexture!==null&&(r+=e._colorsTexture.uuid+`,`)),(e.isInstancedMesh||e.count>1)&&(r+=e.uuid+`,`),r+=this.context.id+`,`,r+=e.receiveShadow+`,`,zp(r)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(this.attributes!==null){let e=this.attributesId;for(let t in e){let n=this.geometry.getAttribute(t);if(n===void 0)return!0;let r=n.isInterleavedBufferAttribute?n.data.uuid:n.id;if(e[t]!==r)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=Vp(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Vp(e,1)),e=Vp(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.object.removeEventListener(`dispose`,this.onObjectDispose),this.material.removeEventListener(`dispose`,this.onMaterialDispose),this.geometry.removeEventListener(`dispose`,this.onGeometryDispose),this._sourceMaterial!==null&&this._sourceMaterial.removeEventListener(`dispose`,this.onMaterialDispose),this.onDispose()}},wE=[],TE=class{constructor(e,t,n,r,i,a){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=r,this.bindings=i,this.info=a,this._chainMaps={},this._renderObjects=new Set}get(e,t,n,r,i,a,o,s){let c=this.getChainMap(s);wE[0]=e,wE[1]=t,wE[2]=a,wE[3]=i;let l=c.get(wE);return l===void 0?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,r,i,a,o,s),c.set(wE,l)):(l.camera=r,l.updateClipping(o),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey===l.getCacheKey()?l.version=t.version:(l.dispose(),l=this.get(e,t,n,r,i,a,o,s)))),wE[0]=null,wE[1]=null,wE[2]=null,wE[3]=null,l}getChainMap(e=`default`){return this._chainMaps[e]||(this._chainMaps[e]=new yE)}dispose(){for(let e of this._renderObjects)e.dispose();this._renderObjects.clear(),this._chainMaps={}}createRenderObject(e,t,n,r,i,a,o,s,c,l,u){let d=this.getChainMap(u),f=new CE(e,t,n,r,i,a,o,s,c,l);return f.onDispose=()=>{this.pipelines.delete(f),this.bindings.deleteForRender(f),this.nodes.delete(f),d.delete(f.getChainArray()),this._renderObjects.delete(f)},this._renderObjects.add(f),f}},EE=class{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}},DE={VERTEX:1,INDEX:2,STORAGE:3,INDIRECT:4},OE=16,kE=class extends EE{constructor(e,t){super(),this.backend=e,this.info=t}delete(e){let t=super.delete(e);return t!==null&&(this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){let n=this.get(e);if(n.version===void 0)t===DE.VERTEX?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===DE.INDEX?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===DE.STORAGE?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===DE.INDIRECT&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),n.version=this._getBufferAttribute(e).version;else{let t=this._getBufferAttribute(e);(n.version<t.version||t.usage===35048)&&(this.backend.updateAttribute(e),n.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}};function AE(e){return e.index===null?e.attributes.position.version:e.index.version}function jE(e){return e.index===null?e.attributes.position.id:e.index.id}function ME(e){let t=[],n=e.index,r=e.attributes.position;if(n!==null){let e=n.array;for(let n=0,r=e.length;n<r;n+=3){let r=e[n+0],i=e[n+1],a=e[n+2];t.push(r,i,i,a,a,r)}}else{let e=r.array;for(let n=0,r=e.length/3-1;n<r;n+=3){let e=n+0,r=n+1,i=n+2;t.push(e,r,r,i,i,e)}}let i=new(r.count>=65535?si:oi)(t,1);return i.version=AE(e),i.__id=jE(e),i}var NE=class extends EE{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){let 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){let t=e.geometry,n=this.get(t);n.initialized=!0,this.info.memory.geometries++;let r=()=>{this.info.memory.geometries--;let n=t.index;n!==null&&this.attributes.delete(n);for(let e of Object.values(t.attributes))this.attributes.delete(e);let i=this.wireframes.get(t);i!==void 0&&this.attributes.delete(i);let a=new Set(Object.values(e.geometry.attributes));for(let t of e.getAttributes())a.has(t)===!1&&this.attributes.delete(t);t.removeEventListener(`dispose`,r),this._geometryDisposeListeners.delete(t)};t.addEventListener(`dispose`,r),this._geometryDisposeListeners.set(t,r)}updateAttributes(e){let t=e.getAttributes();for(let e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,DE.STORAGE):this.updateAttribute(e,DE.VERTEX);let n=this.getIndex(e);n!==null&&this.updateAttribute(n,DE.INDEX);let r=e.geometry.indirect;r!==null&&this.updateAttribute(r,DE.INDIRECT)}updateAttribute(e,t){let 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){let{geometry:t,material:n}=e,r=t.index;if(n.wireframe===!0){let e=this.wireframes,n=e.get(t);n===void 0?(n=ME(t),e.set(t,n)):(n.version!==AE(t)||n.__id!==jE(t))&&(this.attributes.delete(n),n=ME(t),e.set(t,n)),r=n}return r}dispose(){for(let[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener(`dispose`,t);this._geometryDisposeListeners.clear()}},PE=class{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={attributes:0,attributesSize:0,geometries:0,indexAttributes:0,indexAttributesSize:0,indirectStorageAttributes:0,indirectStorageAttributesSize:0,programs:0,programsSize:0,readbackBuffers:0,readbackBuffersSize:0,renderTargets:0,storageAttributes:0,storageAttributesSize:0,textures:0,texturesSize:0,uniformBuffers:0,uniformBuffersSize:0,total:0},this.memoryMap=new WeakMap}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=t/3*n:e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=t/2*n:e.isLine?this.render.lines+=n*(t-1):N(`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(let e in this.memory)this.memory[e]=0;this.memoryMap=new WeakMap}createTexture(e){let t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){let t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){let 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){let 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){let t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:`readbackBuffers`}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){let{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createUniformBuffer(e){let t=e.byteLength;this.memoryMap.set(e,{size:t,type:`uniformBuffers`}),this.memory.uniformBuffers++,this.memory.total+=t,this.memory.uniformBuffersSize+=t}destroyUniformBuffer(e){let t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory.uniformBuffers--,this.memory.total-=t.size,this.memory.uniformBuffersSize-=t.size)}createProgram(e){let t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){let 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===1010||e.type===1009?t=1:e.type===1011||e.type===1012||e.type===1016?t=2:(e.type===1013||e.type===1014||e.type===1015)&&(t=4);let n=4;e.format===1021||e.format===1028||e.format===1029||e.format===1026||e.format===1027?n=1:e.format===1030||e.format===1031?n=2:(e.format===1022||e.format===1032)&&(n=3);let r=t*n;e.type===1017||e.type===1018?r=2:(e.type===1020||e.type===35902||e.type===35899)&&(r=4);let i=e.width||1,a=e.height||1,o=e.isCubeTexture?6:e.depth||1,s=i*a*o*r,c=e.mipmaps;if(c&&c.length>0){let e=0;for(let t=0;t<c.length;t++){let n=c[t];if(n.data)e+=n.data.byteLength;else{let s=n.width||Math.max(1,i>>t),c=n.height||Math.max(1,a>>t);e+=s*c*o*r}}s+=e}else e.generateMipmaps&&(s*=1.333);return Math.round(s)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}},FE=class{constructor(e){this.cacheKey=e,this.usedTimes=0}},IE=class extends FE{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}},LE=class extends FE{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}},RE=0,zE=class{constructor(e,t,n,r=null,i=null){this.id=RE++,this.code=e,this.stage=t,this.name=n,this.transforms=r,this.attributes=i,this.usedTimes=0}},BE=class extends EE{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,n=null){let{backend:r}=this,i=this.get(e);if(this._needsComputeUpdate(e)){let a=i.pipeline;a&&(a.usedTimes--,a.computeProgram.usedTimes--);let o=this.nodes.getForCompute(e),s=this.programs.compute.get(o.computeShader);s===void 0&&(a&&a.computeProgram.usedTimes===0&&this._releaseProgram(a.computeProgram),s=new zE(o.computeShader,`compute`,e.name,o.transforms,o.nodeAttributes),this.programs.compute.set(o.computeShader,s),r.createProgram(s),this.info.createProgram(s));let c=this._getComputeCacheKey(e,s),l=this.caches.get(c);l===void 0&&(a&&a.usedTimes===0&&this._releasePipeline(a),l=this._getComputePipeline(e,s,c,t,n)),l.usedTimes++,s.usedTimes++,i.version=e.version,i.pipeline=l}return i.pipeline}getForRender(e,t=null){let{backend:n}=this,r=this.get(e);if(this._needsRenderUpdate(e)){let i=r.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);let a=e.getNodeBuilderState(),o=e.material?e.material.name:``,s=this.programs.vertex.get(a.vertexShader);s===void 0&&(i&&i.vertexProgram.usedTimes===0&&this._releaseProgram(i.vertexProgram),s=new zE(a.vertexShader,`vertex`,o),this.programs.vertex.set(a.vertexShader,s),n.createProgram(s),this.info.createProgram(s));let c=this.programs.fragment.get(a.fragmentShader);c===void 0&&(i&&i.fragmentProgram.usedTimes===0&&this._releaseProgram(i.fragmentProgram),c=new zE(a.fragmentShader,`fragment`,o),this.programs.fragment.set(a.fragmentShader,c),n.createProgram(c),this.info.createProgram(c));let l=this._getRenderCacheKey(e,s,c),u=this.caches.get(l);u===void 0?(i&&i.usedTimes===0&&this._releasePipeline(i),u=this._getRenderPipeline(e,s,c,l,t)):e.pipeline=u,u.usedTimes++,s.usedTimes++,c.usedTimes++,r.pipeline=u}return r.pipeline}isReady(e){let t=this.get(e).pipeline;if(t===void 0)return!1;let n=this.backend.get(t);return n.pipeline!==void 0&&n.pipeline!==null}delete(e){let 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,r,i){n||=this._getComputeCacheKey(e,t);let a=this.caches.get(n);return a===void 0&&(a=new LE(n,t),this.caches.set(n,a),this.backend.createComputePipeline(a,r,i)),a}_getRenderPipeline(e,t,n,r,i){r||=this._getRenderCacheKey(e,t,n);let a=this.caches.get(r);return a===void 0&&(a=new IE(r,t,n),this.caches.set(r,a),e.pipeline=a,this.backend.createRenderPipeline(e,i)),a}_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){let t=e.code,n=e.stage;this.programs[n].delete(t),this.info.destroyProgram(e)}_needsComputeUpdate(e){let 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)}},VE=class extends EE{constructor(e,t,n,r,i,a){super(),this.backend=e,this.textures=n,this.pipelines=i,this.attributes=r,this.nodes=t,this.info=a,this.pipelines.bindings=this}getForRender(e){let t=e.getBindings(),n=this.get(e);return n.initialized!==!0&&(this._createBindings(t),n.initialized=!0),t}getForCompute(e){let t=this.nodes.getForCompute(e).bindings,n=this.get(e);return(n.initialized!==!0||n.bindings!==t)&&(n.bindings!==void 0&&this._destroyBindings(n.bindings),this._createBindings(t),n.initialized=!0,n.bindings=t),t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}updateSharedForRender(e){let t=this.getForRender(e);for(let e of t)for(let t of e.bindings)if((t.isNodeUniformsGroup===!0||t.isNodeUniformBuffer===!0)&&t.groupNode.shared===!0){if(this.nodes.updateGroup(t)===!1)continue;t.update()&&this.backend.updateBinding(t),t.updateRanges.length>0&&t.clearUpdateRanges()}}deleteForCompute(e){let t=this.get(e).bindings||this.nodes.getForCompute(e).bindings;this._destroyBindings(t),this.delete(e)}deleteForRender(e){let t=e.getBindings();this._destroyBindings(t),this.delete(e)}_createBindings(e){for(let t of e){let n=this.get(t);if(n.bindGroup===void 0){for(let e of t.bindings)if(e.isUniformBuffer)this.backend.createUniformBuffer(e),this.info.createUniformBuffer(e);else if(e.isSampledTexture)this.textures.updateTexture(e.texture);else if(e.isSampler)this.textures.updateSampler(e);else if(e.isStorageBuffer){let t=e.attribute,n=t.isIndirectStorageBufferAttribute?DE.INDIRECT:DE.STORAGE;this.attributes.update(t,n)}this.backend.createBindings(t,e,``),n.bindGroup=t,n.usedTimes=1}else n.usedTimes++}}_destroyBindings(e){for(let t of e){let e=this.get(t);if(e.usedTimes--,e.usedTimes===0){for(let e of t.bindings)if(e.isUniformBuffer)this.backend.destroyUniformBuffer(e),this.info.destroyUniformBuffer(e),e.release();else if(e.isSampler){if(e.isSampledTexture!==!0)this.backend.destroySampler(e);else if(e.texture!==null){let n=this.textures.get(e.texture);n.bindGroups!==void 0&&n.bindGroups.delete(t)}e.release()}this.backend.deleteBindGroupData(t),this.delete(t)}}}_updateBindings(e){for(let t of e)this._update(t,e)}_update(e,t){let{backend:n}=this,r=!1,i=!0,a=``,o=0;for(let t of e.bindings)if(this.nodes.updateGroup(t)!==!1){if(t.isStorageBuffer){let e=t.attribute,i=e.isIndirectStorageBufferAttribute?DE.INDIRECT:DE.STORAGE,o=n.get(t);this.attributes.update(e,i),o.attribute!==e&&(o.attribute=e,r=!0),a+=e.id+`,`}if(t.isUniformBuffer)t.update()&&n.updateBinding(t);else if(t.isSampledTexture){let s=t.update(),c=t.texture,l=this.textures.get(c);if(s&&(this.textures.updateTexture(c),t.generation!==l.generation&&(t.generation=l.generation,r=!0),l.bindGroups.add(e)),n.get(c).externalTexture!==void 0||l.isDefaultTexture?i=!1:(a+=c.id+`,`,o+=c.version),c.isStorageTexture===!0&&c.mipmapsAutoUpdate===!0){let e=this.get(c);t.store===!0?e.needsMipmap=!0:this.textures.needsMipmaps(c)&&e.needsMipmap===!0&&(this.backend.generateMipmaps(c),e.needsMipmap=!1)}}else if(t.isSampler&&t.update()){let e=this.textures.updateSampler(t);t.samplerKey!==e&&(t.samplerKey=e,r=!0)}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}r===!0&&this.backend.updateBindings(e,t,i?a:``,o)}},HE=Object.freeze([]);function UE(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:e.z-t.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function WE(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function GE(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&e.side===2&&e.forceSinglePass===!1}var KE=class{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lighting=e,this.lightsNode=e.getNode(t),this.lightsArray=[],this.scene=t,this.camera=n,this.occlusionQueryCount=0,this.frameId=-1,this._lastOcclusionObject=null}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,n,r,i,a,o){let s=this.renderItems[this.renderItemsIndex];return s===void 0?(s={id:e.id,object:e,geometry:t,material:n,groupOrder:r,renderOrder:e.renderOrder,z:i,group:a,clippingContext:o},this.renderItems[this.renderItemsIndex]=s):(s.id=e.id,s.object=e,s.geometry=t,s.material=n,s.groupOrder=r,s.renderOrder=e.renderOrder,s.z=i,s.group=a,s.clippingContext=o),this.renderItemsIndex++,s}push(e,t,n,r,i,a,o){this.camera.reversedDepth===!0&&(i=-i);let s=this.getNextRenderItem(e,t,n,r,i,a,o);e.occlusionTest===!0&&this._lastOcclusionObject!==e&&(this.occlusionQueryCount++,this._lastOcclusionObject=e),n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(GE(n)&&this.transparentDoublePass.push(s),this.transparent.push(s)):this.opaque.push(s)}unshift(e,t,n,r,i,a,o){let s=this.getNextRenderItem(e,t,n,r,i,a,o);n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(GE(n)&&this.transparentDoublePass.unshift(s),this.transparent.unshift(s)):this.opaque.unshift(s)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||UE),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||WE),this.transparent.length>1&&this.transparent.sort(t||WE)}finish(){this.lightsNode.setLights(this.lighting.enabled?this.lightsArray:HE);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){let t=this.renderItems[e];if(t.id===null)break;qE(t)}this._lastOcclusionObject=null}clear(){for(let e=0,t=this.renderItems.length;e<t;e++){let t=this.renderItems[e];if(t.id===null)break;qE(t)}this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0}};function qE(e){e.id=null,e.object=null,e.geometry=null,e.material=null,e.groupOrder=null,e.renderOrder=null,e.z=null,e.group=null,e.clippingContext=null}var JE=[],YE=class{constructor(){this.lists=new yE,this._activeLists=new Set,this._frameId=-1}get(e,t,n){let r=this.lists;JE[0]=e,JE[1]=t,JE[2]=n;let i=r.get(JE);return i===void 0&&(i=new KE(n,e,t),r.set(JE,i)),JE[0]=null,JE[1]=null,JE[2]=null,i.frameId=this._frameId,this._activeLists.add(i),i}update(e){if(e!==this._frameId){this._frameId=e;for(let t of this._activeLists)e-t.frameId>10&&(t.clear(),this._activeLists.delete(t))}}dispose(){this.lists=new yE,this._activeLists.clear(),this._frameId=-1}},XE=0,ZE=class{constructor(){this.id=XE++,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 Fn,this.scissor=!1,this.scissorValue=new Fn,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.fullscreenPass=!1,this.isRenderContext=!0}getCacheKey(){return QE(this)}};function QE(e){let{textures:t,activeCubeFace:n,activeMipmapLevel:r}=e,i=[n,r];for(let e of t)i.push(e.id);return Bp(i)}var $E=class{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,n=0){let r;if(e===null)r=`default`;else{let t=e.texture.format,n=e.texture.type;r=`${e.textures.length}:${t}:${n}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}let i=t===null?`default`:t.id,a=r+`-`+i+`-`+n,o=this._renderContexts[a];return o===void 0&&(o=new ZE,o.mrt=t,this._renderContexts[a]=o),e!==null&&(o.sampleCount=e.samples===0?1:e.samples),o.clearDepthValue=this.renderer.getClearDepth(),o.clearStencilValue=this.renderer.getClearStencil(),o}dispose(){this._renderContexts={}}},eD=new F,tD=class extends EE{constructor(e,t,n){super(),this.renderer=e,this.backend=t,this.info=n,this._htmlTextures=new Set}updateRenderTarget(e,t=0){let n=this.get(e),r=e.samples===0?1:e.samples,i=n.depthTextureMips||={},a=e.textures,o=this.getSize(a[0]),s=o.width>>t,c=o.height>>t,l=e.depthTexture||i[t],u=e.depthBuffer===!0||e.stencilBuffer===!0,d=!1,f=l!==void 0&&l.image!==void 0&&l.image.depth>1,p=o.depth>1&&(e.useArrayDepthTexture||e.multiview||f);l===void 0&&u&&(l=new ya,l.format=e.stencilBuffer?ve:_e,l.type=e.stencilBuffer?de:oe,l.image.width=s,l.image.height=c,l.image.depth=o.depth,l.renderTarget=e,i[t]=l),l&&(l.isArrayTexture=p),(n.width!==o.width||o.height!==n.height)&&(d=!0,l&&l.renderTarget===e&&(l.needsUpdate=!0,l.image.width=s,l.image.height=c,l.image.depth=p?o.depth:1)),n.width=o.width,n.height=o.height,n.textures=a,n.depthTexture=l||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==r&&(d=!0,l&&l.renderTarget===e&&(l.needsUpdate=!0),n.sampleCount=r);let m={sampleCount:r};if(e.isXRRenderTarget!==!0){for(let e=0;e<a.length;e++){let t=a[e];d&&(t.needsUpdate=!0),this.updateTexture(t,m)}l&&this.updateTexture(l,m)}n.initialized!==!0&&(n.initialized=!0,this.info.memory.renderTargets++,n.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener(`dispose`,n.onDispose))}updateTexture(e,t={}){let n=this.get(e);if(n.initialized===!0&&n.version===e.version)return;let r=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,i=this.backend;if(r&&n.initialized===!0&&i.destroyTexture(e),e.isFramebufferTexture){let t=this.renderer.getRenderTarget();e.type=t?t.texture.type:te}if(e.isHTMLTexture&&e.image){let t=this.renderer.domElement;if(`requestPaint`in t){if(t.hasAttribute(`layoutsubtree`)||t.setAttribute(`layoutsubtree`,`true`),e.image.parentNode!==t&&t.appendChild(e.image),this._htmlTextures.size===0){let e=this._htmlTextures;t.onpaint=t=>{let n=t&&t.changedElements;for(let t of e)(!n||n.includes(t.image))&&(t.needsUpdate=!0)}}this._htmlTextures.add(e)}}let{width:a,height:o,depth:s}=this.getSize(e);if(t.width=a,t.height=o,t.depth=s,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,a,o):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,r||e.isStorageTexture===!0||e.isExternalTexture===!0)i.createTexture(e,t),n.generation=e.version;else if(e.version>0){let r=e.image;if(r===void 0)M(`Renderer: Texture marked for update but image is undefined.`);else if(r.complete===!1)M(`Renderer: Texture marked for update but image is incomplete.`);else{if(e.images){let n=[];for(let t of e.images)n.push(t);t.images=n}else t.image=r;(n.isDefaultTexture===void 0||n.isDefaultTexture===!0)&&(i.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),e.source.dataReady===!0&&i.updateTexture(e,t);let a=e.isStorageTexture===!0&&e.mipmapsAutoUpdate===!1;t.needsMipmaps&&e.mipmaps.length===0&&!a&&i.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else i.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&&I.enabled===!0&&I.getTransfer(e.colorSpace)!==`srgb`&&M(`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=eD){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 r;return r=e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture===!0?1:Math.floor(Math.log2(Math.max(t,n)))+1,r}needsMipmaps(e){return e.generateMipmaps===!0||e.mipmaps.length>0}_destroyRenderTarget(e){if(this.has(e)===!0){let t=this.get(e),n=t.textures,r=t.depthTexture;e.removeEventListener(`dispose`,t.onDispose);for(let e=0;e<n.length;e++)this._destroyTexture(n[e]);r&&r.renderTarget===e&&this._destroyTexture(r),this.delete(e),this.backend.delete(e),this.info.memory.renderTargets--}}_destroyTexture(e){if(this.has(e)===!0){let t=this.get(e);e.removeEventListener(`dispose`,t.onDispose);let n=t.isDefaultTexture;if(this.backend.destroyTexture(e,n),t.bindGroups)for(let n of t.bindGroups){let t=this.backend.get(n);t.groups=void 0,t.versions=void 0;for(let t of n.bindings)t.isSampler&&t.texture===e&&(t.isSampledTexture!==!0&&this.backend.destroySampler(t),t.reset(),t.release())}this._htmlTextures.delete(e),this.delete(e),this.info.destroyTexture(e)}}},nD=class extends L{constructor(e,t,n,r=1){super(e,t,n),this.a=r}set(e,t,n,r=1){return this.a=r,super.set(e,t,n)}copy(e){return e.a!==void 0&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b,yield this.a}},rD=class extends $_{static get type(){return`OverrideContextNode`}constructor(e,t=null){super(t,{overrideNodes:e}),this.isOverrideContextNode=!0}getFlowContextData(){let e=[];this.traverse(t=>{t.isOverrideContextNode===!0&&e.push(t.value.overrideNodes)});let t=new Map(e.flatMap(e=>Array.from(e.entries()))),n=super.getFlowContextData();return n.overrideNodes=t,n}};function iD(e,t=null,n=null){if(t&&t.isNode){let e=t;t=()=>e}return new rD(new Map([[e,t]]),n)}B(`overrideNode`,(e,t,n)=>iD(t,n,e));function aD(e,t=null){let n=new Map;for(let[t,r]of e){let e=r===null?null:typeof r==`function`?r:()=>r;n.set(t,e)}return new rD(n,t)}B(`overrideNodes`,(e,t)=>aD(t,e));var oD=class extends Th{static get type(){return`ParameterNode`}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){let n=this.getNodeType(e),r=e.getStructTypeNode(n),i;return r===null?(N(`TSL: Member "${t}" not found in struct "${n}".`,new Lp),i=`float`):i=r.getMemberType(e,t),i}getHash(){return String(this.id)}generate(){return this.name}},sD=th(class extends z{static get type(){return`StackNode`}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this._nodeDataLibrary=new Map,this.isStackNode=!0}getElementType(e){return this.outputNode?this.outputNode.getElementType(e):`void`}generateNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):`void`}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):`void`}addToStack(e,t=-1){if(e.isNode!==!0)return N(`TSL: Invalid node added to stack.`,new Lp),this;if(t===-1){if(this._currentNode){let e=this._nodeDataLibrary.get(this._currentNode);e===void 0&&(e={delta:0},this._nodeDataLibrary.set(this._currentNode,e)),e.delta++,t=this.nodes.indexOf(this._currentNode)+e.delta}else t=this.nodes.length}return this.nodes.splice(t,0,e),this}addToStackBefore(e){let t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){let n=new Zm(t);return this._currentCond=Q_(e,n),this.addToStack(this._currentCond)}ElseIf(e,t){let n=Q_(e,new Zm(t));return this._currentCond.elseNode=n,this._currentCond=n,this}Else(e){return this._currentCond.elseNode=new Zm(e),this}Switch(e){return this._expressionNode=V(e),this}Case(...e){let t=[];if(e.length>=2)for(let n=0;n<e.length-1;n++)t.push(this._expressionNode.equal(V(e[n])));else N(`TSL: Invalid parameter length. Case() requires at least two parameters.`,new Lp);let n=e[e.length-1],r=new Zm(n),i=t[0];for(let e=1;e<t.length;e++)i=i.or(t[e]);let a=Q_(i,r);return this._currentCond===null?(this._currentCond=a,this.addToStack(this._currentCond)):(this._currentCond.elseNode=a,this._currentCond=a,this)}Default(e){return this.Else(e),this}setup(e){let t=e.getNodeProperties(this),n=0;for(let r of this.getChildren())r.isVarNode&&r.isIntent(e)&&r.isAssign(e)!==!0||(t[`node`+n++]=r);return t.outputNode||null}build(e,...t){let n=ah(),r=e.buildStage;ih(this),e.setActiveStack(this);for(let t=0;t<this.nodes.length;t++){let n=this.nodes[t],i=this._currentNode;if(this._currentNode=n,!(n.isVarNode&&n.isIntent(e)&&n.isAssign(e)!==!0)){if(r===`setup`)n.build(e);else if(r===`analyze`)n.build(e,this);else if(r===`generate`){let t=e.getDataFromNode(n,`any`).stages,r=t&&t[e.shaderStage];if(n.isVarNode&&r&&r.length===1&&r[0]&&r[0].isStackNode)continue;n.build(e,`void`)}this._currentNode=i}}let i;if(this.outputNode){let n=this.outputNode.build(e,...t);(e.buildStage!==`generate`||this.outputNode.getNodeType(e)!==`void`)&&(i=n)}else i=super.build(e,...t);return ih(n),e.removeActiveStack(this),i}}).setParameterLength(0,1),cD=class{constructor(e=1){this.blending=e,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.premultiplyAlpha=!1}copy(e){return this.blending=e.blending,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.premultiplyAlpha=e.premultiplyAlpha,this}clone(){return new this.constructor().copy(this)}};new cD(0),new cD(6),new Oi,new F,new F,new F,new Bn,new F(0,0,-1),new Fn,new F,new F,new Fn,new P;var lD=new In;Sy.flipX(),lD.depthTexture=new ya(1,1);var uD=new ps(-1,1,1,-1,0,1),dD=new class extends xi{constructor(e=!1){super();let t=e===!1?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute(`position`,new li([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute(`uv`,new li(t,2))}},fD=q(dg([-1,-1,3]).element(Fv),dg([3,-1,-1]).element(Fv),0,1),pD=class extends Yi{constructor(e){super(dD,e),this.camera=uD,this.isQuadMesh=!0}async renderAsync(e){Rt(`QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.`),await e.init(),e.render(this,uD)}render(e){let t=this.material.vertexNode;this.material.vertexNode=fD,e.render(this,uD),this.material.vertexNode=t}};function mD(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new L),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}function hD(e,t){return t=mD(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}function gD(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}function _D(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}function vD(e,t){return t=_D(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}function yD(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}function bD(e,t,n){return n=hD(e,n),n=vD(t,n),n}function xD(e,t,n){gD(e,n),yD(t,n)}var SD=W(([e])=>t_(G(52.9829189).mul(t_(P_(e,fh(.06711056,.00583715)))))).setLayout({name:`interleavedGradientNoise`,type:`float`,inputs:[{name:`position`,type:`vec2`}]}),CD=W(([e,t,n])=>{let r=G(2.399963229728653),i=Xg(G(e).add(.5).div(G(t))),a=G(e).mul(r).add(n);return fh(i_(a),n_(a)).mul(i)}).setLayout({name:`vogelDiskSample`,type:`vec2`,inputs:[{name:`sampleIndex`,type:`int`},{name:`samplesCount`,type:`int`},{name:`phi`,type:`float`}]}),wD=new Bn,TD=Y(0).setGroup(J).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),ED=Y(1).setGroup(J).onRenderUpdate(({scene:e})=>e.backgroundIntensity),DD=Y(new Bn).setGroup(J).onRenderUpdate(({scene:e})=>{let t=e.background;return t!==null&&t.isTexture&&t.mapping!==300||e.backgroundNode&&e.backgroundNode.isNode?wD.makeRotationFromEuler(e.backgroundRotation).transpose():wD.identity(),wD}),OD=W(([e,t])=>e.mul(t).clamp()).setLayout({name:`linearToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),kD=W(([e,t])=>(e=e.mul(t),e.div(e.add(1)).clamp())).setLayout({name:`reinhardToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),AD=W(([e,t])=>{e=e.mul(t),e=e.sub(.004).max(0);let n=e.mul(e.mul(6.2).add(.5)),r=e.mul(e.mul(6.2).add(1.7)).add(.06);return n.div(r).pow(2.2)}).setLayout({name:`cineonToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),jD=W(([e])=>{let t=e.mul(e.add(.0245786)).sub(90537e-9),n=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(n)}),MD=W(([e,t])=>{let n=Ch(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),r=Ch(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=jD(e),e=r.mul(e),e.clamp()}).setLayout({name:`acesFilmicToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),ND=Ch(K(1.6605,-.1246,-.0182),K(-.5876,1.1329,-.1006),K(-.0728,-.0083,1.1187)),PD=Ch(K(.6274,.0691,.0164),K(.3293,.9195,.088),K(.0433,.0113,.8956)),FD=W(([e])=>{let t=K(e).toVar(),n=K(t.mul(t)).toVar(),r=K(n.mul(n)).toVar();return G(15.5).mul(r.mul(n)).sub(_g(40.14,r.mul(t))).add(_g(31.96,r).sub(_g(6.868,n.mul(t))).add(_g(.4298,n).add(_g(.1191,t).sub(.00232))))}),ID=W(([e,t])=>{let n=K(e).toVar(),r=Ch(K(.856627153315983,.137318972929847,.11189821299995),K(.0951212405381588,.761241990602591,.0767994186031903),K(.0482516061458583,.101439036467562,.811302368396859)),i=Ch(K(1.1271005818144368,-.1413297634984383,-.14132976349843826),K(-.11060664309660323,1.157823702216272,-.11060664309660294),K(-.016493938717834573,-.016493938717834257,1.2519364065950405)),a=G(-12.47393),o=G(4.026069);return n.mulAssign(t),n.assign(PD.mul(n)),n.assign(r.mul(n)),n.assign(k_(n,1e-10)),n.assign(Yg(n)),n.assign(n.sub(a).div(o.sub(a))),n.assign(K_(n,0,1)),n.assign(FD(n)),n.assign(i.mul(n)),n.assign(I_(k_(K(0),n),K(2.2))),n.assign(ND.mul(n)),n.assign(K_(n,0,1)),n}).setLayout({name:`agxToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),LD=W(([e,t])=>{let n=G(.76),r=G(.15);e=e.mul(t);let i=O_(e.r,O_(e.g,e.b)),a=Q_(i.lessThan(.08),i.sub(_g(6.25,i.mul(i))),.04);e.subAssign(a);let o=k_(e.r,k_(e.g,e.b));oh(o.lessThan(n),()=>e);let s=gg(1,n),c=gg(1,s.mul(s).div(o.add(s.sub(n))));e.mulAssign(c.div(o));let l=gg(1,vg(1,r.mul(o.sub(c)).add(1)));return G_(e,K(c),l)}).setLayout({name:`neutralToneMapping`,type:`vec3`,inputs:[{name:`color`,type:`vec3`},{name:`exposure`,type:`float`}]}),RD=class extends z{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){let t=this.getIncludes(e);for(let n of t)n.build(e,`void`);let 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}},zD=class extends RD{static get type(){return`FunctionNode`}constructor(e=``,t=[],n=``){super(e,t,n)}generateNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){let n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){let t=e.getDataFromNode(this),n=t.nodeFunction;return n===void 0&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);let n=this.getNodeFunction(e),r=n.name,i=n.type,a=e.getCodeFromNode(this,i);if(r!==``){let t=e.getDataFromNode(this);t.declarationRegistered!==!0&&(a.name=r,e.registerDeclaration(a),t.declarationRegistered=!0)}let o=e.getPropertyName(a);return a.code=this.getNodeFunction(e).getCode(o)+`
`,t===`property`?o:e.format(`${o}()`,i,t)}};function BD(e){let t,n=e.context.getViewZ;return n!==void 0&&(t=n(this)),(t||ub.z).negate()}var VD=W(([e,t],n)=>Y_(e,t,BD(n))),HD=W(([e],t)=>{let n=BD(t);return e.mul(e,n,n).negate().exp().oneMinus()}),UD=W(([e,t])=>q(t.toFloat().mix(Jh.rgb,e.toVec3()),Jh.a)),WD;function GD(e){WD||=new WeakMap;let t=WD.get(e);return t===void 0&&WD.set(e,t={}),t}function KD(e){let t=GD(e);return t.shadowMatrix||=Y(`mat4`).setGroup(J).onRenderUpdate(t=>((e.castShadow!==!0||t.renderer.shadowMap.enabled===!1)&&(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix))}function qD(e,t=cb){let n=KD(e).mul(t);return n.xyz.div(n.w)}function JD(e){let t=GD(e);return t.position||=Y(new F).setGroup(J).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.matrixWorld))}function YD(e){let t=GD(e);return t.targetPosition||=Y(new F).setGroup(J).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.target.matrixWorld))}function XD(e){let t=GD(e);return t.viewPosition||=Y(new F).setGroup(J).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new F,n.value.setFromMatrixPosition(e.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)})}var ZD=e=>Wy.transformDirection(JD(e).sub(YD(e))),QD=Eh(`vec3`,`totalDiffuse`),$D=Eh(`vec3`,`totalSpecular`),eO=Eh(`vec3`,`outgoingLight`),tO=e=>e.sort((e,t)=>e.id-t.id),nO=(e,t)=>{for(let n of t)if(n.isAnalyticLightNode&&n.light.id===e)return n;return null},rO=new WeakMap,iO=[],aO=class extends z{static get type(){return`LightsNode`}constructor(){super(`vec3`),this.totalDiffuseNode=QD,this.totalSpecularNode=$D,this.outgoingLightNode=eO,this._lights=[],this.global=!0}customCacheKey(){let e=this.getBuiltinLights();for(let t=0;t<e.length;t++){let n=e[t];if(iO.push(n.id),iO.push(+!!n.castShadow),n.isSpotLight===!0){let e=n.map===null?-1:n.map.id,t=n.colorNode?n.colorNode.getCacheKey():-1;iO.push(e,t)}}let t=Bp(iO);return iO.length=0,t}getHash(e){let t=e.getDataFromNode(this);if(t.lightNodesHash===void 0){let n=this.setupLightsNode(e);t.lightNodes=n;let r=[];for(let e of n)r.push(e.getHash());t.lightNodesHash=`lights-`+r.join(`,`)}return t.lightNodesHash}analyze(e){let t=e.getNodeProperties(this);for(let n of t.nodes)n.build(e);t.outputNode.build(e)}setupLightsNode(e){let t=e.getDataFromNode(this),n=[],r=t.lightNodes||null,i=e.context.materialLightings,a=this.getBuiltinLights(),o=tO([...i,...a]),s=e.renderer.library;for(let e of o)if(e.isNode)n.push(e);else{let t=null;if(r!==null&&(t=nO(e.id,r)),t===null){let n=s.getLightNodeClass(e.constructor);if(n===null){M(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}rO.has(e)===!1&&rO.set(e,new n(e)),t=rO.get(e)}n.push(t)}return n}setupDirectLight(e,t,n){let{lightingModel:r,reflectedLight:i}=e.context;r.direct({...n,lightNode:t,reflectedLight:i},e)}setupDirectRectAreaLight(e,t,n){let{lightingModel:r,reflectedLight:i}=e.context;r.directRectArea({...n,lightNode:t,reflectedLight:i},e)}setupLights(e,t){for(let n of t)n.build(e)}getLightNodes(e){let t=e.getDataFromNode(this);return t.lightNodes===void 0&&(t.lightNodes=this.setupLightsNode(e)),t.lightNodes}setup(e){let t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode,r=e.context,i=r.lightingModel,a=e.getNodeProperties(this);if(i){let{totalDiffuseNode:t,totalSpecularNode:o}=this;r.outgoingLight=n,a.nodes=e.addStack().nodes,i.start(e);let{backdrop:s,backdropAlpha:c}=r,{directDiffuse:l,directSpecular:u,indirectDiffuse:d,indirectSpecular:f}=r.reflectedLight,p=l.add(d);s!==null&&(p=K(c===null?s:c.mix(p,s))),t.assign(p),o.assign(u.add(f)),n.assign(t.add(o)),i.finish(e),n=n.bypass(e.removeStack())}else a.nodes=[];return e.lightsNode=t,n}setLights(e){return this._lights=e,this}getLights(){return this._lights}getBuiltinLights(){return this._lights}get hasLights(){return this._lights.length>0}},oO=new WeakMap,sO=new yE,cO=[],lO=e=>{let t=oO.get(e);return t===void 0&&(t=new hC,t.colorNode=q(0,0,0,1),t.isShadowPassMaterial=!0,t.name=`ShadowMaterial`,t.blending=0,t.fog=!1,oO.set(e,t)),t},uO=e=>{let t=oO.get(e);t!==void 0&&(t.dispose(),oO.delete(e))},dO=(e,t,n,r)=>{cO[0]=e,cO[1]=t;let i=sO.get(cO);return(i===void 0||i.shadowType!==n||i.useVelocity!==r)&&(i=(i,a,o,s,c,l,u,d,f)=>{(i.castShadow===!0||i.receiveShadow&&n===3)&&(r&&(Jp(i).useVelocity=!0),i.onBeforeShadow(e,i,o,t.camera,s,a.overrideMaterial,l),e.renderObject(i,a,o,s,c,l,u,d,f),i.onAfterShadow(e,i,o,t.camera,s,a.overrideMaterial,l))},i.shadowType=n,i.useVelocity=r,sO.set(cO,i)),cO[0]=null,cO[1]=null,i},fO=class extends z{static get type(){return`ShadowBaseNode`}constructor(e){super(),this.light=e,this.updateBeforeType=$p.RENDER,this.isShadowBaseNode=!0}getShadowMaterial(){return lO(this.light)}disposeShadowMaterial(){uO(this.light)}getShadowRenderObjectFunction(e,t=this.light.shadow){let n=e.shadowMap.type,r=e.getMRT();return dO(e,t,n,r?r.has(`velocity`):!1)}setupShadowPosition({context:e,material:t}){pO.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||cb)}},pO=Eh(`vec3`,`shadowPositionWorld`),mO=W(({depthTexture:e,shadowCoord:t,depthLayer:n})=>{let r=uy(e,t.xy).setName(`t_basic`);return e.isArrayTexture&&(r=r.depth(n)),r.compare(t.z)}),hO=W(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:r})=>{let i=(t,n)=>{let i=uy(e,t);return e.isArrayTexture&&(i=i.depth(r)),i.compare(n)},a=Ib(`mapSize`,`vec2`,n).setGroup(J),o=Ib(`radius`,`float`,n).setGroup(J),s=fh(1).div(a),c=o.mul(s.x),l=SD(wy.xy).mul(6.28318530718);return hg(i(t.xy.add(CD(0,5,l).mul(c)),t.z),i(t.xy.add(CD(1,5,l).mul(c)),t.z),i(t.xy.add(CD(2,5,l).mul(c)),t.z),i(t.xy.add(CD(3,5,l).mul(c)),t.z),i(t.xy.add(CD(4,5,l).mul(c)),t.z)).mul(1/5)}),gO=W(({depthTexture:e,shadowCoord:t,depthLayer:n},r)=>{let i=uy(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(n)),i=i.rg;let a=i.x,o=k_(1e-7,i.y.mul(i.y)),s=r.renderer.reversedDepthBuffer?A_(a,t.z):A_(t.z,a),c=G(1).toVar();return oh(s.notEqual(1),()=>{let e=t.z.sub(a),n=o.div(o.add(e.mul(e)));n=K_(gg(n,.3).div(.65)),c.assign(k_(s,n))}),c}),_O=W(({samples:e,radius:t,size:n,shadowPass:r,depthLayer:i})=>{let a=G(0).toVar(`meanVertical`),o=G(0).toVar(`squareMeanVertical`),s=e.lessThanEqual(G(1)).select(G(0),G(2).div(e.sub(1))),c=e.lessThanEqual(G(1)).select(G(0),G(-1));return MS({start:lh(0),end:lh(e),type:`int`,condition:`<`},({i:e})=>{let l=c.add(G(e).mul(s)),u=r.sample(hg(wy.xy,fh(0,l).mul(t)).div(n));r.value.isArrayTexture&&(u=u.depth(i)),u=u.x,a.addAssign(u),o.addAssign(u.mul(u))}),a.divAssign(e),o.divAssign(e),fh(a,Xg(o.sub(a.mul(a)).max(0)))}),vO=W(({samples:e,radius:t,size:n,shadowPass:r,depthLayer:i})=>{let a=G(0).toVar(`meanHorizontal`),o=G(0).toVar(`squareMeanHorizontal`),s=e.lessThanEqual(G(1)).select(G(0),G(2).div(e.sub(1))),c=e.lessThanEqual(G(1)).select(G(0),G(-1));return MS({start:lh(0),end:lh(e),type:`int`,condition:`<`},({i:e})=>{let l=c.add(G(e).mul(s)),u=r.sample(hg(wy.xy,fh(l,0).mul(t)).div(n));r.value.isArrayTexture&&(u=u.depth(i)),a.addAssign(u.x),o.addAssign(hg(u.y.mul(u.y),u.x.mul(u.x)))}),a.divAssign(e),o.divAssign(e),fh(a,Xg(o.sub(a.mul(a)).max(0)))}),yO=[mO,hO,null,gO],bO,xO=new pD,SO=class extends fO{static get type(){return`ShadowNode`}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:r,shadow:i,depthLayer:a}){let o=r.x.greaterThanEqual(0).and(r.x.lessThanEqual(1)).and(r.y.greaterThanEqual(0)).and(r.y.lessThanEqual(1)).and(r.z.lessThanEqual(1)),s=t({depthTexture:n,shadowCoord:r,shadow:i,depthLayer:a});return o.select(s,G(1))}setupShadowCoord(e,t){let{shadow:n}=this,{renderer:r}=e,i=n.biasNode||Ib(`bias`,`float`,n).setGroup(J),a=t,o;if(n.camera.isOrthographicCamera||r.logarithmicDepthBuffer!==!0)a=a.xyz.div(a.w),o=a.z;else{let e=a.w;a=a.xy.div(e);let t=Ib(`near`,`float`,n.camera).setGroup(J),r=Ib(`far`,`float`,n.camera).setGroup(J);o=nC(e.negate(),t,r)}return a=K(a.x,a.y.oneMinus(),r.reversedDepthBuffer?o.sub(i):o.add(i)),a}getShadowFilterFn(e){return yO[e]}setupRenderTarget(e,t){let n=new ya(e.mapSize.width,e.mapSize.height);n.name=`ShadowDepthTexture`,n.compareFunction=t.renderer.reversedDepthBuffer?518:515;let r=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return r.texture.name=`ShadowMap`,r.texture.type=e.mapType,r.depthTexture=n,{shadowMap:r,depthTexture:n}}setupShadow(e){let{renderer:t,camera:n}=e,{light:r,shadow:i}=this,{depthTexture:a,shadowMap:o}=this.setupRenderTarget(i,e),s=t.shadowMap.type,c=t.hasCompatibility(kt.TEXTURE_COMPARE);if(s===1&&c?(a.minFilter=O,a.magFilter=O):(a.minFilter=T,a.magFilter=T),i.camera.coordinateSystem=n.coordinateSystem,i.camera.updateProjectionMatrix(),s===3&&i.isPointLightShadow!==!0){a.compareFunction=null,o.depth>1?(o._vsmShadowMapVertical||(o._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:xe,type:ce,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapVertical.texture.name=`VSMVertical`),this.vsmShadowMapVertical=o._vsmShadowMapVertical,o._vsmShadowMapHorizontal||(o._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:xe,type:ce,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapHorizontal.texture.name=`VSMHorizontal`),this.vsmShadowMapHorizontal=o._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:xe,type:ce,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:xe,type:ce,depthBuffer:!1}));let t=uy(a);a.isArrayTexture&&(t=t.depth(this.depthLayer));let n=uy(this.vsmShadowMapVertical.texture);a.isArrayTexture&&(n=n.depth(this.depthLayer));let r=Ib(`blurSamples`,`float`,i).setGroup(J),s=Ib(`radius`,`float`,i).setGroup(J),c=Ib(`mapSize`,`vec2`,i).setGroup(J),l=ev(e.getSharedContext()),u=this.vsmMaterialVertical||=new hC;u.contextNode=l,u.fragmentNode=_O({samples:r,radius:s,size:c,shadowPass:t,depthLayer:this.depthLayer}),u.name=`VSMVertical`,u=this.vsmMaterialHorizontal||=new hC,u.contextNode=l,u.fragmentNode=vO({samples:r,radius:s,size:c,shadowPass:n,depthLayer:this.depthLayer}),u.name=`VSMHorizontal`}let l=Ib(`intensity`,`float`,i).setGroup(J),u=Ib(`normalBias`,`float`,i).setGroup(J),d=KD(r),f=bb.mul(u),p;p=!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld?d.mul(pO.add(f)):Y(`mat4`).onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(d.value,e.matrixWorld)).mul(ob).add(d.mul(q(f,0)));let m=this.setupShadowCoord(e,p),h=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(h===null)throw Error(`THREE.WebGPURenderer: Shadow map type not supported yet.`);let g=s===3&&i.isPointLightShadow!==!0?this.vsmShadowMapHorizontal.texture:a,_=this.setupShadowFilter(e,{filterFn:h,shadowTexture:o.texture,depthTexture:g,shadowCoord:m,shadow:i,depthLayer:this.depthLayer}),v;t.shadowMap.transmitted===!0&&(o.texture.isCubeTexture?v=Pb(o.texture,m.xyz):(v=uy(o.texture,m),a.isArrayTexture&&(v=v.depth(this.depthLayer))));let y;y=v?G_(1,_.rgb.mix(v,1),l.mul(v.a)).toVar():G_(1,_,l).toVar(),this.shadowMap=o,this.shadow.map=o;let b=`${this.light.type} Shadow [ ${this.light.name||`ID: `+this.light.id} ]`;return v&&y.toInspector(`${b} / Color`,()=>this.shadowMap.texture.isCubeTexture?Pb(this.shadowMap.texture,kC()):uy(this.shadowMap.texture)),y.toInspector(`${b} / Depth`,()=>{let e=Ib(`near`,`float`,this.shadow.camera),t=Ib(`far`,`float`,this.shadow.camera),n;n=this.shadowMap.texture.isCubeTexture?Pb(this.shadowMap.depthTexture,kC()).r:uy(this.shadowMap.depthTexture).r;let r;return r=this.shadow.camera.isPerspectiveCamera?tC(n,e,t):QS(n,e,t),r=ZS(r,e,t),r.oneMinus()})}setup(e){if(e.renderer.shadowMap.enabled!==!1)return W(()=>{let 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){let{shadow:t,shadowMap:n,light:r}=this,{renderer:i,scene:a}=e;t.updateMatrices(r),n.setSize(t.mapSize.width,t.mapSize.height,n.depth);let o=a.name;a.name=`Shadow Map [ ${r.name||`ID: `+r.id} ]`,i.render(a,t.camera),a.name=o}updateShadow(e){let{shadowMap:t,shadow:n}=this,{renderer:r,scene:i,camera:a}=e,o=r.shadowMap.type,s=t.depthTexture.version;this._depthVersionCached=s;let c=n.camera.layers.mask;n.camera.layers.mask&4294967294||(n.camera.layers.mask=a.layers.mask);let l=r.getRenderObjectFunction();bO=bD(r,i,bO),i.overrideMaterial=this.getShadowMaterial(),r.setRenderObjectFunction(this.getShadowRenderObjectFunction(r,this.shadow||this.light.shadow)),r.setClearColor(0,0),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(l),o===3&&n.isPointLightShadow!==!0&&this.vsmPass(r),n.camera.layers.mask=c,xD(r,i,bO)}vsmPass(e){let{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),xO.material=this.vsmMaterialVertical,xO.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),xO.material=this.vsmMaterialHorizontal,xO.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,this.disposeShadowMaterial(),this.shadowMap&&=(this.shadowMap.dispose(),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){if(e.renderer._isPreCompiling===!0)return;let{shadow:t}=this,n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId.get(e.camera)===e.frameId&&(n=!1),this._cameraFrameId.set(e.camera,e.frameId)),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}},CO=(e,t)=>new SO(e,t),wO=new L,TO=new Bn,EO=new F,DO=new F,OO=[new F(1,0,0),new F(-1,0,0),new F(0,-1,0),new F(0,1,0),new F(0,0,1),new F(0,0,-1)],kO=[new F(0,-1,0),new F(0,-1,0),new F(0,0,-1),new F(0,0,1),new F(0,-1,0),new F(0,-1,0)],AO=[new F(1,0,0),new F(-1,0,0),new F(0,1,0),new F(0,-1,0),new F(0,0,1),new F(0,0,-1)],jO=[new F(0,-1,0),new F(0,-1,0),new F(0,0,1),new F(0,0,-1),new F(0,-1,0),new F(0,-1,0)],MO=W(({depthTexture:e,bd3D:t,dp:n})=>Pb(e,t).compare(n)),NO=W(({depthTexture:e,bd3D:t,dp:n,shadow:r})=>{let i=Ib(`radius`,`float`,r).setGroup(J),a=Ib(`mapSize`,`vec2`,r).setGroup(J),o=i.div(a.x),s=m_(t),c=e_(F_(t,s.x.greaterThan(s.z).select(K(0,1,0),K(1,0,0)))),l=F_(t,c),u=SD(wy.xy).mul(6.28318530718),d=CD(0,5,u),f=CD(1,5,u),p=CD(2,5,u),m=CD(3,5,u),h=CD(4,5,u);return Pb(e,t.add(c.mul(d.x).add(l.mul(d.y)).mul(o))).compare(n).add(Pb(e,t.add(c.mul(f.x).add(l.mul(f.y)).mul(o))).compare(n)).add(Pb(e,t.add(c.mul(p.x).add(l.mul(p.y)).mul(o))).compare(n)).add(Pb(e,t.add(c.mul(m.x).add(l.mul(m.y)).mul(o))).compare(n)).add(Pb(e,t.add(c.mul(h.x).add(l.mul(h.y)).mul(o))).compare(n)).mul(1/5)}),PO=W(({filterFn:e,depthTexture:t,shadowCoord:n,shadow:r},i)=>{let a=n.xyz.toConst(),o=a.abs().toConst(),s=o.x.max(o.y).max(o.z),c=Y(`float`).setGroup(J).onRenderUpdate(()=>r.camera.near),l=Y(`float`).setGroup(J).onRenderUpdate(()=>r.camera.far),u=Ib(`bias`,`float`,r).setGroup(J),d=G(1).toVar();return oh(s.sub(l).lessThanEqual(0).and(s.sub(c).greaterThanEqual(0)),()=>{let n;i.renderer.reversedDepthBuffer?(n=eC(s.negate(),c,l),n.subAssign(u)):i.renderer.logarithmicDepthBuffer?(n=nC(s.negate(),c,l),n.addAssign(u)):(n=$S(s.negate(),c,l),n.addAssign(u));let o=a.normalize();d.assign(e({depthTexture:t,bd3D:o,dp:n,shadow:r}))}),d}),FO=class extends SO{static get type(){return`PointShadowNode`}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===0?MO:NO}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:r,shadow:i}){return PO({filterFn:t,depthTexture:n,shadowCoord:r,shadow:i})}setupRenderTarget(e,t){let n=new ba(e.mapSize.width);n.name=`PointShadowDepthTexture`,n.compareFunction=t.renderer.reversedDepthBuffer?518:515;let r=t.createCubeRenderTarget(e.mapSize.width);return r.texture.name=`PointShadowMap`,r.depthTexture=n,{shadowMap:r,depthTexture:n}}renderShadow(e){let{shadow:t,shadowMap:n,light:r}=this,{renderer:i,scene:a}=e,o=t.camera,s=t.matrix,c=i.coordinateSystem===Dt,l=c?OO:AO,u=c?kO:jO;n.setSize(t.mapSize.width,t.mapSize.width);let d=i.autoClear,f=i.getClearColor(wO),p=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){i.setRenderTarget(n,e),i.clear();let c=r.distance||o.far;c!==o.far&&(o.far=c,o.updateProjectionMatrix()),EO.setFromMatrixPosition(r.matrixWorld),o.position.copy(EO),DO.copy(o.position),DO.add(l[e]),o.up.copy(u[e]),o.lookAt(DO),o.updateMatrixWorld(),s.makeTranslation(-EO.x,-EO.y,-EO.z),TO.multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse),t._frustum.setFromProjectionMatrix(TO,o.coordinateSystem,o.reversedDepth);let d=a.name;a.name=`Point Light Shadow [ ${r.name||`ID: `+r.id} ] - Face ${e+1}`,i.render(a,o),a.name=d}i.autoClear=d,i.setClearColor(f,p)}},IO=(e,t)=>new FO(e,t),LO=class extends zS{static get type(){return`AnalyticLightNode`}constructor(e=null){super(),this.light=e,this.color=new L,this.colorNode=e&&e.colorNode||Y(this.color).setGroup(J),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=$p.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 XD(this.light).sub(e.context.positionView||ub)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return CO(this.light)}setupShadow(e){let{renderer:t}=e;if(t.shadowMap.enabled===!1)return;let n=this.shadowColorNode;if(n===null){let e=this.light.shadow.shadowNode,t;t=e===void 0?this.setupShadowNode():V(e),this.shadowNode=t,this.shadowColorNode=n=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(n=e.context.getShadow(this,e)),this.colorNode=n}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);let t=this.setupDirect(e),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){let{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}},RO=W(({lightDistance:e,cutoffDistance:t,decayExponent:n})=>{let r=e.pow(n).max(.01).reciprocal();return t.greaterThan(0).select(r.mul(e.div(t).pow4().oneMinus().clamp().pow2()),r)}),zO=({color:e,lightVector:t,cutoffDistance:n,decayExponent:r})=>{let i=t.normalize(),a=RO({lightDistance:t.length(),cutoffDistance:n,decayExponent:r});return{lightDirection:i,lightColor:e.mul(a)}},BO=class extends LO{static get type(){return`PointLightNode`}constructor(e=null){super(e),this.cutoffDistanceNode=Y(0).setGroup(J),this.decayExponentNode=Y(2).setGroup(J)}update(e){let{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return IO(this.light)}setupDirect(e){return zO({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}},VO=W(([e,t])=>{let n=e.x,r=e.y,i=e.z,a=t.element(0).mul(.886227);return a=a.add(t.element(1).mul(1.023328).mul(r)),a=a.add(t.element(2).mul(1.023328).mul(i)),a=a.add(t.element(3).mul(1.023328).mul(n)),a=a.add(t.element(4).mul(.858086).mul(n).mul(r)),a=a.add(t.element(5).mul(.858086).mul(r).mul(i)),a=a.add(t.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),a=a.add(t.element(7).mul(.858086).mul(n).mul(i)),a=a.add(t.element(8).mul(.429043).mul(_g(n,n).sub(_g(r,r)))),a}),HO=new nD,UO=class extends EE{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){let r=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background,a=!1;if(i===null)r._clearColor.getRGB(HO),HO.a=r._clearColor.a;else if(i.isColor===!0)i.getRGB(HO),HO.a=1,a=!0;else if(i.isNode===!0){let n=this.get(e),a=i;HO.copy(r._clearColor);let o=n.backgroundMesh;if(o===void 0){let e=q(a).mul(ED).context({getUV:()=>DD.mul(vb),getTextureLevel:()=>TD}),t=Hy.element(3).element(3).equal(1),r=vg(1,Hy.element(1).element(1)).mul(3),s=t.select(ob.mul(r),ob),c=eb.mul(q(s,0)),l=Hy.mul(q(c.xyz,1));l=l.setZ(l.w);let u=new hC;u.name=`Background.material`,u.side=1,u.depthTest=!1,u.depthWrite=!1,u.allowOverride=!1,u.fog=!1,u.lights=!1,u.vertexNode=l,u.colorNode=e,n.backgroundMeshNode=e,n.backgroundMesh=o=new Yi(new $a(1,32,32),u),o.frustumCulled=!1,o.name=`Background.mesh`;function d(){i.removeEventListener(`dispose`,d),o.material.dispose(),o.geometry.dispose()}i.addEventListener(`dispose`,d)}let s=a.getCacheKey();n.backgroundCacheKey!==s&&(n.backgroundMeshNode.node=q(a).mul(ED),n.backgroundMeshNode.needsUpdate=!0,o.material.needsUpdate=!0,n.backgroundCacheKey=s),t.unshift(o,o.geometry,o.material,0,0,null,null)}else N(`Renderer: Unsupported background configuration.`,i);let o=r.xr.getEnvironmentBlendMode();if(o===`additive`?HO.set(0,0,0,1):o===`alpha-blend`&&HO.set(0,0,0,0),r.autoClear===!0||a===!0){let e=n.clearColorValue;e.r=HO.r,e.g=HO.g,e.b=HO.b,e.a=HO.a,(r.backend.isWebGLBackend===!0||r.alpha===!0)&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),n.depthClearValue=r.getClearDepth(),n.stencilClearValue=r.getClearStencil(),n.clearColor=r.autoClearColor===!0,n.clearDepth=r.autoClearDepth===!0,n.clearStencil=r.autoClearStencil===!0}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}},WO=0,GO=class{constructor(e=``,t=[]){this.name=e,this.bindings=t,this.id=WO++}},KO=class{constructor(e,t,n,r,i,a,o,s,c,l,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=u,this.nodeAttributes=r,this.bindings=i,this.updateNodes=a,this.updateBeforeNodes=o,this.updateAfterNodes=s,this.observer=c,this.hardwareClipping=l,this.usedTimes=0}createBindings(){let e=[];for(let t of this.bindings)if(t.bindings[0].groupNode.shared!==!0){let n=new GO(t.name,[]);e.push(n);for(let e of t.bindings)n.bindings.push(e.clone())}else e.push(t);return e}},qO=class{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}},JO=class{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}},YO=class{constructor(e,t,n=!1,r=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=r}},XO=class extends YO{constructor(e,t,n=null,r=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=r}},ZO=class{constructor(e,t,n=``){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}},QO=0,$O=class{constructor(e=null){this.id=QO++,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)}},ek=class{constructor(e,t){this.name=e,this.members=t,this.output=!1}},tk=class{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}},nk=class extends tk{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}},rk=class extends tk{constructor(e,t=new P){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}},ik=class extends tk{constructor(e,t=new F){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}},ak=class extends tk{constructor(e,t=new Fn){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}},ok=class extends tk{constructor(e,t=new L){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}},sk=class extends tk{constructor(e,t=new Ws){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}},ck=class extends tk{constructor(e,t=new bn){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}},lk=class extends tk{constructor(e,t=new Bn){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}},uk=class extends nk{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},dk=class extends rk{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},fk=class extends ik{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},pk=class extends ak{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},mk=class extends ok{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},hk=class extends sk{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},gk=class extends ck{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},_k=class extends lk{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}},vk=0,yk=new WeakMap,bk=new WeakMap,xk=new WeakMap,Sk=new Map([[Int8Array,`int`],[Int16Array,`int`],[Int32Array,`int`],[Uint8Array,`uint`],[Uint16Array,`uint`],[Uint32Array,`uint`],[Float32Array,`float`]]),Ck=e=>/e/g.test(e)?String(e).replace(/\+/g,``):(e=Number(e),e+(e%1?``:`.0`)),wk=e=>{if(e.writeUsageCount>0)return!0;if(e.subBuildsCache!==void 0){for(let t in e.subBuildsCache)if(wk(e.subBuildsCache[t]))return!0}return!1},Tk=class{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.compute=null,this.renderer=t,this.parser=n,this.scene=null,this.camera=null,this.nodes=new Set,this.sequentialNodes=new Set,this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.hardwareClipping=!1,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:``,fragment:``,compute:``},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:``},this.chaining=[],this.stack=sD(),this.stacks=[],this.tab=` `,this.currentFunctionNode=null,this.context={material:this.material},this.cache=new $O,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:vk++})}isFlatShading(){return this.material.flatShading===!0||this.geometry.hasAttribute(`normal`)===!1}isOpaque(){let e=this.material;return e.transparent===!1&&e.blending===1&&e.alphaToCoverage===!1}createRenderTarget(e,t,n){return new In(e,t,n)}createCubeRenderTarget(e,t){return new AC(e,t)}includes(e){return this.nodes.has(e)}getOutputType(e=0){let t=this.renderer.getRenderTarget();return t===null?`vec4`:Kp(t.textures[e])}getOutputStructName(){}_getBindGroup(e,t){let n=t[0].groupNode,r=n.shared;if(r)for(let e=1;e<t.length;e++)n!==t[e].groupNode&&(r=!1);let i;if(r){let n=``;for(let e of t)if(e.isNodeUniformsGroup){e.uniforms.sort((e,t)=>e.nodeUniform.node.id-t.nodeUniform.node.id);for(let t of e.uniforms)n+=t.nodeUniform.node.id}else n+=e.nodeUniform.id;let r=this.renderer._currentRenderContext||this.renderer,a=yk.get(r);a===void 0&&(a=new Map,yk.set(r,a));let o=zp(n);i=a.get(o),i===void 0&&(i=new GO(e,t),a.set(o,i))}else i=new GO(e,t);return i}getBindGroupArray(e,t){let n=this.bindings[t],r=n[e];return r===void 0&&(this.bindingsIndexes[e]===void 0&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=r=[]),r}getBindings(){let e=this.bindGroups;if(e===null){let t={},n=this.bindings;for(let e of rm)for(let r in n[e]){let i=n[e][r],a=t[r]||(t[r]=[]);for(let e of i)a.includes(e)===!1&&a.push(e)}e=[];for(let n in t){let r=t[n],i=this._getBindGroup(n,r);e.push(i)}this.bindGroups=e}return e}sortBindingGroups(){let e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){let n=e[t];this.bindingsIndexes[n.name].group=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){this.nodes.has(e)===!1&&(this.nodes.add(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){let t=e.updateBeforeType,n=e.updateAfterType;(t!==$p.NONE||n!==$p.NONE)&&this.sequentialNodes.add(e)}buildUpdateNodes(){for(let e of this.nodes)e.updateType!==$p.NONE&&this.updateNodes.push(e);for(let e of this.sequentialNodes){let t=e.updateBeforeType,n=e.updateAfterType;t!==$p.NONE&&this.updateBeforeNodes.push(e),n!==$p.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}get renderPipeline(){return this.context.renderPipeline}isFilteredTexture(e){return e.magFilter===1006||e.magFilter===1007||e.magFilter===1005||e.magFilter===1008||e.minFilter===1006||e.minFilter===1007||e.minFilter===1005||e.minFilter===1008}getUniformBufferLimit(){return this.renderer.backend.capabilities.getUniformBufferLimit()}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw Error(`THREE.NodeBuilder: Invalid node chaining!`)}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){let t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){let e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getGI,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){let n=this.getDataFromNode(e);return n.cache===void 0&&(n.cache=new $O(t?this.getCache():null)),n.cache}isAvailable(){return!1}getVertexIndex(){M(`Abstract function.`)}getInstanceIndex(){M(`Abstract function.`)}getDrawIndex(){M(`Abstract function.`)}getFrontFacing(){M(`Abstract function.`)}getFragCoord(){M(`Abstract function.`)}isFlipY(){return!1}isContextAssign(){return this.context.assign===!0}increaseUsage(e){let t=this.getDataFromNode(e);return t.usageCount=t.usageCount===void 0?1:t.usageCount+1,this.isContextAssign()?t.writeUsageCount=t.writeUsageCount===void 0?1:t.writeUsageCount+1:t.readUsageCount=t.readUsageCount===void 0?1:t.readUsageCount+1,t.usageCount}hasWriteUsage(e){let t=e.getShared(this),n=(t.isGlobal(this)?this.globalCache:this.cache).getData(t);if(n!==void 0){for(let e in n)if(wk(n[e]))return!0}return!1}generateTexture(){M(`Abstract function.`)}generateTextureLod(){M(`Abstract function.`)}generateTextureSize(){M(`Abstract function.`)}generateArrayDeclaration(e,t){return this.getType(e)+`[ `+t+` ]`}generateArray(e,t,n=null){let r=this.generateArrayDeclaration(e,t)+`( `;for(let i=0;i<t;i++){let a=n?n[i]:null;r+=a===null?this.generateConst(e):a.build(this,e),i<t-1&&(r+=`, `)}return r+=` )`,r}generateStruct(e,t,n=null){let r=[];for(let e of t){let{name:t,type:i}=e;n&&n[t]&&n[t].isNode?r.push(n[t].build(this,i)):r.push(this.generateConst(i))}return e+`( `+r.join(`, `)+` )`}generateConst(e,t=null){if(t===null&&(e===`float`||e===`int`||e===`uint`?t=0:e===`bool`?t=!1:e===`color`?t=new L:e===`vec2`||e===`uvec2`||e===`ivec2`?t=new P:e===`vec3`||e===`uvec3`||e===`ivec3`?t=new F:(e===`vec4`||e===`uvec4`||e===`ivec4`)&&(t=new Fn)),e===`float`)return Ck(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`)}( ${Ck(t.r)}, ${Ck(t.g)}, ${Ck(t.b)} )`;let n=this.getTypeLength(e),r=this.getComponentType(e),i=e=>this.generateConst(r,e);if(n===2)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)} )`;if(n===3)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)}, ${i(t.z)} )`;if(n===4&&e!==`mat2`)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)}, ${i(t.z)}, ${i(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(i).join(`, `)} )`;if(n>4)return`${this.getType(e)}()`;throw Error(`THREE.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){let n=this.attributes;for(let t of n)if(t.name===e)return t;let r=new qO(e,t);return this.registerDeclaration(r),n.push(r),r}getPropertyName(e){return e.name}isReservedKeyword(){return!1}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return e===`void`||e===`property`||e===`sampler`||e===`samplerComparison`||e===`texture`||e===`cubeTexture`||e===`storageTexture`||e===`depthTexture`||e===`texture3D`}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){let t=e.type;return e.isDepthTexture===!0?`float`:t===1013?`int`:t===1014?`uint`:`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;let 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=Wp(e),r=t===`float`?``:t[0];return/mat2/.test(t)===!0&&(n=n.replace(`vec`,`mat`)),r+n}getTypeFromArray(e){return Sk.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);let n=t.array,r=e.itemSize,i=e.normalized,a;return!(e instanceof ci)&&i!==!0&&(a=this.getTypeFromArray(n)),this.getTypeFromLength(r,a)}getTypeLength(e){let t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return n===null?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:Number(n[1])}getVectorFromMatrix(e){return e.replace(`mat`,`vec`)}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){let 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 Error(`THREE.NodeBuilder: Invalid active stack removal.`)}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=sD(this.stack);let e=ah();return this.stacks.push(e),ih(this.stack),this.stack}removeStack(){let e=this.stack;for(let t of e.nodes){let n=this.getDataFromNode(t);n.stack=e}return this.stack=e.parent,ih(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){n=n===null?e.isGlobal(this)?this.globalCache:this.cache:n;let r=n.getData(e);r===void 0&&(r={},n.setData(e,r)),r[t]===void 0&&(r[t]={});let i=r[t];if(this.subBuildLayers.length===0)return i;let a=r.any?r.any.subBuilds:null,o=this.getClosestSubBuild(a);return o&&(i.subBuildsCache===void 0&&(i.subBuildsCache={}),i=i.subBuildsCache[o]||(i.subBuildsCache[o]={}),i.subBuilds=a),i}getNodeProperties(e,t=`any`){let n=this.getDataFromNode(e,t);return n.properties||={outputNode:null}}getBufferAttributeFromNode(e,t,n=null){let r=this.getDataFromNode(e,`vertex`),i=r.bufferAttribute;if(i===void 0){let a=this.uniforms.index++;n===null&&(n=`nodeAttribute`+a),i=new qO(n,t,e),this.bufferAttributes.push(i),r.bufferAttribute=i}return i}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,n=null,r=this.shaderStage){let i=this.getDataFromNode(e,r,this.globalCache),a=i.structType;if(a===void 0){let o=this.structs.index++;n===null&&(n=`StructType`+o),a=new ek(n,t),this.structs[r].push(a),this.types[r][n]=e,i.structType=a}return a}getOutputStructTypeFromNode(e,t){let n=this.getStructTypeFromNode(e,t,`OutputType`,`fragment`);return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,r=null){let i=this.getDataFromNode(e,n,this.globalCache),a=i.uniform;if(a===void 0){let o=this.uniforms.index++;a=new JO(r||`nodeUniform`+o,t,e),this.uniforms[n].push(a),this.registerDeclaration(a),i.uniform=a}return a}getVarFromNode(e,t=null,n=e.getNodeType(this),r=this.shaderStage,i=!1){let a=this.getDataFromNode(e,r),o=this.getSubBuildProperty(`variable`,a.subBuilds),s=a[o];if(s===void 0){let c=i?`_const`:`_var`,l=this.vars[r]||(this.vars[r]=[]),u=this.vars[c]||(this.vars[c]=0);t===null&&(t=(i?`nodeConst`:`nodeVar`)+u,this.vars[c]++),o!==`variable`&&(t=this.getSubBuildProperty(t,a.subBuilds));let d=e.getArrayCount(this);s=new YO(t,n,i,d),i||l.push(s),this.registerDeclaration(s),a[o]=s}return s}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(e.values!==null){for(let t of e.values)if(!this.isDeterministic(t))return!1}return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,n=e.getNodeType(this),r=null,i=null){let a=this.getDataFromNode(e,`any`),o=this.getSubBuildProperty(`varying`,a.subBuilds),s=a[o];if(s===void 0){let e=this.varyings,c=e.length;t===null&&(t=`nodeVarying`+c),o!==`varying`&&(t=this.getSubBuildProperty(t,a.subBuilds)),s=new XO(t,n,r,i),e.push(s),this.registerDeclaration(s),a[o]=s}return s}registerDeclaration(e){let t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),r=this.renderer.debug.diagnostics.keywords,i=e.name,a=i,o=this.getPropertyName(e),s=1;for(;r&&this.isReservedKeyword(a)||n[o]!==void 0;)a=i+`_`+s++,e.name=a,o=this.getPropertyName(e);a!==i&&M(`TSL: Declaration name '${i}' of '${e.type}' is a reserved keyword or already in use. Renamed to '${a}'.`),n[o]=e}getCodeFromNode(e,t,n=this.shaderStage){let r=this.getDataFromNode(e),i=r.code;if(i===void 0){let e=this.codes[n]||(this.codes[n]=[]),a=e.length;i=new ZO(`nodeCode`+a,t),e.push(i),r.code=i}return i}addFlowCodeHierarchy(e,t){let{flowCodes:n,flowCodeBlock:r}=this.getDataFromNode(e),i=!0,a=t;for(;a;){if(r.get(a)===!0){i=!1;break}a=this.getDataFromNode(a).parentNodeBlock}if(i)for(let e of n)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,n){let r=this.getDataFromNode(e),i=r.flowCodes||=[],a=r.flowCodeBlock||=new WeakMap;i.push(t),a.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+=`;
`),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){let 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){let t=this.renderer.backend,n=bk.get(t);n===void 0&&(n=new WeakMap,bk.set(t,n));let r=n.get(e);if(r===void 0){r=new zD;let t=this.currentFunctionNode;this.currentFunctionNode=r,r.code=this.buildFunctionCode(e),this.currentFunctionNode=t,n.set(e,r)}return r}flowShaderNode(e){let t=e.layout,n={[Symbol.iterator](){let e=0,t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(let e of t.inputs)n[e.name]=new oD(e.type,e.name);e.layout=null;let r=e.call(n),i=this.flowStagesNode(r,t.type);return e.layout=t,i}flowBuildStage(e,t,n=null){let r=this.getBuildStage();this.setBuildStage(t);let i=e.build(this,n);return this.setBuildStage(r),i}flowStagesNode(e,t=null){let n=this.flow,r=this.vars,i=this.declarations,a=this.cache,o=this.buildStage,s=this.stack,c={code:``};this.flow=c,this.vars={},this.declarations={},this.cache=new $O,this.stack=sD();for(let n of nm)this.setBuildStage(n),c.result=e.build(this,t);return c.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=r,this.declarations=i,this.cache=a,this.stack=s,this.setBuildStage(o),c}getFunctionOperator(){return null}buildFunctionCode(){M(`Abstract function.`)}flowChildNode(e,t=null){let n=this.flow,r={code:``};return this.flow=r,r.result=e.build(this,t),this.flow=n,r}flowNodeFromShaderStage(e,t,n=null,r=null){let i=this.tab,a=this.cache,o=this.shaderStage,s=this.context;this.setShaderStage(e);let c={...this.context};delete c.nodeBlock,this.cache=this.globalCache,this.tab=` `,this.context=c;let l=null;if(this.buildStage===`generate`){let i=this.flowChildNode(t,n);r!==null&&(i.code+=`${this.tab+r} = ${i.result};\n`),this.flowCode[e]=this.flowCode[e]+i.code,l=i}else l=t.build(this);return this.setShaderStage(o),this.cache=a,this.tab=i,this.context=s,l}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){M(`Abstract function.`)}getVaryings(){M(`Abstract function.`)}getVar(e,t,n=null){return`${n===null?this.getType(e):this.generateArrayDeclaration(e,n)} ${t}`}getVars(e,t=!1){let n=[],r=this.vars[e];if(r!==void 0)for(let e of r)n.push(`${this.getVar(e.type,e.name,e.count)};`);return n.join(t?`
`:`
`)}getUniforms(){M(`Abstract function.`)}getCodes(e){let t=this.codes[e],n=``;if(t!==void 0)for(let e of t)n+=e.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(){M(`Abstract function.`)}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,`any`).subBuilds:e instanceof Set?[...e]:e,!t)return null;let n=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){let r=t[e];if(n.includes(r))return r}return null}getSubBuildOutput(e){return this.getSubBuildProperty(`outputNode`,e)}getSubBuildProperty(e=``,t=null){let n;n=t===null?this.subBuildFn:this.getClosestSubBuild(t);let r;return r=n?e?n+`_`+e:n:e,r}prebuild(){let{renderer:e,material:t}=this;if(e.contextNode.isContextNode===!0?this.context={...this.context,...e.contextNode.getFlowContextData()}:N('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),t&&t.contextNode&&(t.contextNode.isContextNode===!0?this.context={...this.context,...t.contextNode.getFlowContextData()}:N('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),t!==null){let n=e.library.fromMaterial(t);n===null&&(N(`NodeBuilder: Material "${t.type}" is not compatible.`),n=new hC),n.build(this)}else this.addFlow(`compute`,this.compute)}build(){this.prebuild();for(let e of nm){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage(`vertex`,this.context.position);for(let t of rm){this.setShaderStage(t);let n=this.flowNodes[t];for(let t of n)e===`generate`?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}async buildAsync(){this.prebuild();for(let e of nm){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage(`vertex`,this.context.position);for(let t of rm){this.setShaderStage(t);let n=this.flowNodes[t];for(let t of n)e===`generate`?this.flowNode(t):t.build(this);await zt()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=xk.get(e);return t===void 0&&(t={}),t}getNodeUniform(e,t){let n=this.getSharedDataFromNode(e),r=n.cache;if(r===void 0){if(t===`float`||t===`int`||t===`uint`)r=new uk(e);else if(t===`vec2`||t===`ivec2`||t===`uvec2`)r=new dk(e);else if(t===`vec3`||t===`ivec3`||t===`uvec3`)r=new fk(e);else if(t===`vec4`||t===`ivec4`||t===`uvec4`)r=new pk(e);else if(t===`color`)r=new mk(e);else if(t===`mat2`)r=new hk(e);else if(t===`mat3`)r=new gk(e);else if(t===`mat4`)r=new _k(e);else throw Error(`THREE.NodeBuilder: Uniform "${t}" not implemented.`);n.cache=r}return r}format(e,t,n){if(t=this.getVectorType(t),n=this.getVectorType(n),t===n||n===null||this.isReference(n))return e;let r=this.getTypeLength(t),i=this.getTypeLength(n);return r===16&&i===9?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:r===9&&i===4?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:r>4||i>4||i===0?e:r===i?`${this.getType(n)}( ${e} )`:r>i?(e=n===`bool`?`all( ${e} )`:`${e}.${`xyz`.slice(0,i)}`,this.format(e,this.getTypeFromLength(i,this.getComponentType(t)),n)):i===4&&r>1?`${this.getType(n)}( ${this.format(e,t,`vec3`)}, 1.0 )`:r===2?`${this.getType(n)}( ${this.format(e,t,`vec2`)}, 0.0 )`:(r===1&&i>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r186 - Node System
`}needsPreviousData(){let e=this.renderer.getMRT();return e&&e.has(`velocity`)||this.object!==null&&Jp(this.object).useVelocity===!0}},Ek=class{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null,this.compute=null}_getMaps(e,t){let n=e.get(t);return n===void 0&&(n={renderId:0,frameId:0},e.set(t,n)),n}updateBeforeNode(e){let t=e.getUpdateBeforeType(this),n=e.updateReference(this);if(t===$p.FRAME){let t=this._getMaps(this.updateBeforeMap,n);if(t.frameId!==this.frameId){let n=t.frameId;t.frameId=this.frameId,e.updateBefore(this)===!1&&(t.frameId=n)}}else if(t===$p.RENDER){let t=this._getMaps(this.updateBeforeMap,n);if(t.renderId!==this.renderId){let n=t.renderId;t.renderId=this.renderId,e.updateBefore(this)===!1&&(t.renderId=n)}}else t===$p.OBJECT&&e.updateBefore(this)}updateAfterNode(e){let t=e.getUpdateAfterType(this),n=e.updateReference(this);if(t===$p.FRAME){let t=this._getMaps(this.updateAfterMap,n);t.frameId!==this.frameId&&e.updateAfter(this)!==!1&&(t.frameId=this.frameId)}else if(t===$p.RENDER){let t=this._getMaps(this.updateAfterMap,n);t.renderId!==this.renderId&&e.updateAfter(this)!==!1&&(t.renderId=this.renderId)}else t===$p.OBJECT&&e.updateAfter(this)}updateNode(e){let t=e.getUpdateType(this),n=e.updateReference(this);if(t===$p.FRAME){let t=this._getMaps(this.updateMap,n);t.frameId!==this.frameId&&e.update(this)!==!1&&(t.frameId=this.frameId)}else if(t===$p.RENDER){let t=this._getMaps(this.updateMap,n);t.renderId!==this.renderId&&e.update(this)!==!1&&(t.renderId=this.renderId)}else t===$p.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}},Dk=class{constructor(e,t,n=null,r=``,i=!1){this.type=e,this.name=t,this.count=n,this.qualifier=r,this.isConst=i}};Dk.isNodeFunctionInput=!0;var Ok=class extends LO{static get type(){return`AmbientLightNode`}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}},kk=class extends LO{static get type(){return`DirectionalLightNode`}constructor(e=null){super(e)}setupDirect(){let e=this.colorNode;return{lightDirection:ZD(this.light),lightColor:e}}},Ak=class extends LO{static get type(){return`HemisphereLightNode`}constructor(e=null){super(e),this.lightPositionNode=JD(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Y(new L).setGroup(J)}update(e){let{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){let{colorNode:t,groundColorNode:n,lightDirectionNode:r}=this,i=G_(n,t,bb.dot(r).mul(.5).add(.5));e.context.irradiance.addAssign(i)}},jk=class extends LO{static get type(){return`SpotLightNode`}constructor(e=null){super(e),this.coneCosNode=Y(0).setGroup(J),this.penumbraCosNode=Y(0).setGroup(J),this.cutoffDistanceNode=Y(0).setGroup(J),this.decayExponentNode=Y(0).setGroup(J),this.colorNode=Y(this.color).setGroup(J)}update(e){super.update(e);let{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){let{coneCosNode:n,penumbraCosNode:r}=this;return Y_(n,r,t)}getLightCoord(e){let t=e.getNodeProperties(this),n=t.projectionUV;return n===void 0&&(n=qD(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){let{colorNode:t,cutoffDistanceNode:n,decayExponentNode:r,light:i}=this,a=this.getLightVector(e),o=a.normalize(),s=o.dot(ZD(i)),c=this.getSpotAttenuation(e,s),l=RO({lightDistance:a.length(),cutoffDistance:n,decayExponent:r}),u=t.mul(c).mul(l),d,f;return i.colorNode?(f=this.getLightCoord(e),d=i.colorNode(f)):i.map&&(f=this.getLightCoord(e),d=uy(i.map,f.xy).onRenderUpdate(()=>i.map)),d&&(u=f.mul(2).sub(1).abs().lessThan(1).all().select(u.mul(d),u)),{lightColor:u,lightDirection:o}}},Mk=class extends jk{static get type(){return`IESSpotLightNode`}constructor(e=null){super(e),this._iesTextureNode=null}getSpotAttenuation(e,t){let n=this.light.iesMap,r=null;if(n&&n.isTexture===!0){let e=t.acos().mul(1/Math.PI);this._iesTextureNode=uy(n,fh(e,0),0),r=this._iesTextureNode.r}else r=super.getSpotAttenuation(e,t);return r}update(e){super.update(e),this._iesTextureNode!==null&&this.light.iesMap&&(this._iesTextureNode.value=this.light.iesMap)}},Nk=class extends LO{static get type(){return`LightProbeNode`}constructor(e=null){super(e);let t=[];for(let e=0;e<9;e++)t.push(new F);this.lightProbe=gy(t)}update(e){let{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){let t=VO(bb,this.lightProbe);e.context.irradiance.addAssign(t)}},Pk=W(([e,t])=>{let n=e.abs().sub(t);return g_(k_(n,0)).add(O_(k_(n.x,n.y),0))}),Fk=class extends jk{static get type(){return`ProjectorLightNode`}update(e){super.update(e);let t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),t.aspect===null){let e=1;t.map!==null&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){let t=G(0),n=this.penumbraCosNode,r=KD(this.light).mul(e.context.positionWorld||cb);return oh(r.w.greaterThan(0),()=>{let e=Pk(r.xyz.div(r.w).xy.sub(fh(.5)),fh(.5)),i=vg(-1,gg(1,u_(n)).sub(1));t.assign(q_(e.mul(-2).mul(i)))}),t}},Ik=new Bn,Lk=new Bn,Rk=null,zk=class extends LO{static get type(){return`RectAreaLightNode`}constructor(e=null){super(e),this.halfHeight=Y(new F).setGroup(J),this.halfWidth=Y(new F).setGroup(J),this.updateType=$p.RENDER}update(e){super.update(e);let{light:t}=this,n=e.camera.matrixWorldInverse;Lk.identity(),Ik.copy(t.matrixWorld),Ik.premultiply(n),Lk.extractRotation(Ik),this.halfWidth.value.set(t.width*.5,0,0),this.halfHeight.value.set(0,t.height*.5,0),this.halfWidth.value.applyMatrix4(Lk),this.halfHeight.value.applyMatrix4(Lk)}setupDirectRectArea(e){let t,n;e.isAvailable(`float32Filterable`)?(t=uy(Rk.LTC_FLOAT_1),n=uy(Rk.LTC_FLOAT_2)):(t=uy(Rk.LTC_HALF_1),n=uy(Rk.LTC_HALF_2));let{colorNode:r,light:i}=this;return{lightColor:r,lightPosition:XD(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){Rk=e}},Bk=class{parseFunction(){M(`Abstract function.`)}},Vk=class{constructor(e,t,n=``,r=``){this.type=e,this.inputs=t,this.name=n,this.precision=r}getCode(){M(`Abstract function.`)}};Vk.isNodeFunction=!0;var Hk=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,Uk=/[a-z_0-9]+/gi,Wk=`#pragma main`,Gk=e=>{e=e.trim();let t=e.indexOf(Wk),n=(t===-1?e:e.slice(t+12)).replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,``),r=n.match(Hk);if(r!==null&&r.length===5){let i=r[4],a=[],o=null;for(;(o=Uk.exec(i))!==null;)a.push(o);let s=[],c=0;for(;c<a.length;){let e=a[c][0]===`const`;e===!0&&c++;let t=a[c][0];t===`in`||t===`out`||t===`inout`?c++:t=``;let n=a[c++][0],r=Number.parseInt(a[c][0]);Number.isNaN(r)===!1?c++:r=null;let i=a[c++][0];s.push(new Dk(n,i,r,t,e))}let l=n.substring(r[0].length),u=r[3]===void 0?``:r[3];return{type:r[2],inputs:s,name:u,precision:r[1]===void 0?``:r[1],inputsCode:i,blockCode:l,headerCode:t===-1?``:e.slice(0,t)}}throw Error(`THREE.FunctionNode: Function is not a GLSL code.`)},Kk=class extends Vk{constructor(e){let{type:t,inputs:n,name:r,precision:i,inputsCode:a,blockCode:o,headerCode:s}=Gk(e);super(t,n,r,i),this.inputsCode=a,this.blockCode=o,this.headerCode=s}getCode(e=this.name){let t,n=this.blockCode;if(n!==``){let{type:r,inputsCode:i,headerCode:a,precision:o}=this,s=`${r} ${e} ( ${i.trim()} )`;o!==``&&(s=`${o} ${s}`),t=a+s+n}else t=``;return t}},qk=class extends Bk{parseFunction(e){return new Kk(e)}},Jk=[],Yk=[],Xk=Y(0,`int`).setGroup(J),Zk=class extends EE{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new Ek,this.nodeBuilderCache=new Map,this.callHashCache=new yE,this.groupsData=new yE,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){let t=e.groupNode;if(t.updateType===$p.OBJECT)return!0;Jk[0]=t,Jk[1]=e;let n=this.groupsData.get(Jk);return n===void 0&&this.groupsData.set(Jk,n={}),Jk[0]=null,Jk[1]=null,n.version!==t.version&&(n.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}_createNodeBuilder(e,t){let n=this.backend.createNodeBuilder(e.object,this.renderer),r=this.renderer.debug.onNodeBuilderCreated;return r!==null&&r(n,e),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){let n=this.get(e),r=n.nodeBuilderState;if(r===void 0){let{nodeBuilderCache:i}=this,a=this.getForRenderCacheKey(e);if(r=i.get(a),r===void 0){let o=async()=>{let n=this._createNodeBuilder(e,e.material);try{t?await n.buildAsync():n.build()}catch(r){n=this._createNodeBuilder(e,new hC),t?await n.buildAsync():n.build(),N(`TSL: `+r)}return n};if(t)return o().then(e=>(r=this._createNodeBuilderState(e),i.set(a,r),r.usedTimes++,n.nodeBuilderState=r,r));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(n){t=this._createNodeBuilder(e,new hC),t.build();let r=n.stackTrace;!r&&n.stack&&(r=new Lp(n.stack)),N(`TSL: `+n,r)}r=this._createNodeBuilderState(t),i.set(a,r)}}r.usedTimes++,n.nodeBuilderState=r}return r}getForRenderAsync(e){let t=this.getForRender(e,!0);return t.then?t:Promise.resolve(t)}getForRenderDeferred(e){let t=this.get(e);if(t.nodeBuilderState!==void 0)return t.nodeBuilderState;let n=this.getForRenderCacheKey(e),r=this.nodeBuilderCache.get(n);return r===void 0?(t.pendingBuild!==!0&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null):(r.usedTimes++,t.nodeBuilderState=r,r)}_processBuildQueue(){this._buildInProgress||this._buildQueue.length===0||(this._buildInProgress=!0,this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()}))}delete(e){if(e.isRenderObject){let 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,t=!1){let n=this.get(e),r=n.nodeBuilderState;if(r===void 0||n.version!==e.version){let i=this.backend.createNodeBuilder(null,this.renderer);i.compute=e;let a=this.renderer.debug.onNodeBuilderCreated;if(a!==null&&a(i,e),t)return i.buildAsync().then(()=>(r=this._createNodeBuilderState(i),n.nodeBuilderState=r,n.version=e.version,r));i.build(),r=this._createNodeBuilderState(i),n.nodeBuilderState=r,n.version=e.version}return r}getForComputeAsync(e){let t=this.getForCompute(e,!0);return t.then?t:Promise.resolve(t)}_createNodeBuilderState(e){return new KO(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.hardwareClipping,e.transforms)}getEnvironmentNode(e){if(this.renderer.lighting.enabled===!1)return null;this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{let 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{let 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){Jk[0]=e,Jk[1]=t;let n=this.renderer.info.calls,r=this.callHashCache.get(Jk)||{};if(r.callId!==n){if(Yk.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),Yk.push(+!!this.renderer.lighting.enabled),this.renderer.lighting.enabled){Yk.push(t.getCacheKey(!0)),Yk.push(+!!this.renderer.shadowMap.enabled),Yk.push(this.renderer.shadowMap.type);let n=this.getEnvironmentNode(e);n&&Yk.push(n.getCacheKey())}let i=this.getFogNode(e);i&&Yk.push(i.getCacheKey()),r.callId=n,r.cacheKey=Bp(Yk),this.callHashCache.set(Jk,r),Yk.length=0}return Jk[0]=null,Jk[1]=null,r.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){let t=this.get(e),n=e.background;if(n){let r=e.backgroundBlurriness===0&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&t.backgroundBlurriness===0;(t.background!==n||r)&&(t.backgroundNode=this.getCacheNode(`background`,n,()=>{if(n.isCubeTexture===!0||n.mapping===303||n.mapping===304||n.mapping===306){if(e.backgroundBlurriness>0||n.mapping===306)return GT(n);{let e;return e=n.isCubeTexture===!0?Pb(n):uy(n),IC(e)}}if(n.isTexture===!0)return uy(n,Sy.flipY()).setUpdateMatrix(!0);n.isColor!==!0&&N(`WebGPUNodes: Unsupported background configuration.`,n)},r),t.background=n,t.backgroundBlurriness=e.backgroundBlurriness)}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,r=!1){let i=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap),a=i.get(t);if(a===void 0||r){if(a===void 0&&t.isTexture===!0){let e=()=>{t.removeEventListener(`dispose`,e);let n=i.get(t);n!==void 0&&(i.delete(t),n.dispose())};t.addEventListener(`dispose`,e)}a=n(),i.set(t,a)}return a}updateFog(e){let t=this.get(e),n=e.fog;n?t.fog!==n&&(t.fogNode=this.getCacheNode(`fog`,n,()=>{if(n.isFogExp2)return UD(Ib(`color`,`color`,n).setGroup(J),HD(Ib(`density`,`float`,n).setGroup(J)));if(n.isFog)return UD(Ib(`color`,`color`,n).setGroup(J),VD(Ib(`near`,`float`,n).setGroup(J),Ib(`far`,`float`,n).setGroup(J)));N(`Renderer: Unsupported fog configuration.`,n)}),t.fog=n):(delete t.fogNode,delete t.fog)}updateEnvironment(e){let t=this.get(e),n=e.environment;n?t.environment!==n&&(t.environmentNode=this.getCacheNode(`environment`,n,()=>{if(n.isCubeTexture===!0)return Pb(n);if(n.isTexture===!0)return uy(n);N(`Nodes: Unsupported environment configuration.`,n)}),t.environment=n):t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,r=null,i=null,a=null){let o=this.nodeFrame;return o.renderer=e,o.scene=t,o.object=n,o.camera=r,o.material=i,o.compute=a,o}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getNodeFrameForCompute(e){return this.getNodeFrame(this.renderer,null,null,null,null,e)}getOutputCacheKey(){let e=this.renderer;return e.toneMapping+`,`+e.currentColorSpace+`,`+e.xr.isPresenting}getOutputNode(e){let t=this.renderer,n;return n=e.isArrayTexture?this.backend.isWebGLBackend?uy(e,Sy).depth(_y(`gl_ViewID_OVR`)).renderOutput(t.toneMapping,t.currentColorSpace):uy(e,Sy).depth(Xk).renderOutput(t.toneMapping,t.currentColorSpace):uy(e,Sy).renderOutput(t.toneMapping,t.currentColorSpace),n}setOutputLayerIndex(e){Xk.value=e}updateBefore(e){let t=e.getNodeBuilderState();for(let n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){let t=e.getNodeBuilderState();for(let n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateBeforeForCompute(e){let t=this.getForCompute(e);for(let n of t.updateBeforeNodes)this.getNodeFrameForCompute(e).updateBeforeNode(n)}updateAfterForCompute(e){let t=this.getForCompute(e);for(let n of t.updateAfterNodes)this.getNodeFrameForCompute(e).updateAfterNode(n)}updateForCompute(e){let t=this.getNodeFrame(),n=this.getForCompute(e);for(let e of n.updateNodes)t.updateNode(e)}updateForRender(e){let t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(let e of n.updateNodes)t.updateNode(e)}needsRefresh(e){let t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new Ek,this.nodeBuilderCache=new Map,this.cacheLib={}}},Qk=new Oi,$k=0,eA=class e{constructor(e=null){this.id=$k++,this.version=0,this.clipIntersection=null,this.cacheKey=``,this.shadowPass=!1,this.viewMatrix=new Bn,this.viewNormalMatrix=new bn,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,e!==null&&(this.viewMatrix=e.viewMatrix,this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass)}projectPlanes(e,t,n){let r=e.length;for(let i=0;i<r;i++){Qk.copy(e[i]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);let r=t[n+i],a=Qk.normal;r.x=-a.x,r.y=-a.y,r.z=-a.z,r.w=Qk.constant}}updateGlobal(e,t){this.shadowPass=e.overrideMaterial!==null&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix.copy(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);let r=t.clippingPlanes,i=r.length,a,o;if(this.clipIntersection?(a=this.intersectionPlanes,o=e.intersectionPlanes.length):(a=this.unionPlanes,o=e.unionPlanes.length),a.length!==o+i){a.length=o+i;for(let e=0;e<i;e++)a[o+e]=new Fn;n=!0}this.projectPlanes(r,a,o),n&&(this.version++,this.cacheKey=`${this.id}:${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(t){if(this.shadowPass&&!t.clipShadows)return this;let n=this.clippingGroupContexts.get(t);return n===void 0&&(n=new e(this),this.clippingGroupContexts.set(t,n)),n.update(this,t),n}get unionClippingCount(){return this.unionPlanes.length}},tA=class{constructor(e,t,n){this.bundleGroup=e,this.camera=t,this.renderContext=n}},nA=[],rA=class{constructor(){this.bundles=new yE}get(e,t,n){let r=this.bundles;nA[0]=e,nA[1]=t,nA[2]=n;let i=r.get(nA);return i===void 0&&(i=new tA(e,t,n),r.set(nA,i)),nA[0]=null,nA[1]=null,nA[2]=null,i}dispose(){this.bundles=new yE}},iA=class{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null,n=this.getMaterialNodeClass(e.type);if(n!==null){t=new n;for(let n in e)t[n]=e[n]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,n){if(n.has(t)){M(`Redefinition of node ${t}`);return}if(typeof e!=`function`)throw Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if(typeof t==`function`||typeof t==`object`)throw Error(`THREE.NodeLibrary: Base class ${t} is not a class.`);n.set(t,e)}addClass(e,t,n){if(n.has(t)){M(`Redefinition of node ${t.name}`);return}if(typeof e!=`function`)throw Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if(typeof t!=`function`)throw Error(`THREE.NodeLibrary: Base class ${t.name} is not a class.`);n.set(t,e)}},aA=new aO,oA=class{constructor(){this.enabled=!0,this._cache=[],this._lightsNodeMap=new WeakMap}createNode(e=[]){return new aO().setLights(e)}getNode(e){if(e.isScene!==!0&&e.isGroup!==!0)return aA;let t=this._lightsNodeMap.get(e);return t===void 0&&(t=this.createNode(),this._lightsNodeMap.set(e,t)),t}beginRender(e){this._cache.push(this.getNode(e).getLights())}finishRender(e){this.getNode(e).setLights(this._cache.pop())}},sA=class extends In{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}},cA=new F,lA=new F,uA=new WeakMap,dA=class extends Ht{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new cs,this._cameraL.viewport=new Fn,this._cameraL.matrixWorldAutoUpdate=!1,this._cameraR=new cs,this._cameraR.viewport=new Fn,this._cameraR.matrixWorldAutoUpdate=!1,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Cs,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding=typeof XRWebGLBinding<`u`,this._supportsWebGPUBinding=globalThis.XRGPUBinding!==void 0,this._createXRLayer=vA.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new P,this._currentCameraSettings=null,this._onSessionEvent=hA.bind(this),this._onSessionEnd=gA.bind(this),this._onInputSourcesChange=_A.bind(this),this._onAnimationFrame=yA.bind(this),this._referenceSpace=null,this._referenceSpaceType=`local-floor`,this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._webgpuBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&`createProjectionLayer`in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){return this._foveation}setFoveation(e){this._foveation=e,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&&M(`XRManager: Cannot change framebuffer scale while presenting.`)}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,this.isPresenting===!0&&M(`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}getBaseLayer(){return this._glProjLayer===null?this._glBaseLayer:this._glProjLayer}getBinding(){return this._glBinding===null&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}foveateBoundTexture(e){if(e===null||e.isPostProcessingRenderTarget!==!0||this.isPresenting!==!0||this._glProjLayer===null)return;let t=this._renderer.backend;if(t===void 0||t.isWebGLBackend!==!0||t.state===null)return;let n=this._renderer.getOutputRenderTarget();if(n===null||n.isXRRenderTarget!==!0)return;let r=this.getBinding();if(r===null||typeof r.foveateBoundTexture!=`function`)return;this._renderer._textures.updateRenderTarget(e);let{textureGPU:i,glTextureType:a}=t.get(e.texture);if(i!==void 0&&a!==void 0&&e._xrFoveationTextureGPU!==i){e._xrFoveationTextureGPU=i,t.state.bindTexture(a,i);try{r.foveateBoundTexture(a,this.getFoveation())}catch(e){Rt(`XRManager: Unable to foveate bound XR post-processing texture. ${e.name}: ${e.message}`)}finally{t.state.unbindTexture()}}}getWebGPUBinding(){return this._webgpuBinding===null&&this._supportsWebGPUBinding&&(this._webgpuBinding=new globalThis.XRGPUBinding(this._session,this._renderer.backend.device)),this._webgpuBinding}_isWebGPUSession(){return this._renderer.backend.isWebGPUBackend===!0&&this._session!==null&&this._session.enabledFeatures.includes(`webgpu`)}_validateWebGPUSession(){if(this._renderer.backend.isWebGPUBackend===!0&&this._session.enabledFeatures.includes(`webgpu`)===!1)throw Error(`THREE.XRManager: WebGPU XR sessions require the "webgpu" session feature. Use VRButtonGPU/XRButton with "webgpu" enabled or use a WebGL backend.`)}async _initWebGPUSession(e){let t=this.getWebGPUBinding(),n=t.createProjectionLayer({colorFormat:t.getPreferredColorFormat()});this._glProjLayer=n,e.updateRenderState({layers:[n]}),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._xrRenderTarget=new In(n.textureWidth,n.textureHeight,{depth:2,minFilter:O,magFilter:O,depthBuffer:!0,multiview:!1,useArrayDepthTexture:!0,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,samples:this._renderer.samples}),this._xrRenderTarget.texture.isArrayTexture=!0,this._useMultiviewIfPossible===!0&&Rt(`THREE.XRManager: WebGPU XR does not support multiview yet. Disabling multiview for this XR session.`),this._useMultiview=!1}_disposeWebGPUSession(){let e=this._renderer,t=e.backend,n=this._xrRenderTarget;if(n!==null&&t.isWebGPUBackend===!0){e._renderContexts&&e._renderContexts.dispose&&e._renderContexts.dispose(),n.dispose();for(let e of n.textures)t.has(e)&&t.destroyTexture(e);t.delete(n)}}_getWebGPUViewData(e){let t=this.getWebGPUBinding(),n={colorTexture:null,viewDescriptors:[],viewports:[]};for(let r=0;r<e.length;r++){let i=t.getViewSubImage(this._glProjLayer,e[r]);n.colorTexture===null&&(n.colorTexture=i.colorTexture),n.viewports.push(i.viewport),i.getViewDescriptor&&n.viewDescriptors.push(i.getViewDescriptor())}return n}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,n,r,i,a,o,s={}){let c=new Qa(e,t),l=new sA(i,a,{format:ge,type:te,depthTexture:new ya(i,a,s.stencil?de:oe,void 0,void 0,void 0,void 0,void 0,void 0,s.stencil?ve:_e),stencilBuffer:s.stencil,samples:s.samples??this._renderer.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),u=new Li({color:16777215,side:0});u.map=l.texture,u.map.offset.y=1,u.map.repeat.y=-1;let d=new Yi(c,u);d.position.copy(n),d.quaternion.copy(r);let f={type:`quad`,width:e,height:t,translation:n,quaternion:r,pixelwidth:i,pixelheight:a,samples:l.samples,plane:d,material:u,rendercall:o,renderTarget:l};if(this._layers.push(f),this._session!==null){f.plane.material=new Li({color:16777215,side:0}),f.plane.material.blending=5,f.plane.material.blendEquation=100,f.plane.material.blendSrc=200,f.plane.material.blendDst=200,f.xrlayer=this._createXRLayer(f);let e=this._session.renderState.layers;e.unshift(f.xrlayer),this._session.updateRenderState({layers:e})}else l.isXRRenderTarget=!1;return d}createCylinderLayer(e,t,n,r,i,a,o,s,c={}){let l=new Ca(e,e,e*t/n,64,64,!0,Math.PI-t/2,t),u=new sA(a,o,{format:ge,type:te,depthTexture:new ya(a,o,c.stencil?de:oe,void 0,void 0,void 0,void 0,void 0,void 0,c.stencil?ve:_e),stencilBuffer:c.stencil,samples:c.samples??this._renderer.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),d=new Li({color:16777215,side:1});d.map=u.texture,d.map.offset.y=1,d.map.repeat.y=-1;let f=new Yi(l,d);f.position.copy(r),f.quaternion.copy(i);let p={type:`cylinder`,radius:e,centralAngle:t,aspectratio:n,translation:r,quaternion:i,pixelwidth:a,pixelheight:o,samples:u.samples,plane:f,material:d,rendercall:s,renderTarget:u};if(this._layers.push(p),this._session!==null){p.plane.material=new Li({color:16777215,side:1}),p.plane.material.blending=5,p.plane.material.blendEquation=100,p.plane.material.blendSrc=200,p.plane.material.blendDst=200,p.xrlayer=this._createXRLayer(p);let e=this._session.renderState.layers;e.unshift(p.xrlayer),this._session.updateRenderState({layers:e})}else u.isXRRenderTarget=!1;return f}renderLayers(){let e=new F,t=new _n,n=this._renderer,r=this.isPresenting;this.isPresenting=!1;let i=new P;n.getSize(i);let a=n.getRenderTarget();for(let r of this._layers){r.renderTarget.isXRRenderTarget=this._session!==null,r.renderTarget._hasExternalTextures=r.renderTarget.isXRRenderTarget;let i=n.contextNode,a;if(r.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){r.xrlayer.transform=new XRRigidTransform(r.plane.getWorldPosition(e),r.plane.getWorldQuaternion(t));let o=this._glBinding.getSubImage(r.xrlayer,this._xrFrame);n.backend.setXRRenderTargetTextures(r.renderTarget,o.colorTexture,void 0),n._setXRLayerSize(r.renderTarget.width,r.renderTarget.height),a=uA.get(i),a===void 0&&(a=ev({getOutput:e=>Xv(e,n.toneMapping,n.outputColorSpace),...i.getFlowContextData()}),uA.set(i,a))}else a=i;n.contextNode=a,n.setRenderTarget(r.renderTarget),r.rendercall(),n.contextNode=i}n.setRenderTarget(a),n._setXRLayerSize(i.x,i.y),this.isPresenting=r}getSession(){return this._session}async setSession(e){let t=this._renderer;t.initialized===!1&&await t.init(),this._gl=t.getContext();let n=this._gl;if(this._session=e,e!==null){if(e.addEventListener(`select`,this._onSessionEvent),e.addEventListener(`selectstart`,this._onSessionEvent),e.addEventListener(`selectend`,this._onSessionEvent),e.addEventListener(`squeeze`,this._onSessionEvent),e.addEventListener(`squeezestart`,this._onSessionEvent),e.addEventListener(`squeezeend`,this._onSessionEvent),e.addEventListener(`end`,this._onSessionEnd),e.addEventListener(`inputsourceschange`,this._onInputSourcesChange),this._validateWebGPUSession(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._isWebGPUSession())await this._initWebGPUSession(e);else if(this._supportsLayers===!0){let r=null,i=null,a=null,o=n.getContextAttributes();await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation()),t.depth&&(a=t.stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT24,r=t.stencil?ve:_e,i=t.stencil?de:oe);let s={colorFormat:n.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature(`OVR_multiview2`)&&(s.textureType=`texture-array`,this._useMultiview=!0),this._glBinding=this.getBinding();let c=this._glBinding.createProjectionLayer(s),l=[c];this._glProjLayer=c,t.setPixelRatio(1),t._setXRLayerSize(c.textureWidth,c.textureHeight);let u=this._useMultiview?2:1,d=new ya(c.textureWidth,c.textureHeight,i,void 0,void 0,void 0,void 0,void 0,void 0,r,u);if(this._xrRenderTarget=new sA(c.textureWidth,c.textureHeight,{format:ge,type:te,colorSpace:t.outputColorSpace,depthTexture:d,stencilBuffer:t.stencil,samples:o.antialias?4:0,resolveDepthBuffer:c.ignoreDepthValues===!1,resolveStencilBuffer:c.ignoreDepthValues===!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:c.ignoreDepthValues===!1,storeMultisampledStencilBuffer:c.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(let e of this._layers)e.plane.material=new Li({color:16777215,side:+(e.type===`cylinder`)}),e.plane.material.blending=5,e.plane.material.blendEquation=100,e.plane.material.blendSrc=200,e.plane.material.blendDst=200,e.xrlayer=this._createXRLayer(e),l.unshift(e.xrlayer);e.updateRenderState({layers:l})}else{await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation());let r={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},i=new XRWebGLLayer(e,n,r);this._glBaseLayer=i,e.updateRenderState({baseLayer:i}),t.setPixelRatio(1),t._setXRLayerSize(i.framebufferWidth,i.framebufferHeight),this._xrRenderTarget=new sA(i.framebufferWidth,i.framebufferHeight,{format:ge,type:te,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:`sessionstart`})}}updateCamera(e){let t=this._session;if(t===null)return;let n=e.near,r=e.far,i=this._cameraXR,a=this._cameraL,o=this._cameraR;i.near=o.near=a.near=n,i.far=o.far=a.far=r,i.isMultiViewCamera=this._useMultiview,(this._currentDepthNear!==i.near||this._currentDepthFar!==i.far)&&(t.updateRenderState({depthNear:i.near,depthFar:i.far}),this._currentDepthNear=i.near,this._currentDepthFar=i.far),i.layers.mask=e.layers.mask|6,a.layers.mask=i.layers.mask&-5,o.layers.mask=i.layers.mask&-3;let s=e.parent,c=i.cameras;pA(i,s);for(let e=0;e<c.length;e++)pA(c[e],s);c.length===2?fA(i,a,o):i.projectionMatrix.copy(a.projectionMatrix),this._currentCameraSettings===null&&e.isPerspectiveCamera&&(this._currentCameraSettings={camera:e,fov:e.fov,zoom:e.zoom}),mA(e,i,s)}_getController(e){let t=this._controllers[e];return t===void 0&&(t=new gr,this._controllers[e]=t),t}};function fA(e,t,n){cA.setFromMatrixPosition(t.matrixWorld),lA.setFromMatrixPosition(n.matrixWorld);let r=cA.distanceTo(lA),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function pA(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function mA(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=Kt*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}function hA(e){let t=this._controllerInputSources.indexOf(e.inputSource);if(t===-1)return;let n=this._controllers[t];if(n!==void 0){let t=this.getReferenceSpace();n.update(e.inputSource,e.frame,t),n.dispatchEvent({type:e.type,data:e.inputSource})}}function gA(){let e=this._session,t=this._renderer;e.removeEventListener(`select`,this._onSessionEvent),e.removeEventListener(`selectstart`,this._onSessionEvent),e.removeEventListener(`selectend`,this._onSessionEvent),e.removeEventListener(`squeeze`,this._onSessionEvent),e.removeEventListener(`squeezestart`,this._onSessionEvent),e.removeEventListener(`squeezeend`,this._onSessionEvent),e.removeEventListener(`end`,this._onSessionEnd),e.removeEventListener(`inputsourceschange`,this._onInputSourcesChange);for(let e=0;e<this._controllers.length;e++){let t=this._controllerInputSources[e];t!==null&&(this._controllerInputSources[e]=null,this._controllers[e].disconnect(t))}if(this._currentDepthNear=null,this._currentDepthFar=null,t._resetXRState(),this._disposeWebGPUSession(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._webgpuBinding=null,this._glBaseLayer=null,this._glProjLayer=null,this._sessionUsesLayers===!0)for(let e of this._layers)e.renderTarget=new sA(e.pixelwidth,e.pixelheight,{format:ge,type:te,depthTexture:new ya(e.pixelwidth,e.pixelheight,e.stencilBuffer?de:oe,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?ve:_e),stencilBuffer:e.stencilBuffer,samples:e.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,e.material.map.offset.y=1,e.material.map.repeat.y=-1,delete e.xrlayer;if(this.isPresenting=!1,this._useMultiview=!1,t._animation.stop(),t._animation.setAnimationLoop(this._currentAnimationLoop),t._animation.setContext(this._currentAnimationContext),t._animation.start(),t.setPixelRatio(this._currentPixelRatio),t.setSize(this._currentSize.width,this._currentSize.height,!1),this._currentCameraSettings!==null){let e=this._currentCameraSettings.camera;e.fov=this._currentCameraSettings.fov,e.zoom=this._currentCameraSettings.zoom,e.updateProjectionMatrix(),this._currentCameraSettings=null}this.dispatchEvent({type:`sessionend`})}function _A(e){let t=this._controllers,n=this._controllerInputSources;for(let r=0;r<e.removed.length;r++){let i=e.removed[r],a=n.indexOf(i);a>=0&&(n[a]=null,t[a].disconnect(i))}for(let r=0;r<e.added.length;r++){let i=e.added[r],a=n.indexOf(i);if(a===-1){for(let e=0;e<t.length;e++)if(e>=n.length){n.push(i),a=e;break}else if(n[e]===null){n[e]=i,a=e;break}if(a===-1)break}let o=t[a];o&&o.connect(i)}}function vA(e){return e.type===`quad`?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function yA(e,t){if(t===void 0)return;let n=this._cameraXR,r=this._renderer,i=r.backend,a=this._glBaseLayer,o=this.getReferenceSpace(),s=t.getViewerPose(o);if(this._xrFrame=t,s!==null){let e=s.views,t=this._isWebGPUSession()?this._getWebGPUViewData(e):null;this._glBaseLayer!==null&&t===null&&i.setXRTarget(a.framebuffer);let o=!1;e.length!==n.cameras.length&&(n.cameras.length=0,o=!0);for(let r=0;r<e.length;r++){let s=e[r],c;if(t!==null)c=t.viewports[r];else if(this._supportsLayers===!0){let e=this._glBinding.getViewSubImage(this._glProjLayer,s);c=e.viewport,r===0&&i.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else c=a.getViewport(s);let l=this._cameras[r];l===void 0&&(l=new cs,l.layers.enable(r),l.viewport=new Fn,l.matrixWorldAutoUpdate=!1,this._cameras[r]=l),l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.quaternion,l.scale),l.projectionMatrix.fromArray(s.projectionMatrix),l.projectionMatrixInverse.copy(l.projectionMatrix).invert(),l.viewport.set(c.x,c.y,c.width,c.height),r===0&&(n.matrix.copy(l.matrix),n.matrix.decompose(n.position,n.quaternion,n.scale)),o===!0&&n.cameras.push(l)}t!==null&&t.colorTexture!==null&&i.setXRRenderTargetTextures(this._xrRenderTarget,t.colorTexture,t.viewDescriptors),r.setOutputRenderTarget(this._xrRenderTarget);let c=r._getFrameBufferTarget();t!==null&&(this._xrRenderTarget.samples=c===null?r.samples:0,this._xrRenderTarget.depthBuffer=c===null),r.xr.foveateBoundTexture(c)}for(let e=0;e<this._controllers.length;e++){let n=this._controllerInputSources[e],r=this._controllers[e];n!==null&&r!==void 0&&r.update(n,t,o)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:`planesdetected`,data:t}),this._xrFrame=null}var bA=class extends Ht{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new Fn(0,0,this._width,this._height),this._scissor=new Fn(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new _a,this.depthTexture=new ya}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){let t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,n,r){let i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,n,r)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,r,i=0,a=1){let o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,n,r),o.minDepth=i,o.maxDepth=a}_dispatchResize(){this.dispatchEvent({type:`resize`})}dispose(){this.dispatchEvent({type:`dispose`})}},xA=new Sr,SA=new P,CA=new Fn,wA=new ra,TA=new aa,EA=new Bn,DA=new Fn,OA={0:1,1:0,2:2},kA=class{constructor(e,t={}){this.isRenderer=!0;let{logarithmicDepthBuffer:n=!1,reversedDepthBuffer:r=!1,alpha:i=!0,depth:a=!0,stencil:o=!1,antialias:s=!1,samples:c=0,getFallback:l=null,outputBufferType:u=ce,multiview:d=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=n,this.reversedDepthBuffer=r,this.outputColorSpace=pt,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=a,this.stencil=o,this.info=new PE,this.contextNode=ev(),this.library=new iA,this.lighting=new oA,this._samples=c||(s===!0?4:0),this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new bA(e.getDomElement()),this._canvasTarget.addEventListener(`resize`,this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new Qv,this._inspector.setRenderer(this),this._getFallback=l,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quadCache=new Map,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTargets=new Map;let f=this.alpha===!0?0:1;this._clearColor=new nD(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.onError=this._onError,this._outputBufferType=u,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this._isPreCompiling=!1,this._currentSourceMaterial=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:1},this.xr=new dA(this,d),this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onNodeBuilderCreated:null,onShaderError:null,getShaderAsync:async(e,t,n)=>{await this.compileAsync(n,t,e);let r=this.needsFrameBufferTarget&&this._renderTarget===null?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,i=this._renderLists.get(e,t,this.lighting),a=this._renderContexts.get(r,this._mrt),o=e.overrideMaterial||n.material,{fragmentShader:s,vertexShader:c}=this._objects.get(n,o,e,t,i.lightsNode,a,a.clippingContext).getNodeBuilderState();return{fragmentShader:s,vertexShader:c}}}}async init(){return this._initPromise===null&&(this._initPromise=new Promise(async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(e){if(this._getFallback!==null)try{this.backend=n=this._getFallback(e),await n.init(this)}catch(e){t(e);return}else{t(e);return}}this._nodes=new Zk(this,n),this._animation=new vE(this,this._nodes,this.info),this._attributes=new kE(n,this.info),this._background=new UO(this,this._nodes),this._geometries=new NE(this._attributes,this.info),this._textures=new tD(this,n,this.info),this._pipelines=new BE(n,this._nodes,this.info),this._bindings=new VE(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new TE(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new YE,this._bundles=new rA,this._renderContexts=new $E(this),this._animation.start(),this._initialized=!0,e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null,r=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init(),this.shadowMap.type===2&&(M(`WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.`),this.shadowMap.type=1);let i=this._nodes.nodeFrame,a=i.renderId,o=this._currentRenderContext,s=this._currentRenderObjectFunction,c=this._handleObjectFunction,l=this._compilationPromises;n===null&&(n=e);let u=e.isScene===!0?e:n.isScene===!0?n:xA,d=this.needsFrameBufferTarget&&this._renderTarget===null,f=this._renderTarget||this._outputRenderTarget,p=this.xr.isPresenting===!0&&this.isOutputTarget,m=d?this._getFrameBufferTarget():f,h=this._renderContexts.get(m,this._mrt),g=this._activeMipmapLevel,_=[];this._currentRenderContext=h,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=_,i.renderId++,i.update(),h.depth=this.depth,h.stencil=this.stencil,h.clippingContext||=new eA,h.clippingContext.updateGlobal(u,t),e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t=this._updateCamera(t,p),u.onBeforeRender(this,e,t,m),EA.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),t.isArrayCamera?TA.setFromArrayCamera(t):wA.setFromProjectionMatrix(EA,t.coordinateSystem,t.reversedDepth);let v=this._renderLists.get(u,t,this.lighting);if(v.begin(),this._projectObject(e,t,0,v,h.clippingContext),n!==e&&n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&v.pushLight(e)}),v.finish(),m!==null){this._textures.updateRenderTarget(m,g);let e=this._textures.get(m);h.textures=e.textures,h.depthTexture=e.depthTexture}else h.textures=null,h.depthTexture=null;n===e?this._background.update(u,v,h):this._background.update(n,v,h);let y=v.opaque,b=v.transparent,x=v.transparentDoublePass,S=v.lightsNode;this.opaque===!0&&y.length>0&&this._renderObjects(y,t,u,S),this.transparent===!0&&b.length>0&&this._renderTransparents(b,x,t,u,S),i.renderId=a,this._currentRenderContext=o,this._currentRenderObjectFunction=s,this._handleObjectFunction=c,this._compilationPromises=l;let C=_.length,w=0;for(let e of _){let t=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);t.drawRange=e.object.geometry.drawRange,t.group=e.group,await this._nodes.getForRenderAsync(t),this._isPreCompiling=!0,this._nodes.updateBefore(t),this._geometries.updateForRender(t),this._nodes.updateForRender(t),this._bindings.updateForRender(t),this._isPreCompiling=!1;let n=[];this._pipelines.getForRender(t,n),n.length>0&&await Promise.all(n),this._isPreCompiling=!0,this._nodes.updateAfter(t),this._isPreCompiling=!1,w++,r!==null&&r(new ProgressEvent(`progress`,{lengthComputable:!0,loaded:w,total:C})),await zt()}}async compileComputeAsync(e,t=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init();let n=Array.isArray(e)?e:[e];if(n.length===0||n.some(e=>e==null||e.isComputeNode!==!0))throw Error(`THREE.Renderer: .compileComputeAsync() expects a ComputeNode.`);let r=n.length,i=0,a=this._pipelines,o=this._bindings,s=this._nodes;for(let e of n){if(a.has(e)===!1){let t=()=>{e.removeEventListener(`dispose`,t),a.delete(e),o.deleteForCompute(e),s.delete(e)};e.addEventListener(`dispose`,t);let n=e.onInitFunction;n!==null&&n.call(e,{renderer:this})}await s.getForComputeAsync(e),s.updateBeforeForCompute(e),s.updateForCompute(e),o.updateForCompute(e);let n=o.getForCompute(e),c=[];a.getForCompute(e,n,c),await Promise.all(c),s.updateAfterForCompute(e),i++,t!==null&&t(new ProgressEvent(`progress`,{lengthComputable:!0,loaded:i,total:r})),i<r&&await zt()}}async renderAsync(e,t){Rt(`Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.`),await this.init(),this.render(e,t)}async waitForGPU(){N(`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){let t=this.contextNode.value;e===!0?(t.modelViewMatrix=nb,t.modelNormalViewMatrix=rb):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){let e=this.contextNode.value;return e.modelViewMatrix===nb&&e.modelNormalViewMatrix===rb}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Rt(`Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".`),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),N(t),this._isDeviceLost=!0}_onError(e){let t=`WebGPURenderer: Uncaptured ${e.api} ${e.type}`;e.message&&(t+=`: ${e.message}`),N(t)}_bundleNeedsUpdate(e,t){return t.bundleGPU===void 0||e.version!==t.version}_renderBundle(e,t,n){let{bundleGroup:r,camera:i,renderList:a}=e,o=this._currentRenderContext,s=this._bundles.get(r,i,o),c=this.backend.get(s);if(this._bundleNeedsUpdate(r,c)){this.backend.beginBundle(o),this._currentRenderBundle=s;let{transparentDoublePass:e,transparent:l,opaque:u}=a;this.opaque===!0&&u.length>0&&this._renderObjects(u,i,t,n),this.transparent===!0&&l.length>0&&this._renderTransparents(l,e,i,t,n),this._currentRenderBundle=null,this.backend.finishBundle(o,s),c.version=r.version}else{let{renderObjects:e}=c;for(let t=0,n=e.length;t<n;t++){let n=e[t],r=this._nodes.needsRefresh(n);r===At.FULL?(this._nodes.updateBefore(n),this._geometries.updateForRender(n),this._nodes.updateForRender(n),this._bindings.updateForRender(n),this._nodes.updateAfter(n)):r===At.SHARED&&(this._nodes.updateBefore(n),this._nodes.updateForRender(n),this._bindings.updateSharedForRender(n),this._nodes.updateAfter(n))}}this.backend.addBundle(o,s)}render(e,t){if(this._initialized===!1)throw Error(`THREE.Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.`);this._renderScene(e,t)}get initialized(){return this._initialized}_renderOutputLayers(e,t){if(this.backend.isWebGLBackend===!0&&t.multiview===!0||t.texture.isArrayTexture!==!0||t.texture.image.depth<=1){this._renderScene(e,e.camera,!1);return}let n=this._activeCubeFace;try{for(let n=0;n<t.texture.image.depth;n++)this._nodes.setOutputLayerIndex(n),this._activeCubeFace=n,this._renderScene(e,e.camera,!1)}finally{this._nodes.setOutputLayerIndex(0),this._activeCubeFace=n}}_getFrameBufferTarget(){if(this.needsFrameBufferTarget===!1)return null;let{width:e,height:t}=this.getDrawingBufferSize(SA),{depth:n,stencil:r}=this,i=this._outputRenderTarget||this._canvasTarget,a=this._frameBufferTargets.get(i);if(a===void 0){a=new In(e,t,{depthBuffer:n,stencilBuffer:r,type:this._outputBufferType,format:ge,colorSpace:I.workingColorSpace,generateMipmaps:!1,minFilter:O,magFilter:O,samples:this.samples}),a.isPostProcessingRenderTarget=!0;let o=()=>{i.removeEventListener(`dispose`,o),a.dispose(),this._frameBufferTargets.delete(i)};i.addEventListener(`dispose`,o),this._frameBufferTargets.set(i,a)}let o=this.getOutputRenderTarget();a.depthBuffer=n,a.stencilBuffer=r,o===null?a.setSize(e,t,1):a.setSize(o.width,o.height,o.depth);let s=this._outputRenderTarget?this._outputRenderTarget.viewport:i._viewport,c=this._outputRenderTarget?this._outputRenderTarget.scissor:i._scissor,l=this._outputRenderTarget?1:i._pixelRatio,u=this._outputRenderTarget?this._outputRenderTarget.scissorTest:i._scissorTest;return a.viewport.copy(s),a.scissor.copy(c),a.viewport.multiplyScalar(l),a.scissor.multiplyScalar(l),a.scissorTest=u,a.multiview=o!==null&&o.multiview,a.useArrayDepthTexture=o!==null&&o.useArrayDepthTexture,a.resolveDepthBuffer=o===null||o.resolveDepthBuffer,a.resolveStencilBuffer=o===null||o.resolveStencilBuffer,a.storeMultisampledColorBuffer=o===null||o.storeMultisampledColorBuffer,a.storeMultisampledDepthBuffer=o===null||o.storeMultisampledDepthBuffer,a.storeMultisampledStencilBuffer=o===null||o.storeMultisampledStencilBuffer,a._autoAllocateDepthBuffer=o!==null&&o._autoAllocateDepthBuffer,a}_renderScene(e,t,n=!0){if(this._isDeviceLost===!0)return;this.shadowMap.type===2&&(M(`WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.`),this.shadowMap.type=1);let r=n?this._getFrameBufferTarget():null,i=this._nodes.nodeFrame,a=i.renderId,o=this._currentRenderContext,s=this._currentRenderObjectFunction,c=this._handleObjectFunction;this.lighting.beginRender(e),this._callDepth++;let l=e.isScene===!0?e:xA,u=this._renderTarget||this._outputRenderTarget,d=this.xr.isPresenting===!0&&this.isOutputTarget,f=this._activeCubeFace,p=this._activeMipmapLevel,m;if(r===null?m=u:(m=r,this.setRenderTarget(m)),m!==null&&m.depthBuffer===!0){let e=this._textures.get(m);e.depthInitialized!==!0&&((this.autoClear===!1||this.autoClear===!0&&this.autoClearDepth===!1)&&this.clearDepth(),e.depthInitialized=!0)}let h=this._renderContexts.get(m,this._mrt,this._callDepth);this._currentRenderContext=h,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,i.renderId=this.info.calls,this.backend.updateTimeStampUID(h),this.inspector.beginRender(this.backend.getTimestampUID(h),e,t,m),e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t=this._updateCamera(t,d);let g=this._canvasTarget,_=g._viewport,v=g._scissor,y=g._pixelRatio;m!==null&&(_=m.viewport,v=m.scissor,y=1),this.getDrawingBufferSize(SA),CA.set(0,0,SA.width,SA.height);let b=_.minDepth===void 0?0:_.minDepth,x=_.maxDepth===void 0?1:_.maxDepth;h.viewportValue.copy(_).multiplyScalar(y).floor(),h.viewportValue.width>>=p,h.viewportValue.height>>=p,h.viewportValue.minDepth=b,h.viewportValue.maxDepth=x,h.viewport=h.viewportValue.equals(CA)===!1,h.scissorValue.copy(v).multiplyScalar(y).floor(),h.scissor=g._scissorTest&&h.scissorValue.equals(CA)===!1,h.scissorValue.width>>=p,h.scissorValue.height>>=p,h.clippingContext||=new eA,h.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,m),EA.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),t.isArrayCamera?TA.setFromArrayCamera(t):wA.setFromProjectionMatrix(EA,t.coordinateSystem,t.reversedDepth),this._renderLists.update(i.frameId);let S=this._renderLists.get(e,t,this.lighting);if(S.begin(),this._projectObject(e,t,0,S,h.clippingContext),S.finish(),this.sortObjects===!0&&S.sort(this._opaqueSort,this._transparentSort),m!==null){this._textures.updateRenderTarget(m,p);let e=this._textures.get(m);h.textures=e.textures,h.depthTexture=e.depthTexture,h.width=e.width,h.height=e.height,h.renderTarget=m,h.depth=m.depthBuffer,h.stencil=m.stencilBuffer}else h.textures=null,h.depthTexture=null,h.width=SA.width,h.height=SA.height,h.depth=this.depth,h.stencil=this.stencil;h.width>>=p,h.height>>=p,h.activeCubeFace=f,h.activeMipmapLevel=p,h.occlusionQueryCount=S.occlusionQueryCount,h.fullscreenPass=e.isQuadMesh===!0,h.scissorValue.max(DA.set(0,0,0,0)),h.scissorValue.x+h.scissorValue.width>h.width&&(h.scissorValue.width=Math.max(h.width-h.scissorValue.x,0)),h.scissorValue.y+h.scissorValue.height>h.height&&(h.scissorValue.height=Math.max(h.height-h.scissorValue.y,0)),this._background.update(l,S,h),h.camera=t,this.backend.beginRender(h);let{bundles:C,lightsNode:w,transparentDoublePass:T,transparent:E,opaque:D}=S;return C.length>0&&this._renderBundles(C,l,w),this.opaque===!0&&D.length>0&&this._renderObjects(D,t,l,w),this.transparent===!0&&E.length>0&&this._renderTransparents(E,T,t,l,w),this.backend.finishRender(h),i.renderId=a,this._currentRenderContext=o,this._currentRenderObjectFunction=s,this._handleObjectFunction=c,this.lighting.finishRender(e),this._callDepth--,r!==null&&(this.setRenderTarget(u,f,p),this._renderOutput(m)),l.onAfterRender(this,e,t,m),this.inspector.finishRender(this.backend.getTimestampUID(h)),h}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){let t=this._nodes.getOutputCacheKey(),n=this._quadCache.get(e.texture),r;if(n===void 0){r=new pD(new hC),r.name=`Output Color Transform`,r.material.name=`outputColorTransform`,r.material.fragmentNode=this._nodes.getOutputNode(e.texture),n={quad:r,cacheKey:t},this._quadCache.set(e.texture,n);let i=()=>{r.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener(`dispose`,i)};e.texture.addEventListener(`dispose`,i)}else r=n.quad,n.cacheKey!==t&&(r.material.fragmentNode=this._nodes.getOutputNode(e.texture),r.material.needsUpdate=!0,n.cacheKey=t);let i=this.autoClear,a=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderOutputLayers(r,e),this.autoClear=i,this.xr.enabled=a}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,r=-1){if(t!==null&&t.isReadbackBuffer&&this.info.memoryMap.has(t)===!1){this.info.createReadbackBuffer(t);let e=()=>{t.removeEventListener(`dispose`,e),this.info.destroyReadbackBuffer(t)};t.addEventListener(`dispose`,e)}if(n%4!=0||r>0&&r%4!=0)throw Error(`THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.`);return await this.backend.getArrayBufferAsync(e,t,n,r)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,n)}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,n)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,n,r){this._canvasTarget.setScissor(e,t,n,r)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}resetState(){if(this._initialized===!1)throw Error(`THREE.Renderer: .resetState() called before the backend is initialized. Use "await renderer.init();" before using this method.`);this.backend.resetState()}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,n,r,i=0,a=1){this._canvasTarget.setViewport(e,t,n,r,i,a)}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){let t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(this._initialized===!1)throw Error(`THREE.Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before using this method.`);let r=this._renderTarget||this._getFrameBufferTarget(),i=null;if(r!==null){this._textures.updateRenderTarget(r);let e=this._textures.get(r);i=this._renderContexts.get(r,null,-1),i.textures=e.textures,i.depthTexture=e.depthTexture,i.width=e.width,i.height=e.height,i.renderTarget=r,i.depth=r.depthBuffer,i.stencil=r.stencilBuffer;let t=this.backend.getClearColor();i.clearColorValue.r=t.r,i.clearColorValue.g=t.g,i.clearColorValue.b=t.b,i.clearColorValue.a=t.a,i.clearDepthValue=this.getClearDepth(),i.clearStencilValue=this.getClearStencil(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel(),r.depthBuffer===!0&&(e.depthInitialized=!0)}this.backend.clear(e,t,n,i),r!==null&&this._renderTarget===null&&this._renderOutput(r)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){Rt(`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(){Rt(`Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.`),this.clear(!0,!1,!1)}async clearDepthAsync(){Rt(`Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.`),this.clear(!1,!0,!1)}async clearStencilAsync(){Rt(`Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.`),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){let e=this.currentToneMapping!==0,t=this.currentColorSpace!==I.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return this._renderTarget===null?(this.needsFrameBufferTarget||this._currentRenderContext?.fullscreenPass===!0)&&(e=0):e=this._renderTarget.samples,e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:I.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||this._renderTarget===null}async dispose(){if(this._initialized===!0){this.info.dispose(),this._inspector.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(let e of this._frameBufferTargets.keys())e.dispose();await this.backend.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(let 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 M(`Renderer: ".compute()" called before the backend is initialized. Try using ".computeAsync()" instead.`),this.computeAsync(e,t);let n=this._nodes.nodeFrame,r=n.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);let i=this.backend,a=this._pipelines,o=this._bindings,s=this._nodes,c=Array.isArray(e)?e:[e];if(c[0]===void 0||c[0].isComputeNode!==!0)throw Error(`THREE.Renderer: .compute() expects a ComputeNode.`);i.beginCompute(e);for(let n of c){if(a.has(n)===!1){let e=()=>{n.removeEventListener(`dispose`,e),a.delete(n),o.deleteForCompute(n),s.delete(n)};n.addEventListener(`dispose`,e);let t=n.onInitFunction;t!==null&&t.call(n,{renderer:this})}s.updateBeforeForCompute(n),s.updateForCompute(n),o.updateForCompute(n);let r=o.getForCompute(n),c=a.getForCompute(n,r);i.compute(e,n,r,c,t),s.updateAfterForCompute(n)}i.finishCompute(e),n.renderId=r,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 Rt(`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 Error(`THREE.Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before using this method.`);return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Rt(`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 Error(`THREE.Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before using this method.`);this._textures.updateTexture(e)}initRenderTarget(e){if(this._initialized===!1)throw Error(`THREE.Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before using this method.`);this._textures.updateRenderTarget(e);let 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=DA.set(t.x,t.y,e.image.width,e.image.height).floor();else if(t.isVector4)t=DA.copy(t).floor();else{N(`Renderer.copyFramebufferToTexture: Invalid rectangle.`);return}}else t=DA.set(0,0,e.image.width,e.image.height);let n=this._currentRenderContext,r;n===null?(r=this._renderTarget||this._getFrameBufferTarget(),r!==null&&(this._textures.updateRenderTarget(r),n=this._textures.get(r))):r=n.renderTarget,this._textures.updateTexture(e,{renderTarget:r}),this.backend.copyFramebufferToTexture(e,n,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,n=null,r=null,i=0,a=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,r,i,a),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,n,r,i,a=0,o=0){return this.backend.copyTextureToBuffer(e.textures[a],t,n,r,i,o)}_projectObject(e,t,n,r,i){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(i=i.getGroupContext(e));else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)r.pushLight(e);else if(e.isSprite){let a=t.isArrayCamera?TA:wA;if(!e.frustumCulled||e.intersectsFrustum(a)){this.sortObjects===!0&&DA.setFromMatrixPosition(e.matrixWorld).applyMatrix4(EA);let{geometry:t,material:a}=e;a.visible&&r.push(e,t,a,n,DA.z,null,i)}}else if(e.isLineLoop)N(`Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.`);else if(e.isMesh||e.isLine||e.isPoints){let a=t.isArrayCamera?TA:wA;if(!e.frustumCulled||e.intersectsFrustum(a)){let{geometry:t,material:a}=e;if(this.sortObjects===!0&&(t.boundingSphere===null&&t.computeBoundingSphere(),DA.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(EA)),Array.isArray(a)){let o=t.groups;for(let s=0,c=o.length;s<c;s++){let c=o[s],l=a[c.materialIndex];l&&l.visible&&r.push(e,t,l,n,DA.z,c,i)}}else a.visible&&r.push(e,t,a,n,DA.z,null,i)}}}if(e.isBundleGroup===!0&&this.backend.beginBundle!==void 0){let a=r;r=this._renderLists.get(e,t,this.lighting);let o=this._bundles.get(e,t,this._currentRenderContext),s=this.backend.get(o);if(this._bundleNeedsUpdate(e,s)){r.begin(),s.renderObjects===void 0?s.renderObjects=[]:s.renderObjects.length=0;let a=e.children;for(let e=0,o=a.length;e<o;e++)this._projectObject(a[e],t,n,r,i);r.finish()}a.pushBundle({bundleGroup:e,camera:t,renderList:r});return}let a=e.children;for(let e=0,o=a.length;e<o;e++)this._projectObject(a[e],t,n,r,i)}_renderBundles(e,t,n){for(let r of e)this._renderBundle(r,t,n)}_renderTransparents(e,t,n,r,i){if(t.length>0){for(let{material:e}of t)e.side=1;this._renderObjects(t,n,r,i,`backSide`);for(let{material:e}of t)e.side=0;this._renderObjects(e,n,r,i);for(let{material:e}of t)e.side=2}else this._renderObjects(e,n,r,i)}_renderObjects(e,t,n,r,i=null){for(let a=0,o=e.length;a<o;a++){let{object:o,geometry:s,material:c,group:l,clippingContext:u}=e[a];this._currentRenderObjectFunction(o,n,t,s,c,l,r,u,i)}}_getShadowNodes(e){let t=e.version,n=this._cacheShadowNodes.get(e);if(n===void 0||n.version!==t){let r=e.map&&e.map.isTexture,i=e.colorNode&&e.colorNode.isNode,a=e.castShadowNode&&e.castShadowNode.isNode,o=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode,s=null,c=null,l=null;if(r||i||a||o){let t,n;if(a?(t=e.castShadowNode.rgb,n=e.castShadowNode.a,this.shadowMap.transmitted!==!0&&Rt("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(t=K(0),n=G(1)),r&&(n=n.mul(Ib(`map`,`texture`,e).a)),i&&(n=n.mul(e.colorNode.a)),c=q(t,n),o){let t=e.maskShadowNode||e.maskNode;c=W(([e])=>(t.not().discard(),e))(c)}}e.depthNode&&e.depthNode.isNode&&(l=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?s=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(s=e.positionNode),n={version:t,colorNode:c,depthNode:l,positionNode:s},this._cacheShadowNodes.set(e,n)}return n}_updateCamera(e,t){let n=this.xr;if(n.isPresenting===!1||t===!1){let t=!1;if(this.reversedDepthBuffer===!0&&e.reversedDepth!==!0){if(e._reversedDepth=!0,e.isArrayCamera)for(let t of e.cameras)t._reversedDepth=!0;t=!0}let n=this.coordinateSystem;if(e.coordinateSystem!==n){if(e.coordinateSystem=n,e.isArrayCamera)for(let t of e.cameras)t.coordinateSystem=n;t=!0}if(t===!0&&(e.updateProjectionMatrix(),e.isArrayCamera))for(let t of e.cameras)t.updateProjectionMatrix()}return e.parent===null&&e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t===!0&&n.enabled===!0&&n.isPresenting===!0&&(n.cameraAutoUpdate===!0&&n.updateCamera(e),e=n.getCamera()),e}renderObject(e,t,n,r,i,a,o,s=null,c=null){let l=!1,u,d,f,p,m,h,g,_=this._currentSourceMaterial;if(e.onBeforeRender(this,t,n,r,i,a),i.allowOverride===!0&&t.overrideMaterial!==null){this._currentSourceMaterial=i;let e=t.overrideMaterial;if(l=!0,u=e.isNodeMaterial?e.colorNode:null,d=e.isNodeMaterial?e.depthNode:null,f=e.isNodeMaterial?e.positionNode:null,p=t.overrideMaterial.side,m=e.displacementMap,h=e.displacementScale,g=e.displacementBias,i.positionNode&&i.positionNode.isNode&&(e.positionNode=i.positionNode),e.alphaTest=i.alphaTest,e.alphaMap=i.alphaMap,e.displacementMap=i.displacementMap,e.displacementScale=i.displacementScale,e.displacementBias=i.displacementBias,e.transparent=i.transparent||i.transmission>0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode,e.isShadowPassMaterial){let{colorNode:t,depthNode:n,positionNode:r}=this._getShadowNodes(i);e.side=this.shadowMap.type===3?i.shadowSide===null?i.side:i.shadowSide:i.shadowSide===null?OA[i.side]:i.shadowSide,t!==null&&(e.colorNode=t),n!==null&&(e.depthNode=n),r!==null&&(e.positionNode=r)}i=e}i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,this._handleObjectFunction(e,i,t,n,o,a,s,`backSide`),i.side=0,this._handleObjectFunction(e,i,t,n,o,a,s,c),i.side=2):this._handleObjectFunction(e,i,t,n,o,a,s,c),l&&(t.overrideMaterial.colorNode=u,t.overrideMaterial.depthNode=d,t.overrideMaterial.positionNode=f,t.overrideMaterial.side=p,t.overrideMaterial.displacementMap=m,t.overrideMaterial.displacementScale=h,t.overrideMaterial.displacementBias=g),this._currentSourceMaterial=_,e.onAfterRender(this,t,n,r,i,a)}hasCompatibility(e){if(this._initialized===!1)throw Error(`THREE.Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.`);return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,n,r,i,a,o,s){let c=this._objects.get(e,t,n,r,i,this._currentRenderContext,o,s);c.drawRange=e.geometry.drawRange,c.group=a,this._currentRenderBundle!==null&&(this.backend.get(this._currentRenderBundle).renderObjects.push(c),c.bundle=this._currentRenderBundle.bundleGroup);let l=this._nodes.needsRefresh(c);l===At.FULL?(this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c)):l===At.SHARED&&(this._nodes.updateBefore(c),this._nodes.updateForRender(c),this._bindings.updateSharedForRender(c)),this._pipelines.updateForRender(c),this._pipelines.isReady(c)&&(this.backend.draw(c,this.info),l!==At.NONE&&this._nodes.updateAfter(c))}_createObjectPipeline(e,t,n,r,i,a,o,s){if(this._compilationPromises!==null){this._compilationPromises.push({object:e,material:t,scene:n,camera:r,lightsNode:i,group:a,clippingContext:o,passId:s,renderContext:this._currentRenderContext});return}let c=this._objects.get(e,t,n,r,i,this._currentRenderContext,o,s);c.drawRange=e.geometry.drawRange,c.group=a,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}},AA=class{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 jA(e){return e+(OE-e%OE)%OE}var MA=class extends AA{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 jA(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}release(){this._buffer=null}},NA=class extends MA{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}},PA=0,FA=class extends NA{constructor(e,t){let n=e&&e.name?e.name:PA++;super(`UniformBuffer_`+n,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get byteLength(){return jA(this.buffer.byteLength)}get buffer(){return this.nodeUniform.value}},IA=class extends NA{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map,this._addedIndices=new Set}addUniformUpdateRange(e){let t=e.index;if(this._addedIndices.has(t))return;let n=this._updateRangeCache.get(t);n===void 0&&(n={start:0,count:0},this._updateRangeCache.set(t,n)),n.start=e.offset,n.count=e.itemSize,this._addedIndices.add(t),this.updateRanges.push(n)}clearUpdateRanges(){this._addedIndices.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){let 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){let t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){let e=this.bytesPerElement,t=0;for(let n=0,r=this.uniforms.length;n<r;n++){let r=this.uniforms[n],i=r.boundary,a=r.itemSize*e,o=t%OE,s=o%i,c=o+s;t+=s,c!==0&&OE-c<a&&(t+=OE-c),r.offset=t/e,r.index=n,t+=a}return Math.ceil(t/OE)*OE}update(){let e=!1;for(let t of this.uniforms)this.updateByType(t)===!0&&(e=!0);return e}release(){super.release(),this._values=null}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);N(`WebGPUUniformsGroup: Unsupported uniform type.`,e)}updateNumber(e){let t=!1,n=this.values,r=e.getValue(),i=e.offset,a=e.getType();if(n[i]!==r){let o=this._getBufferForType(a);o[i]=n[i]=r,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1,n=this.values,r=e.getValue(),i=e.offset,a=e.getType();if(n[i+0]!==r.x||n[i+1]!==r.y){let o=this._getBufferForType(a);o[i+0]=n[i+0]=r.x,o[i+1]=n[i+1]=r.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1,n=this.values,r=e.getValue(),i=e.offset,a=e.getType();if(n[i+0]!==r.x||n[i+1]!==r.y||n[i+2]!==r.z){let o=this._getBufferForType(a);o[i+0]=n[i+0]=r.x,o[i+1]=n[i+1]=r.y,o[i+2]=n[i+2]=r.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1,n=this.values,r=e.getValue(),i=e.offset,a=e.getType();if(n[i+0]!==r.x||n[i+1]!==r.y||n[i+2]!==r.z||n[i+3]!==r.w){let o=this._getBufferForType(a);o[i+0]=n[i+0]=r.x,o[i+1]=n[i+1]=r.y,o[i+2]=n[i+2]=r.z,o[i+3]=n[i+3]=r.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1,n=this.values,r=e.getValue(),i=e.offset;if(n[i+0]!==r.r||n[i+1]!==r.g||n[i+2]!==r.b){let a=this.buffer;a[i+0]=n[i+0]=r.r,a[i+1]=n[i+1]=r.g,a[i+2]=n[i+2]=r.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1,n=this.values,r=e.getValue().elements,i=e.offset;if(n[i+0]!==r[0]||n[i+1]!==r[1]||n[i+2]!==r[2]||n[i+4]!==r[3]||n[i+5]!==r[4]||n[i+6]!==r[5]||n[i+8]!==r[6]||n[i+9]!==r[7]||n[i+10]!==r[8]){let a=this.buffer;a[i+0]=n[i+0]=r[0],a[i+1]=n[i+1]=r[1],a[i+2]=n[i+2]=r[2],a[i+4]=n[i+4]=r[3],a[i+5]=n[i+5]=r[4],a[i+6]=n[i+6]=r[5],a[i+8]=n[i+8]=r[6],a[i+9]=n[i+9]=r[7],a[i+10]=n[i+10]=r[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1,n=this.values,r=e.getValue().elements,i=e.offset;return RA(n,r,i)===!1&&(this.buffer.set(r,i),LA(n,r,i),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 LA(e,t,n){for(let r=0,i=t.length;r<i;r++)e[n+r]=t[r]}function RA(e,t,n){for(let r=0,i=t.length;r<i;r++)if(e[n+r]!==t[r])return!1;return!0}var zA=0,BA=class extends IA{constructor(e,t){super(e),this.id=zA++,this.groupNode=t,this.isNodeUniformsGroup=!0}},VA=class extends AA{constructor(e,t){super(e),this._texture=t,this.version=-1,this.generation=null,this.samplerKey=``,this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture=e,this.reset())}get texture(){return this._texture}update(){let{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}reset(){this.generation=null,this.version=-1}release(){this._texture=null}},HA=0,UA=class extends VA{constructor(e,t){super(e,t),this.id=HA++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}},WA=class extends UA{constructor(e,t,n,r=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=r}update(){let{textureNode:e}=this;return this.texture===e.value?super.update():(this.texture=e.value,!0)}},GA=class extends WA{constructor(e,t,n,r=null){super(e,t,n,r),this.isSampledCubeTexture=!0}},KA=class extends WA{constructor(e,t,n,r=null){super(e,t,n,r),this.isSampledTexture3D=!0}},qA={textureGather:new RD(`
vec4 tsl_textureGather( const int comp, sampler2D map, vec2 coord, ivec2 offset, bool flipY ) {
if ( flipY ) offset.y = - offset.y;
vec2 size = vec2( textureSize( map, 0 ) );
vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
vec4 ret = vec4(
textureLod( map, ij.xw, 0.0 )[ comp ],
textureLod( map, ij.zw, 0.0 )[ comp ],
textureLod( map, ij.zy, 0.0 )[ comp ],
textureLod( map, ij.xy, 0.0 )[ comp ]
);
return flipY ? ret.wzyx : ret;
}
`),textureGatherArray:new RD(`
vec4 tsl_textureGather_array( const int comp, sampler2DArray map, vec3 coord, ivec2 offset, bool flipY ) {
if ( flipY ) offset.y = - offset.y;
vec2 size = vec2( textureSize( map, 0 ).xy );
vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
vec4 ret = vec4(
textureLod( map, vec3( ij.xw, coord.z ), 0.0 )[ comp ],
textureLod( map, vec3( ij.zw, coord.z ), 0.0 )[ comp ],
textureLod( map, vec3( ij.zy, coord.z ), 0.0 )[ comp ],
textureLod( map, vec3( ij.xy, coord.z ), 0.0 )[ comp ]
);
return flipY ? ret.wzyx : ret;
}
`),textureGatherCompare:new RD(`
vec4 tsl_textureGatherCompare( sampler2DShadow map, vec2 coord, ivec2 offset, float ref, bool flipY ) {
if ( flipY ) offset.y = - offset.y;
vec2 size = vec2( textureSize( map, 0 ) );
vec2 st = floor( coord * size + vec2( offset ) - 0.5 );
vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
vec4 ret = vec4(
textureLod( map, vec3( ij.xw, ref ), 0.0 ),
textureLod( map, vec3( ij.zw, ref ), 0.0 ),
textureLod( map, vec3( ij.zy, ref ), 0.0 ),
textureLod( map, vec3( ij.xy, ref ), 0.0 )
);
return flipY ? ret.wzyx : ret;
}
`),textureGatherCompareArray:new RD(`
vec4 tsl_textureGatherCompare_array( sampler2DArrayShadow map, vec3 coord, ivec2 offset, float ref, bool flipY ) {
if ( flipY ) offset.y = - offset.y;
vec2 size = vec2( textureSize( map, 0 ).xy );
vec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );
vec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;
vec4 ret = vec4(
texture( map, vec4( ij.xw, coord.z, ref ) ),
texture( map, vec4( ij.zw, coord.z, ref ) ),
texture( map, vec4( ij.zy, coord.z, ref ) ),
texture( map, vec4( ij.xy, coord.z, ref ) )
);
return flipY ? ret.wzyx : ret;
}
`),floatpack_snorm_4x8:new RD(`uint tsl_packSnorm4x8( vec4 v ) { uvec4 u = uvec4( ivec4( round( clamp( v, -1.0, 1.0 ) * 127.0 ) ) & 0xff ); return u.x | u.y << 8 | u.z << 16 | u.w << 24; }`),floatpack_unorm_4x8:new RD(`uint tsl_packUnorm4x8( vec4 v ) { uvec4 u = uvec4( round( clamp( v, 0.0, 1.0 ) * 255.0 ) ); return u.x | u.y << 8 | u.z << 16 | u.w << 24; }`),floatunpack_snorm_4x8:new RD(`vec4 tsl_unpackSnorm4x8( uint x ) { return max( vec4( ivec4( x << 24, x << 16, x << 8, x ) >> 24 ) / 127.0, -1.0 ); }`),floatunpack_unorm_4x8:new RD(`vec4 tsl_unpackUnorm4x8( uint x ) { return vec4( uvec4( x, x >> 8, x >> 16, x >> 24 ) & 0xffu ) / 255.0; }`)},JA={equals:`equal`,bitcast_float_int:`floatBitsToInt`,bitcast_int_float:`intBitsToFloat`,bitcast_uint_float:`uintBitsToFloat`,bitcast_float_uint:`floatBitsToUint`,floatpack_snorm_2x16:`packSnorm2x16`,floatpack_unorm_2x16:`packUnorm2x16`,floatpack_float16_2x16:`packHalf2x16`,floatpack_snorm_4x8:`tsl_packSnorm4x8`,floatpack_unorm_4x8:`tsl_packUnorm4x8`,floatunpack_snorm_2x16:`unpackSnorm2x16`,floatunpack_unorm_2x16:`unpackUnorm2x16`,floatunpack_float16_2x16:`unpackHalf2x16`,floatunpack_snorm_4x8:`tsl_unpackSnorm4x8`,floatunpack_unorm_4x8:`tsl_unpackUnorm4x8`},YA={low:`lowp`,medium:`mediump`,high:`highp`},XA={swizzleAssign:!0,storageBuffer:!1},ZA={perspective:`smooth`,linear:`noperspective`},QA={centroid:`centroid`},$A=`
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;
`,ej=new Set(`const.uniform.buffer.shared.attribute.varying.coherent.volatile.restrict.readonly.writeonly.atomic_uint.layout.centroid.flat.smooth.noperspective.patch.sample.invariant.precise.break.continue.do.for.while.switch.case.default.if.else.subroutine.in.out.inout.int.void.bool.true.false.float.double.discard.return.vec2.vec3.vec4.ivec2.ivec3.ivec4.bvec2.bvec3.bvec4.uint.uvec2.uvec3.uvec4.dvec2.dvec3.dvec4.mat2.mat3.mat4.mat2x2.mat2x3.mat2x4.mat3x2.mat3x3.mat3x4.mat4x2.mat4x3.mat4x4.dmat2.dmat3.dmat4.dmat2x2.dmat2x3.dmat2x4.dmat3x2.dmat3x3.dmat3x4.dmat4x2.dmat4x3.dmat4x4.lowp.mediump.highp.precision.sampler2D.sampler3D.samplerCube.sampler2DShadow.samplerCubeShadow.sampler2DArray.sampler2DArrayShadow.isampler2D.isampler3D.isamplerCube.isampler2DArray.usampler2D.usampler3D.usamplerCube.usampler2DArray.struct.common.partition.active.asm.class.union.enum.typedef.template.this.resource.goto.inline.noinline.public.static.extern.external.interface.long.short.half.fixed.unsigned.superp.input.output.hvec2.hvec3.hvec4.fvec2.fvec3.fvec4.sampler3DRect.filter.sizeof.cast.namespace.using.main`.split(`.`)),tj=class extends Tk{constructor(e,t){super(e,t,new qk),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==``}_include(e){let t=qA[e];return t.build(this),this.addInclude(t),t}getMethod(e){return qA[e]!==void 0&&this._include(e),JA[e]||e}getBitcastMethod(e,t){let n=this.getComponentType(t),r=this.getComponentType(e);return n!==`float`&&r!==`float`&&this.getTypeLength(t)===this.getTypeLength(e)?this.getType(e):this.getMethod(`bitcast_${n}_${r}`)}getFloatPackingMethod(e,t=`2x16`){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t=`2x16`){return this.getMethod(`floatunpack_${e}_${t}`)}getTernary(e,t,n){return`${e} ? ${t} : ${n}`}getOutputStructName(){return``}buildFunctionCode(e){let t=e.layout,n=this.flowShaderNode(e),r=[];for(let e of t.inputs)r.push(this.getType(e.type)+` `+e.name);return`${this.getType(t.type)} ${t.name}( ${r.join(`, `)} ) {
${n.vars}
${n.code}
return ${n.result};
}`}setupPBO(e){let t=e.value;if(t.pbo===void 0){let e=t.array,n=t.count*t.itemSize,{itemSize:r}=t,i=t.array.constructor.name.toLowerCase().includes(`int`),a=i?be:ye;r===2?a=i?Se:xe:r===3?a=i?Ce:he:r===4&&(a=i?we:ge);let o={Float32Array:se,Uint8Array:te,Uint16Array:ie,Uint32Array:oe,Int8Array:ne,Int16Array:re,Int32Array:ae,Uint8ClampedArray:te},s=2**Math.ceil(Math.log2(Math.sqrt(n/r))),c=Math.ceil(n/r/s);s*c*r<n&&c++;let l=s*c*r,u=new e.constructor(l);u.set(e,0),t.array=u;let d=new Qi(t.array,s,c,a,o[t.array.constructor.name]||1015);d.needsUpdate=!0,d.isPBOTexture=!0;let f=new cy(d,null,null);f.setPrecision(`high`),t.pboNode=f,t.pbo=f.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)}isReservedKeyword(e){return ej.has(e)}generatePBO(e){let{node:t,indexNode:n}=e,r=t.value;if(this.renderer.backend.has(r)){let e=this.renderer.backend.get(r);e.pbo=r.pbo}let i=this.getUniformFromNode(r.pboNode,`texture`,this.shaderStage,this.context.nodeName),a=this.getPropertyName(i);this.increaseUsage(n);let o=n.build(this,`uint`),s=this.getDataFromNode(e),c=s.propertyName;if(c===void 0){let n=this.getVarFromNode(e);c=this.getPropertyName(n);let i=this.getDataFromNode(t),l=i.propertySizeName;l===void 0&&(l=c+`Size`,this.getVarFromNode(t,l,`uint`),this.addLineFlowCode(`${l} = uint( textureSize( ${a}, 0 ).x )`,e),i.propertySizeName=l);let{itemSize:u}=r,d=`.`+im.join(``).slice(0,u),f=`ivec2(${o} % ${l}, ${o} / ${l})`,p=this.generateTextureLoad(null,a,f,`0`,null,null),m=`vec4`;r.pbo.type===1014?m=`uvec4`:r.pbo.type===1013&&(m=`ivec4`),this.addLineFlowCode(`${c} = ${m}(${p})${d}`,e),s.propertyName=c}return c}generateTextureLoad(e,t,n,r,i,a){r===null&&(r=`0`);let o;return o=i?a?`texelFetchOffset( ${t}, ivec3( ${n}, ${i} ), int( ${r} ), ${a} )`:`texelFetch( ${t}, ivec3( ${n}, ${i} ), int( ${r} ) )`:a?`texelFetchOffset( ${t}, ${n}, int( ${r} ), ${a} )`:`texelFetch( ${t}, ${n}, int( ${r} ) )`,e!==null&&e.isDepthTexture&&(o+=`.x`),o}generateTexture(e,t,n,r,i){return r&&(n=`vec3( ${n}, ${r} )`),e.isDepthTexture?i?`textureOffset( ${t}, ${n}, ${i} ).x`:`texture( ${t}, ${n} ).x`:i?`textureOffset( ${t}, ${n}, ${i} )`:`texture( ${t}, ${n} )`}generateTextureSize(e,t,n){return`textureSize( ${t}, ${n} )`}generateTextureLevel(e,t,n,r,i,a){return i&&(n=`vec3( ${n}, ${i} )`),a?`textureLodOffset( ${t}, ${n}, ${r}, ${a} )`:`textureLod( ${t}, ${n}, ${r} )`}generateTextureBias(e,t,n,r,i,a){return i&&(n=`vec3( ${n}, ${i} )`),a?`textureOffset( ${t}, ${n}, ${a}, ${r} )`:`texture( ${t}, ${n}, ${r} )`}generateTextureGrad(e,t,n,r,i,a){return i&&(n=`vec3( ${n}, ${i} )`),a?`textureGradOffset( ${t}, ${n}, ${r[0]}, ${r[1]}, ${a} )`:`textureGrad( ${t}, ${n}, ${r[0]}, ${r[1]} )`}generateTextureCompare(e,t,n,r,i,a,o=this.shaderStage){if(o===`fragment`)return e.isCubeTexture?`texture( ${t}, vec4( ${n}, ${r} ) )`:i?a?`textureOffset( ${t}, vec4( ${n}, ${i}, ${r} ), ${a} )`:`texture( ${t}, vec4( ${n}, ${i}, ${r} ) )`:a?`textureOffset( ${t}, vec3( ${n}, ${r} ), ${a} )`:`texture( ${t}, vec3( ${n}, ${r} ) )`;N(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}generateTextureGather(e,t,n,r,i,a,o){return e.isDepthTexture&&(r=`0`),a===null&&(a=`ivec2( 0 )`),o===null&&(o=`false`),i?(this._include(`textureGatherArray`),`tsl_textureGather_array( ${r}, ${t}, vec3( ${n}, ${i} ), ${a}, ${o} )`):(this._include(`textureGather`),`tsl_textureGather( ${r}, ${t}, ${n}, ${a}, ${o} )`)}generateTextureGatherCompare(e,t,n,r,i,a,o){return a===null&&(a=`ivec2( 0 )`),o===null&&(o=`false`),i?(this._include(`textureGatherCompareArray`),`tsl_textureGatherCompare_array( ${t}, vec3( ${n}, ${i} ), ${a}, ${r}, ${o} )`):(this._include(`textureGatherCompare`),`tsl_textureGatherCompare( ${t}, ${n}, ${a}, ${r}, ${o} )`)}getUniforms(e){let t=this.uniforms[e],n=[],r={};for(let e of t){let t=null,i=!1;if(e.type===`texture`||e.type===`texture3D`){let n=e.node,r=n.value,i=this.getComponentTypeFromTexture(r),a=i===`float`?``:i.charAt(0);t=e.type===`texture3D`&&r.isArrayTexture===!1?`${a}sampler3D ${e.name};`:r.compareFunction&&n.isSampleCompare()?r.isArrayTexture===!0?`sampler2DArrayShadow ${e.name};`:`sampler2DShadow ${e.name};`:r.isArrayTexture===!0||r.isDataArrayTexture===!0||r.isCompressedArrayTexture===!0?`${a}sampler2DArray ${e.name};`:`${a}sampler2D ${e.name};`}else if(e.type===`cubeTexture`)t=`samplerCube ${e.name};`;else if(e.type===`cubeDepthTexture`)t=e.node.value.compareFunction?`samplerCubeShadow ${e.name};`:`samplerCube ${e.name};`;else if(e.type===`buffer`){let n=e.node,r=this.getType(n.bufferType),i=n.bufferCount,a=i>0?i:``;t=`${n.name} {\n\t${r} ${e.name}[${a}];\n};\n`}else{let t=e.groupNode.name;if(r[t]===void 0){let e=this.uniformGroups[t];if(e!==void 0){let n=[];for(let t of e.uniforms){let e=t.getType(),r=this.getVectorType(e),i=t.nodeUniform.node.precision,a=`${r} ${t.name};`;i!==null&&(a=YA[i]+` `+a),n.push(` `+a)}r[t]=n}}i=!0}if(!i){let r=e.node.precision;r!==null&&(t=YA[r]+` `+t),t=`uniform `+t,n.push(t)}}let i=``;for(let e in r){let t=r[e];i+=this._getGLSLUniformStruct(e,t.join(`
`))+`
`}return i+=n.join(`
`),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==1013){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);let r=n.array;r instanceof Uint32Array||r instanceof Int32Array||(t=t.slice(1))}return t}getAttributes(e){let t=``;if(e===`vertex`||e===`compute`){let e=this.getAttributesArray(),n=0;for(let r of e)t+=`layout( location = ${n++} ) in ${r.type} ${r.name};\n`}return t}getStructMembers(e){let t=[];for(let n of e.members)t.push(`\t${n.type} ${n.name};`);return t.join(`
`)}getStructs(e){let t=[],n=this.structs[e],r=[];for(let e of n)if(e.output)for(let t of e.members)r.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let n=`struct `+e.name+` {
`;n+=this.getStructMembers(e),n+=`
};
`,t.push(n)}return e===`fragment`&&r.length===0&&r.push(`layout( location = 0 ) out ${this.getOutputType()} fragColor;`),`
`+r.join(`
`)+`
`+t.join(`
`)}getVaryings(e){let t=``,n=this.varyings;if(e===`vertex`||e===`compute`)for(let r of n){e===`compute`&&(r.needsInterpolation=!0);let n=this.getType(r.type);if(r.needsInterpolation){if(r.interpolationType){let e=ZA[r.interpolationType]||r.interpolationType,i=QA[r.interpolationSampling]||``;t+=`${e} ${i} out ${n} ${r.name};\n`}else{let e=n.includes(`int`)||n.includes(`uv`)||n.includes(`iv`)?`flat `:``;t+=`${e}out ${n} ${r.name};\n`}}else t+=`${n} ${r.name};\n`}else if(e===`fragment`){for(let e of n)if(e.needsInterpolation){let n=this.getType(e.type);if(e.interpolationType){let r=ZA[e.interpolationType]||e.interpolationType,i=QA[e.interpolationSampling]||``;t+=`${r} ${i} in ${n} ${e.name};\n`}else{let r=n.includes(`int`)||n.includes(`uv`)||n.includes(`iv`)?`flat `:``;t+=`${r}in ${n} ${e.name};\n`}}}for(let n of this.builtins[e])t+=`${n};\n`;return t}getVertexIndex(){return`uint( gl_VertexID )`}getInstanceIndex(){return`uint( gl_InstanceID )`}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.compute.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){N(`GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node`)}getInvocationSubgroupIndex(){N(`GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node`)}getSubgroupIndex(){N(`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){let r=this.extensions[n]||(this.extensions[n]=new Map);r.has(e)===!1&&r.set(e,{name:e,behavior:t})}getExtensions(e){let t=[];if(e===`vertex`){let t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has(`WEBGL_multi_draw`)&&this.enableExtension(`GL_ANGLE_multi_draw`,`require`,e)}let n=this.extensions[e];if(n!==void 0)for(let{name:e,behavior:r}of n.values())t.push(`#extension ${e} : ${r}`);return t.join(`
`)}getClipDistance(){return`gl_ClipDistance`}isAvailable(e){let t=XA[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`}if(n!==void 0){let e=this.renderer.backend.extensions;e.has(n)&&(e.get(n),t=!0)}XA[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(){let e=this.transforms,t=``;for(let n=0;n<e.length;n++){let r=e[n],i=this.getPropertyName(r.attributeNode);i&&(t+=`${r.varyingName} = ${i};\n\t`)}return t}_getGLSLUniformStruct(e,t){return`
layout( std140 ) uniform ${e} {
${t}
};`}_getGLSLVertexCode(e){return`#version 300 es
${this.getSignature()}
// extensions
${e.extensions}
// precision
${$A}
// structs
${e.structs}
// 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
${$A}
// structs
${e.structs}
// uniforms
${e.uniforms}
// varyings
${e.varyings}
// vars
${e.vars}
// codes
${e.codes}
void main() {
// flow
${e.flow}
}
`}buildCode(){let e=this.material===null?{compute:{}}:{fragment:{},vertex:{}};this.sortBindingGroups();for(let t in e){let n=`// code
`;n+=this.flowCode[t];let r=this.flowNodes[t],i=r[r.length-1];for(let e of r){let r=this.getFlowData(e),a=e.name;a&&(n.length>0&&(n+=`
`),n+=`\t// flow -> ${a}\n\t`),n+=`${r.code}\n\t`,e===i&&t!==`compute`&&(n+=`// result
`,t===`vertex`?(n+=`gl_Position = `,n+=`${this.format(r.result,i.getNodeType(this),`vec4`)};`):t===`fragment`&&(e.outputNode.isOutputStructNode||(n+=`fragColor = `,n+=`${this.format(r.result,i.getNodeType(this),this.getOutputType())};`)))}let a=e[t];if(a.extensions=this.getExtensions(t),a.uniforms=this.getUniforms(t),a.attributes=this.getAttributes(t),a.varyings=this.getVaryings(t),a.vars=this.getVars(t,!0),a.structs=this.getStructs(t),a.codes=this.getCodes(t),a.transforms=this.getTransforms(t),a.flow=n,t===`vertex`){let e=this.renderer.backend.extensions;this.object.isBatchedMesh&&e.has(`WEBGL_multi_draw`)===!1&&(a.uniforms+=`
uniform uint nodeUniformDrawId;
`)}}this.material===null?this.computeShader=this._getGLSLVertexCode(e.compute):(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment))}getUniformFromNode(e,t,n,r=null){let i=super.getUniformFromNode(e,t,n,r),a=this.getDataFromNode(e,n,this.globalCache),o=a.uniformGPU;if(o===void 0){let r=e.groupNode,s=r.name,c=this.getBindGroupArray(s,n);if(t===`texture`)o=new WA(i.name,i.node,r),c.push(o);else if(t===`cubeTexture`||t===`cubeDepthTexture`)o=new GA(i.name,i.node,r),c.push(o);else if(t===`texture3D`)o=new KA(i.name,i.node,r),c.push(o);else if(t===`buffer`){i.name=`buffer${e.id}`;let t=this.getSharedDataFromNode(e),n=t.buffer;n===void 0&&(e.name=`NodeBuffer_${e.id}`,n=new FA(e,r),n.name=e.name,t.buffer=n),c.push(n),o=n}else{let e=this.uniformGroups[s];e===void 0?(e=new BA(s,r),this.uniformGroups[s]=e,c.push(e)):c.indexOf(e)===-1&&c.push(e),o=this.getNodeUniform(i,t);let n=o.name;e.uniforms.some(e=>e.name===n)||e.addUniform(o)}a.uniformGPU=o}return i}},nj=null,rj=null,ij=class{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Ot.RENDER]:null,[Ot.COMPUTE]:null},this.trackTimestamp=e.trackTimestamp===!0}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}setXRTarget(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}createUniformBuffer(){}destroyUniformBuffer(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){let t=this.get(e),n=this.renderer.info.frame,r,i=e.id;Array.isArray(e)?(i=e.map(e=>e.id).join(`,`),r=`c:`+this.renderer.info.compute.frameCalls):r=e.isComputeNode===!0?`c:`+this.renderer.info.compute.frameCalls:`r:`+this.renderer.info.render.frameCalls,t.timestampUID=r+`:`+i+`:f`+n}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){let t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){let t=e.startsWith(`c:`)?Ot.COMPUTE:Ot.RENDER;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}get hasTimestamp(){return!1}hasTimestampQuery(e){return this._getQueryPool(e).hasTimestampQuery(e)}isOccluded(){}async resolveTimestampsAsync(e=`render`){if(!this.trackTimestamp){Rt(`WebGPURenderer: Timestamp tracking is disabled.`);return}let t=this.timestampQueryPool[e];if(!t)return;let n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getDrawingBufferSize(){return nj||=new P,this.renderer.getDrawingBufferSize(nj)}setScissorTest(){}resetState(){}getClearColor(){let e=this.renderer;return rj||=new nD,e.getClearColor(rj),rj.getRGB(rj),rj}getDomElement(){let e=this.domElement;return e===null&&(e=this.parameters.canvas===void 0?Pt():this.parameters.canvas,`setAttribute`in e&&e.setAttribute(`data-engine`,`three.js r186 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(){}async dispose(){for(let e of Object.values(this.timestampQueryPool))e!==null&&await e.dispose()}},aj=0,oj=class{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}},sj=class{constructor(e){this.backend=e}createAttribute(e,t){let n=this.backend,{gl:r}=n,i=e.array,a=e.usage||r.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,s=n.get(o),c=s.bufferGPU;c===void 0&&(c=this._createBuffer(r,t,i,a),s.bufferGPU=c,s.bufferType=t,s.version=o.version);let l;if(i instanceof Float32Array)l=r.FLOAT;else if(typeof Float16Array<`u`&&i instanceof Float16Array)l=r.HALF_FLOAT;else if(i instanceof Uint16Array)l=e.isFloat16BufferAttribute?r.HALF_FLOAT:r.UNSIGNED_SHORT;else if(i instanceof Int16Array)l=r.SHORT;else if(i instanceof Uint32Array)l=r.UNSIGNED_INT;else if(i instanceof Int32Array)l=r.INT;else if(i instanceof Int8Array)l=r.BYTE;else if(i instanceof Uint8Array)l=r.UNSIGNED_BYTE;else if(i instanceof Uint8ClampedArray)l=r.UNSIGNED_BYTE;else throw Error(`THREE.WebGLBackend: Unsupported buffer data format: `+i);let u={bufferGPU:c,bufferType:t,type:l,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===r.INT||l===r.UNSIGNED_INT||e.gpuType===1013,id:aj++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){let e=this._createBuffer(r,t,i,a);u=new oj(u,e)}n.set(e,u)}updateAttribute(e){let t=this.backend,{gl:n}=t,r=e.array,i=e.isInterleavedBufferAttribute?e.data:e,a=t.get(i),o=a.bufferType,s=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(o,a.bufferGPU),s.length===0)n.bufferSubData(o,0,r);else{for(let e=0,t=s.length;e<t;e++){let t=s[e];n.bufferSubData(o,t.start*r.BYTES_PER_ELEMENT,r,t.start,t.count)}i.clearUpdateRanges()}n.bindBuffer(o,null),a.version=i.version}destroyAttribute(e){let t=this.backend,{gl:n}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);let r=t.get(e);n.deleteBuffer(r.bufferGPU),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,r=-1){let i=this.backend,{gl:a}=i,o=e.isInterleavedBufferAttribute?e.data:e,s=i.get(o),{bufferGPU:c}=s,l=r===-1?s.byteLength-n:r,u;if(t===null)u=new Uint8Array(new ArrayBuffer(l));else if(t.isReadbackBuffer){if(t._mapped===!0)throw Error(`THREE.WebGPURenderer: ReadbackBuffer must be released before being used again.`);let e=()=>{t.buffer=null,t._mapped=!1,t.removeEventListener(`release`,e),t.removeEventListener(`dispose`,e)};t.addEventListener(`release`,e),t.addEventListener(`dispose`,e),u=new Uint8Array(new ArrayBuffer(l)),t.buffer=u.buffer}else u=new Uint8Array(t);return a.bindBuffer(a.COPY_READ_BUFFER,c),a.getBufferSubData(a.COPY_READ_BUFFER,n,u),a.bindBuffer(a.COPY_READ_BUFFER,null),a.bindBuffer(a.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:u.buffer}_createBuffer(e,t,n,r){let i=e.createBuffer();return e.bindBuffer(t,i),e.bufferData(t,n,r),e.bindBuffer(t,null),i}},cj,lj,uj=class{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendEquation=null,this.currentBlendEquationAlpha=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlendColor=new L(0,0,0),this.currentBlendAlpha=0,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){let e=this.gl;cj={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT,103:e.MIN,104:e.MAX},lj={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};let t=e.getParameter(e.SCISSOR_BOX),n=e.getParameter(e.VIEWPORT);this.currentScissor=new Fn().fromArray(t),this.currentViewport=new Fn().fromArray(n),this._tempVec4=new Fn}enable(e){let{enabled:t}=this;t[e]!==!0&&(this.gl.enable(e),t[e]=!0)}disable(e){let{enabled:t}=this;t[e]!==!1&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){let{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){let{gl:t}=this;e===0?this.disable(t.CULL_FACE):(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===1?t.cullFace(t.BACK):e===2?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))),this.currentCullFace=e}setLineWidth(e){let{currentLineWidth:t,gl:n}=this;e!==t&&(n.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,n){let r=this.gl,i=this.backend.drawBuffersIndexedExt;if(!i){Rt(`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 a=0;a<e.length;a++){let o=e[a],s=null;if(t!==null){let e=t.getBlendMode(o.name);e.blending===6?s=n:e.blending!==0&&(s=e)}else s=n;s===null?i.blendFuncSeparateiOES(a,r.ONE,r.ZERO,r.ONE,r.ZERO):this._setMRTBlendingIndex(a,s)}}_setMRTBlendingIndex(e,t){let{gl:n}=this,r=this.backend.drawBuffersIndexedExt,i=t.blending,a=t.blendSrc,o=t.blendDst,s=t.blendEquation,c=t.premultipliedAlpha;if(i===5){let n=t.blendSrcAlpha===null?a:t.blendSrcAlpha,i=t.blendDstAlpha===null?o:t.blendDstAlpha,c=t.blendEquationAlpha===null?s:t.blendEquationAlpha;r.blendEquationSeparateiOES(e,cj[s],cj[c]),r.blendFuncSeparateiOES(e,lj[a],lj[o],lj[n],lj[i])}else if(r.blendEquationSeparateiOES(e,n.FUNC_ADD,n.FUNC_ADD),c)switch(i){case 1:r.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case 2:r.blendFuncSeparateiOES(e,n.ONE,n.ONE,n.ONE,n.ONE);break;case 3:r.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case 4:r.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:r.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)}else switch(i){case 1:r.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case 2:r.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE,n.ONE,n.ONE);break;case 3:r.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case 4:r.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:r.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)}}setBlending(e,t,n,r,i,a,o,s,c,l){let{gl:u}=this;if(e===0){this.currentBlendingEnabled===!0&&(this.disable(u.BLEND),this.currentBlendingEnabled=!1);return}if(this.currentBlendingEnabled===!1&&(this.enable(u.BLEND),this.currentBlendingEnabled=!0),e!==5){if(e!==this.currentBlending||l!==this.currentPremultipledAlpha){if((this.currentBlendEquation!==100||this.currentBlendEquationAlpha!==100)&&(u.blendEquation(u.FUNC_ADD),this.currentBlendEquation=100,this.currentBlendEquationAlpha=100),l)switch(e){case 1:u.blendFuncSeparate(u.ONE,u.ONE_MINUS_SRC_ALPHA,u.ONE,u.ONE_MINUS_SRC_ALPHA);break;case 2:u.blendFunc(u.ONE,u.ONE);break;case 3:u.blendFuncSeparate(u.ZERO,u.ONE_MINUS_SRC_COLOR,u.ZERO,u.ONE);break;case 4:u.blendFuncSeparate(u.DST_COLOR,u.ONE_MINUS_SRC_ALPHA,u.ZERO,u.ONE);break;default:N(`WebGLState: Invalid blending: `,e)}else switch(e){case 1:u.blendFuncSeparate(u.SRC_ALPHA,u.ONE_MINUS_SRC_ALPHA,u.ONE,u.ONE_MINUS_SRC_ALPHA);break;case 2:u.blendFuncSeparate(u.SRC_ALPHA,u.ONE,u.ONE,u.ONE);break;case 3:N(`WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:N(`WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:N(`WebGLState: Invalid blending: `,e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=l}return}i||=t,a||=n,o||=r,(t!==this.currentBlendEquation||i!==this.currentBlendEquationAlpha)&&(u.blendEquationSeparate(cj[t],cj[i]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=i),(n!==this.currentBlendSrc||r!==this.currentBlendDst||a!==this.currentBlendSrcAlpha||o!==this.currentBlendDstAlpha)&&(u.blendFuncSeparate(lj[n],lj[r],lj[a],lj[o]),this.currentBlendSrc=n,this.currentBlendDst=r,this.currentBlendSrcAlpha=a,this.currentBlendDstAlpha=o),(s.equals(this.currentBlendColor)===!1||c!==this.currentBlendAlpha)&&(u.blendColor(s.r,s.g,s.b,c),this.currentBlendColor.copy(s),this.currentBlendAlpha=c),this.currentBlending=e,this.currentPremultipledAlpha=!1}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){let{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setReversedDepth(e){if(this.currentDepthReversed!==e){let 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=Vt[e]),this.currentDepthFunc!==e){let{gl:t}=this;switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}this.currentDepthFunc=e}}scissor(e,t,n,r){let i=this._tempVec4.set(e,t,n,r);if(this.currentScissor.equals(i)===!1){let{gl:e}=this;e.scissor(i.x,i.y,i.z,i.w),this.currentScissor.copy(i)}}viewport(e,t,n,r){let i=this._tempVec4.set(e,t,n,r);if(this.currentViewport.equals(i)===!1){let{gl:e}=this;e.viewport(i.x,i.y,i.z,i.w),this.currentViewport.copy(i)}}setScissorTest(e){let t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){let{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){let{gl:r}=this;e.side===2?this.disable(r.CULL_FACE):this.enable(r.CULL_FACE);let i=e.side===1;t&&(i=!i),this.setFlipSided(i),e.blending===1&&e.transparent===!1?this.setBlending(0):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.blendColor,e.blendAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);let a=e.stencilWrite;if(this.setStencilTest(a),a&&(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(r.SAMPLE_ALPHA_TO_COVERAGE):this.disable(r.SAMPLE_ALPHA_TO_COVERAGE),this.currentClippingPlanes!==n){let e=12288;for(let t=0;t<8;t++)t<n?this.enable(e+t):this.disable(e+t);this.currentClippingPlanes=n}}setPolygonOffset(e,t,n){let{gl:r}=this;e?(this.enable(r.POLYGON_OFFSET_FILL),(this.currentPolygonOffsetFactor!==t||this.currentPolygonOffsetUnits!==n)&&(r.polygonOffset(t,n),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=n)):this.disable(r.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){let 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(){let e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){let{gl:n,currentBoundFramebuffers:r}=this;return r[e]!==t&&(n.bindFramebuffer(e,t),r[e]=t,e===n.DRAW_FRAMEBUFFER&&(r[n.FRAMEBUFFER]=t),e===n.FRAMEBUFFER&&(r[n.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){let{gl:n}=this,r=[],i=!1;if(e.textures!==null){r=this.currentDrawbuffers.get(t),r===void 0&&(r=[],this.currentDrawbuffers.set(t,r));let a=e.textures;if(r.length!==a.length||r[0]!==n.COLOR_ATTACHMENT0){for(let e=0,t=a.length;e<t;e++)r[e]=n.COLOR_ATTACHMENT0+e;r.length=a.length,i=!0}}else r[0]!==n.BACK&&(r[0]=n.BACK,i=!0);i&&n.drawBuffers(r)}activeTexture(e){let{gl:t,currentTextureSlot:n,maxTextures:r}=this;e===void 0&&(e=t.TEXTURE0+r-1),n!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,n){let{gl:r,currentTextureSlot:i,currentBoundTextures:a,maxTextures:o}=this;n===void 0&&(n=i===null?r.TEXTURE0+o-1:i);let s=a[n];s===void 0&&(s={type:void 0,texture:void 0},a[n]=s),(s.type!==e||s.texture!==t)&&(i!==n&&(r.activeTexture(n),this.currentTextureSlot=n),r.bindTexture(e,t),s.type=e,s.texture=t)}bindBufferBase(e,t,n){let{gl:r}=this,i=`${e}-${t}`;return this.currentBoundBufferBases[i]!==n&&(r.bindBufferBase(e,t,n),this.currentBoundBufferBases[i]=n,!0)}unbindTexture(){let{gl:e,currentTextureSlot:t,currentBoundTextures:n}=this,r=n[t];r!==void 0&&r.type!==void 0&&(e.bindTexture(r.type,null),r.type=void 0,r.texture=void 0)}getParameter(e){let{gl:t,parameters:n}=this;return n[e]===void 0?t.getParameter(e):n[e]}pixelStorei(e,t){let{gl:n,parameters:r}=this;r[e]!==t&&(n.pixelStorei(e,t),r[e]=t)}reset(){let{gl:e}=this;e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),this.resetVertexState(),this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendEquation=null,this.currentBlendEquationAlpha=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlendColor.set(0,0,0),this.currentBlendAlpha=0,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this.currentScissor.set(0,0,e.canvas.width,e.canvas.height),this.currentViewport.set(0,0,e.canvas.width,e.canvas.height),this.currentDepthReversed=!1,this.backend.renderer.reversedDepthBuffer===!0&&this.setReversedDepth(!0)}},dj=class{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=``){let{gl:n,extensions:r}=this,i,a=I.getTransfer(t);if(e===1009)return n.UNSIGNED_BYTE;if(e===1017)return n.UNSIGNED_SHORT_4_4_4_4;if(e===1018)return n.UNSIGNED_SHORT_5_5_5_1;if(e===35902)return n.UNSIGNED_INT_5_9_9_9_REV;if(e===35899)return n.UNSIGNED_INT_10F_11F_11F_REV;if(e===1010)return n.BYTE;if(e===1011)return n.SHORT;if(e===1012)return n.UNSIGNED_SHORT;if(e===1013)return n.INT;if(e===1014)return n.UNSIGNED_INT;if(e===1015)return n.FLOAT;if(e===1016)return n.HALF_FLOAT;if(e===1021)return n.ALPHA;if(e===1022)return n.RGB;if(e===1023)return n.RGBA;if(e===1026)return n.DEPTH_COMPONENT;if(e===1027)return n.DEPTH_STENCIL;if(e===1028)return n.RED;if(e===1029)return n.RED_INTEGER;if(e===1030)return n.RG;if(e===1031)return n.RG_INTEGER;if(e===1033)return n.RGBA_INTEGER;if(e===33776||e===33777||e===33778||e===33779){if(a===`srgb`){if(i=r.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(e===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null}else if(i=r.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(e===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null}if(e===35840||e===35841||e===35842||e===35843){if(i=r.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(e===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null}if(e===36196||e===37492||e===37496||e===37488||e===37489||e===37490||e===37491){if(i=r.get(`WEBGL_compressed_texture_etc`),i!==null){if(e===36196||e===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(e===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(e===37488)return i.COMPRESSED_R11_EAC;if(e===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(e===37490)return i.COMPRESSED_RG11_EAC;if(e===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null}if(e===37808||e===37809||e===37810||e===37811||e===37812||e===37813||e===37814||e===37815||e===37816||e===37817||e===37818||e===37819||e===37820||e===37821){if(i=r.get(`WEBGL_compressed_texture_astc`),i!==null){if(e===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null}if(e===36492||e===36494||e===36495){if(i=r.get(`EXT_texture_compression_bptc`),i!==null){if(e===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(e===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(e===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null}if(e===36283||e===36284||e===36285||e===36286){if(i=r.get(`EXT_texture_compression_rgtc`),i!==null){if(e===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(e===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null}return e===1020?n.UNSIGNED_INT_24_8:n[e]===void 0?null:n[e]}_clientWaitAsync(){let{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((n,r)=>{function i(){let a=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(a===e.WAIT_FAILED){e.deleteSync(t),r();return}if(a===e.TIMEOUT_EXPIRED){requestAnimationFrame(i);return}e.deleteSync(t),n()}i()})}},fj=!1,pj,mj,hj,gj=class{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,fj===!1&&(this._init(),fj=!0)}_init(){let e=this.gl;pj={[S]:e.REPEAT,[C]:e.CLAMP_TO_EDGE,[w]:e.MIRRORED_REPEAT},mj={[T]:e.NEAREST,[E]:e.NEAREST_MIPMAP_NEAREST,[D]:e.NEAREST_MIPMAP_LINEAR,[O]:e.LINEAR,[k]:e.LINEAR_MIPMAP_NEAREST,[ee]:e.LINEAR_MIPMAP_LINEAR},hj={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL}}getGLTextureType(e){let{gl:t}=this,n;return n=e.isCubeTexture===!0?t.TEXTURE_CUBE_MAP:e.isArrayTexture===!0||e.isDataArrayTexture===!0||e.isCompressedArrayTexture===!0?t.TEXTURE_2D_ARRAY:e.isData3DTexture===!0?t.TEXTURE_3D:t.TEXTURE_2D,n}getInternalFormat(e,t,n,r,i,a=!1){let{gl:o,extensions:s}=this;if(e!==null){if(o[e]!==void 0)return o[e];M(`WebGLBackend: Attempt to use non-existing WebGL internal format '`+e+`'`)}let c=null;r&&(c=s.get(`EXT_texture_norm16`),c||M(`WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension`));let l=t;if(t===o.RED&&(n===o.FLOAT&&(l=o.R32F),n===o.HALF_FLOAT&&(l=o.R16F),n===o.UNSIGNED_BYTE&&(l=o.R8),n===o.BYTE&&(l=o.R8_SNORM),n===o.UNSIGNED_SHORT&&c&&(l=c.R16_EXT),n===o.SHORT&&c&&(l=c.R16_SNORM_EXT)),t===o.RED_INTEGER&&(n===o.UNSIGNED_BYTE&&(l=o.R8UI),n===o.UNSIGNED_SHORT&&(l=o.R16UI),n===o.UNSIGNED_INT&&(l=o.R32UI),n===o.BYTE&&(l=o.R8I),n===o.SHORT&&(l=o.R16I),n===o.INT&&(l=o.R32I)),t===o.RG&&(n===o.FLOAT&&(l=o.RG32F),n===o.HALF_FLOAT&&(l=o.RG16F),n===o.UNSIGNED_BYTE&&(l=o.RG8),n===o.BYTE&&(l=o.RG8_SNORM),n===o.UNSIGNED_SHORT&&c&&(l=c.RG16_EXT),n===o.SHORT&&c&&(l=c.RG16_SNORM_EXT)),t===o.RG_INTEGER&&(n===o.UNSIGNED_BYTE&&(l=o.RG8UI),n===o.UNSIGNED_SHORT&&(l=o.RG16UI),n===o.UNSIGNED_INT&&(l=o.RG32UI),n===o.BYTE&&(l=o.RG8I),n===o.SHORT&&(l=o.RG16I),n===o.INT&&(l=o.RG32I)),t===o.RGB){let e=a?ht:I.getTransfer(i);n===o.FLOAT&&(l=o.RGB32F),n===o.HALF_FLOAT&&(l=o.RGB16F),n===o.UNSIGNED_BYTE&&(l=e===`srgb`?o.SRGB8:o.RGB8),n===o.BYTE&&(l=o.RGB8_SNORM),n===o.UNSIGNED_SHORT&&c&&(l=c.RGB16_EXT),n===o.SHORT&&c&&(l=c.RGB16_SNORM_EXT),n===o.UNSIGNED_SHORT_5_6_5&&(l=o.RGB565),n===o.UNSIGNED_SHORT_5_5_5_1&&(l=o.RGB5_A1),n===o.UNSIGNED_SHORT_4_4_4_4&&(l=o.RGB4),n===o.UNSIGNED_INT_5_9_9_9_REV&&(l=o.RGB9_E5),n===o.UNSIGNED_INT_10F_11F_11F_REV&&(l=o.R11F_G11F_B10F)}if(t===o.RGB_INTEGER&&(n===o.UNSIGNED_BYTE&&(l=o.RGB8UI),n===o.UNSIGNED_SHORT&&(l=o.RGB16UI),n===o.UNSIGNED_INT&&(l=o.RGB32UI),n===o.BYTE&&(l=o.RGB8I),n===o.SHORT&&(l=o.RGB16I),n===o.INT&&(l=o.RGB32I)),t===o.RGBA){let e=a?ht:I.getTransfer(i);n===o.FLOAT&&(l=o.RGBA32F),n===o.HALF_FLOAT&&(l=o.RGBA16F),n===o.UNSIGNED_BYTE&&(l=e===`srgb`?o.SRGB8_ALPHA8:o.RGBA8),n===o.BYTE&&(l=o.RGBA8_SNORM),n===o.UNSIGNED_SHORT&&c&&(l=c.RGBA16_EXT),n===o.SHORT&&c&&(l=c.RGBA16_SNORM_EXT),n===o.UNSIGNED_SHORT_4_4_4_4&&(l=o.RGBA4),n===o.UNSIGNED_SHORT_5_5_5_1&&(l=o.RGB5_A1)}return t===o.RGBA_INTEGER&&(n===o.UNSIGNED_BYTE&&(l=o.RGBA8UI),n===o.UNSIGNED_SHORT&&(l=o.RGBA16UI),n===o.UNSIGNED_INT&&(l=o.RGBA32UI),n===o.BYTE&&(l=o.RGBA8I),n===o.SHORT&&(l=o.RGBA16I),n===o.INT&&(l=o.RGBA32I)),t===o.DEPTH_COMPONENT&&(n===o.UNSIGNED_SHORT&&(l=o.DEPTH_COMPONENT16),n===o.UNSIGNED_INT&&(l=o.DEPTH_COMPONENT24),n===o.FLOAT&&(l=o.DEPTH_COMPONENT32F)),t===o.DEPTH_STENCIL&&n===o.UNSIGNED_INT_24_8&&(l=o.DEPTH24_STENCIL8),(l===o.R16F||l===o.R32F||l===o.RG16F||l===o.RG32F||l===o.RGBA16F||l===o.RGBA32F)&&s.get(`EXT_color_buffer_float`),l}setTextureParameters(e,t){let{gl:n,extensions:r,backend:i}=this,{state:a}=this.backend,o=I.getPrimaries(I.workingColorSpace),s=t.colorSpace===``?null:I.getPrimaries(t.colorSpace),c=t.colorSpace===``||o===s?n.NONE:n.BROWSER_DEFAULT_WEBGL;a.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),a.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),a.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),a.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,c),n.texParameteri(e,n.TEXTURE_WRAP_S,pj[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,pj[t.wrapT]),(e===n.TEXTURE_3D||e===n.TEXTURE_2D_ARRAY)&&(t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,pj[t.wrapR])),n.texParameteri(e,n.TEXTURE_MAG_FILTER,mj[t.magFilter]);let l=t.mipmaps!==void 0&&t.mipmaps.length>0,u=t.minFilter===1006&&l?ee:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,mj[u]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,hj[t.compareFunction])),r.has(`EXT_texture_filter_anisotropic`)===!0){if(t.magFilter===1003||t.minFilter!==1005&&t.minFilter!==1008||t.type===1015&&r.has(`OES_texture_float_linear`)===!1)return;if(t.anisotropy>1){let a=r.get(`EXT_texture_filter_anisotropic`);n.texParameterf(e,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){let{gl:t,backend:n,defaultTextures:r}=this,i=this.getGLTextureType(e),a=r[i];a===void 0&&(a=t.createTexture(),n.state.bindTexture(i,a),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),r[i]=a),n.set(e,{textureGPU:a,glTextureType:i})}createTexture(e,t){let{gl:n,backend:r}=this,i,a,o,s,c;if(e.isExternalTexture===!0)i=e.sourceTexture,a=this.getGLTextureType(e);else{let{levels:l,width:u,height:d,depth:f}=t;o=r.utils.convert(e.format,e.colorSpace),s=r.utils.convert(e.type),c=this.getInternalFormat(e.internalFormat,o,s,e.normalized,e.colorSpace,e.isVideoTexture),i=n.createTexture(),a=this.getGLTextureType(e),r.state.bindTexture(a,i),this.setTextureParameters(a,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,l,c,u,d,f):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,l,c,u,d,f):e.isVideoTexture||n.texStorage2D(a,l,c,u,d)}r.set(e,{textureGPU:i,glTextureType:a,glFormat:o,glType:s,glInternalFormat:c})}copyBufferToTexture(e,t){let{gl:n,backend:r}=this,{state:i}=r,{textureGPU:a,glTextureType:o,glFormat:s,glType:c}=r.get(t),{width:l,height:u}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),r.state.bindTexture(o,a),i.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),i.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(o,0,0,0,l,u,s,c,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),r.state.unbindTexture()}updateTexture(e,t){let{gl:n}=this,{width:r,height:i}=t,{textureGPU:a,glTextureType:o,glFormat:s,glType:c,glInternalFormat:l}=this.backend.get(e);if(!(e.isRenderTargetTexture||a===void 0)){if(this.backend.state.bindTexture(o,a),this.setTextureParameters(o,e),e.isCompressedTexture){let r=e.mipmaps,i=t.image;for(let t=0;t<r.length;t++){let a=r[t];if(e.isCompressedArrayTexture){if(e.format!==n.RGBA){if(s!==null){if(e.layerUpdates.size>0){let r=Ks(a.width,a.height,e.format,e.type);for(let i of e.layerUpdates){let e=a.data.subarray(i*r/a.data.BYTES_PER_ELEMENT,(i+1)*r/a.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,i,a.width,a.height,1,s,e)}}else n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,a.width,a.height,i.depth,s,a.data)}else M(`WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()`)}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,a.width,a.height,i.depth,s,c,a.data)}else s===null?M(`WebGLBackend: Unsupported compressed texture format`):n.compressedTexSubImage2D(n.TEXTURE_2D,t,0,0,a.width,a.height,s,a.data)}e.isCompressedArrayTexture&&e.layerUpdates.size>0&&e.clearLayerUpdates()}else if(e.isCubeTexture){let a=t.images,o=e.mipmaps;for(let e=0;e<6;e++){let t=_j(a[e]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,r,i,s,c,t);for(let t=0;t<o.length;t++){let r=o[t],i=_j(r.images[e]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,i.width,i.height,s,c,i)}}}else if(e.isDataArrayTexture||e.isArrayTexture){let r=t.image;if(e.layerUpdates.size>0){let t=Ks(r.width,r.height,e.format,e.type);for(let i of e.layerUpdates){let e=r.data.subarray(i*t/r.data.BYTES_PER_ELEMENT,(i+1)*t/r.data.BYTES_PER_ELEMENT);n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,i,r.width,r.height,1,s,c,e)}e.clearLayerUpdates()}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,r.width,r.height,r.depth,s,c,r.data)}else if(e.isData3DTexture){let e=t.image;n.texSubImage3D(n.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,s,c,e.data)}else if(e.isVideoTexture)e.update(),n.texImage2D(o,0,l,s,c,t.image);else if(e.isHTMLTexture)typeof n.texElementImage2D==`function`&&(n.texElementImage2D.length===3?n.texElementImage2D(n.TEXTURE_2D,n.RGBA8,t.image):n.texElementImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t.image));else{let a=e.mipmaps;if(a.length>0)for(let e=0,t=a.length;e<t;e++){let t=a[e],r=_j(t);n.texSubImage2D(o,e,0,0,t.width,t.height,s,c,r)}else{let e=_j(t.image);n.texSubImage2D(o,0,0,0,r,i,s,c,e)}}}}generateMipmaps(e){let{gl:t,backend:n}=this,{textureGPU:r,glTextureType:i}=n.get(e);n.state.bindTexture(i,r),t.generateMipmap(i)}deallocateRenderBuffers(e){let{gl:t,backend:n}=this;if(e){let r=n.get(e);if(r.renderBufferStorageSetup=void 0,r.framebuffers){for(let e in r.framebuffers)t.deleteFramebuffer(r.framebuffers[e]);delete r.framebuffers}if(r.depthRenderbuffer&&(t.deleteRenderbuffer(r.depthRenderbuffer),delete r.depthRenderbuffer),r.stencilRenderbuffer&&(t.deleteRenderbuffer(r.stencilRenderbuffer),delete r.stencilRenderbuffer),r.msaaFrameBuffer&&(t.deleteFramebuffer(r.msaaFrameBuffer),delete r.msaaFrameBuffer),r.msaaRenderbuffers){for(let e=0;e<r.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(r.msaaRenderbuffers[e]);delete r.msaaRenderbuffers}}}destroyTexture(e,t=!1){let{gl:n,backend:r}=this,{textureGPU:i,renderTarget:a}=r.get(e);this.deallocateRenderBuffers(a),t===!1&&e.isExternalTexture!==!0&&n.deleteTexture(i),r.delete(e)}copyTextureToTexture(e,t,n=null,r=null,i=0,a=0){let{gl:o,backend:s}=this,{state:c}=this.backend,{textureGPU:l,glTextureType:u,glType:d,glFormat:f}=s.get(t);c.bindTexture(u,l);let p,m,h,g,_,v,y,b,x,S=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)p=n.max.x-n.min.x,m=n.max.y-n.min.y,h=n.isBox3?n.max.z-n.min.z:1,g=n.min.x,_=n.min.y,v=n.isBox3?n.min.z:0;else{let t=2**-i;p=Math.floor(S.width*t),m=Math.floor(S.height*t),h=e.isDataArrayTexture||e.isArrayTexture?S.depth:e.isData3DTexture?Math.floor(S.depth*t):1,g=0,_=0,v=0}r===null?(y=0,b=0,x=0):(y=r.x,b=r.y,x=r.z),c.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,t.flipY),c.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),c.pixelStorei(o.UNPACK_ALIGNMENT,t.unpackAlignment);let C=c.getParameter(o.UNPACK_ROW_LENGTH),w=c.getParameter(o.UNPACK_IMAGE_HEIGHT),T=c.getParameter(o.UNPACK_SKIP_PIXELS),E=c.getParameter(o.UNPACK_SKIP_ROWS),D=c.getParameter(o.UNPACK_SKIP_IMAGES);c.pixelStorei(o.UNPACK_ROW_LENGTH,S.width),c.pixelStorei(o.UNPACK_IMAGE_HEIGHT,S.height),c.pixelStorei(o.UNPACK_SKIP_PIXELS,g),c.pixelStorei(o.UNPACK_SKIP_ROWS,_),c.pixelStorei(o.UNPACK_SKIP_IMAGES,v);let O=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,k=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){let n=s.get(e),r=s.get(t),u=s.get(n.renderTarget),d=s.get(r.renderTarget),f=u.framebuffers[n.cacheKey],S=d.framebuffers[r.cacheKey],C=c.currentBoundFramebuffers[o.READ_FRAMEBUFFER]??null,w=c.currentBoundFramebuffers[o.DRAW_FRAMEBUFFER]??null;c.bindFramebuffer(o.READ_FRAMEBUFFER,f),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,S);for(let e=0;e<h;e++)O&&(o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,n.textureGPU,i,v+e),o.framebufferTextureLayer(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,l,a,x+e)),o.blitFramebuffer(g,_,p,m,y,b,p,m,o.DEPTH_BUFFER_BIT,o.NEAREST);c.bindFramebuffer(o.READ_FRAMEBUFFER,C),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,w)}else if(i!==0||e.isRenderTargetTexture||s.has(e)){let t=s.get(e);this._srcFramebuffer===null&&(this._srcFramebuffer=o.createFramebuffer()),this._dstFramebuffer===null&&(this._dstFramebuffer=o.createFramebuffer());let n=c.currentBoundFramebuffers[o.READ_FRAMEBUFFER]??null,r=c.currentBoundFramebuffers[o.DRAW_FRAMEBUFFER]??null;c.bindFramebuffer(o.READ_FRAMEBUFFER,this._srcFramebuffer),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let e=0;e<h;e++)O?o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,t.textureGPU,i,v+e):o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,t.textureGPU,i),k?o.framebufferTextureLayer(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,l,a,x+e):o.framebufferTexture2D(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,l,a),i===0?k?o.copyTexSubImage3D(u,a,y,b,x+e,g,_,p,m):o.copyTexSubImage2D(u,a,y,b,g,_,p,m):o.blitFramebuffer(g,_,p,m,y,b,p,m,o.COLOR_BUFFER_BIT,o.NEAREST);c.bindFramebuffer(o.READ_FRAMEBUFFER,n),c.bindFramebuffer(o.DRAW_FRAMEBUFFER,r)}else k?e.isDataTexture||e.isData3DTexture?o.texSubImage3D(u,a,y,b,x,p,m,h,f,d,S.data):t.isCompressedArrayTexture?o.compressedTexSubImage3D(u,a,y,b,x,p,m,h,f,S.data):o.texSubImage3D(u,a,y,b,x,p,m,h,f,d,S):e.isDataTexture?o.texSubImage2D(o.TEXTURE_2D,a,y,b,p,m,f,d,S.data):e.isCompressedTexture?o.compressedTexSubImage2D(o.TEXTURE_2D,a,y,b,S.width,S.height,f,S.data):o.texSubImage2D(o.TEXTURE_2D,a,y,b,p,m,f,d,S);c.pixelStorei(o.UNPACK_ROW_LENGTH,C),c.pixelStorei(o.UNPACK_IMAGE_HEIGHT,w),c.pixelStorei(o.UNPACK_SKIP_PIXELS,T),c.pixelStorei(o.UNPACK_SKIP_ROWS,E),c.pixelStorei(o.UNPACK_SKIP_IMAGES,D),a===0&&t.generateMipmaps&&o.generateMipmap(u),c.unbindTexture()}copyFramebufferToTexture(e,t,n){let{gl:r}=this,{state:i}=this.backend,{textureGPU:a}=this.backend.get(e),{x:o,y:s,z:c,w:l}=n,u=e.isDepthTexture===!0||t.renderTarget&&t.renderTarget.samples>0,d=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(u){let n=o!==0||s!==0,u,f;if(e.isDepthTexture===!0?(u=r.DEPTH_BUFFER_BIT,f=r.DEPTH_ATTACHMENT,t.stencil&&(u|=r.STENCIL_BUFFER_BIT)):(u=r.COLOR_BUFFER_BIT,f=r.COLOR_ATTACHMENT0),n){let e=this.backend.get(t.renderTarget),n=e.framebuffers[t.getCacheKey()],f=e.msaaFrameBuffer;i.bindFramebuffer(r.DRAW_FRAMEBUFFER,n),i.bindFramebuffer(r.READ_FRAMEBUFFER,f);let p=d-s-l;r.blitFramebuffer(o,p,o+c,p+l,o,p,o+c,p+l,u,r.NEAREST),i.bindFramebuffer(r.READ_FRAMEBUFFER,n),i.bindTexture(r.TEXTURE_2D,a),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,o,p,c,l),i.unbindTexture()}else{let e=r.createFramebuffer();i.bindFramebuffer(r.DRAW_FRAMEBUFFER,e),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,f,r.TEXTURE_2D,a,0),r.blitFramebuffer(0,0,c,l,0,0,c,l,u,r.NEAREST),r.deleteFramebuffer(e)}}else i.bindTexture(r.TEXTURE_2D,a),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,o,d-l-s,c,l),i.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,r=!1){let{gl:i}=this,a=t.renderTarget,{depthTexture:o,depthBuffer:s,stencilBuffer:c,width:l,height:u}=a;if(i.bindRenderbuffer(i.RENDERBUFFER,e),s&&!c){let t=i.DEPTH_COMPONENT24;r===!0?this.extensions.get(`WEBGL_multisampled_render_to_texture`).renderbufferStorageMultisampleEXT(i.RENDERBUFFER,a.samples,t,l,u):n>0?(o&&o.isDepthTexture&&o.type===i.FLOAT&&(t=i.DEPTH_COMPONENT32F),i.renderbufferStorageMultisample(i.RENDERBUFFER,n,t,l,u)):i.renderbufferStorage(i.RENDERBUFFER,t,l,u),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,e)}else s&&c&&(n>0?i.renderbufferStorageMultisample(i.RENDERBUFFER,n,i.DEPTH24_STENCIL8,l,u):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,l,u),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e));i.bindRenderbuffer(i.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,r,i,a){let{backend:o,gl:s}=this,{textureGPU:c,glFormat:l,glType:u}=this.backend.get(e),d=s.createFramebuffer();if(o.state.bindFramebuffer(s.READ_FRAMEBUFFER,d),e.isData3DTexture||e.isDataArrayTexture||e.isArrayTexture)s.framebufferTextureLayer(s.READ_FRAMEBUFFER,s.COLOR_ATTACHMENT0,c,0,a);else{let t=e.isCubeTexture?s.TEXTURE_CUBE_MAP_POSITIVE_X+a:s.TEXTURE_2D;s.framebufferTexture2D(s.READ_FRAMEBUFFER,s.COLOR_ATTACHMENT0,t,c,0)}let f=this._getTypedArrayType(u),p=this._getBytesPerTexel(u,l),m=r*i*p,h=s.createBuffer();s.bindBuffer(s.PIXEL_PACK_BUFFER,h),s.bufferData(s.PIXEL_PACK_BUFFER,m,s.STREAM_READ),s.readPixels(t,n,r,i,l,u,0),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();let g=new f(m/f.BYTES_PER_ELEMENT);return s.bindBuffer(s.PIXEL_PACK_BUFFER,h),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,g),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),o.state.bindFramebuffer(s.READ_FRAMEBUFFER,null),s.deleteBuffer(h),s.deleteFramebuffer(d),g}_getTypedArrayType(e){let{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 Error(`THREE.WebGLTextureUtils: Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){let{gl:n}=this,r=0;if(e===n.UNSIGNED_BYTE&&(r=1),(e===n.UNSIGNED_SHORT_4_4_4_4||e===n.UNSIGNED_SHORT_5_5_5_1||e===n.UNSIGNED_SHORT_5_6_5||e===n.UNSIGNED_SHORT||e===n.HALF_FLOAT)&&(r=2),(e===n.UNSIGNED_INT||e===n.FLOAT)&&(r=4),t===n.RGBA)return r*4;if(t===n.RGB)return r*3;if(t===n.ALPHA)return r}dispose(){let{gl:e}=this;this._srcFramebuffer!==null&&e.deleteFramebuffer(this._srcFramebuffer),this._dstFramebuffer!==null&&e.deleteFramebuffer(this._dstFramebuffer)}};function _j(e){return e.isDataTexture?e.image.data:typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas?e:e.data}var vj=class{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)}},yj=class{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=null}getMaxAnisotropy(){if(this.maxAnisotropy!==null)return this.maxAnisotropy;let e=this.backend.gl,t=this.backend.extensions;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let 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;let e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}},bj={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`},xj=class{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){let{gl:n,mode:r,object:i,type:a,info:o,index:s}=this;s===0?n.drawArrays(r,e,t):n.drawElements(r,t,a,e),o.update(i,t,1)}renderInstances(e,t,n){let{gl:r,mode:i,type:a,index:o,object:s,info:c}=this;n!==0&&(o===0?r.drawArraysInstanced(i,e,t,n):r.drawElementsInstanced(i,t,a,e,n),c.update(s,t,n))}renderMultiDraw(e,t,n){let{extensions:r,mode:i,object:a,info:o}=this;if(n===0)return;let s=r.get(`WEBGL_multi_draw`);if(s===null)for(let r=0;r<n;r++)this.render(e[r],t[r]);else{this.index===0?s.multiDrawArraysWEBGL(i,e,0,t,0,n):s.multiDrawElementsWEBGL(i,t,0,this.type,e,0,n);let r=0;for(let e=0;e<n;e++)r+=t[e];o.update(a,r,1)}}},Sj=class{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&&(M(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestampQuery(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}},Cj=class extends Sj{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){M(`EXT_disjoint_timer_query not supported; timestamps will be disabled.`),this.trackTimestamp=!1;return}this.queries=[];for(let t=0;t<this.maxQueries;t++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;this.currentQueryIndex+2>this.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null);let 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;let t=this.queryOffsets.get(e);if(t==null||this.activeQuery!==null)return;let 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(e){N(`Error in beginQuery:`,e),this.activeQuery=null,this.queryStates.set(t,`inactive`)}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;let 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(e){N(`Error in endQuery:`,e),this.queryStates.set(t,`inactive`),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{let e=new Map;for(let[t,n]of this.queryOffsets)if(this.queryStates.get(n)===`ended`){let r=this.queries[n];e.set(t,this.resolveQuery(r))}if(e.size===0)return this.lastValue;let t={},n=[];this.timestamps.clear();for(let[r,i]of e){let e=r.match(/^(.*):f(\d+)$/),a=parseInt(e[2]);n.includes(a)===!1&&n.push(a),t[a]===void 0&&(t[a]=0);let o=await i;this.timestamps.set(r,o),t[a]+=o}let r=t[n[n.length-1]];return this.lastValue=r,this.frames=n,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,r}catch(e){return N(`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,r=!1,i=()=>{n&&=(clearTimeout(n),null)},a=e=>{r||(r=!0,i(),t(e))},o=()=>{if(this.isDisposed){a(this.lastValue);return}try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT)){a(this.lastValue);return}if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE)){n=setTimeout(o,1);return}let r=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(r)/1e6)}catch(e){N(`Error checking query:`,e),t(this.lastValue)}};o()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(let e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.timestamps.clear(),this.frames=[],this.lastValue=0,this.activeQuery=null}}},wj=[],Tj=class extends ij{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);let t=this.parameters,n={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},r=t.context===void 0?e.domElement.getContext(`webgl2`,n):t.context;function i(t){t.preventDefault();let n={api:`WebGL`,message:t.statusMessage||`Unknown reason`,reason:null,originalEvent:t};e.onDeviceLost(n)}this._onContextLost=i,e.domElement.addEventListener(`webglcontextlost`,i,!1),this.gl=r,this.extensions=new vj(this),this.capabilities=new yj(this),this.attributeUtils=new sj(this),this.textureUtils=new gj(this),this.bufferRenderer=new xj(this),this.state=new uj(this),this.utils=new dj(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:(M(`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 Et}get hasTimestamp(){return this.disjoint!==null}async getArrayBufferAsync(e,t=null,n=0,r=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,r)}async makeXRCompatible(){this.gl.getContextAttributes().xrCompatible!==!0&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){let r=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:r.RGBA8}),n!==null){let t=e.stencilBuffer?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:t}),this.extensions.has(`WEBGL_multisampled_render_to_texture`)===!0&&e._autoAllocateDepthBuffer===!0&&e.multiview===!1&&M(`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 Cj(this.gl,e,2048));let n=this.timestampQueryPool[e];n.allocateQueriesForContext(t)!==null&&n.beginQuery(t)}prepareTimestampBuffer(e,t){this.disjoint&&this.trackTimestamp&&this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){let{state:t}=this,n=this.get(e);if(e.viewport)this.updateViewport(e);else{let{width:e,height:n}=this.getDrawingBufferSize();t.viewport(0,0,e,n)}if(e.scissor)this.updateScissor(e);else{let{width:e,height:n}=this.getDrawingBufferSize();t.scissor(0,0,e,n)}this.initTimestampQuery(Ot.RENDER,this.getTimestampUID(e)),n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);let r=e.occlusionQueryCount;r>0?(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=Array(r),n.occlusionQueryObjects=Array(r),n.occlusionQueryIndex=0):n.lastOcclusionObject!==void 0&&(n.lastOcclusionObject=void 0)}finishRender(e){let{gl:t,state:n}=this,r=this.get(e),i=r.previousContext;if(n.resetVertexState(),e.occlusionQueryCount>0){let n=r.lastOcclusionObject;n&&n.occlusionTest===!0&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e)}let a=e.textures;if(a!==null)for(let e=0;e<a.length;e++){let t=a[e];t.generateMipmaps&&this.generateMipmaps(t)}if(this._currentContext=i,this._resolveRenderTarget(e),i!==null){if(this._setFramebuffer(i),i.viewport)this.updateViewport(i);else{let{width:e,height:t}=this.getDrawingBufferSize();n.viewport(0,0,e,t)}if(i.scissor)this.updateScissor(i);else{let{width:e,height:t}=this.getDrawingBufferSize();n.scissor(0,0,e,t)}}this.prepareTimestampBuffer(Ot.RENDER,this.getTimestampUID(e))}resolveOccludedAsync(e){let t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:r}=t;if(n&&r){let e=new WeakSet,{gl:i}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;let a=()=>{let o=!0;for(let t=0;t<n.length;t++){let a=n[t];a&&(i.getQueryParameter(a,i.QUERY_RESULT_AVAILABLE)?(i.getQueryParameter(a,i.QUERY_RESULT)===0&&e.add(r[t]),n[t]=null,i.deleteQuery(a)):o=!1)}o===!1?requestAnimationFrame(a):t.occluded=e};a()}}isOccluded(e,t){let n=this.get(e);return n.occluded&&n.occluded.has(t)}updateViewport(e){let{state:t}=this,{x:n,y:r,width:i,height:a}=e.viewportValue;t.viewport(n,e.height-a-r,i,a)}updateScissor(e){let{state:t}=this,{x:n,y:r,width:i,height:a}=e.scissorValue;t.scissor(n,e.height-a-r,i,a)}setScissorTest(e){this.state.setScissorTest(e)}resetState(){this.state.reset()}getClearColor(){let e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,n,r=null,i=!0,a=!0){let{gl:o,renderer:s}=this;r===null&&(r={textures:null,clearColorValue:this.getClearColor()});let c=0;if(e&&(c|=o.COLOR_BUFFER_BIT),t&&(c|=o.DEPTH_BUFFER_BIT),n&&(c|=o.STENCIL_BUFFER_BIT),c!==0){let l;l=r.clearColorValue?r.clearColorValue:this.getClearColor();let u=s.getClearDepth(),d=s.getClearStencil();if(t&&this.state.setDepthMask(!0),n&&this.state.setStencilMask(4294967295),r.textures===null)e&&o.clearColor(l.r,l.g,l.b,l.a),t&&o.clearDepth(u),n&&o.clearStencil(d),o.clear(c);else{if(i&&this._setFramebuffer(r),e)for(let e=0;e<r.textures.length;e++){let t=r.mrt?r.mrt.getClearColor(r.textures[e].name):null;t===null?e===0?o.clearBufferfv(o.COLOR,e,[l.r,l.g,l.b,l.a]):o.clearBufferfv(o.COLOR,e,[0,0,0,1]):o.clearBufferfv(o.COLOR,e,[t.r,t.g,t.b,t.a])}t&&n?o.clearBufferfi(o.DEPTH_STENCIL,0,u,d):t?o.clearBufferfv(o.DEPTH,0,[u]):n&&o.clearBufferiv(o.STENCIL,0,[d]),i&&a&&this._resolveRenderTarget(r),i&&this._currentContext!==null&&this._currentContext!==r&&this._setFramebuffer(this._currentContext)}}}beginCompute(e){let{state:t,gl:n}=this;t.bindFramebuffer(n.FRAMEBUFFER,null),this.initTimestampQuery(Ot.COMPUTE,this.getTimestampUID(e))}compute(e,t,n,r,i=null){let{state:a,gl:o}=this;this.discard===!1&&(a.enable(o.RASTERIZER_DISCARD),this.discard=!0);let{programGPU:s,transformBuffers:c,attributes:l}=this.get(r),u=this._getVaoKey(l),d=this.vaoCache[u];d===void 0?this.vaoCache[u]=this._createVao(l):a.setVertexState(d),a.useProgram(s),this._bindUniforms(n);let f=this._getTransformFeedback(c);o.bindTransformFeedback(o.TRANSFORM_FEEDBACK,f),o.beginTransformFeedback(o.POINTS),i=i===null?t.count:i,Array.isArray(i)?(Rt(`WebGLBackend.compute(): The count parameter must be a single number, not an array.`),i=i[0]):i&&typeof i==`object`&&i.isIndirectStorageBufferAttribute&&(Rt(`WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute`),i=t.count),l[0].isStorageInstancedBufferAttribute?o.drawArraysInstanced(o.POINTS,0,1,i):o.drawArrays(o.POINTS,0,i),o.endTransformFeedback(),o.bindTransformFeedback(o.TRANSFORM_FEEDBACK,null);for(let e=0;e<c.length;e++){let t=c[e];t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){let{state:t,gl:n}=this;this.discard=!1,t.disable(n.RASTERIZER_DISCARD),this.prepareTimestampBuffer(Ot.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,r,i,a){if(e.isBatchedMesh){if(this.hasFeature(`WEBGL_multi_draw`)===!1){let{gl:n}=this,r=n.getUniformLocation(a,`nodeUniformDrawId`),i=e._multiDrawStarts,o=e._multiDrawCounts,s=e._multiDrawCount;for(let e=0;e<s;e++)n.uniform1ui(r,e),t.render(i[e],o[e])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount)}else i>1?t.renderInstances(n,r,i):t.render(n,r)}draw(e){let{object:t,pipeline:n,material:r,context:i,hardwareClippingPlanes:a}=e,{programGPU:o}=this.get(n),{gl:s,state:c}=this,l=this.get(i),u=e.getDrawParameters();if(u===null)return;this._bindUniforms(e.getBindings());let d=t.isMesh&&t.matrixWorld.determinantAffine()<0;c.setMaterial(r,d,a),i.mrt!==null&&i.textures!==null&&c.setMRTBlending(i.textures,i.mrt,r),c.useProgram(o);let f=e.getAttributes(),p=this.get(f),m=p.vaoGPU;if(m===void 0){let e=this._getVaoKey(f);m=this.vaoCache[e],m===void 0&&(m=this._createVao(f),this.vaoCache[e]=m,p.vaoGPU=m)}let h=e.getIndex(),g=h===null?null:this.get(h).bufferGPU;c.setVertexState(m,g);let _=l.lastOcclusionObject;if(_!==t&&_!==void 0){if(_!==null&&_.occlusionTest===!0&&(s.endQuery(s.ANY_SAMPLES_PASSED),l.occlusionQueryIndex++),t.occlusionTest===!0){let e=s.createQuery();s.beginQuery(s.ANY_SAMPLES_PASSED,e),l.occlusionQueries[l.occlusionQueryIndex]=e,l.occlusionQueryObjects[l.occlusionQueryIndex]=t}l.lastOcclusionObject=t}let v=this.bufferRenderer;t.isPoints?v.mode=s.POINTS:t.isLineSegments?v.mode=s.LINES:t.isLine?v.mode=s.LINE_STRIP:t.isLineLoop?v.mode=s.LINE_LOOP:r.wireframe===!0?(c.setLineWidth(r.wireframeLinewidth*this.renderer.getPixelRatio()),v.mode=s.LINES):v.mode=s.TRIANGLES;let{vertexCount:y,instanceCount:b}=u,{firstVertex:x}=u;if(v.object=t,h!==null){x*=h.array.BYTES_PER_ELEMENT;let e=this.get(h);v.index=h.count,v.type=e.type}else v.index=0;if(e.camera.isArrayCamera===!0&&e.camera.cameras.length>0&&e.camera.isMultiViewCamera===!1){let n=this.get(e.camera),r=e.camera.cameras,i=e.getBindingGroup(`cameraIndex`).bindings[0];if(n.indexesGPU===void 0||n.indexesGPU.length!==r.length){let e=new Uint32Array([0,0,0,0]),t=[];for(let n=0,i=r.length;n<i;n++){let r=s.createBuffer();e[0]=n,s.bindBuffer(s.UNIFORM_BUFFER,r),s.bufferData(s.UNIFORM_BUFFER,e,s.STATIC_DRAW),t.push(r)}n.indexesGPU=t}let a=0;bindingsSearch:for(let t of e.getBindings())for(let e of t.bindings){if(e===i)break bindingsSearch;(e.isUniformsGroup||e.isUniformBuffer)&&a++}let l=this._currentContext.renderTarget,u=l===null||l.isPostProcessingRenderTarget===!0?this.renderer.getPixelRatio():1,d=this._isRenderCameraDepthArray(this._currentContext),f=this._currentContext.activeCubeFace;if(d){let e=this.get(l.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;let{stencilBuffer:t}=l;for(let e=0,n=r.length;e<n;e++)this.renderer._activeCubeFace=e,this._currentContext.activeCubeFace=e,this._setFramebuffer(this._currentContext),this.clear(!1,!0,t,this._currentContext,!1,!1);this.renderer._activeCubeFace=f,this._currentContext.activeCubeFace=f}}for(let i=0,l=r.length;i<l;i++){let l=r[i];if(t.layers.test(l.layers)){d&&(this.renderer._activeCubeFace=i,this._currentContext.activeCubeFace=i,this._setFramebuffer(this._currentContext));let r=l.viewport;if(r!==void 0){let t=r.x*u,n=r.y*u,i=r.width*u,a=r.height*u;c.viewport(Math.floor(t),Math.floor(e.context.height-a-n),Math.floor(i),Math.floor(a))}c.bindBufferBase(s.UNIFORM_BUFFER,a,n.indexesGPU[i]),this._draw(t,v,x,y,b,o)}this._currentContext.activeCubeFace=f,this.renderer._activeCubeFace=f}}else this._draw(t,v,x,y,b,o)}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,r,i,a){return this.textureUtils.copyTextureToBuffer(e,t,n,r,i,a)}updateSampler(){return``}createNodeBuilder(e,t){return new tj(e,t)}createProgram(e){let t=this.gl,{stage:n,code:r}=e,i=n===`fragment`?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(i,r),t.compileShader(i),this.set(e,{shaderGPU:i})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){let n=this.gl,r=e.pipeline,{fragmentProgram:i,vertexProgram:a}=r,o=n.createProgram(),s=this.get(i).shaderGPU,c=this.get(a).shaderGPU;if(n.attachShader(o,s),n.attachShader(o,c),n.linkProgram(o),this.set(r,{programGPU:o,fragmentShader:s,vertexShader:c}),t!==null&&this.parallel){let i=new Promise(t=>{let i=this.parallel,a=()=>{n.getProgramParameter(o,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,r),t()):requestAnimationFrame(a)};a()});t.push(i);return}this._completeCompile(e,r)}_handleSource(e,t){let n=e.split(`
`),r=[],i=Math.max(t-6,0),a=Math.min(t+6,n.length);for(let e=i;e<a;e++){let i=e+1;r.push(`${i===t?`>`:` `} ${i}: ${n[e]}`)}return r.join(`
`)}_getShaderErrors(e,t,n){let r=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||``).trim();if(r&&i===``)return``;let a=/ERROR: 0:(\d+)/.exec(i);if(a){let r=parseInt(a[1]);return n.toUpperCase()+`
`+i+`
`+this._handleSource(e.getShaderSource(t),r)}return i}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){let r=this.gl,i=(r.getProgramInfoLog(e)||``).trim();if(r.getProgramParameter(e,r.LINK_STATUS)===!1){if(typeof this.renderer.debug.onShaderError==`function`)this.renderer.debug.onShaderError(r,e,n,t);else{let a=this._getShaderErrors(r,n,`vertex`),o=this._getShaderErrors(r,t,`fragment`);N(`WebGLProgram: Shader Error `+r.getError()+` - VALIDATE_STATUS `+r.getProgramParameter(e,r.VALIDATE_STATUS)+`
Program Info Log: `+i+`
`+a+`
`+o)}}else i!==``&&M(`WebGLProgram: Program Info Log:`,i)}}_completeCompile(e,t){let{state:n,gl:r}=this,{programGPU:i,fragmentShader:a,vertexShader:o}=this.get(t);r.getProgramParameter(i,r.LINK_STATUS)===!1&&this._logProgramError(i,a,o),n.useProgram(i);let s=e.getBindings();this._setupBindings(s,i),this.set(t,{programGPU:i,pipeline:i})}createComputePipeline(e,t,n=null){let{gl:r}=this,i={stage:`fragment`,code:`#version 300 es
precision highp float;
void main() {}`};this.createProgram(i);let{computeProgram:a}=e,o=r.createProgram(),s=this.get(i).shaderGPU,c=this.get(a).shaderGPU,l=a.transforms,u=[],d=[];for(let e=0;e<l.length;e++){let t=l[e];u.push(t.varyingName),d.push(t.attributeNode)}r.attachShader(o,s),r.attachShader(o,c),r.transformFeedbackVaryings(o,u,r.SEPARATE_ATTRIBS),r.linkProgram(o);let f=a.attributes,p=[],m=[];for(let e=0;e<f.length;e++){let t=f[e].node.attribute;p.push(t),this.has(t)||this.attributeUtils.createAttribute(t,r.ARRAY_BUFFER)}for(let e=0;e<d.length;e++){let t=d[e].attribute;this.has(t)||this.attributeUtils.createAttribute(t,r.ARRAY_BUFFER);let n=this.get(t);m.push(n)}if(this.set(e,{programGPU:o,fragmentShader:s,vertexShader:c,transformBuffers:m,attributes:p}),n!==null&&this.parallel){let i=this.parallel,a=new Promise(n=>{let a=()=>{r.getProgramParameter(o,i.COMPLETION_STATUS_KHR)?(this._completeComputeCompile(e,t),n()):requestAnimationFrame(a)};a()});n.push(a);return}this._completeComputeCompile(e,t)}_completeComputeCompile(e,t){let{state:n,gl:r}=this,{programGPU:i,fragmentShader:a,vertexShader:o}=this.get(e);r.getProgramParameter(i,r.LINK_STATUS)===!1&&this._logProgramError(i,a,o),n.useProgram(i),this._setupBindings(t,i)}createBindings(e,t){if(this._knownBindings.has(t)===!1){this._knownBindings.add(t);let e=0,n=0;for(let r of t){this.set(r,{textures:n,uniformBuffers:e});for(let t of r.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&n++}}this.updateBindings(e,t)}updateBindings(e){let{gl:t}=this;for(let n of e.bindings){let e=this.get(n);if(n.isUniformsGroup||n.isUniformBuffer){let r=n.buffer,i=e.bufferGPU;t.bindBuffer(t.UNIFORM_BUFFER,i);let a=n.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,i),a.length===0)t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW);else{let e=Mt(r),n=e?1:r.BYTES_PER_ELEMENT;for(let i=0,o=a.length;i<o;i++){let o=a[i],s=o.start*n,c=o.count*n,l=s*(e?r.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,l,r,s,c)}}this.set(n,e)}else if(n.isSampledTexture){let{textureGPU:t,glTextureType:r}=this.get(n.texture);e.textureGPU=t,e.glTextureType=r,this.set(n,e)}}}updateBinding(e){let t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){let n=this.get(e).bufferGPU,r=e.buffer,i=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,n),i.length===0)t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW);else{let e=Mt(r),n=e?1:r.BYTES_PER_ELEMENT,a=i[0].start;for(let o=0,s=i.length;o<s;o++){let s=i[o],c=i[o+1],l=s.start+s.count;if(c!==void 0&&c.start===l)continue;let u=a*n,d=(l-a)*n,f=u*(e?r.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,f,r,u,d),c!==void 0&&(a=c.start)}}}}createUniformBuffer(e){let t=this.get(e);if(t.bufferGPU===void 0){let n=this.gl,r=e.buffer;t.bufferGPU=n.createBuffer(),n.bindBuffer(n.UNIFORM_BUFFER,t.bufferGPU),n.bufferData(n.UNIFORM_BUFFER,r.byteLength,n.DYNAMIC_DRAW)}}destroyUniformBuffer(e){let t=this.get(e);this.gl.deleteBuffer(t.bufferGPU),this.delete(e)}createIndexAttribute(e){let t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;let t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;let t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){let t=Object.keys(bj).filter(t=>bj[t]===e),n=this.extensions;for(let e=0;e<t.length;e++)if(n.has(t[e]))return!0;return!1}copyTextureToTexture(e,t,n=null,r=null,i=0,a=0){this.textureUtils.copyTextureToTexture(e,t,n,r,i,a)}copyFramebufferToTexture(e,t,n){this.textureUtils.copyFramebufferToTexture(e,t,n)}hasCompatibility(e){return e===kt.TEXTURE_COMPARE||super.hasCompatibility(e)}initRenderTarget(e){let{gl:t,state:n}=this;this._setFramebuffer(e),n.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){let{gl:t,state:n}=this,r=null;if(e.textures!==null){let i=e.renderTarget,a=this.get(i),{depthBuffer:o,stencilBuffer:s}=i,c=i.isCubeRenderTarget===!0,l=i.isRenderTarget3D===!0,u=i.depth>1,d=i.isXRRenderTarget===!0,f=d===!0&&i._hasExternalTextures===!0,p=a.msaaFrameBuffer,m=a.depthRenderbuffer,h=this.extensions.get(`WEBGL_multisampled_render_to_texture`),g=this.extensions.get(`OVR_multiview2`),_=this._useMultisampledExtension(i),v=i.samples;e.depthTexture!==null&&e.depthTexture.renderTarget!==i&&_===!1&&v>0&&(Rt(`WebGLBackend: Shared depth texture is not supported with MSAA when "WEBGL_multisampled_render_to_texture" is unsupported. Falling back to single-sample rendering.`),v=0);let y=QE(e),b;if(c?(a.cubeFramebuffers||={},b=a.cubeFramebuffers[y]):d&&f===!1?b=this._xrFramebuffer:(a.framebuffers||={},b=a.framebuffers[y]),b===void 0){b=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,b);let r=e.textures,o=[];if(c){a.cubeFramebuffers[y]=b;let{textureGPU:e}=this.get(r[0]),n=this.renderer._activeCubeFace,i=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,e,i)}else{a.framebuffers[y]=b;for(let n=0;n<r.length;n++){let a=r[n],o=this.get(a);o.renderTarget=e.renderTarget,o.cacheKey=y;let s=t.COLOR_ATTACHMENT0+n;if(i.multiview)g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,s,o.textureGPU,0,v,0,2);else if(l||u){let e=this.renderer._activeCubeFace,n=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,s,o.textureGPU,n,e)}else if(_)h.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,s,t.TEXTURE_2D,o.textureGPU,0,v);else{let e=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,s,t.TEXTURE_2D,o.textureGPU,e)}}}let d=s?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(i._autoAllocateDepthBuffer===!0){let n=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(n,e,0,_),a.xrDepthRenderbuffer=n,o.push(s?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,n),t.framebufferRenderbuffer(t.FRAMEBUFFER,d,t.RENDERBUFFER,n)}else if(e.depthTexture!==null){o.push(s?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);let n=this.get(e.depthTexture);if(n.renderTarget=e.renderTarget,n.cacheKey=y,i.multiview)g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,d,n.textureGPU,0,v,0,2);else if(f&&_)h.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,d,t.TEXTURE_2D,n.textureGPU,0,v);else if(e.depthTexture.isArrayTexture){let e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,d,n.textureGPU,0,e)}else if(e.depthTexture.isCubeTexture){let e=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_CUBE_MAP_POSITIVE_X+e,n.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_2D,n.textureGPU,0)}a.depthInvalidationArray=o}else{if(this._isRenderCameraDepthArray(e)){n.bindFramebuffer(t.FRAMEBUFFER,b);let r=this.renderer._activeCubeFace,i=this.get(e.depthTexture),a=s?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,a,i.textureGPU,0,r)}if((d||_||i.multiview)&&i._isOpaqueFramebuffer!==!0){n.bindFramebuffer(t.FRAMEBUFFER,b);let r=this.get(e.textures[0]);i.multiview?g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,r.textureGPU,0,v,0,2):_?h.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r.textureGPU,0,v):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r.textureGPU,0);let o=s?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(i._autoAllocateDepthBuffer===!0){let e=a.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,o,t.RENDERBUFFER,e)}else{let n=this.get(e.depthTexture);i.multiview?g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,n.textureGPU,0,v,0,2):_?h.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,n.textureGPU,0,v):t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,n.textureGPU,0)}}}if(v>0&&_===!1&&!i.multiview){if(p===void 0){p=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,p);let r=[],i=e.textures;for(let n=0;n<i.length;n++){r[n]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,r[n]);let i=e.textures[n],a=this.get(i);t.renderbufferStorageMultisample(t.RENDERBUFFER,v,a.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+n,t.RENDERBUFFER,r[n])}t.bindRenderbuffer(t.RENDERBUFFER,null),a.msaaFrameBuffer=p,a.msaaRenderbuffers=r,o&&m===void 0&&(m=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(m,e,v),a.depthRenderbuffer=m)}r=a.msaaFrameBuffer}else r=b;n.drawBuffers(e,b)}n.bindFramebuffer(t.FRAMEBUFFER,r)}_getVaoKey(e){let t=``;for(let n=0;n<e.length;n++){let r=this.get(e[n]);t+=`:`+r.id}return t}_createVao(e){let{gl:t}=this,n=t.createVertexArray();t.bindVertexArray(n);for(let n=0;n<e.length;n++){let r=e[n],i=this.get(r);t.bindBuffer(t.ARRAY_BUFFER,i.bufferGPU),t.enableVertexAttribArray(n);let a,o;r.isInterleavedBufferAttribute===!0?(a=r.data.stride*i.bytesPerElement,o=r.offset*i.bytesPerElement):(a=0,o=0),i.isInteger?t.vertexAttribIPointer(n,r.itemSize,i.type,a,o):t.vertexAttribPointer(n,r.itemSize,i.type,r.normalized,a,o),r.isInstancedBufferAttribute&&!r.isInterleavedBufferAttribute?t.vertexAttribDivisor(n,r.meshPerAttribute):r.isInterleavedBufferAttribute&&r.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(n,r.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),n}_getTransformFeedback(e){let t=``;for(let n=0;n<e.length;n++)t+=`:`+e[n].id;let n=this.transformFeedbackCache[t];if(n!==void 0)return n;let{gl:r}=this;n=r.createTransformFeedback(),r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,n);for(let t=0;t<e.length;t++){let n=e[t];r.bindBufferBase(r.TRANSFORM_FEEDBACK_BUFFER,t,n.transformBuffer)}return r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=n,n}_setupBindings(e,t){let n=this.gl,r=0,i=0;for(let a of e)for(let e of a.bindings)if(e.isUniformsGroup||e.isUniformBuffer){let i=r++,a=n.getUniformBlockIndex(t,e.name);n.uniformBlockBinding(t,a,i)}else if(e.isSampledTexture){let r=i++,a=n.getUniformLocation(t,e.name);n.uniform1i(a,r)}}_bindUniforms(e){let{gl:t,state:n}=this,r=0,i=0;for(let a of e)for(let e of a.bindings){let a=this.get(e);if(e.isUniformsGroup||e.isUniformBuffer){let e=r++;n.bindBufferBase(t.UNIFORM_BUFFER,e,a.bufferGPU)}else if(e.isSampledTexture){let e=i++;n.bindTexture(a.glTextureType,a.textureGPU,t.TEXTURE0+e)}}}_resolveRenderTarget(e){let{gl:t,state:n}=this,r=e.renderTarget;if(e.textures!==null&&r){let i=this.get(r);if(r.samples>0&&i.msaaFrameBuffer!==void 0&&this._useMultisampledExtension(r)===!1){let a=i.framebuffers[e.getCacheKey()],o=r.resolveColorBuffer===!1?0:t.COLOR_BUFFER_BIT;r.resolveDepthBuffer&&(r.depthBuffer&&(o|=t.DEPTH_BUFFER_BIT),r.stencilBuffer&&r.resolveStencilBuffer&&(o|=t.STENCIL_BUFFER_BIT));let s=i.msaaFrameBuffer,c=i.msaaRenderbuffers,l=e.textures,u=l.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,s),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,a),u)for(let e=0;e<l.length;e++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);for(let n=0;n<l.length;n++){if(u){let{textureGPU:e}=this.get(l[n]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,c[n]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){let{x:n,y:r,width:i,height:a}=e.scissorValue,s=e.height-a-r;t.blitFramebuffer(n,s,n+i,s+a,n,s,n+i,s+a,o,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,o,t.NEAREST)}if(u)for(let e=0;e<l.length;e++){let{textureGPU:n}=this.get(l[e]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,c[e]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,n,0)}if(this._supportsInvalidateFramebuffer===!0){if(r.storeMultisampledColorBuffer===!1)for(let e=0;e<l.length;e++)wj.push(t.COLOR_ATTACHMENT0+e);r.depthBuffer&&r.storeMultisampledDepthBuffer===!1&&wj.push(r.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),wj.length>0&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,wj),wj.length=0)}}else if(this._supportsInvalidateFramebuffer===!0&&i.framebuffers&&(r._autoAllocateDepthBuffer===!0||r.samples>0&&r.storeMultisampledDepthBuffer===!1)){let r=i.framebuffers[e.getCacheKey()];n.bindFramebuffer(t.DRAW_FRAMEBUFFER,r),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,i.depthInvalidationArray)}}}_useMultisampledExtension(e){return e.multiview===!0||e.samples>0&&this.extensions.has(`WEBGL_multisampled_render_to_texture`)===!0&&e._autoAllocateDepthBuffer!==!1}async dispose(){await super.dispose(),this.textureUtils!==null&&this.textureUtils.dispose();let e=this.extensions.get(`WEBGL_lose_context`);e&&e.loseContext(),this.renderer.domElement.removeEventListener(`webglcontextlost`,this._onContextLost)}},Ej={PointList:`point-list`,LineList:`line-list`,LineStrip:`line-strip`,TriangleList:`triangle-list`},Dj=typeof self<`u`&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},Oj={Never:`never`,Less:`less`,Equal:`equal`,LessEqual:`less-equal`,Greater:`greater`,NotEqual:`not-equal`,GreaterEqual:`greater-equal`,Always:`always`},kj={Store:`store`,Discard:`discard`},Aj={Load:`load`,Clear:`clear`},jj={CCW:`ccw`,CW:`cw`},Mj={None:`none`,Back:`back`},Nj={Uint16:`uint16`,Uint32:`uint32`},Q={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`},Pj={ClampToEdge:`clamp-to-edge`,Repeat:`repeat`,MirrorRepeat:`mirror-repeat`},Fj={Linear:`linear`,Nearest:`nearest`},Ij={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`},Lj={Add:`add`,Subtract:`subtract`,ReverseSubtract:`reverse-subtract`,Min:`min`,Max:`max`},Rj={None:0,All:15},zj={Keep:`keep`,Zero:`zero`,Replace:`replace`,Invert:`invert`,IncrementClamp:`increment-clamp`,DecrementClamp:`decrement-clamp`,IncrementWrap:`increment-wrap`,DecrementWrap:`decrement-wrap`},Bj={Storage:`storage`,ReadOnlyStorage:`read-only-storage`},Vj={WriteOnly:`write-only`,ReadOnly:`read-only`,ReadWrite:`read-write`},Hj={NonFiltering:`non-filtering`,Comparison:`comparison`},Uj={Float:`float`,UnfilterableFloat:`unfilterable-float`,Depth:`depth`,SInt:`sint`,UInt:`uint`},Wj={TwoD:`2d`,ThreeD:`3d`},Gj={TwoD:`2d`,TwoDArray:`2d-array`,Cube:`cube`,ThreeD:`3d`},Kj={All:`all`},qj={Vertex:`vertex`,Instance:`instance`},Jj={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`},Yj={"texture-compression-s3tc":`texture-compression-bc`,"texture-compression-etc1":`texture-compression-etc2`},Xj=class extends VA{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){let{textureNode:e}=this;return this.texture===e.value?super.update():(this.texture=e.value,!0)}},Zj=class extends MA{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}},Qj=0,$j=class extends Zj{constructor(e,t){let n=e&&e.name?e.name:Qj++;super(`StorageBuffer_`+n,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:em.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}},eM=[null],tM=class{constructor(e){this.backend=e,this._preferredCanvasFormat=null}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=e.depthTexture===null?e.stencil?this.backend.renderer.reversedDepthBuffer===!0?Q.Depth32FloatStencil8:Q.Depth24PlusStencil8:this.backend.renderer.reversedDepthBuffer===!0?Q.Depth32Float:Q.Depth24Plus:this.getTextureFormatGPU(e.depthTexture)),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){let n=this.backend.get(e);t=n.texture===void 0?this.backend.renderer.currentSamples:n.texture.sampleCount}else e.renderTarget&&(t=e.renderTarget.samples);t=this.getSampleCount(t||1);let n=t>1&&e.renderTarget!==null&&e.isDepthTexture!==!0&&e.isFramebufferTexture!==!0,r=t>1&&e.renderTarget!==null&&e.isDepthTexture===!0&&e.isArrayTexture===!0;return{samples:t,primarySamples:n||r?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return t=e.textures===null?this.getPreferredCanvasFormat():this.getTextureFormatGPU(e.textures[0]),t}getCurrentColorFormats(e){return e.textures===null?[this.getPreferredCanvasFormat()]:e.textures.map(e=>this.getTextureFormatGPU(e))}getCurrentColorSpace(e){return e.textures===null?this.backend.renderer.outputColorSpace:e.textures[0].colorSpace}getPrimitiveTopology(e,t){if(e.isPoints)return Ej.PointList;if(e.isLineSegments||e.isMesh&&t.wireframe===!0)return Ej.LineList;if(e.isLine)return Ej.LineStrip;if(e.isMesh)return Ej.TriangleList}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return e.textures===null?this.getSampleCount(this.backend.renderer.currentSamples):this.getSampleCount(e.sampleCount)}getPreferredCanvasFormat(){let e=this.backend.parameters.outputType;if(e===void 0)return this._preferredCanvasFormat===null&&(this._preferredCanvasFormat=navigator.gpu.getPreferredCanvasFormat()),this._preferredCanvasFormat;if(e===1009)return Q.BGRA8Unorm;if(e===1016)return Q.RGBA16Float;throw Error(`THREE.WebGPUUtils: Unsupported output buffer type.`)}};function nM(e,t){eM[0]=t,e.queue.submit(eM),eM[0]=null}var rM=class{constructor(){this.label=``,this.layout=null,this.entries=[]}reset(){this.label=``,this.layout=null,this.entries.length=0}},iM=class{constructor(){this.label=``,this.size=0,this.usage=0,this.mappedAtCreation=!1}reset(){this.label=``,this.size=0,this.usage=0,this.mappedAtCreation=!1}},aM=class{constructor(){this.label=``}reset(){this.label=``}},oM=class{constructor(){this.label=``,this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}reset(){this.label=``,this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}},sM=class{constructor(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}reset(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}},cM=class{constructor(){this.label=``,this.colorAttachments=[],this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}reset(){this.label=``,this.colorAttachments.length=0,this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}},lM=class{constructor(){this.label=``,this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample=new uM,this.fragment=null}reset(){this.label=``,this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample.reset(),this.fragment=null}},uM=class{constructor(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}reset(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}},dM=class{constructor(){this.label=``,this.code=``,this.compilationHints=[]}reset(){this.label=``,this.code=``,this.compilationHints.length=0}},fM=class{constructor(){this.label=``,this.size={width:0,height:1,depthOrArrayLayers:1},this.mipLevelCount=1,this.sampleCount=1,this.dimension=`2d`,this.format=void 0,this.usage=void 0,this.viewFormats=[],this.textureBindingViewDimension=void 0}reset(){this.label=``,this.size.width=0,this.size.height=1,this.size.depthOrArrayLayers=1,this.mipLevelCount=1,this.sampleCount=1,this.dimension=`2d`,this.format=void 0,this.usage=void 0,this.viewFormats.length=0,this.textureBindingViewDimension=void 0}},pM=class{constructor(){this.label=``,this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect=`all`,this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle=`rgba`}reset(){this.label=``,this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect=`all`,this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle=`rgba`}},mM=new rM,hM=new iM,gM=new aM,_M=new oM,vM=new cM,yM=new lM,bM=new sM,xM=new dM,SM=new fM,CM=new pM,wM=class extends EE{constructor(e){super(),this.device=e,this.mipmapSampler=e.createSampler({minFilter:Fj.Linear}),this.flipYSampler=e.createSampler({minFilter:Fj.Nearest}),hM.size=4,hM.usage=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,this.flipUniformBuffer=e.createBuffer(hM),hM.reset(),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),hM.size=4,hM.usage=GPUBufferUsage.UNIFORM,this.noFlipUniformBuffer=e.createBuffer(hM),hM.reset(),this.transferPipelines={},xM.label=`mipmap`,xM.code=`
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.mipmapShaderModule=e.createShaderModule(xM),xM.reset()}getTransferPipeline(e,t){t||=`2d-array`;let n=`${e}-${t}`,r=this.transferPipelines[n];return r===void 0&&(yM.label=`mipmap-${e}-${t}`,yM.vertex={module:this.mipmapShaderModule},yM.fragment={module:this.mipmapShaderModule,entryPoint:`main_${t.replace(`-`,`_`)}`,targets:[{format:e}]},yM.layout=`auto`,r=this.device.createRenderPipeline(yM),yM.reset(),this.transferPipelines[n]=r),r}flipY(e,t,n=0){let r=t.format,{width:i,height:a}=t.size;SM.size.width=i,SM.size.height=a,SM.format=r,SM.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING;let o=this.device.createTexture(SM);SM.reset();let s=this.getTransferPipeline(r,e.textureBindingViewDimension),c=this.getTransferPipeline(r,o.textureBindingViewDimension),l=this.device.createCommandEncoder(gM),u=(e,t,n,r,i,a)=>{let o=e.getBindGroupLayout(0);CM.dimension=t.textureBindingViewDimension||`2d-array`,CM.mipLevelCount=1;let s=t.createView(CM);CM.reset(),mM.layout=o,mM.entries.push({binding:0,resource:this.flipYSampler},{binding:1,resource:s},{binding:2,resource:{buffer:a?this.flipUniformBuffer:this.noFlipUniformBuffer}});let c=this.device.createBindGroup(mM);mM.reset(),CM.dimension=`2d`,CM.mipLevelCount=1,CM.baseArrayLayer=i,CM.arrayLayerCount=1;let u=r.createView(CM);CM.reset(),bM.view=u,bM.loadOp=Aj.Clear,bM.storeOp=kj.Store,vM.colorAttachments.push(bM);let d=l.beginRenderPass(vM);vM.reset(),bM.reset(),d.setPipeline(e),d.setBindGroup(0,c),d.draw(3,1,0,n),d.end()};u(s,e,n,o,0,!1),u(c,o,0,e,n,!0),nM(this.device,l.finish()),o.destroy()}generateMipmaps(e,t=null){let n=this.get(e),r=n.layers||this._mipmapCreateBundles(e),i=t;i===null&&(gM.label=`mipmapEncoder`,i=this.device.createCommandEncoder(gM),gM.reset()),this._mipmapRunBundles(i,r),t===null&&nM(this.device,i.finish()),n.layers=r}_mipmapCreateBundles(e){let t=e.textureBindingViewDimension||`2d-array`,n=this.getTransferPipeline(e.format,t),r=n.getBindGroupLayout(0),i=[];for(let a=1;a<e.mipLevelCount;a++)for(let o=0;o<e.depthOrArrayLayers;o++){CM.dimension=t,CM.baseMipLevel=a-1,CM.mipLevelCount=1;let s=e.createView(CM);CM.reset(),mM.layout=r,mM.entries.push({binding:0,resource:this.mipmapSampler},{binding:1,resource:s},{binding:2,resource:{buffer:this.noFlipUniformBuffer}});let c=this.device.createBindGroup(mM);mM.reset(),CM.dimension=`2d`,CM.baseMipLevel=a,CM.mipLevelCount=1,CM.baseArrayLayer=o,CM.arrayLayerCount=1;let l=e.createView(CM);CM.reset();let u=new sM;u.view=l,u.loadOp=Aj.Clear,u.storeOp=kj.Store;let d=new cM;d.colorAttachments.push(u),_M.colorFormats=[e.format];let f=this.device.createRenderBundleEncoder(_M);_M.reset(),f.setPipeline(n),f.setBindGroup(0,c),f.draw(3,1,0,o),i.push({renderBundles:[f.finish()],passDescriptor:d})}return i}_mipmapRunBundles(e,t){let n=t.length;for(let r=0;r<n;r++){let n=t[r],i=e.beginRenderPass(n.passDescriptor);i.executeBundles(n.renderBundles),i.end()}}},TM=class{constructor(){this.label=``,this.addressModeU=`clamp-to-edge`,this.addressModeV=`clamp-to-edge`,this.addressModeW=`clamp-to-edge`,this.magFilter=`nearest`,this.minFilter=`nearest`,this.mipmapFilter=`nearest`,this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}reset(){this.label=``,this.addressModeU=`clamp-to-edge`,this.addressModeV=`clamp-to-edge`,this.addressModeW=`clamp-to-edge`,this.magFilter=`nearest`,this.minFilter=`nearest`,this.mipmapFilter=`nearest`,this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}},EM=class{constructor(){this.texture=null,this.mipLevel=0,this.origin={x:0,y:0,z:0},this.aspect=`all`}reset(){this.texture=null,this.mipLevel=0,this.origin.x=0,this.origin.y=0,this.origin.z=0,this.aspect=`all`}},DM=class{constructor(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},OM=class{constructor(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},kM=class{constructor(){this.source=null,this.origin={x:0,y:0},this.flipY=!1}reset(){this.source=null,this.origin.x=0,this.origin.y=0,this.flipY=!1}},AM=class extends EM{constructor(){super(),this.colorSpace=`srgb`,this.premultipliedAlpha=!1}reset(){super.reset(),this.colorSpace=`srgb`,this.premultipliedAlpha=!1}},jM=class{constructor(){this.width=0,this.height=1,this.depthOrArrayLayers=1}reset(){this.width=0,this.height=1,this.depthOrArrayLayers=1}},MM=new iM,NM=new aM,PM=new TM,FM=new EM,IM=new DM,LM=new OM,RM=new kM,zM=new AM,BM=new fM,VM=new jM,HM={512:`never`,513:`less`,514:`equal`,515:`less-equal`,516:`greater`,518:`greater-equal`,519:`always`,517:`not-equal`},UM=[0,1,3,2,4,5];function WM(e,t,n,r,i,a,o,s,c,l){FM.texture=t,FM.mipLevel=n,FM.origin.z=r,LM.offset=r*a,LM.bytesPerRow=o,LM.rowsPerImage=s,VM.width=c,VM.height=l,e.queue.writeTexture(FM,i.data,LM,VM),FM.reset(),LM.reset(),VM.reset()}var GM=class{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){let t=this.backend,n=e.texture,r=e.textureNode,i=n.isDepthTexture===!0&&n.compareFunction!==null&&r.isSampleCompare()&&t.hasCompatibility(kt.TEXTURE_COMPARE),a=n.minFilter+`-`+n.magFilter+`-`+n.wrapS+`-`+n.wrapT+`-`+(n.wrapR||`0`)+`-`+n.anisotropy+`-`+ +(n.isDepthTexture===!0)+`-`+(i?n.compareFunction:0),o=this._samplerCache.get(a);if(o===void 0){PM.addressModeU=this._convertAddressMode(n.wrapS),PM.addressModeV=this._convertAddressMode(n.wrapT),PM.addressModeW=this._convertAddressMode(n.wrapR),PM.magFilter=this._convertFilterMode(n.magFilter),PM.minFilter=this._convertFilterMode(n.minFilter),PM.mipmapFilter=this._convertMipmapFilterMode(n.minFilter),n.isDepthTexture&&i===!1&&(PM.magFilter=Fj.Nearest,PM.minFilter=Fj.Nearest,PM.mipmapFilter=Fj.Nearest),PM.magFilter===Fj.Linear&&PM.minFilter===Fj.Linear&&PM.mipmapFilter===Fj.Linear&&(PM.maxAnisotropy=n.anisotropy),i&&(PM.compare=HM[n.compareFunction]);let e=t.device.createSampler(PM);PM.reset(),o={sampler:e,usedTimes:0},this._samplerCache.set(a,o)}let s=t.get(e);return s.sampler!==o.sampler&&(this._releaseSampler(s),s.samplerKey=a,s.sampler=o.sampler,o.usedTimes++),a}destroySampler(e){this._releaseSampler(this.backend.get(e))}_releaseSampler(e){if(e.sampler!==void 0){let t=this._samplerCache.get(e.samplerKey);t.usedTimes--,t.usedTimes===0&&this._samplerCache.delete(e.samplerKey),e.sampler=void 0,e.samplerKey=void 0}}createDefaultTexture(e){let t,n=KM(e,this.backend.device);t=e.isCubeTexture?this._getDefaultCubeTextureGPU(n):this._getDefaultTextureGPU(n),this.backend.get(e).texture=t}createTexture(e,t={}){let n=this.backend,r=n.get(e);if(r.initialized){if(r.externalTexture===!0)return;throw Error(`THREE.WebGPUTextureUtils: Texture already initialized.`)}if(e.isExternalTexture){r.texture=e.sourceTexture,r.initialized=!0;return}t.needsMipmaps===void 0&&(t.needsMipmaps=!1),t.levels===void 0&&(t.levels=1),t.depth===void 0&&(t.depth=1);let{width:i,height:a,depth:o,levels:s}=t;e.isFramebufferTexture&&(t.format=t.renderTarget?this.backend.utils.getCurrentColorFormat(t.renderTarget):this.backend.utils.getPreferredCanvasFormat());let c=this._getDimension(e),l=e.internalFormat||t.format||KM(e,n.device);r.format=l;let{samples:u,primarySamples:d,isMSAA:f}=n.utils.getTextureSampleData(e),p=e.renderTarget,m=u>1&&p!==null&&o>1&&c===Wj.TwoD,h=GPUTextureUsage.TRANSIENT_ATTACHMENT!==void 0&&m===!1,g=e.isDepthTexture===!0&&h&&p?.storeMultisampledDepthBuffer===!1&&(p.stencilBuffer===!1||p.storeMultisampledStencilBuffer===!1),_=e.isDepthTexture!==!0&&h&&p?.storeMultisampledColorBuffer===!1,v=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;e.isStorageTexture===!0&&(v|=GPUTextureUsage.STORAGE_BINDING),e.isCompressedTexture!==!0&&e.isCompressedArrayTexture!==!0&&l!==Q.RGB9E5UFloat&&(v|=GPUTextureUsage.RENDER_ATTACHMENT),d>1&&g&&(v=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT);let y=new fM;if(y.label=e.name,y.size.width=i,y.size.height=a,y.size.depthOrArrayLayers=o,y.mipLevelCount=s,y.sampleCount=d,y.dimension=c,y.format=l,y.usage=v,l===void 0){M(`WebGPURenderer: Texture format not supported.`),this.createDefaultTexture(e);return}e.isCubeTexture&&(y.textureBindingViewDimension=Gj.Cube);try{r.texture=n.device.createTexture(y)}catch{M(`WebGPURenderer: Failed to create texture with descriptor:`,y),this.createDefaultTexture(e);return}if(f||m){let e=Object.assign({},y);if(e.label+=`-msaa`,e.sampleCount=u,e.mipLevelCount=1,(g||_)&&(e.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT),m){e.size=Object.assign({},e.size,{depthOrArrayLayers:1}),r.msaaTextures=[];for(let t=0;t<o;t++)e.label=y.label+`-msaa-`+t,r.msaaTextures.push(n.device.createTexture(e))}else r.msaaTexture=n.device.createTexture(e)}r.initialized=!0,r.textureDescriptorGPU=y}destroyTexture(e,t=!1){let n=this.backend,r=n.get(e);if(r.texture!==void 0&&t===!1&&e.isExternalTexture!==!0&&r.externalTexture!==!0&&r.texture.destroy(),r.msaaTexture!==void 0&&r.msaaTexture.destroy(),r.msaaTextures!==void 0)for(let e of r.msaaTextures)e.destroy();n.delete(e)}generateMipmaps(e,t=null){let n=this.backend.get(e);this._generateMipmaps(n.texture,t)}getColorBuffer(){let e=this.backend,t=e.renderer.getCanvasTarget(),{width:n,height:r}=e.getDrawingBufferSize(),i=e.renderer.currentSamples,a=t.colorTexture,o=e.get(a);if(a.width===n&&a.height===r&&a.samples===i)return o.texture;let s=o.texture;return s&&s.destroy(),BM.label=`colorBuffer`,BM.size.width=n,BM.size.height=r,BM.sampleCount=e.utils.getSampleCount(e.renderer.currentSamples),BM.format=e.utils.getPreferredCanvasFormat(),BM.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,s=e.device.createTexture(BM),BM.reset(),a.source.width=n,a.source.height=r,a.samples=i,o.texture=s,s}getDepthBuffer(e=!0,t=!1){let n=this.backend,r=n.renderer.getCanvasTarget(),{width:i,height:a}=n.getDrawingBufferSize(),o=n.renderer.currentSamples,s=r.depthTexture;if(s.width===i&&s.height===a&&s.samples===o&&s.depth===e&&s.stencil===t)return n.get(s).texture;let c=n.get(s).texture,l,u;if(t?(l=ve,u=n.renderer.reversedDepthBuffer===!0?se:de):e&&(l=_e,u=n.renderer.reversedDepthBuffer===!0?se:oe),c!==void 0){if(s.image.width===i&&s.image.height===a&&s.format===l&&s.type===u&&s.samples===o)return c;this.destroyTexture(s)}return s.name=`depthBuffer`,s.format=l,s.type=u,s.image.width=i,s.image.height=a,s.samples=o,this.createTexture(s,{width:i,height:a}),n.get(s).texture}updateTexture(e,t){let n=this.backend.get(e),r=e.mipmaps,{textureDescriptorGPU:i}=n;if(!(e.isRenderTargetTexture||i===void 0)){if(e.isDataTexture){if(r.length>0)for(let t=0,a=r.length;t<a;t++){let a=r[t];this._copyBufferToTexture(a,n.texture,i,0,e.flipY,0,t)}else this._copyBufferToTexture(t.image,n.texture,i,0,e.flipY)}else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture){if(e.layerUpdates&&e.layerUpdates.size>0){for(let r of e.layerUpdates)this._copyBufferToTexture(t.image,n.texture,i,r,e.flipY,r);e.clearLayerUpdates()}else for(let r=0;r<t.image.depth;r++)this._copyBufferToTexture(t.image,n.texture,i,r,e.flipY,r)}else if(e.isCompressedTexture||e.isCompressedArrayTexture)e.isCompressedArrayTexture&&e.layerUpdates.size>0?(this._copyCompressedBufferToTexture(e.mipmaps,n.texture,i,e.layerUpdates),e.clearLayerUpdates()):this._copyCompressedBufferToTexture(e.mipmaps,n.texture,i);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,n.texture,i);else if(e.isHTMLTexture){let t=this.backend.device,r=this.backend.renderer.domElement,a=e.image;if(typeof t.queue.copyElementImageToTexture!=`function`)return;if(!n.hasPaintCallback){n.hasPaintCallback=!0,r.requestPaint();return}let o=i.size.width,s=i.size.height;t.queue.copyElementImageToTexture.length===2?t.queue.copyElementImageToTexture({source:a},{destination:{texture:n.texture},width:o,height:s}):t.queue.copyElementImageToTexture(a,o,s,{texture:n.texture}),e.flipY&&this._flipY(n.texture,i)}else if(r.length>0)for(let t=0,a=r.length;t<a;t++){let a=r[t];this._copyImageToTexture(a,n.texture,i,0,e.flipY,e.premultiplyAlpha,t)}else this._copyImageToTexture(t.image,n.texture,i,0,e.flipY,e.premultiplyAlpha);n.version=e.version}}async copyTextureToBuffer(e,t,n,r,i,a){let o=this.backend.device,s=this.backend.get(e),c=s.texture,l=s.textureDescriptorGPU.format,u=this._getBytesPerTexel(l),d=r*u;d=Math.ceil(d/256)*256,MM.size=(i-1)*d+r*u,MM.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;let f=o.createBuffer(MM);MM.reset();let p=o.createCommandEncoder(NM);FM.texture=c,FM.origin.x=t,FM.origin.y=n,FM.origin.z=a,IM.buffer=f,IM.bytesPerRow=d,VM.width=r,VM.height=i,p.copyTextureToBuffer(FM,IM,VM),FM.reset(),IM.reset(),VM.reset();let m=this._getTypedArrayType(l);nM(o,p.finish()),await f.mapAsync(GPUMapMode.READ);let h=f.getMappedRange().slice();return f.destroy(),new m(h)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){let n=new Pn;n.minFilter=T,n.magFilter=T,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){let n=new va;n.minFilter=T,n.magFilter=T,this.createTexture(n,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=n}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,n){let r=e.images,i=e.mipmaps;for(let a=0;a<6;a++){let o=r[a],s=e.flipY===!0?UM[a]:a;o.isDataTexture?this._copyBufferToTexture(o.image,t,n,s,e.flipY):this._copyImageToTexture(o,t,n,s,e.flipY,e.premultiplyAlpha);for(let r=0;r<i.length;r++){let o=i[r].images[a];o.isDataTexture?this._copyBufferToTexture(o.image,t,n,s,e.flipY,0,r+1):this._copyImageToTexture(o,t,n,s,e.flipY,e.premultiplyAlpha,r+1)}}}_copyImageToTexture(e,t,n,r,i,a,o=0){let s=this.backend.device,c=o>0?e.width:n.size.width,l=o>0?e.height:n.size.height;RM.source=e,RM.flipY=i,zM.texture=t,zM.mipLevel=o,zM.origin.z=r,zM.premultipliedAlpha=a,VM.width=c,VM.height=l;try{s.queue.copyExternalImageToTexture(RM,zM,VM)}catch{}finally{RM.reset(),zM.reset(),VM.reset()}}_getPassUtils(){let e=this._passUtils;return e===null&&(this._passUtils=e=new wM(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,r,i,a=0,o=0){let s=this.backend.device,c=e.data,l=this._getBytesPerTexel(n.format),u=e.width*l;FM.texture=t,FM.mipLevel=o,FM.origin.z=r,LM.offset=e.width*e.height*l*a,LM.bytesPerRow=u,VM.width=e.width,VM.height=e.height,s.queue.writeTexture(FM,c,LM,VM),FM.reset(),LM.reset(),VM.reset(),i===!0&&this._flipY(t,n,r)}_copyCompressedBufferToTexture(e,t,n,r=null){let i=this.backend.device,a=this._getBlockData(n.format),o=n.size.depthOrArrayLayers>1,s=r&&r.size>0?r:null;for(let r=0;r<e.length;r++){let c=e[r],l=c.width,u=c.height,d=o?n.size.depthOrArrayLayers:1,f=Math.ceil(l/a.width)*a.byteLength,p=Math.ceil(u/a.height),m=f*p,h=Math.ceil(l/a.width)*a.width,g=p*a.height;if(s!==null)for(let e of s)WM(i,t,r,e,c,m,f,p,h,g);else for(let e=0;e<d;e++)WM(i,t,r,e,c,m,f,p,h,g)}}_getBlockData(e){if(e===Q.BC1RGBAUnorm||e===Q.BC1RGBAUnormSRGB)return{byteLength:8,width:4,height:4};if(e===Q.BC2RGBAUnorm||e===Q.BC2RGBAUnormSRGB||e===Q.BC3RGBAUnorm||e===Q.BC3RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===Q.BC4RUnorm||e===Q.BC4RSnorm)return{byteLength:8,width:4,height:4};if(e===Q.BC5RGUnorm||e===Q.BC5RGSnorm||e===Q.BC6HRGBUFloat||e===Q.BC6HRGBFloat||e===Q.BC7RGBAUnorm||e===Q.BC7RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===Q.ETC2RGB8Unorm||e===Q.ETC2RGB8UnormSRGB||e===Q.ETC2RGB8A1Unorm||e===Q.ETC2RGB8A1UnormSRGB)return{byteLength:8,width:4,height:4};if(e===Q.ETC2RGBA8Unorm||e===Q.ETC2RGBA8UnormSRGB)return{byteLength:16,width:4,height:4};if(e===Q.EACR11Unorm||e===Q.EACR11Snorm)return{byteLength:8,width:4,height:4};if(e===Q.EACRG11Unorm||e===Q.EACRG11Snorm||e===Q.ASTC4x4Unorm||e===Q.ASTC4x4UnormSRGB)return{byteLength:16,width:4,height:4};if(e===Q.ASTC5x4Unorm||e===Q.ASTC5x4UnormSRGB)return{byteLength:16,width:5,height:4};if(e===Q.ASTC5x5Unorm||e===Q.ASTC5x5UnormSRGB)return{byteLength:16,width:5,height:5};if(e===Q.ASTC6x5Unorm||e===Q.ASTC6x5UnormSRGB)return{byteLength:16,width:6,height:5};if(e===Q.ASTC6x6Unorm||e===Q.ASTC6x6UnormSRGB)return{byteLength:16,width:6,height:6};if(e===Q.ASTC8x5Unorm||e===Q.ASTC8x5UnormSRGB)return{byteLength:16,width:8,height:5};if(e===Q.ASTC8x6Unorm||e===Q.ASTC8x6UnormSRGB)return{byteLength:16,width:8,height:6};if(e===Q.ASTC8x8Unorm||e===Q.ASTC8x8UnormSRGB)return{byteLength:16,width:8,height:8};if(e===Q.ASTC10x5Unorm||e===Q.ASTC10x5UnormSRGB)return{byteLength:16,width:10,height:5};if(e===Q.ASTC10x6Unorm||e===Q.ASTC10x6UnormSRGB)return{byteLength:16,width:10,height:6};if(e===Q.ASTC10x8Unorm||e===Q.ASTC10x8UnormSRGB)return{byteLength:16,width:10,height:8};if(e===Q.ASTC10x10Unorm||e===Q.ASTC10x10UnormSRGB)return{byteLength:16,width:10,height:10};if(e===Q.ASTC12x10Unorm||e===Q.ASTC12x10UnormSRGB)return{byteLength:16,width:12,height:10};if(e===Q.ASTC12x12Unorm||e===Q.ASTC12x12UnormSRGB)return{byteLength:16,width:12,height:12}}_convertAddressMode(e){let t=Pj.ClampToEdge;return e===1e3?t=Pj.Repeat:e===1002&&(t=Pj.MirrorRepeat),t}_convertFilterMode(e){let t=Fj.Linear;return(e===1003||e===1004||e===1005)&&(t=Fj.Nearest),t}_convertMipmapFilterMode(e){return e===1005||e===1008?Fj.Linear:Fj.Nearest}_getBytesPerTexel(e){if(e===Q.R8Unorm||e===Q.R8Snorm||e===Q.R8Uint||e===Q.R8Sint)return 1;if(e===Q.R16Uint||e===Q.R16Sint||e===Q.R16Float||e===Q.RG8Unorm||e===Q.RG8Snorm||e===Q.RG8Uint||e===Q.RG8Sint||e===Q.R16Unorm||e===Q.R16Snorm)return 2;if(e===Q.R32Uint||e===Q.R32Sint||e===Q.R32Float||e===Q.RG16Uint||e===Q.RG16Sint||e===Q.RG16Float||e===Q.RGBA8Unorm||e===Q.RGBA8UnormSRGB||e===Q.RGBA8Snorm||e===Q.RGBA8Uint||e===Q.RGBA8Sint||e===Q.BGRA8Unorm||e===Q.BGRA8UnormSRGB||e===Q.RG16Unorm||e===Q.RG16Snorm||e===Q.RGB9E5UFloat||e===Q.RGB10A2Unorm||e===Q.RG11B10UFloat||e===Q.Depth32Float||e===Q.Depth24Plus||e===Q.Depth24PlusStencil8||e===Q.Depth32FloatStencil8)return 4;if(e===Q.RG32Uint||e===Q.RG32Sint||e===Q.RG32Float||e===Q.RGBA16Uint||e===Q.RGBA16Sint||e===Q.RGBA16Float||e===Q.RGBA16Unorm||e===Q.RGBA16Snorm)return 8;if(e===Q.RGBA32Uint||e===Q.RGBA32Sint||e===Q.RGBA32Float)return 16}_getTypedArrayType(e){if(e===Q.R8Uint)return Uint8Array;if(e===Q.R8Sint)return Int8Array;if(e===Q.R8Unorm)return Uint8Array;if(e===Q.R8Snorm)return Int8Array;if(e===Q.RG8Uint)return Uint8Array;if(e===Q.RG8Sint)return Int8Array;if(e===Q.RG8Unorm)return Uint8Array;if(e===Q.RG8Snorm)return Int8Array;if(e===Q.RGBA8Uint)return Uint8Array;if(e===Q.RGBA8Sint)return Int8Array;if(e===Q.RGBA8Unorm||e===Q.RGBA8UnormSRGB)return Uint8Array;if(e===Q.RGBA8Snorm)return Int8Array;if(e===Q.R16Uint)return Uint16Array;if(e===Q.R16Sint)return Int16Array;if(e===Q.RG16Uint)return Uint16Array;if(e===Q.RG16Sint)return Int16Array;if(e===Q.RGBA16Uint)return Uint16Array;if(e===Q.RGBA16Sint)return Int16Array;if(e===Q.R16Float||e===Q.RG16Float||e===Q.RGBA16Float||e===Q.R16Unorm)return Uint16Array;if(e===Q.R16Snorm)return Int16Array;if(e===Q.RG16Unorm)return Uint16Array;if(e===Q.RG16Snorm)return Int16Array;if(e===Q.RGBA16Unorm)return Uint16Array;if(e===Q.RGBA16Snorm)return Int16Array;if(e===Q.R32Uint)return Uint32Array;if(e===Q.R32Sint)return Int32Array;if(e===Q.R32Float)return Float32Array;if(e===Q.RG32Uint)return Uint32Array;if(e===Q.RG32Sint)return Int32Array;if(e===Q.RG32Float)return Float32Array;if(e===Q.RGBA32Uint)return Uint32Array;if(e===Q.RGBA32Sint)return Int32Array;if(e===Q.RGBA32Float)return Float32Array;if(e===Q.BGRA8Unorm||e===Q.BGRA8UnormSRGB)return Uint8Array;if(e===Q.RGB10A2Unorm||e===Q.RGB9E5UFloat||e===Q.RG11B10UFloat)return Uint32Array;if(e===Q.Depth32Float)return Float32Array;if(e===Q.Depth24Plus||e===Q.Depth24PlusStencil8)return Uint32Array;if(e===Q.Depth32FloatStencil8)return Float32Array}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?Wj.ThreeD:Wj.TwoD,t}};function KM(e,t){let n=e.format,r=e.type,i=e.normalized,a=e.colorSpace,o=I.getTransfer(a),s,c=!1;if(i&&(c=t.features.has(Jj.TextureFormatsTier1),c===!1&&M(`WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.`)),e.isCompressedTexture===!0||e.isCompressedArrayTexture===!0)switch(n){case Te:case Ee:s=o===`srgb`?Q.BC1RGBAUnormSRGB:Q.BC1RGBAUnorm;break;case De:s=o===`srgb`?Q.BC2RGBAUnormSRGB:Q.BC2RGBAUnorm;break;case Oe:s=o===`srgb`?Q.BC3RGBAUnormSRGB:Q.BC3RGBAUnorm;break;case tt:s=Q.BC4RUnorm;break;case nt:s=Q.BC4RSnorm;break;case rt:s=Q.BC5RGUnorm;break;case it:s=Q.BC5RGSnorm;break;case Qe:s=o===`srgb`?Q.BC7RGBAUnormSRGB:Q.BC7RGBAUnorm;break;case $e:s=Q.BC6HRGBFloat;break;case et:s=Q.BC6HRGBUFloat;break;case Pe:case Ne:s=o===`srgb`?Q.ETC2RGB8UnormSRGB:Q.ETC2RGB8Unorm;break;case Fe:s=o===`srgb`?Q.ETC2RGBA8UnormSRGB:Q.ETC2RGBA8Unorm;break;case Ie:s=Q.EACR11Unorm;break;case Le:s=Q.EACR11Snorm;break;case Re:s=Q.EACRG11Unorm;break;case A:s=Q.EACRG11Snorm;break;case ze:s=o===`srgb`?Q.ASTC4x4UnormSRGB:Q.ASTC4x4Unorm;break;case Be:s=o===`srgb`?Q.ASTC5x4UnormSRGB:Q.ASTC5x4Unorm;break;case Ve:s=o===`srgb`?Q.ASTC5x5UnormSRGB:Q.ASTC5x5Unorm;break;case j:s=o===`srgb`?Q.ASTC6x5UnormSRGB:Q.ASTC6x5Unorm;break;case He:s=o===`srgb`?Q.ASTC6x6UnormSRGB:Q.ASTC6x6Unorm;break;case Ue:s=o===`srgb`?Q.ASTC8x5UnormSRGB:Q.ASTC8x5Unorm;break;case We:s=o===`srgb`?Q.ASTC8x6UnormSRGB:Q.ASTC8x6Unorm;break;case Ge:s=o===`srgb`?Q.ASTC8x8UnormSRGB:Q.ASTC8x8Unorm;break;case Ke:s=o===`srgb`?Q.ASTC10x5UnormSRGB:Q.ASTC10x5Unorm;break;case qe:s=o===`srgb`?Q.ASTC10x6UnormSRGB:Q.ASTC10x6Unorm;break;case Je:s=o===`srgb`?Q.ASTC10x8UnormSRGB:Q.ASTC10x8Unorm;break;case Ye:s=o===`srgb`?Q.ASTC10x10UnormSRGB:Q.ASTC10x10Unorm;break;case Xe:s=o===`srgb`?Q.ASTC12x10UnormSRGB:Q.ASTC12x10Unorm;break;case Ze:s=o===`srgb`?Q.ASTC12x12UnormSRGB:Q.ASTC12x12Unorm;break;case ge:s=o===`srgb`?Q.RGBA8UnormSRGB:Q.RGBA8Unorm;break;default:N(`WebGPURenderer: Unsupported texture format.`,n)}else switch(n){case ge:switch(r){case ne:s=Q.RGBA8Snorm;break;case re:s=c?Q.RGBA16Snorm:Q.RGBA16Sint;break;case ie:s=c?Q.RGBA16Unorm:Q.RGBA16Uint;break;case oe:s=Q.RGBA32Uint;break;case ae:s=Q.RGBA32Sint;break;case te:s=o===`srgb`?Q.RGBA8UnormSRGB:Q.RGBA8Unorm;break;case ce:s=Q.RGBA16Float;break;case se:s=Q.RGBA32Float;break;default:N(`WebGPURenderer: Unsupported texture type with RGBAFormat.`,r)}break;case he:switch(r){case fe:s=Q.RGB9E5UFloat;break;case pe:s=Q.RG11B10UFloat;break;default:N(`WebGPURenderer: Unsupported texture type with RGBFormat.`,r)}break;case ye:switch(r){case ne:s=Q.R8Snorm;break;case re:s=c?Q.R16Snorm:Q.R16Sint;break;case ie:s=c?Q.R16Unorm:Q.R16Uint;break;case oe:s=Q.R32Uint;break;case ae:s=Q.R32Sint;break;case te:s=Q.R8Unorm;break;case ce:s=Q.R16Float;break;case se:s=Q.R32Float;break;default:N(`WebGPURenderer: Unsupported texture type with RedFormat.`,r)}break;case xe:switch(r){case ne:s=Q.RG8Snorm;break;case re:s=c?Q.RG16Snorm:Q.RG16Sint;break;case ie:s=c?Q.RG16Unorm:Q.RG16Uint;break;case oe:s=Q.RG32Uint;break;case ae:s=Q.RG32Sint;break;case te:s=Q.RG8Unorm;break;case ce:s=Q.RG16Float;break;case se:s=Q.RG32Float;break;default:N(`WebGPURenderer: Unsupported texture type with RGFormat.`,r)}break;case _e:switch(r){case ie:s=Q.Depth16Unorm;break;case oe:s=Q.Depth24Plus;break;case se:s=Q.Depth32Float;break;default:N(`WebGPURenderer: Unsupported texture type with DepthFormat.`,r)}break;case ve:switch(r){case de:s=Q.Depth24PlusStencil8;break;case se:t&&t.features.has(Jj.Depth32FloatStencil8)===!1&&N(`WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.`),s=Q.Depth32FloatStencil8;break;default:N(`WebGPURenderer: Unsupported texture type with DepthStencilFormat.`,r)}break;case be:switch(r){case ae:s=Q.R32Sint;break;case oe:s=Q.R32Uint;break;default:N(`WebGPURenderer: Unsupported texture type with RedIntegerFormat.`,r)}break;case Se:switch(r){case ae:s=Q.RG32Sint;break;case oe:s=Q.RG32Uint;break;default:N(`WebGPURenderer: Unsupported texture type with RGIntegerFormat.`,r)}break;case we:switch(r){case ae:s=Q.RGBA32Sint;break;case oe:s=Q.RGBA32Uint;break;default:N(`WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.`,r)}break;default:N(`WebGPURenderer: Unsupported texture format.`,n)}return s}var qM=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,JM=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,YM={f32:`float`,i32:`int`,u32:`uint`,bool:`bool`,"vec2<f32>":`vec2`,"vec2<i32>":`ivec2`,"vec2<u32>":`uvec2`,"vec2<bool>":`bvec2`,vec2f:`vec2`,vec2i:`ivec2`,vec2u:`uvec2`,vec2b:`bvec2`,"vec3<f32>":`vec3`,"vec3<i32>":`ivec3`,"vec3<u32>":`uvec3`,"vec3<bool>":`bvec3`,vec3f:`vec3`,vec3i:`ivec3`,vec3u:`uvec3`,vec3b:`bvec3`,"vec4<f32>":`vec4`,"vec4<i32>":`ivec4`,"vec4<u32>":`uvec4`,"vec4<bool>":`bvec4`,vec4f:`vec4`,vec4i:`ivec4`,vec4u:`uvec4`,vec4b:`bvec4`,"mat2x2<f32>":`mat2`,mat2x2f:`mat2`,"mat3x3<f32>":`mat3`,mat3x3f:`mat3`,"mat4x4<f32>":`mat4`,mat4x4f:`mat4`,sampler:`sampler`,sampler_comparison:`samplerComparison`,texture_1d:`texture`,texture_2d:`texture`,texture_2d_array:`texture`,texture_multisampled_2d:`cubeTexture`,texture_depth_2d:`depthTexture`,texture_depth_2d_array:`depthTexture`,texture_depth_multisampled_2d:`depthTexture`,texture_depth_cube:`depthTexture`,texture_depth_cube_array:`depthTexture`,texture_3d:`texture3D`,texture_cube:`cubeTexture`,texture_cube_array:`cubeTexture`,texture_storage_1d:`storageTexture`,texture_storage_2d:`storageTexture`,texture_storage_2d_array:`storageTexture`,texture_storage_3d:`storageTexture`},XM=e=>{e=e.replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,``);let t=e.match(qM);if(t!==null&&t.length===4){let n=t[2],r=[],i=null;for(;(i=JM.exec(n))!==null;)r.push({name:i[1],type:i[2]});let a=[];for(let e=0;e<r.length;e++){let{name:t,type:n}=r[e],i=n;i.startsWith(`ptr`)?i=`pointer`:(i.startsWith(`texture`)&&(i=n.split(`<`)[0]),i=YM[i]),a.push(new Dk(i,t))}let o=e.substring(t[0].length),s=t[3]||`void`,c=t[1]===void 0?``:t[1];return{type:YM[s]||s,inputs:a,name:c,inputsCode:n,blockCode:o,outputType:s}}throw Error(`THREE.WGSLNodeFunction: Function is not a WGSL code.`)},ZM=class extends Vk{constructor(e){let{type:t,inputs:n,name:r,inputsCode:i,blockCode:a,outputType:o}=XM(e);super(t,n,r),this.inputsCode=i,this.blockCode=a,this.outputType=o}getCode(e=this.name){let t=this.outputType===`void`?``:`-> `+this.outputType;return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}},QM=class extends Bk{parseFunction(e){return new ZM(e)}},$M={[em.READ_ONLY]:`read`,[em.WRITE_ONLY]:`write`,[em.READ_WRITE]:`read_write`},eN={[S]:`repeat`,[C]:`clamp`,[w]:`mirror`},tN={vertex:Dj.VERTEX,fragment:Dj.FRAGMENT,compute:Dj.COMPUTE},nN={instance:!0,swizzleAssign:!1,storageBuffer:!0},rN={"^^":`tsl_xor`},iN={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>`},aN={},oN={tsl_xor:new RD(`fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }`),mod_float:new RD(`fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }`),mod_vec2:new RD(`fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }`),mod_vec3:new RD(`fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }`),mod_vec4:new RD(`fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }`),equals_bool:new RD(`fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }`),equals_bvec2:new RD(`fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }`),equals_bvec3:new RD(`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 RD(`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 RD(`fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }`),mirrorWrapping_float:new RD(`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 RD(`fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }`),inverse_mat2:new RD(`
fn tsl_inverse_mat2( m : mat2x2<f32> ) -> mat2x2<f32> {
let det = m[ 0 ][ 0 ] * m[ 1 ][ 1 ] - m[ 0 ][ 1 ] * m[ 1 ][ 0 ];
return mat2x2<f32>(
m[ 1 ][ 1 ], - m[ 0 ][ 1 ],
- m[ 1 ][ 0 ], m[ 0 ][ 0 ]
) * ( 1.0 / det );
}
`),inverse_mat3:new RD(`
fn tsl_inverse_mat3( m : mat3x3<f32> ) -> mat3x3<f32> {
let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ];
let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ];
let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ];
let b01 = a22 * a11 - a12 * a21;
let b11 = - a22 * a10 + a12 * a20;
let b21 = a21 * a10 - a11 * a20;
let det = a00 * b01 + a01 * b11 + a02 * b21;
return mat3x3<f32>(
b01, ( - a22 * a01 + a02 * a21 ), ( a12 * a01 - a02 * a11 ),
b11, ( a22 * a00 - a02 * a20 ), ( - a12 * a00 + a02 * a10 ),
b21, ( - a21 * a00 + a01 * a20 ), ( a11 * a00 - a01 * a10 )
) * ( 1.0 / det );
}
`),inverse_mat4:new RD(`
fn tsl_inverse_mat4( m : mat4x4<f32> ) -> mat4x4<f32> {
let a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ]; let a03 = m[ 0 ][ 3 ];
let a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ]; let a13 = m[ 1 ][ 3 ];
let a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ]; let a23 = m[ 2 ][ 3 ];
let a30 = m[ 3 ][ 0 ]; let a31 = m[ 3 ][ 1 ]; let a32 = m[ 3 ][ 2 ]; let a33 = m[ 3 ][ 3 ];
let b00 = a00 * a11 - a01 * a10;
let b01 = a00 * a12 - a02 * a10;
let b02 = a00 * a13 - a03 * a10;
let b03 = a01 * a12 - a02 * a11;
let b04 = a01 * a13 - a03 * a11;
let b05 = a02 * a13 - a03 * a12;
let b06 = a20 * a31 - a21 * a30;
let b07 = a20 * a32 - a22 * a30;
let b08 = a20 * a33 - a23 * a30;
let b09 = a21 * a32 - a22 * a31;
let b10 = a21 * a33 - a23 * a31;
let b11 = a22 * a33 - a23 * a32;
let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
return mat4x4<f32>(
a11 * b11 - a12 * b10 + a13 * b09,
a02 * b10 - a01 * b11 - a03 * b09,
a31 * b05 - a32 * b04 + a33 * b03,
a22 * b04 - a21 * b05 - a23 * b03,
a12 * b08 - a10 * b11 - a13 * b07,
a00 * b11 - a02 * b08 + a03 * b07,
a32 * b02 - a30 * b05 - a33 * b01,
a20 * b05 - a22 * b02 + a23 * b01,
a10 * b10 - a11 * b08 + a13 * b06,
a01 * b08 - a00 * b10 - a03 * b06,
a30 * b04 - a31 * b02 + a33 * b00,
a21 * b02 - a20 * b04 - a23 * b00,
a11 * b07 - a10 * b09 - a12 * b06,
a00 * b09 - a01 * b07 + a02 * b06,
a31 * b01 - a30 * b03 - a32 * b00,
a20 * b03 - a21 * b01 + a22 * b00
) * ( 1.0 / det );
}
`),biquadraticTexture:new RD(`
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 RD(`
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 );
}
`)},sN={dFdx:`dpdx`,dFdy:`- dpdy`,mod_float:`tsl_mod_float`,mod_vec2:`tsl_mod_vec2`,mod_vec3:`tsl_mod_vec3`,mod_vec4:`tsl_mod_vec4`,equals_bool:`tsl_equals_bool`,equals_bvec2:`tsl_equals_bvec2`,equals_bvec3:`tsl_equals_bvec3`,equals_bvec4:`tsl_equals_bvec4`,inverse_mat2:`tsl_inverse_mat2`,inverse_mat3:`tsl_inverse_mat3`,inverse_mat4:`tsl_inverse_mat4`,inversesqrt:`inverseSqrt`,faceforward:`faceForward`,bitcast:`bitcast<f32>`,floatpack_snorm_2x16:`pack2x16snorm`,floatpack_unorm_2x16:`pack2x16unorm`,floatpack_float16_2x16:`pack2x16float`,floatpack_snorm_4x8:`pack4x8snorm`,floatpack_unorm_4x8:`pack4x8unorm`,floatunpack_snorm_2x16:`unpack2x16snorm`,floatunpack_unorm_2x16:`unpack2x16unorm`,floatunpack_float16_2x16:`unpack2x16float`,floatunpack_snorm_4x8:`unpack4x8snorm`,floatunpack_unorm_4x8:`unpack4x8unorm`},cN=new Set(`alias.break.case.const.const_assert.continue.continuing.default.diagnostic.discard.else.enable.false.fn.for.if.let.loop.override.requires.return.struct.switch.true.var.while.NULL.Self.abstract.active.alignas.alignof.as.asm.asm_fragment.async.attribute.auto.await.become.binding_array.cast.catch.class.co_await.co_return.co_yield.coherent.column_major.common.compile.compile_fragment.concept.const_cast.consteval.constexpr.constinit.crate.debugger.decltype.delete.demote.demote_to_helper.do.dynamic_cast.enum.explicit.export.extends.extern.external.fallthrough.filter.final.finally.friend.from.fxgroup.get.goto.groupshared.highp.impl.implements.import.inline.instanceof.interface.layout.lowp.macro.macro_rules.match.mediump.meta.mod.module.move.mut.mutable.namespace.new.nil.noexcept.noinline.nointerpolation.non_coherent.noncoherent.noperspective.null.nullptr.of.operator.package.packoffset.partition.pass.patch.pixelfragment.precise.precision.premerge.priv.protected.pub.public.readonly.ref.regardless.register.reinterpret_cast.require.resource.restrict.self.set.shared.sizeof.smooth.snorm.static.static_assert.static_cast.std.subroutine.super.target.template.this.thread_local.throw.trait.try.type.typedef.typeid.typename.typeof.union.unless.unorm.unsafe.unsized.use.using.varying.virtual.volatile.wgsl.where.with.writeonly.yield.main`.split(`.`)),lN=``;(typeof navigator<`u`&&/Firefox|Deno/g.test(navigator.userAgent))!==!0&&(lN+=`diagnostic( off, derivative_uniformity );
`);var uN=class extends Tk{constructor(e,t){super(e,t,new QM),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,n,r,i,a=this.shaderStage){return a===`fragment`?r?i?`textureSample( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${n}, ${r} )`:i?`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureSampleLevel(e,t,n,`0`,r)}generateTextureSampleLevel(e,t,n,r,i,a){return this.isUnfilterable(e)===!1?i?a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${r}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,a,r,i):this.generateTextureLod(e,t,n,i,a,r)}generateWrapFunction(e){let t=`tsl_coord_${eN[e.wrapS]}S_${eN[e.wrapT]}T_${e.is3DTexture||e.isData3DTexture?`3d`:`2d`}`,n=aN[t];if(n===void 0){let r=[],i=e.is3DTexture||e.isData3DTexture?`vec3f`:`vec2f`,a=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`,o=(e,t)=>{e===1e3?(r.push(oN.repeatWrapping_float),a+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===1001?(r.push(oN.clampWrapping_float),a+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===1002?(r.push(oN.mirrorWrapping_float),a+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(a+=`\t\tcoord.${t}`,M(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};o(e.wrapS,`x`),a+=`,
`,o(e.wrapT,`y`),(e.is3DTexture||e.isData3DTexture)&&(a+=`,
`,o(e.wrapR,`z`)),a+=`
);
}
`,aN[t]=n=new RD(a,r)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){let r=this.getDataFromNode(e,this.shaderStage,this.cache);r.dimensionsSnippet===void 0&&(r.dimensionsSnippet={});let i=r.dimensionsSnippet[n];if(r.dimensionsSnippet[n]===void 0){let a,o,{primarySamples:s}=this.renderer.backend.utils.getTextureSampleData(e),c=s>1;o=e.is3DTexture||e.isData3DTexture?`vec3<u32>`:`vec2<u32>`,a=c||e.isStorageTexture?t:`${t}${n?`, u32( ${n} )`:``}`,i=new sv(new Gv(`textureDimensions( ${a} )`,o)),r.dimensionsSnippet[n]=i,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(r.arrayLayerCount=new sv(new Gv(`textureNumLayers(${t})`,`u32`))),e.isTextureCube&&(r.cubeFaceCount=new sv(new Gv(`6u`,`u32`)))}return i.build(this)}generateTextureSize(e,t,n){let{primarySamples:r}=this.renderer.backend.utils.getTextureSampleData(e);return`textureDimensions( ${r>1||e.isStorageTexture?t:`${t}, ${n}`} )`}generateFilteredTexture(e,t,n,r,i=`0u`,a){let o=this.generateWrapFunction(e),s=this.generateTextureDimension(e,t,i);return r&&(n=`${n} + vec2<f32>(${r}) / ${s}`),a?(this._include(`biquadraticTextureArray`),`tsl_biquadraticTexture_array( ${t}, ${o}( ${n} ), ${s}, u32( ${a} ), u32( ${i} ) )`):(this._include(`biquadraticTexture`),`tsl_biquadraticTexture( ${t}, ${o}( ${n} ), ${s}, u32( ${i} ) )`)}generateTextureLod(e,t,n,r,i,a=`0u`){if(e.isCubeTexture===!0){i&&(n=`${n} + vec3<f32>(${i})`);let r=e.isDepthTexture?`u32`:`f32`;return`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}( ${a} ) )`}let o=this.generateWrapFunction(e),s=this.generateTextureDimension(e,t,a),c=e.is3DTexture||e.isData3DTexture?`vec3`:`vec2`,l=c===`vec3`?`vec3<u32>( 1, 1, 1 )`:`vec2<u32>( 1, 1 )`;i&&(n=`${n} + ${c}<f32>(${i}) / ${c}<f32>( ${s} )`);let u=`${c}<f32>( 0 )`,d=`${c}<f32>( ${s} - ${l} )`;return n=`${c}<u32>( clamp( floor( ${o}( ${n} ) * ${c}<f32>( ${s} ) ), ${u}, ${d} ) )`,this.generateTextureLoad(e,t,n,a,r,null)}generateStorageTextureLoad(e,t,n,r,i,a){a&&(n=`${n} + ${a}`);let o;return o=i?`textureLoad( ${t}, ${n}, ${i} )`:`textureLoad( ${t}, ${n} )`,o}generateTextureLoad(e,t,n,r,i,a){r===null&&(r=`0u`),a&&(n=`${n} + ${a}`);let o;return i?o=`textureLoad( ${t}, ${n}, ${i}, u32( ${r} ) )`:(o=`textureLoad( ${t}, ${n}, u32( ${r} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(o+=`.x`)),o}generateTextureStore(e,t,n,r,i){let a;return a=r?`textureStore( ${t}, ${n}, ${r}, ${i} )`:`textureStore( ${t}, ${n}, ${i} )`,a}isSampleCompare(e){return e.isDepthTexture===!0&&e.compareFunction!==null&&this.renderer.hasCompatibility(kt.TEXTURE_COMPARE)}isUnfilterable(e){return this.getComponentTypeFromTexture(e)!==`float`||!this.isAvailable(`float32Filterable`)&&e.type===1015||this.isSampleCompare(e)===!1&&e.minFilter===1003&&e.magFilter===1003||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1||e.normalized===!0&&(e.type===1011||e.type===1012)}generateTexture(e,t,n,r,i,a=this.shaderStage){let o=null;return o=this.isUnfilterable(e)?this.generateTextureLod(e,t,n,r,i,`0`,a):this._generateTextureSample(e,t,n,r,i,a),o}generateTextureGrad(e,t,n,r,i,a,o=this.shaderStage){if(o===`fragment`)return i?a?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i}, ${r[0]}, ${r[1]}, ${a} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i}, ${r[0]}, ${r[1]} )`:a?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r[0]}, ${r[1]}, ${a} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r[0]}, ${r[1]} )`;N(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${o} shader.`)}generateTextureCompare(e,t,n,r,i,a,o=this.shaderStage){if(o===`fragment`)return e.isDepthTexture===!0&&e.isArrayTexture===!0?a?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r}, ${a} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:a?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${a} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r} )`;N(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}generateTextureGather(e,t,n,r,i,a){let o=e.isDepthTexture===!0?``:`${r}, `;return i?a?`textureGather( ${o}${t}, ${t}_sampler, ${n}, ${i}, ${a} )`:`textureGather( ${o}${t}, ${t}_sampler, ${n}, ${i} )`:a?`textureGather( ${o}${t}, ${t}_sampler, ${n}, ${a} )`:`textureGather( ${o}${t}, ${t}_sampler, ${n})`}generateTextureGatherCompare(e,t,n,r,i,a){return i?a?`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r}, ${a} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r})`:a?`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${a} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${n}, ${r})`}generateTextureLevel(e,t,n,r,i,a){return this.isUnfilterable(e)===!1?i?a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${r}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:a?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${a} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,a,r,i):this.generateTextureLod(e,t,n,i,a,r)}generateTextureBias(e,t,n,r,i,a,o=this.shaderStage){if(o===`fragment`)return i?a?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i}, ${r}, ${a} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:a?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${a} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r} )`;N(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${o} 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){let t=e.name,n=e.type;return n===`texture`||n===`cubeTexture`||n===`cubeDepthTexture`||n===`storageTexture`||n===`texture3D`?t:n===`buffer`||n===`storageBuffer`||n===`indirectStorageBuffer`?this.isCustomStruct(e)?t:t+`.value`:e.groupNode.name+`.`+t}return super.getPropertyName(e)}isReservedKeyword(e){return cN.has(e)}getOutputStructName(){return`output`}getFunctionOperator(e){let t=rN[e];return t===void 0?null:(this._include(t),t)}getNodeAccess(e,t){return t===`compute`?e.access:e.isAtomic===!0?t===`vertex`?(M(`WebGPURenderer: Atomic operations are not supported in the vertex stage. They are only available in the fragment and compute stages.`),em.READ_ONLY):em.READ_WRITE:em.READ_ONLY}getStorageAccess(e,t){return $M[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,r=null){let i=super.getUniformFromNode(e,t,n,r),a=this.getDataFromNode(e,n,this.globalCache);if(a.uniformGPU===void 0){let o,s=e.groupNode,c=s.name,l=this.getBindGroupArray(c,n);if(t===`texture`||t===`cubeTexture`||t===`cubeDepthTexture`||t===`storageTexture`||t===`texture3D`){let r=null,a=this.getNodeAccess(e,n);if(t===`texture`||t===`storageTexture`?r=e.value.is3DTexture===!0?new KA(i.name,i.node,s,a):new WA(i.name,i.node,s,a):t===`cubeTexture`||t===`cubeDepthTexture`?r=new GA(i.name,i.node,s,a):t===`texture3D`&&(r=new KA(i.name,i.node,s,a)),r.store=e.isStorageTextureNode===!0,r.mipLevel=r.store?e.mipLevel:0,r.setVisibility(tN[n]),e.value.isCubeTexture===!0||this.isUnfilterable(e.value)===!1&&r.store===!1||e.gatherNode!==null){let e=new Xj(`${i.name}_sampler`,i.node,s);e.setVisibility(tN[n]),l.push(e,r),o=[e,r]}else l.push(r),o=[r]}else if(t===`buffer`||t===`storageBuffer`||t===`indirectStorageBuffer`){let a=this.getSharedDataFromNode(e),c=a.buffer;c===void 0&&(c=new(t===`buffer`?FA:$j)(e,s),a.buffer=c),c.setVisibility(c.getVisibility()|tN[n]),l.push(c),o=c,i.name=r||`NodeBuffer_`+i.id}else{let e=this.uniformGroups[c];e===void 0&&(e=new BA(c,s),e.setVisibility(Dj.VERTEX|Dj.FRAGMENT|Dj.COMPUTE),this.uniformGroups[c]=e),l.indexOf(e)===-1&&l.push(e),o=this.getNodeUniform(i,t);let n=o.name;e.uniforms.some(e=>e.name===n)||e.addUniform(o)}a.uniformGPU=o}return i}getBuiltin(e,t,n,r=this.shaderStage){let i=this.builtins[r]||(this.builtins[r]=new Map);return i.has(e)===!1&&i.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){let t=e.layout,n=this.flowShaderNode(e),r=[];for(let e of t.inputs)r.push(e.name+` : `+this.getType(e.type));let i=`fn ${t.name}( ${r.join(`, `)} ) -> ${this.getType(t.type)} {
${n.vars}
${n.code}
`;return n.result&&(i+=`\treturn ${n.result};\n`),i+=`
}
`,i}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){let t=[],n=this.directives[e];if(n!==void 0)for(let e of n)t.push(`enable ${e};`);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){let t=[],n=this.builtins[e];if(n!==void 0)for(let{name:e,property:r,type:i}of n.values())t.push(`@builtin( ${e} ) ${r} : ${i}`);return t.join(`,
`)}getScopedArray(e,t,n,r,i){return this.scopedArrays.has(e)===!1&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:r,isAtomic:i}),e}getScopedArrays(e){if(e!==`compute`)return;let t=[];for(let{name:e,scope:n,bufferType:r,bufferCount:i,isAtomic:a}of this.scopedArrays.values()){let o=this.getType(r);a===!0&&(o=`atomic<${o}>`),t.push(`var<${n}> ${e}: array< ${o}, ${i} >;`)}return t.join(`
`)}getAttributes(e){let 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`){let e=this.getBuiltins(`attribute`);e&&t.push(e);let n=this.getAttributesArray();for(let e=0,r=n.length;e<r;e++){let r=n[e],i=r.name,a=this.getType(r.type);t.push(`@location( ${e} ) ${i} : ${a}`)}}return t.join(`,
`)}getStructMembers(e){let t=[];for(let n of e.members){let r=e.output?`@location( `+n.index+` ) `:``,i=this.getType(n.type);n.atomic&&(i=`atomic< `+i+` >`),t.push(`\t${r+n.name} : ${i}`)}return e.output&&t.push(`\t${this.getBuiltins(`output`)}`),t.join(`,
`)}getStructs(e){let t=``,n=this.structs[e];if(n.length>0){let e=[];for(let t of n){let n=`struct ${t.name} {\n`;n+=this.getStructMembers(t),n+=`
};`,e.push(n)}t=`
`+e.join(`
`)+`
`}return t}getVar(e,t,n=null,r=``){let i=`var${r} ${t} : `;return i+=n===null?this.getType(e):this.generateArrayDeclaration(e,n),i}getVars(e,t=!1){let n=``;t&&(n=`<private>`);let r=[],i=this.vars[e];if(i!==void 0)for(let e of i)r.push(`${this.getVar(e.type,e.name,e.count,n)};`);return t?r.join(`
`):`\n\t${r.join(`
`)}\n`}getVaryings(e){let t=[];if(e===`vertex`&&this.getBuiltin(`position`,`builtinClipSpace`,`vec4<f32>`,`vertex`),e===`vertex`||e===`fragment`){let n=this.varyings,r=this.vars[e],i=0;for(let a=0;a<n.length;a++){let o=n[a];if(o.needsInterpolation){let e=`@location( ${i++} )`;if(o.interpolationType){let t=o.interpolationSampling===null?` )`:`, ${o.interpolationSampling} )`;e+=` @interpolate( ${o.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(o.type)&&(e+=` @interpolate(flat, either)`);t.push(`${e} ${o.name} : ${this.getType(o.type)}`)}else e===`vertex`&&r.includes(o)===!1&&r.push(o)}}let n=this.getBuiltins(e);n&&t.push(n);let r=t.join(`,
`);return e===`vertex`?this._getWGSLStruct(`VaryingsStruct`,` `+r):r}isCustomStruct(e){let t=e.value,n=e.node,r=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&n.structTypeNode!==null,i=n.value&&n.value.array&&typeof n.value.itemSize==`number`&&n.value.array.length>n.value.itemSize;return r&&!i}getUniforms(e){let t=this.renderer.backend,n=this.uniforms[e],r=[],i=[],a=[],o={};for(let a of n){let n=a.groupNode.name,s=this.bindingsIndexes[n];if(a.type===`texture`||a.type===`cubeTexture`||a.type===`cubeDepthTexture`||a.type===`storageTexture`||a.type===`texture3D`){let n=a.node,i=n.value;(i.isCubeTexture===!0||this.isUnfilterable(i)===!1&&n.isStorageTextureNode!==!0||n.gatherNode!==null)&&(this.isSampleCompare(i)&&n.isSampleCompare()?r.push(`@binding( ${s.binding++} ) @group( ${s.group} ) var ${a.name}_sampler : sampler_comparison;`):r.push(`@binding( ${s.binding++} ) @group( ${s.group} ) var ${a.name}_sampler : sampler;`));let o,c=``,{primarySamples:l}=t.utils.getTextureSampleData(i);if(l>1&&(c=`_multisampled`),i.isCubeTexture===!0&&i.isDepthTexture===!0)o=`texture_depth_cube`;else if(i.isCubeTexture===!0)o=`texture_cube<f32>`;else if(i.isDepthTexture===!0)o=t.compatibilityMode&&i.compareFunction===null?`texture${c}_2d<f32>`:`texture_depth${c}_2d${i.isArrayTexture===!0?`_array`:``}`;else if(a.node.isStorageTextureNode===!0){let n=KM(i,t.device),r=this.getStorageAccess(a.node,e),s=a.node.value.is3DTexture,c=a.node.value.isArrayTexture;o=`texture_storage_${s?`3d`:`2d${c?`_array`:``}`}<${n}, ${r}>`}else if(i.isArrayTexture===!0||i.isDataArrayTexture===!0||i.isCompressedArrayTexture===!0)o=`texture_2d_array<${this.getComponentTypeFromTexture(i).charAt(0)}32>`;else if(i.is3DTexture===!0||i.isData3DTexture===!0)o=`texture_3d<${this.getComponentTypeFromTexture(i).charAt(0)}32>`;else{let e=this.getComponentTypeFromTexture(i).charAt(0);o=`texture${c}_2d<${e}32>`}r.push(`@binding( ${s.binding++} ) @group( ${s.group} ) var ${a.name} : ${o};`)}else if(a.type===`buffer`||a.type===`storageBuffer`||a.type===`indirectStorageBuffer`){let t=a.node,n=this.getType(t.getNodeType(this)),r=t.bufferCount,o=r>0&&a.type===`buffer`?`, `+r:``,c=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:`uniform`;if(this.isCustomStruct(a))i.push(`@binding( ${s.binding++} ) @group( ${s.group} ) var<${c}> ${a.name} : ${n};`);else{let e=`\tvalue : array< ${t.isAtomic?`atomic<${n}>`:`${n}`}${o} >`;i.push(this._getWGSLStructBinding(a.name,e,c,s.binding++,s.group))}}else{let e=a.groupNode.name;if(o[e]===void 0){let t=this.uniformGroups[e];if(t!==void 0){let n=[];for(let e of t.uniforms){let t=e.getType(),r=this.getType(this.getVectorType(t));n.push(`\t${e.name} : ${r}`)}let r=this.uniformGroupsBindings[e];r===void 0&&(r={index:s.binding++,id:s.group},this.uniformGroupsBindings[e]=r),o[e]={index:r.index,id:r.id,snippets:n}}}}}for(let e in o){let t=o[e];a.push(this._getWGSLStructBinding(e,t.snippets.join(`,
`),`uniform`,t.index,t.id))}return[...r,...i,...a].join(`
`)}buildCode(){let e=this.material===null?{compute:{}}:{fragment:{},vertex:{}};this.sortBindingGroups();for(let t in e){this.shaderStage=t;let n=this.allowGlobalVariables,r=e[t];r.uniforms=this.getUniforms(t),r.attributes=this.getAttributes(t),r.varyings=this.getVaryings(t),r.structs=this.getStructs(t),r.vars=this.getVars(t,n),r.codes=this.getCodes(t),r.directives=this.getDirectives(t),r.scopedArrays=this.getScopedArrays(t);let i=`// code
`;i+=this.flowCode[t];let a=this.flowNodes[t],o=a[a.length-1],s=o.outputNode,c=s!==void 0&&s.isOutputStructNode===!0;for(let e of a){let n=this.getFlowData(e),a=e.name;if(a&&(i.length>0&&(i+=`
`),i+=`\t// flow -> ${a}\n`),i+=`${n.code}\n\t`,e===o&&t!==`compute`){if(i+=`// result
`,t===`vertex`)i+=`varyings.builtinClipSpace = ${n.result};`;else if(t===`fragment`){if(c)r.returnType=s.getNodeType(this),r.structs+=`var<private> output : `+r.returnType+`;`,i+=`return ${n.result};`;else{let e=`\t@location( 0 ) color: ${this.getType(this.getOutputType())}`,t=this.getBuiltins(`output`);t&&(e+=`,
`+t),r.returnType=`OutputStruct`,r.structs+=this._getWGSLStruct(`OutputStruct`,e),r.structs+=`
var<private> output : OutputStruct;`,i+=`output.color = ${this.format(n.result,o.getNodeType(this),this.getOutputType())};\n\n\treturn output;`}}}}r.flow=i}if(this.shaderStage=null,this.material!==null)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{let t=this.compute.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,t=`2x16`){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t=`2x16`){return this.getMethod(`floatunpack_${e}_${t}`)}getTernary(e,t,n){return`select( ${n}, ${t}, ${e} )`}getType(e){return iN[e]||e}isAvailable(e){let t=nN[e];return t===void 0&&(e===`float32Filterable`?t=this.renderer.hasFeature(`float32-filterable`):e===`clipDistance`&&(t=this.renderer.hasFeature(`clip-distances`)),nN[e]=t),t}_getWGSLMethod(e){return oN[e]!==void 0&&this._include(e),sN[e]}_include(e){let t=oN[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
${lN}
// 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){let[n,r,i]=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}, ${r}, ${i} )
fn main( ${e.attributes} ) {
// local vars
${this.allowGlobalVariables?``:e.vars}
// system
instanceIndex = globalId.x
+ globalId.y * ( ${n} * numWorkgroups.x )
+ globalId.z * ( ${n} * numWorkgroups.x ) * ( ${r} * numWorkgroups.y );
// flow
${e.flow}
}
`}_getWGSLStruct(e,t){return`
struct ${e} {
${t}
};`}_getWGSLStructBinding(e,t,n,r=0,i=0){let a=e+`Struct`;return`${this._getWGSLStruct(a,t)}
@binding( ${r} ) @group( ${i} )
var<${n}> ${e} : ${a};`}},dN=new iM,fN=new aM,pN=new Map([[Int8Array,[`sint8`,`snorm8`]],[Uint8Array,[`uint8`,`unorm8`]],[Int16Array,[`sint16`,`snorm16`]],[Uint16Array,[`uint16`,`unorm16`]],[Int32Array,[`sint32`]],[Uint32Array,[`uint32`]],[Float32Array,[`float32`]]]);typeof Float16Array<`u`&&pN.set(Float16Array,[`float16`]);var mN=new Map([[ci,[`float16`]]]),hN=new Map([[Int32Array,`sint32`],[Uint32Array,`uint32`],[Float32Array,`float32`]]),gN=class{constructor(e){this.backend=e}createAttribute(e,t){let n=this._getBufferAttribute(e),r=this.backend,i=r.get(n),a=i.buffer;if(a===void 0){let o=r.device,s=n.array;if(e.normalized===!1&&e.isInterleavedBufferAttribute!==!0){if(s.constructor===Int16Array||s.constructor===Int8Array)s=new Int32Array(s);else if((s.constructor===Uint16Array||s.constructor===Uint8Array)&&(s=new Uint32Array(s),t&GPUBufferUsage.INDEX))for(let e=0;e<s.length;e++)s[e]===65535&&(s[e]=4294967295)}n.array=s;let c;if((n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&n.itemSize===3)c=4;else if(n.itemSize>1&&n.itemSize*s.BYTES_PER_ELEMENT%4!=0){let e=n.itemSize*s.BYTES_PER_ELEMENT;c=Math.floor((e+3)/4)*4/s.BYTES_PER_ELEMENT}if(c!==void 0){let e=n.itemSize,t=new s.constructor(n.count*c);for(let r=0;r<n.count;r++)t.set(s.subarray(r*e,r*e+e),r*c);(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&(n.itemSize=c,n.array=t),s=t,i._itemSize=e,i._paddedItemSize=c}let l=s.byteLength,u=l+(4-l%4)%4;dN.label=n.name,dN.size=u,dN.usage=t,dN.mappedAtCreation=!0,a=o.createBuffer(dN),dN.reset(),new s.constructor(a.getMappedRange()).set(s),a.unmap(),i.buffer=a}}updateAttribute(e){let t=this._getBufferAttribute(e),n=this.backend,r=n.device,i=n.get(t),a=n.get(t).buffer,o=t.array,s=i._itemSize,c=i._paddedItemSize;if(c!==void 0){o=new o.constructor(t.count*c);for(let e=0;e<t.count;e++)o.set(t.array.subarray(e*s,e*s+s),e*c);(t.isStorageBufferAttribute||t.isStorageInstancedBufferAttribute)&&(t.array=o)}let l=t.updateRanges;if(l.length===0)r.queue.writeBuffer(a,0,o,0);else{let e=Mt(o),n=e?1:o.BYTES_PER_ELEMENT;for(let t=0,i=l.length;t<i;t++){let i=l[t],u,d;if(c!==void 0){let e=Math.floor(i.start/s),t=Math.ceil((i.start+i.count)/s)-e;u=e*c*n,d=t*c*n}else u=i.start*n,d=i.count*n;let f=u*(e?o.BYTES_PER_ELEMENT:1);r.queue.writeBuffer(a,f,o,u,d)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){let t=e.getAttributes(),n=new Map;for(let e=0;e<t.length;e++){let r=t[e],i=r.array.BYTES_PER_ELEMENT,a=this._getBufferAttribute(r),o=n.get(a);if(o===void 0){let e,t;r.isInterleavedBufferAttribute===!0?(e=r.data.stride*i,t=r.data.isInstancedInterleavedBuffer?qj.Instance:qj.Vertex):(e=r.itemSize*i,t=r.isInstancedBufferAttribute?qj.Instance:qj.Vertex,r.itemSize>1&&e%4!=0&&(e=Math.floor((e+3)/4)*4)),o={arrayStride:e,attributes:[],stepMode:t},n.set(a,o)}let s=this._getVertexFormat(r),c=r.isInterleavedBufferAttribute===!0?r.offset*i:0;o.attributes.push({shaderLocation:e,offset:c,format:s})}return Array.from(n.values())}destroyAttribute(e){let t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,r=-1){let i=this.backend,a=i.device,o=i.get(this._getBufferAttribute(e)).buffer,s=r===-1?o.size-n:r,c;if(t!==null&&t.isReadbackBuffer){let e=i.get(t);if(t._mapped===!0)throw Error(`THREE.WebGPUAttributeUtils: ReadbackBuffer must be released before being used again.`);if(t._mapped=!0,e.readBufferGPU===void 0){dN.label=`${t.name}_readback`,dN.size=t.maxByteLength,dN.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,c=a.createBuffer(dN),dN.reset();let n=()=>{t.buffer=null,t._mapped=!1,c.unmap()},r=()=>{t.buffer=null,t._mapped=!1,c.destroy(),i.delete(t),t.removeEventListener(`release`,n),t.removeEventListener(`dispose`,r)};t.addEventListener(`release`,n),t.addEventListener(`dispose`,r),e.readBufferGPU=c}else c=e.readBufferGPU}else dN.label=`${e.name}_readback`,dN.size=s,dN.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,c=a.createBuffer(dN),dN.reset();fN.label=`readback_encoder_${e.name}`;let l=a.createCommandEncoder(fN);if(fN.reset(),l.copyBufferToBuffer(o,n,c,0,s),nM(a,l.finish()),await c.mapAsync(GPUMapMode.READ,0,s),t===null){let e=c.getMappedRange(0,s).slice();return c.destroy(),e}if(t.isReadbackBuffer)return t.buffer=c.getMappedRange(0,s),t;{let e=c.getMappedRange(0,s);return new Uint8Array(t).set(new Uint8Array(e)),c.destroy(),t}}_getVertexFormat(e){let{itemSize:t,normalized:n}=e,r=e.array.constructor,i=e.constructor,a;if(t===1)a=hN.get(r);else{let e=(mN.get(i)||pN.get(r))[+!!n];if(e){let n=r.BYTES_PER_ELEMENT*t,i=Math.floor((n+3)/4)*4/r.BYTES_PER_ELEMENT;if(i%1)throw Error(`THREE.WebGPUAttributeUtils: Bad vertex format item size.`);a=`${e}x${i}`}}return a||N(`WebGPUAttributeUtils: Vertex format not supported yet.`),a}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}},_N=new rM,vN=new iM,yN=new pM,bN=class{constructor(e){this.layoutGPU=e,this.usedTimes=0}},xN=class{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){let t=this.backend,n=t.device,r=t.get(e);if(r.layout)return r.layout.layoutGPU;let i=this._createLayoutEntries(e),a=zp(JSON.stringify(i)),o=this._bindGroupLayoutCache.get(a);return o===void 0&&(o=new bN(n.createBindGroupLayout({entries:i})),this._bindGroupLayoutCache.set(a,o)),o.usedTimes++,r.layout=o,r.layoutKey=a,o.layoutGPU}createBindings(e,t,n,r=0){let{backend:i}=this,a=i.get(e),o=this.createBindingsLayout(e),s;n!==``&&(a.groups===void 0&&(a.groups={},a.versions={}),a.versions[n]===r&&(s=a.groups[n])),s===void 0&&(s=this.createBindGroup(e,o),n!==``&&(a.groups[n]=s,a.versions[n]=r)),a.group=s}updateBinding(e){let t=this.backend,n=t.device,r=e.buffer,i=t.get(e).buffer,a=e.updateRanges;if(a.length===0)n.queue.writeBuffer(i,0,r,0);else{let e=Mt(r),t=e?1:r.BYTES_PER_ELEMENT,o=a[0].start;for(let s=0,c=a.length;s<c;s++){let c=a[s],l=a[s+1],u=c.start+c.count;if(l!==void 0&&l.start===u)continue;let d=o*t,f=(u-o)*t,p=d*(e?r.BYTES_PER_ELEMENT:1);n.queue.writeBuffer(i,p,r,d,f),l!==void 0&&(o=l.start)}}}createBindGroupIndex(e,t){let n=this.backend.device,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=e[0];vN.label=`bindingCameraIndex_`+i,vN.size=16,vN.usage=r;let a=n.createBuffer(vN);vN.reset(),n.queue.writeBuffer(a,0,e,0),_N.label=`bindGroupCameraIndex_`+i,_N.layout=t,_N.entries.push({binding:0,resource:{buffer:a}});let o=n.createBindGroup(_N);return _N.reset(),o}createBindGroup(e,t){let n=this.backend,r=n.device,i=0;_N.label=`bindGroup_`+e.name,_N.layout=t;for(let t of e.bindings){if(t.isUniformBuffer){let e=n.get(t);_N.entries.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){let e=n.get(t.attribute).buffer;_N.entries.push({binding:i,resource:{buffer:e}})}else if(t.isSampledTexture){let e=n.get(t.texture),a;if(e.externalTexture!==void 0)a=r.importExternalTexture({source:e.externalTexture});else{let n=t.store?1:e.texture.mipLevelCount,r=t.store?t.mipLevel:0,i=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(i+=`-${e.texture.depthOrArrayLayers}`),i+=`-${n}-${r}`,a=e[i],a===void 0){let o=Kj.All,s;s=t.isSampledCubeTexture?Gj.Cube:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?Gj.TwoDArray:t.isSampledTexture3D?Gj.ThreeD:Gj.TwoD,yN.aspect=o,yN.dimension=s,yN.mipLevelCount=n,yN.baseMipLevel=r,a=e[i]=e.texture.createView(yN),yN.reset()}}_N.entries.push({binding:i,resource:a})}else if(t.isSampler){let e=n.get(t);_N.entries.push({binding:i,resource:e.sampler})}i++}let a=r.createBindGroup(_N);return _N.reset(),a}_createLayoutEntries(e){let t=[],n=0;for(let r of e.bindings){let e=this.backend,i={binding:n,visibility:r.visibility};if(r.isUniformBuffer||r.isStorageBuffer){let e={};r.isStorageBuffer&&(e.type=r.visibility&Dj.COMPUTE?r.access===em.READ_WRITE||r.access===em.WRITE_ONLY?Bj.Storage:Bj.ReadOnlyStorage:r.nodeUniform&&r.nodeUniform.isAtomic&&r.visibility&Dj.FRAGMENT?Bj.Storage:Bj.ReadOnlyStorage),i.buffer=e}else if(r.isSampledTexture&&r.store){let e={};e.format=this.backend.get(r.texture).texture.format;let t=r.access;e.access=t===em.READ_WRITE?Vj.ReadWrite:t===em.WRITE_ONLY?Vj.WriteOnly:Vj.ReadOnly,r.texture.isArrayTexture?e.viewDimension=Gj.TwoDArray:r.texture.is3DTexture&&(e.viewDimension=Gj.ThreeD),i.storageTexture=e}else if(r.isSampledTexture){let t={},{primarySamples:n}=e.utils.getTextureSampleData(r.texture);if(n>1&&(t.multisampled=!0,r.texture.isDepthTexture||(t.sampleType=Uj.UnfilterableFloat)),r.texture.isDepthTexture)t.sampleType=e.compatibilityMode&&r.texture.compareFunction===null?Uj.UnfilterableFloat:Uj.Depth;else{let e=r.texture.type;e===1013?t.sampleType=Uj.SInt:e===1014?t.sampleType=Uj.UInt:r.texture.normalized===!0&&(e===1011||e===1012)?t.sampleType=Uj.UnfilterableFloat:e===1015&&(t.sampleType=this.backend.hasFeature(`float32-filterable`)?Uj.Float:Uj.UnfilterableFloat)}r.isSampledCubeTexture?t.viewDimension=Gj.Cube:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?t.viewDimension=Gj.TwoDArray:r.isSampledTexture3D&&(t.viewDimension=Gj.ThreeD),i.texture=t}else if(r.isSampler){let t={};r.texture.isDepthTexture&&(t.type=r.texture.compareFunction!==null&&r.textureNode.isSampleCompare()&&e.hasCompatibility(kt.TEXTURE_COMPARE)?Hj.Comparison:Hj.NonFiltering),i.sampler=t}else N(`WebGPUBindingUtils: Unsupported binding "${r}".`);t.push(i),n++}return t}deleteBindGroupData(e){let{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()}},SN=class{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}},CN=class{constructor(){this.label=``,this.layout=null,this.compute=null}reset(){this.label=``,this.layout=null,this.compute=null}},wN=class{constructor(){this.label=``,this.bindGroupLayouts=null}reset(){this.label=``,this.bindGroupLayouts=null}},TN=new CN,EN=new wN,DN=new oM,ON=new lM,kN=class{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){let{object:n,material:r,geometry:i,pipeline:a}=e,{vertexProgram:o,fragmentProgram:s}=a,c=this.backend,l=c.device,u=c.utils,d=c.get(a),f=[];for(let t of e.getBindings()){let{layoutGPU:e}=c.get(t).layout;f.push(e)}let p=c.attributeUtils.createShaderVertexBuffers(e),m;r.blending!==0&&(r.blending!==1||r.transparent!==!1)&&(m=this._getBlending(r));let h={};r.stencilWrite===!0&&(h={compare:this._getStencilCompare(r),failOp:this._getStencilOperation(r.stencilFail),depthFailOp:this._getStencilOperation(r.stencilZFail),passOp:this._getStencilOperation(r.stencilZPass)});let g=this._getColorWriteMask(r),_=[];if(e.context.textures!==null){let t=e.context.textures,n=e.context.mrt;for(let e=0;e<t.length;e++){let r=t[e],i=u.getTextureFormatGPU(r),a;if(n!==null){if(this.backend.compatibilityMode!==!0){let e=n.getBlendMode(r.name);e.blending===6?a=m:e.blending!==0&&(a=this._getBlending(e))}else Rt(`WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.`),a=m}else a=m;_.push({format:i,blend:a,writeMask:g})}}else{let t=u.getCurrentColorFormat(e.context);_.push({format:t,blend:m,writeMask:g})}let v=c.get(o).module,y=c.get(s).module,b=this._getPrimitiveState(n,i,r),x=this._getDepthCompare(r),S=u.getCurrentDepthStencilFormat(e.context),C=this._getSampleCount(e.context);EN.bindGroupLayouts=f;let w=l.createPipelineLayout(EN);EN.reset(),ON.label=`renderPipeline_${r.name||r.type}_${r.id}`,ON.vertex=Object.assign({},v,{buffers:p}),ON.fragment=Object.assign({},y,{targets:_}),ON.primitive=b,ON.multisample.count=C,ON.multisample.alphaToCoverageEnabled=r.alphaToCoverage&&C>1,ON.layout=w;let T={},E=e.context.depth,D=e.context.stencil;(E===!0||D===!0)&&(E===!0&&(T.format=S,T.depthWriteEnabled=r.depthWrite,T.depthCompare=x),D===!0&&(T.stencilFront=h,T.stencilBack=h,T.stencilReadMask=r.stencilFuncMask,T.stencilWriteMask=r.stencilWriteMask),r.polygonOffset===!0&&b.topology===Ej.TriangleList&&(T.depthBias=r.polygonOffsetUnits,T.depthBiasSlopeScale=r.polygonOffsetFactor,T.depthBiasClamp=0),ON.depthStencil=T),l.pushErrorScope(`validation`);let O=[{program:o,module:v.module},{program:s,module:y.module}],k=ON.label;if(t===null)d.pipeline=l.createRenderPipeline(ON),ON.reset(),l.popErrorScope().then(e=>{e!==null&&(d.error=!0,N(`WebGPURenderer: Render pipeline creation failed (${k}): ${e.message}`),this._reportShaderDiagnostics(O,k))});else{let e=new Promise(async e=>{try{let e=null,t=null;try{t=l.createRenderPipelineAsync(ON)}catch(t){e=t}if(ON.reset(),t!==null)try{d.pipeline=await t}catch(t){e=t}let n=await l.popErrorScope();if(n!==null||e!==null){d.error=!0;let t=n&&n.message||e&&e.message||`unknown`;N(`WebGPURenderer: Async render pipeline creation failed (${k}): ${t}`),await this._reportShaderDiagnostics(O,k)}}finally{e()}});t.push(e)}}createBundleEncoder(e,t=`renderBundleEncoder`){let{utils:n,device:r}=this.backend,i=n.getCurrentDepthStencilFormat(e),a=n.getCurrentColorFormats(e),o=this._getSampleCount(e);DN.label=t,DN.colorFormats=a,DN.depthStencilFormat=i,DN.sampleCount=o;let s=r.createRenderBundleEncoder(DN);return DN.reset(),s}createComputePipeline(e,t,n=null){let r=this.backend,i=r.device,a=r.get(e.computeProgram).module,o=r.get(e),s=[];for(let e of t){let{layoutGPU:t}=r.get(e).layout;s.push(t)}let c=e.computeProgram,l=`computePipeline_${c.stage}${c.name?`_${c.name}`:``}`;i.pushErrorScope(`validation`),EN.bindGroupLayouts=s;let u=i.createPipelineLayout(EN);if(EN.reset(),TN.label=l,TN.compute=a,TN.layout=u,n===null)o.pipeline=i.createComputePipeline(TN),TN.reset(),i.popErrorScope().then(e=>{e!==null&&(o.error=!0,N(`WebGPURenderer: Compute pipeline creation failed (${l}): ${e.message}`),this._reportShaderDiagnostics([{program:c,module:a.module}],l))});else{let e=new Promise(async e=>{try{let e=null,t=null;try{t=i.createComputePipelineAsync(TN)}catch(t){e=t}if(TN.reset(),t!==null)try{o.pipeline=await t}catch(t){e=t}let n=await i.popErrorScope();if(n!==null||e!==null){o.error=!0;let t=n&&n.message||e&&e.message||`unknown`;N(`WebGPURenderer: Async compute pipeline creation failed (${l}): ${t}`),await this._reportShaderDiagnostics([{program:c,module:a.module}],l)}}finally{e()}});n.push(e)}}async _reportShaderDiagnostics(e,t){for(let{program:n,module:r}of e){let e=await r.getCompilationInfo();if(e.messages.length===0)continue;let i=n.code.split(`
`);for(let r of e.messages){let e=r.lineNum>0?` at line ${r.lineNum}${r.linePos>0?`:${r.linePos}`:``}`:``,a=`WebGPURenderer [${t} / ${n.stage} ${r.type}]${e}: ${r.message}`,o=``;r.lineNum>0&&r.lineNum<=i.length&&(o=`\n ${i[r.lineNum-1]}`,r.linePos>0&&(o+=`\n ${` `.repeat(r.linePos-1)}^`)),(r.type===`error`?N:M)(a+o)}}}_getBlending(e){let t,n,r=e.blending,i=e.blendSrc,a=e.blendDst,o=e.blendEquation;if(r===5){let r=e.blendSrcAlpha===null?i:e.blendSrcAlpha,s=e.blendDstAlpha===null?a:e.blendDstAlpha,c=e.blendEquationAlpha===null?o:e.blendEquationAlpha;t={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(o)},n={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(s),operation:this._getBlendOperation(c)}}else{let i=e.premultipliedAlpha,a=(e,r,i,a)=>{t={srcFactor:e,dstFactor:r,operation:Lj.Add},n={srcFactor:i,dstFactor:a,operation:Lj.Add}};if(i)switch(r){case 1:a(Ij.One,Ij.OneMinusSrcAlpha,Ij.One,Ij.OneMinusSrcAlpha);break;case 2:a(Ij.One,Ij.One,Ij.One,Ij.One);break;case 3:a(Ij.Zero,Ij.OneMinusSrc,Ij.Zero,Ij.One);break;case 4:a(Ij.Dst,Ij.OneMinusSrcAlpha,Ij.Zero,Ij.One)}else switch(r){case 1:a(Ij.SrcAlpha,Ij.OneMinusSrcAlpha,Ij.One,Ij.OneMinusSrcAlpha);break;case 2:a(Ij.SrcAlpha,Ij.One,Ij.One,Ij.One);break;case 3:N(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?`material`:`blendMode`}.premultipliedAlpha = true".`);break;case 4:N(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?`material`:`blendMode`}.premultipliedAlpha = true".`)}}if(t!==void 0&&n!==void 0)return{color:t,alpha:n};N(`WebGPURenderer: Invalid blending: `,r)}_getBlendFactor(e){let t;switch(e){case 200:t=Ij.Zero;break;case 201:t=Ij.One;break;case 202:t=Ij.Src;break;case 203:t=Ij.OneMinusSrc;break;case 204:t=Ij.SrcAlpha;break;case 205:t=Ij.OneMinusSrcAlpha;break;case 208:t=Ij.Dst;break;case 209:t=Ij.OneMinusDst;break;case 206:t=Ij.DstAlpha;break;case 207:t=Ij.OneMinusDstAlpha;break;case 210:t=Ij.SrcAlphaSaturated;break;case 211:case 213:t=Ij.Constant;break;case 212:case 214:t=Ij.OneMinusConstant;break;default:N(`WebGPURenderer: Blend factor not supported.`,e)}return t}_getStencilCompare(e){let t,n=e.stencilFunc;switch(n){case 512:t=Oj.Never;break;case 519:t=Oj.Always;break;case 513:t=Oj.Less;break;case 515:t=Oj.LessEqual;break;case 514:t=Oj.Equal;break;case 518:t=Oj.GreaterEqual;break;case 516:t=Oj.Greater;break;case 517:t=Oj.NotEqual;break;default:N(`WebGPURenderer: Invalid stencil function.`,n)}return t}_getStencilOperation(e){let t;switch(e){case _t:t=zj.Keep;break;case 0:t=zj.Zero;break;case vt:t=zj.Replace;break;case Ct:t=zj.Invert;break;case yt:t=zj.IncrementClamp;break;case bt:t=zj.DecrementClamp;break;case xt:t=zj.IncrementWrap;break;case St:t=zj.DecrementWrap;break;default:N(`WebGPURenderer: Invalid stencil operation.`,t)}return t}_getBlendOperation(e){let t;switch(e){case 100:t=Lj.Add;break;case 101:t=Lj.Subtract;break;case 102:t=Lj.ReverseSubtract;break;case 103:t=Lj.Min;break;case 104:t=Lj.Max;break;default:N(`WebGPUPipelineUtils: Blend equation not supported.`,e)}return t}_getPrimitiveState(e,t,n){let r={};r.topology=this.backend.utils.getPrimitiveTopology(e,n),t.index!==null&&e.isLine===!0&&e.isLineSegments!==!0&&(r.stripIndexFormat=t.index.array instanceof Uint16Array?Nj.Uint16:Nj.Uint32);let i=n.side===1;return e.isMesh&&e.matrixWorld.determinantAffine()<0&&(i=!i),r.frontFace=i===!0?jj.CW:jj.CCW,r.cullMode=n.side===2?Mj.None:Mj.Back,r}_getColorWriteMask(e){return e.colorWrite===!0?Rj.All:Rj.None}_getDepthCompare(e){let t;if(e.depthTest===!1)t=Oj.Always;else{let n=this.backend.parameters.reversedDepthBuffer?Vt[e.depthFunc]:e.depthFunc;switch(n){case 0:t=Oj.Never;break;case 1:t=Oj.Always;break;case 2:t=Oj.Less;break;case 3:t=Oj.LessEqual;break;case 4:t=Oj.Equal;break;case 5:t=Oj.GreaterEqual;break;case 6:t=Oj.Greater;break;case 7:t=Oj.NotEqual;break;default:N(`WebGPUPipelineUtils: Invalid depth function.`,n)}}return t}},AN=class{constructor(){this.label=``,this.type=void 0,this.count=0}reset(){this.label=``,this.type=void 0,this.count=0}},jN=new iM,MN=new aM,NN=new AN,PN=class extends Sj{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,NN.label=`queryset_global_timestamp_${t}`,NN.type=`timestamp`,NN.count=this.maxQueries,this.querySet=this.device.createQuerySet(NN),NN.reset();let r=this.maxQueries*8;jN.label=`buffer_timestamp_resolve_${t}`,jN.size=r,jN.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,this.resolveBuffer=this.device.createBuffer(jN),jN.reset(),jN.label=`buffer_timestamp_result_${t}`,jN.size=r,jN.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this.resultBuffer=this.device.createBuffer(jN),jN.reset()}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;this.currentQueryIndex+2>this.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear());let 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;let e=new Map(this.queryOffsets),t=this.currentQueryIndex,n=t*8;this.currentQueryIndex=0,this.queryOffsets.clear();let r=this.device.createCommandEncoder(MN);r.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),r.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);let i=r.finish();if(nM(this.device,i),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;let a=new BigUint64Array(this.resultBuffer.getMappedRange(0,n)),o={},s=[];this.timestamps.clear();for(let[t,n]of e){let e=t.match(/^(.*):f(\d+)$/),r=parseInt(e[2]);s.includes(r)===!1&&s.push(r),o[r]===void 0&&(o[r]=0);let i=a[n],c=a[n+1],l=Number(c-i)/1e6;this.timestamps.set(t,l),o[r]+=l}let c=o[s[s.length-1]];return this.resultBuffer.unmap(),this.lastValue=c,this.frames=s,c}catch(e){return N(`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){N(`Error waiting for pending resolve:`,e)}if(this.resultBuffer&&this.resultBuffer.mapState===`mapped`)try{this.resultBuffer.unmap()}catch(e){N(`Error unmapping buffer:`,e)}this.querySet&&=(this.querySet.destroy(),null),this.resolveBuffer&&=(this.resolveBuffer.destroy(),null),this.resultBuffer&&=(this.resultBuffer.destroy(),null),this.queryOffsets.clear(),this.timestamps.clear(),this.frames=[],this.pendingResolve=null}}},FN=class{constructor(){this.label=``,this.timestampWrites=void 0}reset(){this.label=``,this.timestampWrites=void 0}},IN=class{constructor(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}reset(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}},LN=class{constructor(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}reset(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}},RN={r:0,g:0,b:0,a:1},zN={r:0,g:0,b:0,a:0},BN=new iM,VN=new aM,HN=new FN,UN=new AN,WN=new dM,GN=new LN,KN=new EM,qN=new EM,JN=new fM,YN=new pM,XN=new jM,ZN=class extends ij{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=e.alpha===void 0||e.alpha,this.parameters.requiredLimits=e.requiredLimits===void 0?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new tM(this),this.attributeUtils=new gN(this),this.bindingUtils=new xN(this),this.capabilities=new SN(this),this.pipelineUtils=new kN(this),this.textureUtils=new GM(this),this.occludedResolveCache=new Map;let t=typeof navigator>`u`||/Android/.test(navigator.userAgent)===!1;this._compatibility={[kt.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);let t=this.parameters,n;if(t.device===void 0){let r={powerPreference:t.powerPreference,featureLevel:`compatibility`,xrCompatible:e.xr.enabled},i=typeof navigator<`u`?await navigator.gpu.requestAdapter(r):null;if(i===null)throw Error(`THREE.WebGPUBackend: Unable to create WebGPU adapter.`);let a=Object.values(Jj),o=[];for(let e of a)i.features.has(e)&&o.push(e);let s={requiredFeatures:o,requiredLimits:t.requiredLimits};n=await i.requestDevice(s)}else n=t.device;this.compatibilityMode=!n.features.has(`core-features-and-limits`),this.compatibilityMode&&(e._samples=0),n.lost.then(t=>{if(t.reason===`destroyed`)return;let n={api:`WebGPU`,message:t.message||`Unknown reason`,reason:t.reason||null,originalEvent:t};e.onDeviceLost(n)}),n.onuncapturederror=t=>{let n=t.error,r=n&&n.constructor?n.constructor.name:`GPUError`,i=n&&n.message||`Unknown uncaptured GPU error`;e.onError({api:`WebGPU`,type:r,message:i,originalEvent:t})},this.device=n,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(Jj.TimestampQuery),this.updateSize()}setXRRenderTargetTextures(e,t,n=null){let r=this.get(e.texture);r.texture=t,r.format=t.format,r.externalTexture=!0,r.xrViewDescriptors=n,r.initialized=!0}get context(){let e=this.renderer.getCanvasTarget(),t=this.get(e),n=t.context;if(n===void 0){let r=this.parameters;n=e.isDefaultCanvasTarget===!0&&r.context!==void 0?r.context:e.domElement.getContext(`webgpu`),`setAttribute`in e.domElement&&e.domElement.setAttribute(`data-engine`,`three.js r186 webgpu`);let i=r.alpha?`premultiplied`:`opaque`,a=r.outputType===1016?`extended`:`standard`;n.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i,toneMapping:{mode:a}}),t.context=n}return n}get coordinateSystem(){return Dt}get hasTimestamp(){return!0}async getArrayBufferAsync(e,t=null,n=0,r=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,r)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.renderer,t=e.getCanvasTarget(),n=this.get(t),r=e.currentSamples,i=n.descriptor;if(i===void 0||n.samples!==r){if(i=new cM,i.colorAttachments.push(new sM),e.depth===!0||e.stencil===!0){let t=new IN;t.view=this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView(),i.depthStencilAttachment=t}let t=i.colorAttachments[0];r>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,n.descriptor=i,n.samples=r}let a=i.colorAttachments[0];return r>0?a.resolveTarget=this.context.getCurrentTexture().createView():a.view=this.context.getCurrentTexture().createView(),i}_isRenderCameraDepthArray(e){let t=e.camera;return e.depthTexture&&e.depthTexture.isArrayTexture===!0&&t!==null&&t.isArrayCamera===!0}_hasExternalTexture(e){let t=e.textures;if(t===null)return!1;for(let e=0;e<t.length;e++)if(this.get(t[e]).externalTexture===!0)return!0;return!1}_getExternalMSAATextures(e,t,n){let r=this.utils.getSampleCount(e.sampleCount);if(r===1){if(t.msaaTextures!==void 0){for(let e of t.msaaTextures)e.destroy();t.msaaTextures=void 0}return null}let i=e.renderTarget,a=i.width,o=i.height,s=t.format;if(t.msaaTextures===void 0||t.msaaTextures.length!==n||t.msaaWidth!==a||t.msaaHeight!==o||t.msaaSamples!==r||t.msaaFormat!==s){if(t.msaaTextures!==void 0)for(let e of t.msaaTextures)e.destroy();JN.size.width=a,JN.size.height=o,JN.sampleCount=r,JN.format=s,JN.usage=GPUTextureUsage.RENDER_ATTACHMENT,t.msaaTextures=[];for(let e=0;e<n;e++)JN.label=i.texture.name+`-msaa-`+e,t.msaaTextures.push(this.device.createTexture(JN));JN.reset(),t.msaaWidth=a,t.msaaHeight=o,t.msaaSamples=r,t.msaaFormat=s}return t.msaaTextures}_createExternalTextureViews(e,t){let n=[],r=e.camera,i=t.xrViewDescriptors,a=Math.max(i?.length||0,e.activeCubeFace+1,1),o=this._getExternalMSAATextures(e,t,a);if(i&&r!==null&&r.isArrayCamera===!0)for(let r=0;r<i.length;r++){let a=t.texture.createView(i[r]);n.push({view:o===null?a:o[r].createView(),resolveTarget:o!==null&&e.renderTarget.resolveColorBuffer===!0?a:void 0,depthSlice:void 0})}else{let r=e.activeCubeFace,i=t.texture.createView({dimension:Gj.TwoD,baseArrayLayer:r,arrayLayerCount:1});n.push({view:o===null?i:o[r].createView(),resolveTarget:o!==null&&e.renderTarget.resolveColorBuffer===!0?i:void 0,depthSlice:void 0})}return n}_getRenderPassDescriptor(e,t={}){let n=e.renderTarget,r=this.get(n),i=this._hasExternalTexture(e),a=r.descriptors;(a===void 0||r.width!==n.width||r.height!==n.height||r.samples!==n.samples||i)&&(a={},r.descriptors=a);let o=e.getCacheKey(),s=a[o];if(s===void 0||i){let t=e.textures,i=[],c,l=this._isRenderCameraDepthArray(e);for(let r=0;r<t.length;r++){let a=this.get(t[r]);if(a.externalTexture===!0){i.push(...this._createExternalTextureViews(e,a));continue}if(YN.label=`colorAttachment_${r}`,YN.baseMipLevel=e.activeMipmapLevel,YN.mipLevelCount=1,YN.baseArrayLayer=e.activeCubeFace,YN.arrayLayerCount=1,YN.dimension=Gj.TwoD,n.isRenderTarget3D)c=e.activeCubeFace,YN.baseArrayLayer=0,YN.dimension=Gj.ThreeD;else if(n.isRenderTarget&&t[r].image.depth>1){if(l===!0){let t=e.camera.cameras;for(let e=0;e<t.length;e++){YN.baseArrayLayer=e,YN.arrayLayerCount=1,YN.dimension=Gj.TwoD;let t=a.texture.createView(YN),r=a.msaaTextures?.[e];i.push({view:r===void 0?t:r.createView(),resolveTarget:r!==void 0&&n.resolveColorBuffer===!0?t:void 0,depthSlice:void 0})}}else YN.dimension=Gj.TwoDArray}if(l!==!0){let t=a.texture.createView(YN),r,o;a.msaaTexture===void 0?a.msaaTextures===void 0?(r=t,o=void 0):(r=a.msaaTextures[e.activeCubeFace].createView(),o=n.resolveColorBuffer===!0?t:void 0):(r=a.msaaTexture.createView(),o=n.resolveColorBuffer===!0?t:void 0),i.push({view:r,resolveTarget:o,depthSlice:c})}YN.reset()}let u=[];for(let e=0;e<i.length;e++){let t=i[e],n=new sM;n.view=t.view,n.depthSlice=t.depthSlice,n.resolveTarget=t.resolveTarget,u.push(n)}if(s={textureViews:i,colorAttachments:u,descriptor:new cM},e.depth){let t=this.get(e.depthTexture);(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(YN.dimension=Gj.TwoD,YN.arrayLayerCount=1,YN.baseArrayLayer=e.activeCubeFace);let n=new IN,r=t.msaaTextures?.[e.activeCubeFace];n.view=r===void 0?t.texture.createView(YN):r.createView(),s.depthStencilAttachment=n,YN.reset()}a[o]=s,r.width=n.width,r.height=n.height,r.samples=n.samples,r.activeMipmapLevel=e.activeMipmapLevel,r.activeCubeFace=e.activeCubeFace}let c=s.descriptor;c.reset();for(let e=0;e<s.colorAttachments.length;e++){let n=s.colorAttachments[e],r={r:0,g:0,b:0,a:1};e===0&&t.clearValue&&(r=t.clearValue),n.loadOp=t.loadOp||Aj.Load,n.storeOp=t.storeOp||kj.Store,n.clearValue=r,c.colorAttachments.push(n)}return s.depthStencilAttachment&&(c.depthStencilAttachment=s.depthStencilAttachment),c}beginRender(e){let t=this.get(e),n=this.device,r=e.occlusionQueryCount,i;r>0?(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,UN.label=`occlusionQuerySet_${e.id}`,UN.type=`occlusion`,UN.count=r,i=n.createQuerySet(UN),UN.reset(),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=Array(r),t.lastOcclusionObject=null):t.lastOcclusionObject!==void 0&&(t.lastOcclusionObject=void 0,t.occlusionQuerySet.destroy(),t.occlusionQuerySet=void 0);let a;a=e.textures===null?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:Aj.Load}),this.initTimestampQuery(Ot.RENDER,this.getTimestampUID(e),a),a.occlusionQuerySet=i;let o=a.depthStencilAttachment,s=e.renderTarget,c=e.sampleCount>1&&s?.storeMultisampledColorBuffer===!1,l=e.sampleCount>1&&s?.storeMultisampledDepthBuffer===!1,u=e.sampleCount>1&&s?.storeMultisampledStencilBuffer===!1,d=e.fullscreenPass===!0&&this._hasExternalTexture(e);if(e.textures!==null){let t=a.colorAttachments;for(let n=0;n<t.length;n++){let r=t[n];if(e.clearColor||c||d){let t=e.mrt?e.mrt.getClearColor(e.textures[n].name):null;t===null?n===0?r.clearValue=e.clearColorValue:(RN.r=0,RN.g=0,RN.b=0,RN.a=1,r.clearValue=RN):r.clearValue=t,r.loadOp=Aj.Clear}else r.loadOp=Aj.Load;r.storeOp=c?kj.Discard:kj.Store}}else{let t=a.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=Aj.Clear):t.loadOp=Aj.Load,t.storeOp=kj.Store}e.depth&&(e.clearDepth||l?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=Aj.Clear):o.depthLoadOp=Aj.Load,o.depthStoreOp=l?kj.Discard:kj.Store),e.stencil&&(e.clearStencil||u?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=Aj.Clear):o.stencilLoadOp=Aj.Load,o.stencilStoreOp=u?kj.Discard:kj.Store),VN.label=`renderContext_`+e.id;let f=n.createCommandEncoder(VN);if(VN.reset(),this._isRenderCameraDepthArray(e)===!0){let n=e.camera.cameras;!t.layerDescriptors||t.layerDescriptors.length!==n.length?this._createArrayCameraLayerDescriptors(e,t,a,n):this._updateArrayCameraLayerDescriptors(e,t,a,n),this._createArrayCameraBundleEncoders(e,t),t.arrayCameraRenderStages=[],t.currentPass=null}else t.bundleEncoders=void 0,t.bundleSets=void 0,t.arrayCameraRenderStages=void 0,t.currentPass=f.beginRenderPass(a),e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e);t.descriptor=a,t.encoder=f,t.renderBundles=[],this._resetRenderContextData(t)}_resetRenderContextData(e){e.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},e.currentBlendColor===void 0&&(e.currentBlendColor=new L),e.currentBlendColor.setRGB(0,0,0),e.currentBlendAlpha=0,e.currentStencilRef=0}_createArrayCameraBundleEncoders(e,t){let n=e.camera.cameras;t.bundleEncoders=[],t.bundleSets=[];for(let r=0;r<n.length;r++){let n=this.pipelineUtils.createBundleEncoder(e,`renderBundleArrayCamera_`+r);t.bundleEncoders.push(n),t.bundleSets.push({attributes:{},bindingGroups:[],pipeline:null,index:null})}}_finishArrayCameraBundleEncoders(e){let t=[];for(let n of e.bundleEncoders)t.push(n.finish());return t}_createArrayCameraLayerDescriptors(e,t,n,r){let i=n.depthStencilAttachment;t.layerDescriptors=[];let a=this.get(e.depthTexture);a.viewCache||=[];for(let o=0;o<r.length;o++){let r=n.colorAttachments[0],s=n.colorAttachments[o],c=new sM;c.view=s.view,c.depthSlice=s.depthSlice,c.resolveTarget=s.resolveTarget,c.loadOp=r.loadOp,c.storeOp=r.storeOp,c.clearValue=r.clearValue;let l=new cM;if(l.label=n.label,l.occlusionQuerySet=n.occlusionQuerySet,l.timestampWrites=n.timestampWrites,l.colorAttachments.push(c),n.depthStencilAttachment){let t=o;if(!a.viewCache[t]){let e=a.msaaTextures?.[t];e===void 0?(YN.dimension=Gj.TwoD,YN.baseArrayLayer=o,YN.arrayLayerCount=1,a.viewCache[t]=a.texture.createView(YN)):a.viewCache[t]=e.createView(),YN.reset()}let n=new IN;n.view=a.viewCache[t],n.depthLoadOp=i.depthLoadOp||Aj.Clear,n.depthStoreOp=i.depthStoreOp||kj.Store,n.depthClearValue=i.depthClearValue||1,e.stencil&&(n.stencilLoadOp=i.stencilLoadOp,n.stencilStoreOp=i.stencilStoreOp,n.stencilClearValue=i.stencilClearValue),l.depthStencilAttachment=n}else{let e=new IN;e.view=i.view,e.depthLoadOp=i.depthLoadOp,e.depthStoreOp=i.depthStoreOp,e.depthClearValue=i.depthClearValue,e.depthReadOnly=i.depthReadOnly,e.stencilLoadOp=i.stencilLoadOp,e.stencilStoreOp=i.stencilStoreOp,e.stencilClearValue=i.stencilClearValue,e.stencilReadOnly=i.stencilReadOnly,l.depthStencilAttachment=e}t.layerDescriptors.push(l)}}_updateArrayCameraLayerDescriptors(e,t,n,r){let i=e.renderTarget,a=e.sampleCount>1&&i?.storeMultisampledDepthBuffer===!1,o=e.sampleCount>1&&i?.storeMultisampledStencilBuffer===!1;for(let i=0;i<r.length;i++){let r=t.layerDescriptors[i],s=n.colorAttachments[0],c=n.colorAttachments[i],l=r.colorAttachments[0];if(l.view=c.view,l.resolveTarget=c.resolveTarget,l.depthSlice=c.depthSlice,l.loadOp=s.loadOp,l.storeOp=s.storeOp,l.clearValue=s.clearValue,r.depthStencilAttachment){let t=r.depthStencilAttachment;e.depth&&(e.clearDepth||a?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=Aj.Clear):t.depthLoadOp=Aj.Load),e.stencil&&(e.clearStencil||o?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=Aj.Clear):t.stencilLoadOp=Aj.Load)}}}finishRender(e){let t=this.get(e),n=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles);let r=t.lastOcclusionObject;r&&r.occlusionTest===!0&&t.currentPass.endOcclusionQuery();let i=t.encoder;if(this._isRenderCameraDepthArray(e)===!0){let n=this._finishArrayCameraBundleEncoders(t),r=t.arrayCameraRenderStages;r.push({bundles:n});for(let n=0;n<t.layerDescriptors.length;n++){let a=t.layerDescriptors[n],o=a.colorAttachments.map(e=>e.loadOp),s=a.colorAttachments.map(e=>e.storeOp),c=a.depthStencilAttachment?.depthLoadOp,l=a.depthStencilAttachment?.depthStoreOp,u=a.depthStencilAttachment?.stencilLoadOp,d=a.depthStencilAttachment?.stencilStoreOp;for(let t=0;t<r.length;t++){let f=r[t],p=f.bundles[n],m=t===r.length-1;for(let e=0;e<a.colorAttachments.length;e++){let n=a.colorAttachments[e];n.loadOp=t===0?o[e]:Aj.Load,n.storeOp=m?s[e]:kj.Store}e.depth&&(a.depthStencilAttachment.depthLoadOp=t===0?c:Aj.Load,a.depthStencilAttachment.depthStoreOp=m?l:kj.Store),e.stencil&&(a.depthStencilAttachment.stencilLoadOp=t===0?u:Aj.Load,a.depthStencilAttachment.stencilStoreOp=m?d:kj.Store);let h=i.beginRenderPass(a);if(e.viewport){let{x:t,y:n,width:r,height:i,minDepth:a,maxDepth:o}=e.viewportValue;h.setViewport(t,n,r,i,a,o)}if(e.scissor){let{x:t,y:n,width:r,height:i}=e.scissorValue;h.setScissorRect(t,n,r,i)}if(h.executeBundles([p]),h.end(),f.framebufferCopy!==void 0){let{texture:e,sourceGPU:t,destinationGPU:r,rectangle:a,generateMipmaps:o}=f.framebufferCopy;this._copyFramebufferToTexture(i,e,t,r,a,n,o)}}for(let e=0;e<a.colorAttachments.length;e++)a.colorAttachments[e].loadOp=o[e],a.colorAttachments[e].storeOp=s[e];e.depth&&(a.depthStencilAttachment.depthLoadOp=c,a.depthStencilAttachment.depthStoreOp=l),e.stencil&&(a.depthStencilAttachment.stencilLoadOp=u,a.depthStencilAttachment.stencilStoreOp=d)}}else t.currentPass&&t.currentPass.end();if(n>0){let r=n*8,i=this.occludedResolveCache.get(r);i===void 0&&(BN.size=r,BN.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,i=this.device.createBuffer(BN),BN.reset(),this.occludedResolveCache.set(r,i)),BN.size=r,BN.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;let a=this.device.createBuffer(BN);BN.reset(),t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,i,0),t.encoder.copyBufferToBuffer(i,0,a,0,r),t.occlusionQueryBuffer=a,this.resolveOccludedAsync(e)}if(nM(this.device,t.encoder.finish()),e.textures!==null){let t=e.textures;for(let e=0;e<t.length;e++){let n=t[e];n.generateMipmaps===!0&&this.textureUtils.generateMipmaps(n)}}}isOccluded(e,t){let n=this.get(e);return n.occluded&&n.occluded.has(t)}async resolveOccludedAsync(e){let t=this.get(e),{currentOcclusionQueryBuffer:n,currentOcclusionQueryObjects:r}=t;if(n&&r){let e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await n.mapAsync(GPUMapMode.READ);let i=n.getMappedRange(),a=new BigUint64Array(i);for(let t=0;t<r.length;t++){let n=r[t];n!==void 0&&a[t]===BigInt(0)&&e.add(n)}n.destroy(),t.occluded=e}}updateViewport(e){let{currentPass:t}=this.get(e),{x:n,y:r,width:i,height:a,minDepth:o,maxDepth:s}=e.viewportValue;t.setViewport(n,r,i,a,o,s)}updateScissor(e){let{currentPass:t}=this.get(e),{x:n,y:r,width:i,height:a}=e.scissorValue;t.setScissorRect(n,r,i,a)}getClearColor(){let 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,r=null){let i=this.device,a=this.renderer,o=[],s,c,l;if(e){let e=this.getClearColor();RN.r=e.r,RN.g=e.g,RN.b=e.b,RN.a=e.a}if(r===null){c=a.depth,l=a.stencil;let t=this._getDefaultRenderPassDescriptor();if(e){o=t.colorAttachments;let e=o[0];e.clearValue=RN,e.loadOp=Aj.Clear,e.storeOp=kj.Store}(c||l)&&(s=t.depthStencilAttachment)}else{c=r.depth,l=r.stencil;let i={loadOp:e?Aj.Clear:Aj.Load,clearValue:e?RN:void 0};c&&(i.depthLoadOp=t?Aj.Clear:Aj.Load,i.depthClearValue=t?a.getClearDepth():void 0,i.depthStoreOp=kj.Store),l&&(i.stencilLoadOp=n?Aj.Clear:Aj.Load,i.stencilClearValue=n?a.getClearStencil():void 0,i.stencilStoreOp=kj.Store);let u=this._getRenderPassDescriptor(r,i);o=u.colorAttachments,s=u.depthStencilAttachment}c&&s&&(t?(s.depthLoadOp=Aj.Clear,s.depthClearValue=a.getClearDepth(),s.depthStoreOp=kj.Store):(s.depthLoadOp=Aj.Load,s.depthStoreOp=kj.Store)),l&&s&&(n?(s.stencilLoadOp=Aj.Clear,s.stencilClearValue=a.getClearStencil(),s.stencilStoreOp=kj.Store):(s.stencilLoadOp=Aj.Load,s.stencilStoreOp=kj.Store)),VN.label=`clear`;let u=i.createCommandEncoder(VN);VN.reset(),u.beginRenderPass({colorAttachments:o,depthStencilAttachment:s}).end(),nM(i,u.finish())}beginCompute(e){let t=this.get(e),n=`computeGroup_`+e.id;HN.label=n,VN.label=n,this.initTimestampQuery(Ot.COMPUTE,this.getTimestampUID(e),HN),t.cmdEncoderGPU=this.device.createCommandEncoder(VN),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(HN),t.currentPipeline=null,VN.reset(),HN.reset()}compute(e,t,n,r,i=null){let a=this.get(t),o=this.get(e),{passEncoderGPU:s}=o,c=this.get(r).pipeline;o.currentPipeline!==c&&(s.setPipeline(c),o.currentPipeline=c);for(let e=0,t=n.length;e<t;e++){let t=n[e],r=this.get(t);s.setBindGroup(e,r.group)}if(i===null&&(i=t.dispatchSize||t.count),i&&i.isIndirectStorageBufferAttribute){let e=this.get(i).buffer;s.dispatchWorkgroupsIndirect(e,0);return}if(typeof i==`number`){let e=i;if(a.dispatchSize===void 0||a.count!==e){a.dispatchSize=[0,1,1],a.count=e;let n=t.workgroupSize,r=n[0];for(let e=1;e<n.length;e++)r*=n[e];let o=Math.ceil(e/r),s=this.device.limits.maxComputeWorkgroupsPerDimension;i=[o,1,1],o>s&&(i[0]=Math.min(o,s),i[1]=Math.ceil(o/s)),a.dispatchSize=i}i=a.dispatchSize}s.dispatchWorkgroups(i[0],i[1]||1,i[2]||1)}finishCompute(e){let t=this.get(e);t.passEncoderGPU.end(),nM(this.device,t.cmdEncoderGPU.finish())}_draw(e,t,n,r,i,a,o,s,c,l=-1){let{object:u,material:d,context:f}=e,p=e.getIndex(),m=p!==null;c.pipeline!==r&&(s.setPipeline(r),c.pipeline=r);let h=c.bindingGroups;for(let e=0,t=i.length;e<t;e++){if(e===l)continue;let t=i[e],n=this.get(t).group;h[e]!==n&&(s.setBindGroup(e,n),h[e]=n)}if(m===!0&&c.index!==p){let e=this.get(p).buffer,t=p.array instanceof Uint16Array?Nj.Uint16:Nj.Uint32;s.setIndexBuffer(e,t),c.index=p}for(let e=0,t=a.length;e<t;e++){let t=a[e];if(c.attributes[e]!==t){let n=this.get(t).buffer;s.setVertexBuffer(e,n),c.attributes[e]=t}}if(f.stencil===!0&&d.stencilWrite===!0&&n.currentStencilRef!==d.stencilRef&&(s.setStencilReference(d.stencilRef),n.currentStencilRef=d.stencilRef),d.blending===5&&s.setBlendConstant!==void 0){let e=d.blendColor,t=d.blendAlpha;(e.equals(n.currentBlendColor)===!1||t!==n.currentBlendAlpha)&&(zN.r=e.r,zN.g=e.g,zN.b=e.b,zN.a=t,s.setBlendConstant(zN),n.currentBlendColor.copy(e),n.currentBlendAlpha=t)}if(u.isBatchedMesh===!0){let e=u._multiDrawStarts,n=u._multiDrawCounts,r=u._multiDrawCount,i=u._multiDrawBytesPerElement;for(let a=0;a<r;a++)m===!0?s.drawIndexed(n[a],1,e[a]/i,0,a):s.draw(n[a],1,e[a],a),t.update(u,n[a],1)}else if(m===!0){let{vertexCount:n,instanceCount:r,firstVertex:i}=o,a=e.getIndirect();if(a!==null){let t=this.get(a).buffer,n=e.getIndirectOffset(),r=Array.isArray(n)?n:[n];for(let e=0;e<r.length;e++)s.drawIndexedIndirect(t,r[e])}else s.drawIndexed(n,r,i,0,0);t.update(u,n,r)}else{let{vertexCount:n,instanceCount:r,firstVertex:i}=o,a=e.getIndirect();if(a!==null){let t=this.get(a).buffer,n=e.getIndirectOffset(),r=Array.isArray(n)?n:[n];for(let e=0;e<r.length;e++)s.drawIndirect(t,r[e])}else s.draw(n,r,i,0);t.update(u,n,r)}}draw(e,t){let{object:n,context:r,pipeline:i}=e,a=this.get(r),o=this.get(i),s=o.pipeline;if(o.error===!0)return;let c=e.getDrawParameters();if(c===null)return;let l=e.getBindings(),u=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){let i=this.get(e.camera),o=e.camera.cameras,d=e.getBindingGroup(`cameraIndex`);if(i.indexesGPU===void 0||i.indexesGPU.length!==o.length){let e=this.get(d),t=[],n=new Uint32Array([0,0,0,0]);for(let r=0,i=o.length;r<i;r++){n[0]=r;let{layoutGPU:i}=e.layout,a=this.bindingUtils.createBindGroupIndex(n,i);t.push(a)}i.indexesGPU=t}let f=r.renderTarget,p=f===null||f.isPostProcessingRenderTarget===!0?this.renderer.getPixelRatio():1,m=d?l.indexOf(d):-1;for(let d=0,f=o.length;d<f;d++){let f=o[d];if(n.layers.test(f.layers)){let n=f.viewport,o=a.currentPass,h=a.currentSets,g=a.bundleEncoders!==void 0;if(g){let e=a.bundleEncoders[d],t=a.bundleSets[d];o=e,h=t}if(n&&!g&&o.setViewport(Math.floor(n.x*p),Math.floor(n.y*p),Math.floor(n.width*p),Math.floor(n.height*p),r.viewportValue.minDepth,r.viewportValue.maxDepth),m!==-1&&i.indexesGPU){let e=i.indexesGPU[d];h.bindingGroups[m]!==e&&(o.setBindGroup(m,e),h.bindingGroups[m]=e)}this._draw(e,t,a,s,l,u,c,o,h,m)}}}else if(a.currentPass){if(a.currentPass instanceof GPURenderBundleEncoder)n.occlusionTest===!0&&Rt(`WebGPUBackend: Occlusion queries can not be recorded into render bundles.`);else if(a.occlusionQuerySet!==void 0){let e=a.lastOcclusionObject;e!==n&&(e!==null&&e.occlusionTest===!0&&(a.currentPass.endOcclusionQuery(),a.occlusionQueryIndex++),n.occlusionTest===!0&&(a.currentPass.beginOcclusionQuery(a.occlusionQueryIndex),a.occlusionQueryObjects[a.occlusionQueryIndex]=n),a.lastOcclusionObject=n)}this._draw(e,t,a,s,l,u,c,a.currentPass,a.currentSets)}}needsRenderUpdate(e){let t=this.get(e),{object:n,material:r}=e,i=this.utils,a=i.getSampleCountRenderContext(e.context),o=i.getCurrentColorSpace(e.context),s=i.getCurrentColorFormat(e.context),c=i.getCurrentDepthStencilFormat(e.context),l=i.getPrimitiveTopology(n,r),u=n.isMesh&&n.matrixWorld.determinantAffine()<0,d=!1;return(t.material!==r||t.materialVersion!==r.version||t.transparent!==r.transparent||t.blending!==r.blending||t.premultipliedAlpha!==r.premultipliedAlpha||t.blendSrc!==r.blendSrc||t.blendDst!==r.blendDst||t.blendEquation!==r.blendEquation||t.blendSrcAlpha!==r.blendSrcAlpha||t.blendDstAlpha!==r.blendDstAlpha||t.blendEquationAlpha!==r.blendEquationAlpha||t.colorWrite!==r.colorWrite||t.depthWrite!==r.depthWrite||t.depthTest!==r.depthTest||t.depthFunc!==r.depthFunc||t.stencilWrite!==r.stencilWrite||t.stencilFunc!==r.stencilFunc||t.stencilFail!==r.stencilFail||t.stencilZFail!==r.stencilZFail||t.stencilZPass!==r.stencilZPass||t.stencilFuncMask!==r.stencilFuncMask||t.stencilWriteMask!==r.stencilWriteMask||t.polygonOffset!==r.polygonOffset||t.polygonOffsetFactor!==r.polygonOffsetFactor||t.polygonOffsetUnits!==r.polygonOffsetUnits||t.side!==r.side||t.alphaToCoverage!==r.alphaToCoverage||t.sampleCount!==a||t.colorSpace!==o||t.colorFormat!==s||t.depthStencilFormat!==c||t.primitiveTopology!==l||t.frontFaceCW!==u||t.clippingContextCacheKey!==e.clippingContextCacheKey)&&(t.material=r,t.materialVersion=r.version,t.transparent=r.transparent,t.blending=r.blending,t.premultipliedAlpha=r.premultipliedAlpha,t.blendSrc=r.blendSrc,t.blendDst=r.blendDst,t.blendEquation=r.blendEquation,t.blendSrcAlpha=r.blendSrcAlpha,t.blendDstAlpha=r.blendDstAlpha,t.blendEquationAlpha=r.blendEquationAlpha,t.colorWrite=r.colorWrite,t.depthWrite=r.depthWrite,t.depthTest=r.depthTest,t.depthFunc=r.depthFunc,t.stencilWrite=r.stencilWrite,t.stencilFunc=r.stencilFunc,t.stencilFail=r.stencilFail,t.stencilZFail=r.stencilZFail,t.stencilZPass=r.stencilZPass,t.stencilFuncMask=r.stencilFuncMask,t.stencilWriteMask=r.stencilWriteMask,t.polygonOffset=r.polygonOffset,t.polygonOffsetFactor=r.polygonOffsetFactor,t.polygonOffsetUnits=r.polygonOffsetUnits,t.side=r.side,t.alphaToCoverage=r.alphaToCoverage,t.sampleCount=a,t.colorSpace=o,t.colorFormat=s,t.depthStencilFormat=c,t.primitiveTopology=l,t.frontFaceCW=u,t.clippingContextCacheKey=e.clippingContextCacheKey,d=!0),d}getRenderCacheKey(e){let{object:t,material:n}=e,r=this.utils,i=e.context,a=t.isMesh&&t.matrixWorld.determinantAffine()<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.polygonOffset,n.polygonOffsetFactor,n.polygonOffsetUnits,n.side,n.alphaToCoverage,a,r.getSampleCountRenderContext(i),r.getCurrentColorSpace(i),r.getCurrentColorFormat(i),r.getCurrentDepthStencilFormat(i),r.getPrimitiveTopology(t,n),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,r,i,a){return this.textureUtils.copyTextureToBuffer(e,t,n,r,i,a)}initTimestampQuery(e,t,n){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new PN(this.device,e,2048));let r=this.timestampQueryPool[e],i=r.allocateQueriesForContext(t);GN.querySet=r.querySet,GN.beginningOfPassWriteIndex=i,GN.endOfPassWriteIndex=i+1,n.timestampWrites=GN}createNodeBuilder(e,t){return new uN(e,t)}createProgram(e){let t=this.get(e);WN.label=e.stage+(e.name===``?``:`_${e.name}`),WN.code=e.code,t.module={module:this.device.createShaderModule(WN),entryPoint:`main`},WN.reset()}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t,n=null){this.pipelineUtils.createComputePipeline(e,t,n)}beginBundle(e){let 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){let n=this.get(e),r=n.currentPass.finish();this.get(t).bundleGPU=r,n.currentSets=n._currentSets,n.currentPass=n._currentPass,n._currentPass=null,n._currentSets=null}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createUniformBuffer(e){let t=this.get(e);if(t.buffer===void 0){let n=e.byteLength,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=[];e.visibility&Dj.VERTEX&&i.push(`vertex`),e.visibility&Dj.FRAGMENT&&i.push(`fragment`),e.visibility&Dj.COMPUTE&&i.push(`compute`);let a=`(${i.join(`,`)})`;BN.label=`bindingBuffer${e.id}_${e.name}_${a}`,BN.size=n,BN.usage=r;let o=this.device.createBuffer(BN);BN.reset(),t.buffer=o}}destroyUniformBuffer(e){this.get(e).buffer.destroy(),this.delete(e)}createBindings(e,t,n,r){this.bindingUtils.createBindings(e,t,n,r)}updateBindings(e,t,n,r){this.bindingUtils.createBindings(e,t,n,r)}updateBinding(e){this.bindingUtils.updateBinding(e)}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 Yj[e]!==void 0&&(e=Yj[e]),this.device.features.has(e)}copyTextureToTexture(e,t,n=null,r=null,i=0,a=0){let o=0,s=0,c=0,l=0,u=0,d=0,f=e.image.width,p=e.image.height,m=1;n!==null&&(n.isBox3===!0?(l=n.min.x,u=n.min.y,d=n.min.z,f=n.max.x-n.min.x,p=n.max.y-n.min.y,m=n.max.z-n.min.z):(l=n.min.x,u=n.min.y,f=n.max.x-n.min.x,p=n.max.y-n.min.y,m=1)),r!==null&&(o=r.x,s=r.y,c=r.z||0),VN.label=`copyTextureToTexture_`+e.id+`_`+t.id;let h=this.device.createCommandEncoder(VN);VN.reset();let g=this.get(e).texture,_=this.get(t).texture;KN.texture=g,KN.mipLevel=i,KN.origin.x=l,KN.origin.y=u,KN.origin.z=d,qN.texture=_,qN.mipLevel=a,qN.origin.x=o,qN.origin.y=s,qN.origin.z=c,XN.width=f,XN.height=p,XN.depthOrArrayLayers=m,h.copyTextureToTexture(KN,qN,XN),KN.reset(),qN.reset(),XN.reset(),nM(this.device,h.finish()),a===0&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,n){let r=this.get(t),i=null;i=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();let a=this.get(e).texture;if(i.format!==a.format){N(`WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.`,i.format,a.format);return}if(this._isRenderCameraDepthArray(t)===!0){let o=this._finishArrayCameraBundleEncoders(r);r.arrayCameraRenderStages.push({bundles:o,framebufferCopy:{texture:e,sourceGPU:i,destinationGPU:a,rectangle:{x:n.x,y:n.y,z:n.z,w:n.w},generateMipmaps:e.generateMipmaps}}),this._createArrayCameraBundleEncoders(t,r);return}let o;if(r.currentPass?(r.currentPass.end(),o=r.encoder):(VN.label=`copyFramebufferToTexture_`+e.id,o=this.device.createCommandEncoder(VN),VN.reset()),this._copyFramebufferToTexture(o,e,i,a,n),r.currentPass){let{descriptor:e}=r;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=Aj.Load;t.depth&&(e.depthStencilAttachment.depthLoadOp=Aj.Load),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=Aj.Load),r.currentPass=o.beginRenderPass(e),this._resetRenderContextData(r),t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else nM(this.device,o.finish())}_copyFramebufferToTexture(e,t,n,r,i,a=0,o=t.generateMipmaps){KN.texture=n,KN.origin.x=i.x,KN.origin.y=i.y,KN.origin.z=a,qN.texture=r,XN.width=i.z,XN.height=i.w,e.copyTextureToTexture(KN,qN,XN),KN.reset(),qN.reset(),XN.reset(),o&&this.textureUtils.generateMipmaps(t,e)}hasCompatibility(e){return this._compatibility[e]===void 0?super.hasCompatibility(e):this._compatibility[e]}async dispose(){if(await super.dispose(),this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(let e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}this.parameters.device===void 0&&this.device!==null&&this.device.destroy()}},QN=class extends us{constructor(e,t,n,r,i,a){super(e,t,n,r,i,a),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}},$N=class extends us{constructor(e,t,n,r,i,a){super(e,t,n,r,i,a),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}},eP=class extends iA{constructor(){super(),this.addMaterial(QC,`MeshPhongMaterial`),this.addMaterial(QT,`MeshStandardMaterial`),this.addMaterial(eE,`MeshPhysicalMaterial`),this.addMaterial(iE,`MeshToonMaterial`),this.addMaterial(HC,`MeshBasicMaterial`),this.addMaterial(XC,`MeshLambertMaterial`),this.addMaterial(DC,`MeshNormalMaterial`),this.addMaterial(sE,`MeshMatcapMaterial`),this.addMaterial(_C,`LineBasicMaterial`),this.addMaterial(yC,`LineDashedMaterial`),this.addMaterial(pE,`PointsMaterial`),this.addMaterial(uE,`SpriteMaterial`),this.addMaterial(_E,`ShadowMaterial`),this.addLight(BO,fs),this.addLight(kk,hs),this.addLight(zk,_s),this.addLight(jk,us),this.addLight(Ok,gs),this.addLight(Ak,Xo),this.addLight(Nk,ys),this.addLight(Mk,QN),this.addLight(Fk,$N),this.addToneMapping(OD,1),this.addToneMapping(kD,2),this.addToneMapping(AD,3),this.addToneMapping(MD,4),this.addToneMapping(ID,6),this.addToneMapping(LD,7)}},tP=class extends kA{constructor(e={}){let t;e.forceWebGL?t=Tj:(t=ZN,e.getFallback=()=>(M(`WebGPURenderer: WebGPU is not available, running under WebGL2 backend.`),new Tj(e)));let n=new t(e);super(n,e),this.library=new eP,this.isWebGPURenderer=!0,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}},nP={type:`change`},rP={type:`start`},iP={type:`end`},aP=1e-6,oP={NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4},sP=new P,cP=new P,lP=new F,uP=new F,dP=new F,fP=new _n,pP=new F,mP=new F,hP=new F,gP=new F,_P=class extends Gs{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.rollSpeed=1,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.multiTouchRoll=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=[`KeyA`,`KeyS`,`KeyD`],this.mouseButtons={LEFT:b.ROTATE,MIDDLE:b.DOLLY,RIGHT:b.PAN},this.target=new F,this.state=oP.NONE,this.keyState=oP.NONE,this._lastPosition=new F,this._lastUp=new F,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._touchRollAngle=0,this._touchRollPointerIds=``,this._lastAngle=0,this._lastRollAngle=0,this._eye=new F,this._movePrev=new P,this._moveCurr=new P,this._lastAxis=new F,this._zoomStart=new P,this._zoomEnd=new P,this._panStart=new P,this._panEnd=new P,this._pointers=[],this._pointerPositions={},this._onPointerMove=yP.bind(this),this._onPointerDown=vP.bind(this),this._onPointerUp=bP.bind(this),this._onPointerCancel=xP.bind(this),this._onContextMenu=OP.bind(this),this._onMouseWheel=DP.bind(this),this._onKeyDown=CP.bind(this),this._onKeyUp=SP.bind(this),this._onTouchStart=kP.bind(this),this._onTouchMove=AP.bind(this),this._onTouchEnd=jP.bind(this),this._onMouseDown=wP.bind(this),this._onMouseMove=TP.bind(this),this._onMouseUp=EP.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(){let e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){if(this._eye.subVectors(this.object.position,this.target),this.noRotate||(this._rotateCamera(),this.multiTouchRoll===!0&&this._rollCamera()),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera){this._checkDistances(),this.object.lookAt(this.target);let e=this._lastPosition.distanceToSquared(this.object.position)>aP,t=this._lastUp.distanceToSquared(this.object.up)>aP;(e||t)&&(this.dispatchEvent(nP),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up))}else if(this.object.isOrthographicCamera){this.object.lookAt(this.target);let e=this._lastPosition.distanceToSquared(this.object.position)>aP,t=this._lastUp.distanceToSquared(this.object.up)>aP,n=this._lastZoom!==this.object.zoom;(e||t||n)&&(this.dispatchEvent(nP),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up),this._lastZoom=this.object.zoom)}else console.warn(`THREE.TrackballControls: Unsupported camera type.`)}reset(){this.state=oP.NONE,this.keyState=oP.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(nP),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up),this._lastZoom=this.object.zoom}_panCamera(){if(cP.copy(this._panEnd).sub(this._panStart),cP.lengthSq()){if(this.object.isOrthographicCamera){let 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;cP.x*=e,cP.y*=t}cP.multiplyScalar(this._eye.length()*this.panSpeed),uP.copy(this._eye).cross(this.object.up).setLength(cP.x),uP.add(lP.copy(this.object.up).setLength(cP.y)),this.object.position.add(uP),this.target.add(uP),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(cP.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){gP.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=gP.length();e?(this._eye.copy(this.object.position).sub(this.target),pP.copy(this._eye).normalize(),mP.copy(this.object.up).normalize(),hP.crossVectors(mP,pP).normalize(),mP.setLength(this._moveCurr.y-this._movePrev.y),hP.setLength(this._moveCurr.x-this._movePrev.x),gP.copy(mP.add(hP)),dP.crossVectors(gP,this._eye).normalize(),e*=this.rotateSpeed,fP.setFromAxisAngle(dP,e),this._eye.applyQuaternion(fP),this.object.up.applyQuaternion(fP),this._lastAxis.copy(dP),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),fP.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(fP),this.object.up.applyQuaternion(fP)),this._movePrev.copy(this._moveCurr)}_rollCamera(){let e=this._getTouchRollAngle();if(e)this._lastRollAngle=e*this.rollSpeed;else if(!this.staticMoving&&this._lastRollAngle)this._lastRollAngle*=Math.sqrt(1-this.dynamicDampingFactor);else return;pP.copy(this._eye).normalize(),fP.setFromAxisAngle(pP,this._lastRollAngle),this.object.up.applyQuaternion(fP)}_getTouchRollAngle(){let e=this._pointers[0],t=this._pointers[1];if(t===void 0||e.pointerType!==`touch`||t.pointerType!==`touch`)return this._touchRollPointerIds=``,0;let n=`${e.pointerId},${t.pointerId}`,r=this._pointerPositions[e.pointerId],i=this._pointerPositions[t.pointerId],a=Math.atan2(i.y-r.y,i.x-r.x);if(n!==this._touchRollPointerIds)return this._touchRollPointerIds=n,this._touchRollAngle=a,0;let o=a-this._touchRollAngle;return this._touchRollAngle=a,o>Math.PI?o-=2*Math.PI:o<-Math.PI&&(o+=2*Math.PI),o}_zoomCamera(){let e;this.state===oP.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=gn.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=gn.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 sP.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),sP}_getMouseOnCircle(e,t){return sP.set((e-this.screen.width*.5-this.screen.left)/(this.screen.width*.5),(this.screen.height+2*(this.screen.top-t))/this.screen.width),sP}_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 P,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){let 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 vP(e){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener(`pointermove`,this._onPointerMove),this.domElement.ownerDocument.addEventListener(`pointerup`,this._onPointerUp)),this._addPointer(e),e.pointerType===`touch`?this._onTouchStart(e):this._onMouseDown(e))}function yP(e){this.enabled!==!1&&(e.pointerType===`touch`?this._onTouchMove(e):this._onMouseMove(e))}function bP(e){this.enabled!==!1&&(e.pointerType===`touch`?this._onTouchEnd(e):this._onMouseUp(),this._removePointer(e),this._pointers.length===0&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener(`pointermove`,this._onPointerMove),this.domElement.ownerDocument.removeEventListener(`pointerup`,this._onPointerUp)))}function xP(e){this._removePointer(e)}function SP(){this.enabled!==!1&&(this.keyState=oP.NONE,window.addEventListener(`keydown`,this._onKeyDown))}function CP(e){this.enabled!==!1&&(window.removeEventListener(`keydown`,this._onKeyDown),this.keyState===oP.NONE&&(e.code===this.keys[oP.ROTATE]&&!this.noRotate?this.keyState=oP.ROTATE:e.code===this.keys[oP.ZOOM]&&!this.noZoom?this.keyState=oP.ZOOM:e.code===this.keys[oP.PAN]&&!this.noPan&&(this.keyState=oP.PAN)))}function wP(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case b.DOLLY:this.state=oP.ZOOM;break;case b.ROTATE:this.state=oP.ROTATE;break;case b.PAN:this.state=oP.PAN;break;default:this.state=oP.NONE}let n=this.keyState===oP.NONE?this.state:this.keyState;n===oP.ROTATE&&!this.noRotate?(this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr)):n===oP.ZOOM&&!this.noZoom?(this._zoomStart.copy(this._getMouseOnScreen(e.pageX,e.pageY)),this._zoomEnd.copy(this._zoomStart)):n===oP.PAN&&!this.noPan&&(this._panStart.copy(this._getMouseOnScreen(e.pageX,e.pageY)),this._panEnd.copy(this._panStart)),this.dispatchEvent(rP)}function TP(e){let t=this.keyState===oP.NONE?this.state:this.keyState;t===oP.ROTATE&&!this.noRotate?this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)):t===oP.ZOOM&&!this.noZoom?this._zoomEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):t===oP.PAN&&!this.noPan&&this._panEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY))}function EP(){this.state=oP.NONE,this.dispatchEvent(iP)}function DP(e){if(this.enabled!==!1&&this.noZoom!==!0){switch(e.preventDefault(),e.deltaMode){case 2:this._zoomStart.y-=e.deltaY*.025;break;case 1:this._zoomStart.y-=e.deltaY*.01;break;default:this._zoomStart.y-=e.deltaY*25e-5}this.dispatchEvent(rP),this.dispatchEvent(iP)}}function OP(e){this.enabled!==!1&&e.preventDefault()}function kP(e){switch(this._trackPointer(e),this._pointers.length){case 1:this.state=oP.TOUCH_ROTATE,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);break;default:this.state=oP.TOUCH_ZOOM_PAN;let 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);let n=(this._pointers[0].pageX+this._pointers[1].pageX)/2,r=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(n,r)),this._panEnd.copy(this._panStart)}this.dispatchEvent(rP)}function AP(e){switch(this._trackPointer(e),this._pointers.length){case 1:this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY));break;default:let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,r=e.pageY-t.y;this._touchZoomDistanceEnd=Math.sqrt(n*n+r*r);let i=(e.pageX+t.x)/2,a=(e.pageY+t.y)/2;this._panEnd.copy(this._getMouseOnScreen(i,a))}}function jP(e){switch(this._pointers.length){case 0:this.state=oP.NONE;break;case 1:this.state=oP.TOUCH_ROTATE,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=oP.TOUCH_ZOOM_PAN;for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId!==e.pointerId){let e=this._pointerPositions[this._pointers[t].pointerId];this._moveCurr.copy(this._getMouseOnCircle(e.x,e.y)),this._movePrev.copy(this._moveCurr);break}}this.dispatchEvent(iP)}var MP={type:`change`},NP={type:`start`},PP={type:`end`},FP=new Ii,IP=new Oi,LP=Math.cos(70*gn.DEG2RAD),RP=new F,zP=2*Math.PI,BP={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},VP=1e-6,HP=class extends Gs{constructor(e,t=null){super(e,t),this.state=BP.NONE,this.target=new F,this.cursor=new F,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:b.ROTATE,MIDDLE:b.DOLLY,RIGHT:b.PAN},this.touches={ONE:x.ROTATE,TWO:x.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 F,this._lastQuaternion=new _n,this._lastTargetPosition=new F,this._quat=new _n().setFromUnitVectors(e.up,new F(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Us,this._sphericalDelta=new Us,this._scale=1,this._panOffset=new F,this._rotateStart=new P,this._rotateEnd=new P,this._rotateDelta=new P,this._panStart=new P,this._panEnd=new P,this._panDelta=new P,this._dollyStart=new P,this._dollyEnd=new P,this._dollyDelta=new P,this._dollyDirection=new F,this._mouse=new P,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=WP.bind(this),this._onPointerDown=UP.bind(this),this._onPointerUp=GP.bind(this),this._onContextMenu=QP.bind(this),this._onMouseWheel=JP.bind(this),this._onKeyDown=YP.bind(this),this._onTouchStart=XP.bind(this),this._onTouchMove=ZP.bind(this),this._onMouseDown=KP.bind(this),this._onMouseMove=qP.bind(this),this._interceptControlDown=$P.bind(this),this._interceptControlUp=eF.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.state=BP.NONE,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();let e=this.domElement.getRootNode();e.removeEventListener(`keydown`,this._interceptControlDown,{capture:!0}),e.removeEventListener(`keyup`,this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction=``,this.domElement.style.cursor=`auto`}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener(`keydown`,this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){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(MP),this.update(),this.state=BP.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){let t=this.object.position;RP.copy(t).sub(this.target),RP.applyQuaternion(this._quat),this._spherical.setFromVector3(RP),this.autoRotate&&this.state===BP.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,r=this.maxAzimuthAngle;isFinite(n)&&isFinite(r)&&(n<-Math.PI?n+=zP:n>Math.PI&&(n-=zP),r<-Math.PI?r+=zP:r>Math.PI&&(r-=zP),n<=r?this._spherical.theta=Math.max(n,Math.min(r,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+r)/2?Math.max(n,this._spherical.theta):Math.min(r,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),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 i=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),i=e!=this._spherical.radius}if(RP.setFromSpherical(this._spherical),RP.applyQuaternion(this._quatInverse),t.copy(this.target).add(RP),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 e=null;if(this.object.isPerspectiveCamera){let t=RP.length();e=this._clampDistance(t*this._scale);let n=t-e;this.object.position.addScaledVector(this._dollyDirection,n),this.object.updateMatrixWorld(),i=!!n}else if(this.object.isOrthographicCamera){let t=new F(this._mouse.x,this._mouse.y,0);t.unproject(this.object);let n=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),i=n!==this.object.zoom;let r=new F(this._mouse.x,this._mouse.y,0);r.unproject(this.object),this.object.position.sub(r).add(t),this.object.updateMatrixWorld(),e=RP.length()}else console.warn(`WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.`),this.zoomToCursor=!1;e!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position):(FP.origin.copy(this.object.position),FP.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(FP.direction))<LP?this.object.lookAt(this.target):(IP.setFromNormalAndCoplanarPoint(this.object.up,this.target),FP.intersectPlane(IP,this.target))))}else if(this.object.isOrthographicCamera){let e=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),e!==this.object.zoom&&(this.object.updateProjectionMatrix(),i=!0)}return this._scale=1,this._performCursorZoom=!1,i||this._lastPosition.distanceToSquared(this.object.position)>VP||8*(1-this._lastQuaternion.dot(this.object.quaternion))>VP||this._lastTargetPosition.distanceToSquared(this.target)>VP?(this.dispatchEvent(MP),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e===null?zP/60/60*this.autoRotateSpeed:zP/60*this.autoRotateSpeed*e}_getZoomScale(e){let t=Math.abs(e*.01);return .95**(this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){RP.setFromMatrixColumn(t,0),RP.multiplyScalar(-e),this._panOffset.add(RP)}_panUp(e,t){this.screenSpacePanning===!0?RP.setFromMatrixColumn(t,1):(RP.setFromMatrixColumn(t,0),RP.crossVectors(this.object.up,RP)),RP.multiplyScalar(e),this._panOffset.add(RP)}_pan(e,t){let n=this.domElement;if(this.object.isPerspectiveCamera){let r=this.object.position;RP.copy(r).sub(this.target);let i=RP.length();i*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*i/n.clientHeight,this.object.matrix),this._panUp(2*t*i/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn(`WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.`),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn(`WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.`),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn(`WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.`),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let n=this.domElement.getBoundingClientRect(),r=e-n.left,i=t-n.top,a=n.width,o=n.height;this._mouse.x=r/a*2-1,this._mouse.y=-(i/o)*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);let t=this.domElement;this._rotateLeft(zP*this._rotateDelta.x/t.clientHeight),this._rotateUp(zP*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(zP*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(-zP*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(zP*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(-zP*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateStart.set(n,r)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panStart.set(n,r)}}_handleTouchStartDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,r=e.pageY-t.y,i=Math.sqrt(n*n+r*r);this._dollyStart.set(0,i)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateEnd.set(n,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(zP*this._rotateDelta.x/t.clientHeight),this._rotateUp(zP*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{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panEnd.set(n,r)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,r=e.pageY-t.y,i=Math.sqrt(n*n+r*r);this._dollyEnd.set(0,i),this._dollyDelta.set(0,(this._dollyEnd.y/this._dollyStart.y)**+this.zoomSpeed),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let a=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(a,o)}_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 P,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){let t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){let t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}};function UP(e){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener(`pointermove`,this._onPointerMove),this.domElement.ownerDocument.addEventListener(`pointerup`,this._onPointerUp)),!this._isTrackingPointer(e)&&(this._addPointer(e),e.pointerType===`touch`?this._onTouchStart(e):this._onMouseDown(e),this._cursorStyle===`grab`&&(this.domElement.style.cursor=`grabbing`)))}function WP(e){this.enabled!==!1&&(e.pointerType===`touch`?this._onTouchMove(e):this._onMouseMove(e))}function GP(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener(`pointermove`,this._onPointerMove),this.domElement.ownerDocument.removeEventListener(`pointerup`,this._onPointerUp),this.dispatchEvent(PP),this.state=BP.NONE,this._cursorStyle===`grab`&&(this.domElement.style.cursor=`grab`);break;case 1:let t=this._pointers[0],n=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:n.x,pageY:n.y})}}function KP(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case b.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(e),this.state=BP.DOLLY;break;case b.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=BP.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=BP.ROTATE}break;case b.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=BP.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=BP.PAN}break;default:this.state=BP.NONE}this.state!==BP.NONE&&this.dispatchEvent(NP)}function qP(e){switch(this.state){case BP.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(e);break;case BP.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(e);break;case BP.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(e)}}function JP(e){this.enabled!==!1&&this.enableZoom!==!1&&this.state===BP.NONE&&(e.preventDefault(),this.dispatchEvent(NP),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(PP))}function YP(e){this.enabled!==!1&&this._handleKeyDown(e)}function XP(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case x.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(e),this.state=BP.TOUCH_ROTATE;break;case x.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(e),this.state=BP.TOUCH_PAN;break;default:this.state=BP.NONE}break;case 2:switch(this.touches.TWO){case x.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(e),this.state=BP.TOUCH_DOLLY_PAN;break;case x.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(e),this.state=BP.TOUCH_DOLLY_ROTATE;break;default:this.state=BP.NONE}break;default:this.state=BP.NONE}this.state!==BP.NONE&&this.dispatchEvent(NP)}function ZP(e){switch(this._trackPointer(e),this.state){case BP.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(e),this.update();break;case BP.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(e),this.update();break;case BP.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(e),this.update();break;case BP.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=BP.NONE}}function QP(e){this.enabled!==!1&&e.preventDefault()}function $P(e){e.key===`Control`&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener(`keyup`,this._interceptControlUp,{passive:!0,capture:!0}))}function eF(e){e.key===`Control`&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener(`keyup`,this._interceptControlUp,{passive:!0,capture:!0}))}var tF={type:`change`},nF=1e-6,rF=new _n,iF=class extends Gs{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 F(0,0,0),this._rotationVector=new F(0,0,0),this._lastQuaternion=new _n,this._lastPosition=new F,this._status=0,this._onKeyDown=aF.bind(this),this._onKeyUp=oF.bind(this),this._onPointerMove=cF.bind(this),this._onPointerDown=sF.bind(this),this._onPointerUp=lF.bind(this),this._onPointerCancel=uF.bind(this),this._onContextMenu=dF.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;let t=this.object,n=e*this.movementSpeed,r=e*this.rollSpeed;t.translateX(this._moveVector.x*n),t.translateY(this._moveVector.y*n),t.translateZ(this._moveVector.z*n),rF.set(this._rotationVector.x*r,this._rotationVector.y*r,this._rotationVector.z*r,1).normalize(),t.quaternion.multiply(rF),(this._lastPosition.distanceToSquared(t.position)>nF||8*(1-this._lastQuaternion.dot(t.quaternion))>nF)&&(this.dispatchEvent(tF),this._lastQuaternion.copy(t.quaternion),this._lastPosition.copy(t.position))}_updateMovementVector(){let 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:[window.innerWidth,window.innerHeight],offset:[0,0]}:{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}}};function aF(e){if(!(e.altKey||this.enabled===!1)){switch(e.code){case`ShiftLeft`:case`ShiftRight`:this.movementSpeedMultiplier=.1;break;case`KeyW`:this._moveState.forward=1;break;case`KeyS`:this._moveState.back=1;break;case`KeyA`:this._moveState.left=1;break;case`KeyD`:this._moveState.right=1;break;case`KeyR`:this._moveState.up=1;break;case`KeyF`:this._moveState.down=1;break;case`ArrowUp`:this._moveState.pitchUp=1;break;case`ArrowDown`:this._moveState.pitchDown=1;break;case`ArrowLeft`:this._moveState.yawLeft=1;break;case`ArrowRight`:this._moveState.yawRight=1;break;case`KeyQ`:this._moveState.rollLeft=1;break;case`KeyE`:this._moveState.rollRight=1}this._updateMovementVector(),this._updateRotationVector()}}function oF(e){if(this.enabled!==!1){switch(e.code){case`ShiftLeft`:case`ShiftRight`:this.movementSpeedMultiplier=1;break;case`KeyW`:this._moveState.forward=0;break;case`KeyS`:this._moveState.back=0;break;case`KeyA`:this._moveState.left=0;break;case`KeyD`:this._moveState.right=0;break;case`KeyR`:this._moveState.up=0;break;case`KeyF`:this._moveState.down=0;break;case`ArrowUp`:this._moveState.pitchUp=0;break;case`ArrowDown`:this._moveState.pitchDown=0;break;case`ArrowLeft`:this._moveState.yawLeft=0;break;case`ArrowRight`:this._moveState.yawRight=0;break;case`KeyQ`:this._moveState.rollLeft=0;break;case`KeyE`:this._moveState.rollRight=0}this._updateMovementVector(),this._updateRotationVector()}}function sF(e){if(this.enabled!==!1){if(this.dragToLook)this._status++;else{switch(e.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1}this._updateMovementVector()}}}function cF(e){if(this.enabled!==!1&&(!this.dragToLook||this._status>0)){let t=this._getContainerDimensions(),n=t.size[0]/2,r=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-n)/n,this._moveState.pitchDown=(e.pageY-t.offset[1]-r)/r,this._updateRotationVector()}}function lF(e){if(this.enabled!==!1){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(e.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0}this._updateMovementVector()}this._updateRotationVector()}}function uF(){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 dF(e){this.enabled!==!1&&e.preventDefault()}var fF={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;
}`},pF=class{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(){}},mF=new ps(-1,1,1,-1,0,1),hF=new class extends xi{constructor(){super(),this.setAttribute(`position`,new li([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute(`uv`,new li([0,2,0,0,2,0],2))}},gF=class{constructor(e){this._mesh=new Yi(hF,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,mF)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}},_F=class extends pF{constructor(e,t=`tDiffuse`){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof uo?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=so.clone(e.uniforms),this.material=new uo({name:e.name===void 0?`unspecified`:e.name,defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this._fsQuad=new gF(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()}},vF=class extends pF{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){let r=e.getContext(),i=e.state;i.buffers.color.setMask(!1),i.buffers.depth.setMask(!1),i.buffers.color.setLocked(!0),i.buffers.depth.setLocked(!0);let a,o;this.inverse?(a=0,o=1):(a=1,o=0),i.buffers.stencil.setTest(!0),i.buffers.stencil.setOp(r.REPLACE,r.REPLACE,r.REPLACE),i.buffers.stencil.setFunc(r.ALWAYS,a,4294967295),i.buffers.stencil.setClear(o),i.buffers.stencil.setLocked(!0),e.setRenderTarget(n),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),i.buffers.color.setLocked(!1),i.buffers.depth.setLocked(!1),i.buffers.color.setMask(!0),i.buffers.depth.setMask(!0),i.buffers.stencil.setLocked(!1),i.buffers.stencil.setFunc(r.EQUAL,1,4294967295),i.buffers.stencil.setOp(r.KEEP,r.KEEP,r.KEEP),i.buffers.stencil.setLocked(!0)}},yF=class extends pF{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}},bF=class{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){let n=e.getSize(new P);this._width=n.width,this._height=n.height,t=new Ln(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ce}),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 _F(fF),this.copyPass.material.blending=0,this.timer=new ws}swapBuffers(){let 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){let 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());let t=this.renderer.getRenderTarget(),n=!1;for(let t=0,r=this.passes.length;t<r;t++){let r=this.passes[t];if(r.enabled!==!1){if(r.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),r.render(this.renderer,this.writeBuffer,this.readBuffer,e,n),r.needsSwap){if(n){let t=this.renderer.getContext(),n=this.renderer.state.buffers.stencil;n.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),n.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}vF!==void 0&&(r instanceof vF?n=!0:r instanceof yF&&(n=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(e===void 0){let t=this.renderer.getSize(new P);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;let n=this._width*this._pixelRatio,r=this._height*this._pixelRatio;this.renderTarget1.setSize(n,r),this.renderTarget2.setSize(n,r);for(let e=0;e<this.passes.length;e++)this.passes[e].setSize(n,r)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}},xF=class extends pF{constructor(e,t,n=null,r=null,i=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=n,this.clearColor=r,this.clearAlpha=i,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new L}render(e,t,n){let r=e.autoClear;e.autoClear=!1;let i,a;this.overrideMaterial!==null&&(a=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),this.clearColor!==null&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),this.clearAlpha!==null&&(i=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),this.clearDepth==1&&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(i),this.overrideMaterial!==null&&(this.scene.overrideMaterial=a),e.autoClear=r}};function SF(){return SF=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},SF.apply(null,arguments)}function CF(e){if(e===void 0)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return e}function wF(e,t){return wF=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},wF(e,t)}function TF(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,wF(e,t)}function EF(e){return EF=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},EF(e)}function DF(e){try{return Function.toString.call(e).indexOf(`[native code]`)!==-1}catch{return typeof e==`function`}}function OF(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(OF=function(){return!!e})()}function kF(e,t,n){if(OF())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&wF(i,n.prototype),i}function AF(e){var t=typeof Map==`function`?new Map:void 0;return AF=function(e){if(e===null||!DF(e))return e;if(typeof e!=`function`)throw TypeError(`Super expression must either be null or a function`);if(t!==void 0){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return kF(e,arguments,EF(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),wF(n,e)},AF(e)}var jF=function(e){TF(t,e);function t(t){return CF(e.call(this,`An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#`+t+` for more information.`)||this)}return t}(AF(Error));function MF(e){return Math.round(e*255)}function NF(e,t,n){return MF(e)+`,`+MF(t)+`,`+MF(n)}function PF(e,t,n,r){if(r===void 0&&(r=NF),t===0)return r(n,n,n);var i=(e%360+360)%360/60,a=(1-Math.abs(2*n-1))*t,o=a*(1-Math.abs(i%2-1)),s=0,c=0,l=0;i>=0&&i<1?(s=a,c=o):i>=1&&i<2?(s=o,c=a):i>=2&&i<3?(c=a,l=o):i>=3&&i<4?(c=o,l=a):i>=4&&i<5?(s=o,l=a):i>=5&&i<6&&(s=a,l=o);var u=n-a/2,d=s+u,f=c+u,p=l+u;return r(d,f,p)}var FF={aliceblue:`f0f8ff`,antiquewhite:`faebd7`,aqua:`00ffff`,aquamarine:`7fffd4`,azure:`f0ffff`,beige:`f5f5dc`,bisque:`ffe4c4`,black:`000`,blanchedalmond:`ffebcd`,blue:`0000ff`,blueviolet:`8a2be2`,brown:`a52a2a`,burlywood:`deb887`,cadetblue:`5f9ea0`,chartreuse:`7fff00`,chocolate:`d2691e`,coral:`ff7f50`,cornflowerblue:`6495ed`,cornsilk:`fff8dc`,crimson:`dc143c`,cyan:`00ffff`,darkblue:`00008b`,darkcyan:`008b8b`,darkgoldenrod:`b8860b`,darkgray:`a9a9a9`,darkgreen:`006400`,darkgrey:`a9a9a9`,darkkhaki:`bdb76b`,darkmagenta:`8b008b`,darkolivegreen:`556b2f`,darkorange:`ff8c00`,darkorchid:`9932cc`,darkred:`8b0000`,darksalmon:`e9967a`,darkseagreen:`8fbc8f`,darkslateblue:`483d8b`,darkslategray:`2f4f4f`,darkslategrey:`2f4f4f`,darkturquoise:`00ced1`,darkviolet:`9400d3`,deeppink:`ff1493`,deepskyblue:`00bfff`,dimgray:`696969`,dimgrey:`696969`,dodgerblue:`1e90ff`,firebrick:`b22222`,floralwhite:`fffaf0`,forestgreen:`228b22`,fuchsia:`ff00ff`,gainsboro:`dcdcdc`,ghostwhite:`f8f8ff`,gold:`ffd700`,goldenrod:`daa520`,gray:`808080`,green:`008000`,greenyellow:`adff2f`,grey:`808080`,honeydew:`f0fff0`,hotpink:`ff69b4`,indianred:`cd5c5c`,indigo:`4b0082`,ivory:`fffff0`,khaki:`f0e68c`,lavender:`e6e6fa`,lavenderblush:`fff0f5`,lawngreen:`7cfc00`,lemonchiffon:`fffacd`,lightblue:`add8e6`,lightcoral:`f08080`,lightcyan:`e0ffff`,lightgoldenrodyellow:`fafad2`,lightgray:`d3d3d3`,lightgreen:`90ee90`,lightgrey:`d3d3d3`,lightpink:`ffb6c1`,lightsalmon:`ffa07a`,lightseagreen:`20b2aa`,lightskyblue:`87cefa`,lightslategray:`789`,lightslategrey:`789`,lightsteelblue:`b0c4de`,lightyellow:`ffffe0`,lime:`0f0`,limegreen:`32cd32`,linen:`faf0e6`,magenta:`f0f`,maroon:`800000`,mediumaquamarine:`66cdaa`,mediumblue:`0000cd`,mediumorchid:`ba55d3`,mediumpurple:`9370db`,mediumseagreen:`3cb371`,mediumslateblue:`7b68ee`,mediumspringgreen:`00fa9a`,mediumturquoise:`48d1cc`,mediumvioletred:`c71585`,midnightblue:`191970`,mintcream:`f5fffa`,mistyrose:`ffe4e1`,moccasin:`ffe4b5`,navajowhite:`ffdead`,navy:`000080`,oldlace:`fdf5e6`,olive:`808000`,olivedrab:`6b8e23`,orange:`ffa500`,orangered:`ff4500`,orchid:`da70d6`,palegoldenrod:`eee8aa`,palegreen:`98fb98`,paleturquoise:`afeeee`,palevioletred:`db7093`,papayawhip:`ffefd5`,peachpuff:`ffdab9`,peru:`cd853f`,pink:`ffc0cb`,plum:`dda0dd`,powderblue:`b0e0e6`,purple:`800080`,rebeccapurple:`639`,red:`f00`,rosybrown:`bc8f8f`,royalblue:`4169e1`,saddlebrown:`8b4513`,salmon:`fa8072`,sandybrown:`f4a460`,seagreen:`2e8b57`,seashell:`fff5ee`,sienna:`a0522d`,silver:`c0c0c0`,skyblue:`87ceeb`,slateblue:`6a5acd`,slategray:`708090`,slategrey:`708090`,snow:`fffafa`,springgreen:`00ff7f`,steelblue:`4682b4`,tan:`d2b48c`,teal:`008080`,thistle:`d8bfd8`,tomato:`ff6347`,turquoise:`40e0d0`,violet:`ee82ee`,wheat:`f5deb3`,white:`fff`,whitesmoke:`f5f5f5`,yellow:`ff0`,yellowgreen:`9acd32`};function IF(e){if(typeof e!=`string`)return e;var t=e.toLowerCase();return FF[t]?`#`+FF[t]:e}var LF=/^#[a-fA-F0-9]{6}$/,RF=/^#[a-fA-F0-9]{8}$/,zF=/^#[a-fA-F0-9]{3}$/,BF=/^#[a-fA-F0-9]{4}$/,VF=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,HF=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,UF=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,WF=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function GF(e){if(typeof e!=`string`)throw new jF(3);var t=IF(e);if(t.match(LF))return{red:parseInt(``+t[1]+t[2],16),green:parseInt(``+t[3]+t[4],16),blue:parseInt(``+t[5]+t[6],16)};if(t.match(RF)){var n=parseFloat((parseInt(``+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(``+t[1]+t[2],16),green:parseInt(``+t[3]+t[4],16),blue:parseInt(``+t[5]+t[6],16),alpha:n}}if(t.match(zF))return{red:parseInt(``+t[1]+t[1],16),green:parseInt(``+t[2]+t[2],16),blue:parseInt(``+t[3]+t[3],16)};if(t.match(BF)){var r=parseFloat((parseInt(``+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(``+t[1]+t[1],16),green:parseInt(``+t[2]+t[2],16),blue:parseInt(``+t[3]+t[3],16),alpha:r}}var i=VF.exec(t);if(i)return{red:parseInt(``+i[1],10),green:parseInt(``+i[2],10),blue:parseInt(``+i[3],10)};var a=HF.exec(t.substring(0,50));if(a)return{red:parseInt(``+a[1],10),green:parseInt(``+a[2],10),blue:parseInt(``+a[3],10),alpha:parseFloat(``+a[4])>1?parseFloat(``+a[4])/100:parseFloat(``+a[4])};var o=UF.exec(t);if(o){var s=`rgb(`+PF(parseInt(``+o[1],10),parseInt(``+o[2],10)/100,parseInt(``+o[3],10)/100)+`)`,c=VF.exec(s);if(!c)throw new jF(4,t,s);return{red:parseInt(``+c[1],10),green:parseInt(``+c[2],10),blue:parseInt(``+c[3],10)}}var l=WF.exec(t.substring(0,50));if(l){var u=`rgb(`+PF(parseInt(``+l[1],10),parseInt(``+l[2],10)/100,parseInt(``+l[3],10)/100)+`)`,d=VF.exec(u);if(!d)throw new jF(4,t,u);return{red:parseInt(``+d[1],10),green:parseInt(``+d[2],10),blue:parseInt(``+d[3],10),alpha:parseFloat(``+l[4])>1?parseFloat(``+l[4])/100:parseFloat(``+l[4])}}throw new jF(5)}function KF(e){var t=e.red/255,n=e.green/255,r=e.blue/255,i=Math.max(t,n,r),a=Math.min(t,n,r),o=(i+a)/2;if(i===a)return e.alpha===void 0?{hue:0,saturation:0,lightness:o}:{hue:0,saturation:0,lightness:o,alpha:e.alpha};var s,c=i-a,l=o>.5?c/(2-i-a):c/(i+a);switch(i){case t:s=(n-r)/c+(n<r?6:0);break;case n:s=(r-t)/c+2;break;default:s=(t-n)/c+4}return s*=60,e.alpha===void 0?{hue:s,saturation:l,lightness:o}:{hue:s,saturation:l,lightness:o,alpha:e.alpha}}function qF(e){return KF(GF(e))}var JF=function(e){return e.length===7&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?`#`+e[1]+e[3]+e[5]:e};function YF(e){var t=e.toString(16);return t.length===1?`0`+t:t}function XF(e){return YF(Math.round(e*255))}function ZF(e,t,n){return JF(`#`+XF(e)+XF(t)+XF(n))}function QF(e,t,n){return PF(e,t,n,ZF)}function $F(e,t,n){if(typeof e==`number`&&typeof t==`number`&&typeof n==`number`)return QF(e,t,n);if(typeof e==`object`&&t===void 0&&n===void 0)return QF(e.hue,e.saturation,e.lightness);throw new jF(1)}function eI(e,t,n,r){if(typeof e==`number`&&typeof t==`number`&&typeof n==`number`&&typeof r==`number`)return r>=1?QF(e,t,n):`rgba(`+PF(e,t,n)+`,`+r+`)`;if(typeof e==`object`&&t===void 0&&n===void 0&&r===void 0)return e.alpha>=1?QF(e.hue,e.saturation,e.lightness):`rgba(`+PF(e.hue,e.saturation,e.lightness)+`,`+e.alpha+`)`;throw new jF(2)}function tI(e,t,n){if(typeof e==`number`&&typeof t==`number`&&typeof n==`number`)return JF(`#`+YF(e)+YF(t)+YF(n));if(typeof e==`object`&&t===void 0&&n===void 0)return JF(`#`+YF(e.red)+YF(e.green)+YF(e.blue));throw new jF(6)}function nI(e,t,n,r){if(typeof e==`string`&&typeof t==`number`){var i=GF(e);return`rgba(`+i.red+`,`+i.green+`,`+i.blue+`,`+t+`)`}if(typeof e==`number`&&typeof t==`number`&&typeof n==`number`&&typeof r==`number`)return r>=1?tI(e,t,n):`rgba(`+e+`,`+t+`,`+n+`,`+r+`)`;if(typeof e==`object`&&t===void 0&&n===void 0&&r===void 0)return e.alpha>=1?tI(e.red,e.green,e.blue):`rgba(`+e.red+`,`+e.green+`,`+e.blue+`,`+e.alpha+`)`;throw new jF(7)}var rI=function(e){return typeof e.red==`number`&&typeof e.green==`number`&&typeof e.blue==`number`&&(typeof e.alpha!=`number`||e.alpha===void 0)},iI=function(e){return typeof e.red==`number`&&typeof e.green==`number`&&typeof e.blue==`number`&&typeof e.alpha==`number`},aI=function(e){return typeof e.hue==`number`&&typeof e.saturation==`number`&&typeof e.lightness==`number`&&(typeof e.alpha!=`number`||e.alpha===void 0)},oI=function(e){return typeof e.hue==`number`&&typeof e.saturation==`number`&&typeof e.lightness==`number`&&typeof e.alpha==`number`};function sI(e){if(typeof e!=`object`)throw new jF(8);if(iI(e))return nI(e);if(rI(e))return tI(e);if(oI(e))return eI(e);if(aI(e))return $F(e);throw new jF(8)}function cI(e,t,n){return function(){var r=n.concat(Array.prototype.slice.call(arguments));return r.length>=t?e.apply(this,r):cI(e,t,r)}}function lI(e){return cI(e,e.length,[])}function uI(e,t){if(t===`transparent`)return t;var n=qF(t);return sI(SF({},n,{hue:n.hue+parseFloat(e)}))}lI(uI);function dI(e,t,n){return Math.max(e,Math.min(t,n))}function fI(e,t){if(t===`transparent`)return t;var n=qF(t);return sI(SF({},n,{lightness:dI(0,1,n.lightness-parseFloat(e))}))}lI(fI);function pI(e,t){if(t===`transparent`)return t;var n=qF(t);return sI(SF({},n,{saturation:dI(0,1,n.saturation-parseFloat(e))}))}lI(pI);function mI(e,t){if(t===`transparent`)return t;var n=qF(t);return sI(SF({},n,{lightness:dI(0,1,n.lightness+parseFloat(e))}))}lI(mI);function hI(e,t,n){if(t===`transparent`)return n;if(n===`transparent`)return t;if(e===0)return n;var r=GF(t),i=SF({},r,{alpha:typeof r.alpha==`number`?r.alpha:1}),a=GF(n),o=SF({},a,{alpha:typeof a.alpha==`number`?a.alpha:1}),s=i.alpha-o.alpha,c=parseFloat(e)*2-1,l=((c*s===-1?c:c+s)/(1+c*s)+1)/2,u=1-l;return nI({red:Math.floor(i.red*l+o.red*u),green:Math.floor(i.green*l+o.green*u),blue:Math.floor(i.blue*l+o.blue*u),alpha:i.alpha*parseFloat(e)+o.alpha*(1-parseFloat(e))})}var gI=lI(hI);function _I(e,t){if(t===`transparent`)return t;var n=GF(t),r=typeof n.alpha==`number`?n.alpha:1;return nI(SF({},n,{alpha:dI(0,1,(r*100+parseFloat(e)*100)/100)}))}var vI=lI(_I);function yI(e,t){if(t===`transparent`)return t;var n=qF(t);return sI(SF({},n,{saturation:dI(0,1,n.saturation+parseFloat(e))}))}lI(yI);function bI(e,t){return t===`transparent`?t:sI(SF({},qF(t),{hue:parseFloat(e)}))}lI(bI);function xI(e,t){return t===`transparent`?t:sI(SF({},qF(t),{lightness:parseFloat(e)}))}lI(xI);function SI(e,t){return t===`transparent`?t:sI(SF({},qF(t),{saturation:parseFloat(e)}))}lI(SI);function CI(e,t){return t===`transparent`?t:gI(parseFloat(e),`rgb(0, 0, 0)`,t)}lI(CI);function wI(e,t){return t===`transparent`?t:gI(parseFloat(e),`rgb(255, 255, 255)`,t)}lI(wI);function TI(e,t){if(t===`transparent`)return t;var n=GF(t),r=typeof n.alpha==`number`?n.alpha:1;return nI(SF({},n,{alpha:dI(0,1,(r*100-parseFloat(e)*100).toFixed(2)/100)}))}lI(TI);function EI(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(typeof document>`u`)){var r=document.head||document.getElementsByTagName(`head`)[0],i=document.createElement(`style`);i.type=`text/css`,n===`top`&&r.firstChild?r.insertBefore(i,r.firstChild):r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}EI(`.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;
}`);function DI(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function OI(e){if(Array.isArray(e))return e}function kI(e){if(Array.isArray(e))return DI(e)}function AI(e,t,n){return(t=RI(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function jI(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function MI(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function NI(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function PI(){throw TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function FI(e,t){return OI(e)||MI(e,t)||zI(e,t)||NI()}function II(e){return kI(e)||jI(e)||zI(e)||PI()}function LI(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function RI(e){var t=LI(e,`string`);return typeof t==`symbol`?t:t+``}function zI(e,t){if(e){if(typeof e==`string`)return DI(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?DI(e,t):void 0}}var BI=function(e){e instanceof Array?e.forEach(BI):(e.map&&e.map.dispose(),e.dispose())},VI=function(e){e.geometry&&e.geometry.dispose(),e.material&&BI(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(VI)},HI=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),VI(t)}},UI=window.THREE?window.THREE:{WebGLRenderer:dd,Scene:Sr,PerspectiveCamera:cs,Raycaster:Bs,SRGBColorSpace:pt,TextureLoader:Jo,Vector2:P,Vector3:F,Box3:Lr,Color:L,Mesh:Yi,SphereGeometry:$a,MeshBasicMaterial:Li,BackSide:1,Timer:ws},WI=o({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(t){return t.render(e.scene,e.camera)});var t=+new Date;if(e.enablePointerInteraction&&t-e.lastRaycasterCheck>=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;var n=null;if(e.hoverDuringDrag||!e.isPointerDragging){var r=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&r.sort(function(t,n){return e.hoverOrderComparator(t.object,n.object)});var i=r.find(function(t){return e.hoverFilter(t.object)})||null;n=i?i.object:null,e.intersection=i||null}n!==e.hoverObj&&(e.onHover(n,e.hoverObj,e.intersection),e.tooltip.content(n&&a(e.tooltipContent)(n,e.intersection)||null),e.hoverObj=n)}e.tweenGroup.update()}return this},getPointerPos:function(e){var t=e.pointerPos;return{x:t.x,y:t.y}},cameraPosition:function(e,t,n,i){var a=e.camera;if(t&&e.initialised){var o,s,c=t,l=n||{x:0,y:0,z:0};if((o=e.povPosTween)==null||o.end(),(s=e.povTgtTween)==null||s.end(),!i)f(c),p(l);else{var u=Object.assign({},a.position),d=m();e.tweenGroup.add(e.povPosTween=new r(u).to(c,i).easing(h.Quadratic.Out).onUpdate(f).onComplete(function(){e.povPosTween=void 0,e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(e.povTgtTween=new r(d).to(l,i/3).easing(h.Quadratic.Out).onUpdate(p).onComplete(function(){e.povTgtTween=void 0,e.tweenGroup.remove(this)}).start())}return this}return Object.assign({},a.position,{lookAt:m()});function f(e){var t=e.x,n=e.y,r=e.z;t!==void 0&&(a.position.x=t),n!==void 0&&(a.position.y=n),r!==void 0&&(a.position.z=r)}function p(t){var n=new UI.Vector3(t.x,t.y,t.z);e.controls.enabled&&e.controls.target?e.controls.target=n:a.lookAt(n)}function m(){return Object.assign(new UI.Vector3(0,0,-1e3).applyQuaternion(a.quaternion).add(a.position))}},zoomToFit:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:10,r=[...arguments].slice(3);return this.fitToBbox(this.getBbox.apply(this,r),t,n)},fitToBbox:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:10,i=e.camera;if(t){var a=new UI.Vector3(0,0,0),o=Math.max.apply(Math,II(Object.entries(t).map(function(e){var t=FI(e,2),n=t[0],r=t[1];return Math.max.apply(Math,II(r.map(function(e){return Math.abs(a[n]-e)})))})))*2,s=(1-r*2/e.height)*i.fov,c=o/Math.atan(s*Math.PI/180),l=c/i.aspect,u=Math.max(c,l);if(u>0){var d=a.clone().sub(i.position).normalize().multiplyScalar(-u);this.cameraPosition(d,a,n)}}return this},getBbox:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){return!0},n=new UI.Box3(new UI.Vector3(0,0,0),new UI.Vector3(0,0,0)),r=e.objects.filter(t);return r.length?(r.forEach(function(e){return n.expandByObject(e)}),Object.assign.apply(Object,II([`x`,`y`,`z`].map(function(e){return AI({},e,[n.min[e],n.max[e]])})))):null},getScreenCoords:function(e,t,n,r){var i=new UI.Vector3(t,n,r);return i.project(this.camera()),{x:(i.x+1)*e.width/2,y:-(i.y-1)*e.height/2}},getSceneCoords:function(e,t,n){var r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,i=new UI.Vector2(t/e.width*2-1,-(n/e.height)*2+1),a=new UI.Raycaster;return a.setFromCamera(i,e.camera),Object.assign({},a.ray.at(r,new UI.Vector3))},intersectingObjects:function(e,t,n){var r=new UI.Vector2(t/e.width*2-1,-(n/e.height)*2+1),i=new UI.Raycaster;return i.params.Line.threshold=e.lineHoverPrecision,i.params.Points.threshold=e.pointsHoverPrecision,i.setFromCamera(r,e.camera),i.intersectObjects(e.objects,!0)},renderer:function(e){return e.renderer},scene:function(e){return e.scene},camera:function(e){return e.camera},postProcessingComposer:function(e){return e.postProcessingComposer},controls:function(e){return e.controls},tbControls:function(e){return e.controls},_destructor:function(e){var t,n,r;HI(e.scene),(t=e.controls)==null||t.dispose(),(n=e.renderer)==null||n.dispose(),(r=e.postProcessingComposer)==null||r.dispose()}},stateInit:function(){return{scene:new UI.Scene,camera:new UI.PerspectiveCamera,timer:new UI.Timer,tweenGroup:new l,lastRaycasterCheck:0}},init:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.controlType,i=r===void 0?`trackball`:r,a=n.useWebGPU,o=a!==void 0&&a,s=n.rendererConfig,c=s===void 0?{}:s,l=n.extraRenderers,u=l===void 0?[]:l,d=n.waitForLoadComplete,p=d===void 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`}[i]||``,t.navInfo.style.display=t.showNavInfo?null:`none`,t.tooltip=new f(t.container),t.pointerPos=new UI.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,[`pointermove`,`pointerdown`].forEach(function(e){return t.container.addEventListener(e,function(n){if(e===`pointerdown`&&(t.isPointerPressed=!0),!t.isPointerDragging&&n.type===`pointermove`&&(n.pressure>0||t.isPointerPressed)&&(n.pointerType===`mouse`||n.movementX===void 0||[n.movementX,n.movementY].some(function(e){return Math.abs(e)>1}))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var r=i(t.container);t.pointerPos.x=n.pageX-r.left,t.pointerPos.y=n.pageY-r.top}function i(e){var t=e.getBoundingClientRect(),n=window.pageXOffset||document.documentElement.scrollLeft,r=window.pageYOffset||document.documentElement.scrollTop;return{top:t.top+r,left:t.left+n}}},{passive:!0})}),t.container.addEventListener(`pointerup`,function(e){t.isPointerPressed&&(t.isPointerPressed=!1,!(t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag))&&requestAnimationFrame(function(){e.button===0&&t.onClick(t.hoverObj||null,e,t.intersection),e.button===2&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener(`contextmenu`,function(e){t.onRightClick&&e.preventDefault()}),t.renderer=new(o?tP:UI.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},c)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=u,t.extraRenderers.forEach(function(e){e.domElement.style.position=`absolute`,e.domElement.style.top=`0px`,e.domElement.style.pointerEvents=`none`,t.container.appendChild(e.domElement)}),t.postProcessingComposer=new bF(t.renderer),t.postProcessingComposer.addPass(new xF(t.scene,t.camera)),t.controls=new{trackball:_P,orbit:HP,fly:iF}[i](t.camera,t.renderer.domElement),i===`fly`&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),(i===`trackball`||i===`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(II(t.extraRenderers)).forEach(function(e){return e.setSize(t.width,t.height)}),t.camera.aspect=t.width/t.height,t.camera.updateProjectionMatrix(),t.camera.position.z=1e3,t.scene.add(t.skysphere=new UI.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!p,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty(`width`)||t.hasOwnProperty(`height`))){var n,r=e.width,i=e.height;e.container.style.width=`${r}px`,e.container.style.height=`${i}px`,[e.renderer,e.postProcessingComposer].concat(II(e.extraRenderers)).forEach(function(e){return e.setSize(r,i)}),e.camera.aspect=r/i;var a=e.viewOffset.slice(0,2);a.some(function(e){return e})&&(n=e.camera).setViewOffset.apply(n,[r,i].concat(II(a),[r,i])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty(`viewOffset`)){var o,s=e.width,c=e.height,l=e.viewOffset.slice(0,2);l.some(function(e){return e})?(o=e.camera).setViewOffset.apply(o,[s,c].concat(II(l),[s,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 UI.SphereGeometry(e.skyRadius)),t.hasOwnProperty(`backgroundColor`)){var u=GF(e.backgroundColor).alpha;u===void 0&&(u=1),e.renderer.setClearColor(new UI.Color(vI(1,e.backgroundColor)),u)}t.hasOwnProperty(`backgroundImageUrl`)&&(e.backgroundImageUrl?new UI.TextureLoader().load(e.backgroundImageUrl,function(t){t.colorSpace=UI.SRGBColorSpace,e.skysphere.material=new UI.MeshBasicMaterial({map:t,side:UI.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&d()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&d())),t.hasOwnProperty(`showNavInfo`)&&(e.navInfo.style.display=e.showNavInfo?null:`none`),t.hasOwnProperty(`lights`)&&((t.lights||[]).forEach(function(t){return e.scene.remove(t)}),e.lights.forEach(function(t){return e.scene.add(t)})),t.hasOwnProperty(`objects`)&&((t.objects||[]).forEach(function(t){return e.scene.remove(t)}),e.objects.forEach(function(t){return e.scene.add(t)}));function d(){e.loadComplete=e.scene.visible=!0}}});function GI(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(typeof document>`u`)){var r=document.head||document.getElementsByTagName(`head`)[0],i=document.createElement(`style`);i.type=`text/css`,n===`top`&&r.firstChild?r.insertBefore(i,r.firstChild):r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}GI(`.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;
}`);function KI(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function qI(e){if(Array.isArray(e))return KI(e)}function JI(e,t,n){return(t=tL(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function YI(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function XI(){throw TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ZI(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function QI(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ZI(Object(n),!0).forEach(function(t){JI(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ZI(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function $I(e){return qI(e)||YI(e)||nL(e)||XI()}function eL(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function tL(e){var t=eL(e,`string`);return typeof t==`symbol`?t:t+``}function nL(e,t){if(e){if(typeof e==`string`)return KI(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?KI(e,t):void 0}}function rL(e,t){var n=new t;return n._destructor&&n._destructor(),{linkProp:function(t){return{default:n[t](),onChange:function(n,r){r[e][t](n)},triggerUpdate:!1}},linkMethod:function(t){return function(n){var r=n[e],i=[...arguments].slice(1),a=r[t].apply(r,i);return a===r?this:a}}}}var iL=window.THREE?window.THREE:{AmbientLight:gs,DirectionalLight:hs,REVISION:`186`},aL=170,oL=rL(`forceGraph`,Op),sL=Object.assign.apply(Object,$I(`jsonUrl.graphData.numDimensions.dagMode.dagLevelDistance.dagNodeFilter.onDagError.nodeRelSize.nodeId.nodeVal.nodeResolution.nodeColor.nodeAutoColorBy.nodeOpacity.nodeVisibility.nodeThreeObject.nodeThreeObjectExtend.nodePositionUpdate.linkSource.linkTarget.linkVisibility.linkColor.linkAutoColorBy.linkOpacity.linkWidth.linkResolution.linkCurvature.linkCurveRotation.linkMaterial.linkThreeObject.linkThreeObjectExtend.linkPositionUpdate.linkDirectionalArrowLength.linkDirectionalArrowColor.linkDirectionalArrowRelPos.linkDirectionalArrowResolution.linkDirectionalParticles.linkDirectionalParticleSpeed.linkDirectionalParticleOffset.linkDirectionalParticleWidth.linkDirectionalParticleColor.linkDirectionalParticleResolution.linkDirectionalParticleThreeObject.forceEngine.d3AlphaDecay.d3VelocityDecay.d3AlphaMin.ngraphPhysics.warmupTicks.cooldownTicks.cooldownTime.onEngineTick.onEngineStop`.split(`.`).map(function(e){return JI({},e,oL.linkProp(e))}))),cL=Object.assign.apply(Object,$I([`refresh`,`getGraphBbox`,`d3Force`,`d3ReheatSimulation`,`emitParticle`].map(function(e){return JI({},e,oL.linkMethod(e))}))),lL=rL(`renderObjs`,WI),uL=Object.assign.apply(Object,$I([`width`,`height`,`backgroundColor`,`showNavInfo`,`enablePointerInteraction`].map(function(e){return JI({},e,lL.linkProp(e))}))),dL=Object.assign.apply(Object,$I([`lights`,`cameraPosition`,`postProcessingComposer`].map(function(e){return JI({},e,lL.linkMethod(e))})).concat([{graph2ScreenCoords:lL.linkMethod(`getScreenCoords`),screen2GraphCoords:lL.linkMethod(`getSceneCoords`)}])),fL=o({props:QI(QI({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}},sL),uL),methods:QI(QI({zoomToFit:function(e,t,n){var r,i=[...arguments].slice(3);return e.renderObjs.fitToBbox((r=e.forceGraph).getGraphBbox.apply(r,i),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.call(n),e.renderObjs._destructor()}},cL),dL),stateInit:function(e){var t=e.controlType,n=e.rendererConfig,r=e.extraRenderers,i=new Op;return{forceGraph:i,renderObjs:WI({controlType:t,rendererConfig:n,extraRenderers:r}).objects([i]).lights([new iL.AmbientLight(13421772,Math.PI),new iL.DirectionalLight(16777215,.6*Math.PI)])}},init:function(e,t){e.innerHTML=``,e.appendChild(t.container=document.createElement(`div`)),t.container.style.position=`relative`;var n=document.createElement(`div`);t.container.appendChild(n),t.renderObjs(n);var r=t.renderObjs.camera(),i=t.renderObjs.renderer(),o=t.renderObjs.controls();o.enabled=!!t.enableNavigationControls,t.lastSetCameraZ=r.position.z;var s;t.container.appendChild(s=document.createElement(`div`)),s.className=`graph-info-msg`,s.textContent=``,t.forceGraph.onLoading(function(){s.textContent=`Loading...`}).onFinishLoading(function(){s.textContent=``}).onUpdate(function(){t.graphData=t.forceGraph.graphData(),r.position.x===0&&r.position.y===0&&r.position.z===t.lastSetCameraZ&&t.graphData.nodes.length&&(r.lookAt(t.forceGraph.position),t.lastSetCameraZ=r.position.z=Math.cbrt(t.graphData.nodes.length)*aL)}).onFinishUpdate(function(){if(t._dragControls){var e=t.graphData.nodes.find(function(e){return e.__initialFixedPos&&!e.__disposeControlsAfterDrag});e?e.__disposeControlsAfterDrag=!0:t._dragControls.dispose(),t._dragControls=void 0}if(t.enableNodeDrag&&t.enablePointerInteraction&&t.forceEngine===`d3`){var n=t._dragControls=new Ed(t.graphData.nodes.map(function(e){return e.__threeObj}).filter(function(e){return e}),r,i.domElement);n.addEventListener(`dragstart`,function(e){var t=pL(e.object);if(t){o.enabled=!1,e.object.__initialPos=e.object.position.clone(),e.object.__prevPos=e.object.position.clone();var n=t.__data;!n.__initialFixedPos&&(n.__initialFixedPos={fx:n.fx,fy:n.fy,fz:n.fz}),!n.__initialPos&&(n.__initialPos={x:n.x,y:n.y,z:n.z}),[`x`,`y`,`z`].forEach(function(e){return n[`f${e}`]=n[e]}),i.domElement.classList.add(`grabbable`)}}),n.addEventListener(`drag`,function(e){var n=pL(e.object);if(n){if(!e.object.hasOwnProperty(`__graphObjType`)){var r=e.object.__initialPos,i=e.object.__prevPos,a=e.object.position;n.position.add(a.clone().sub(i)),i.copy(a),a.copy(r)}var o=n.__data,s=n.position,c={x:s.x-o.x,y:s.y-o.y,z:s.z-o.z};[`x`,`y`,`z`].forEach(function(e){return o[`f${e}`]=o[e]=s[e]}),t.forceGraph.d3AlphaTarget(.3).resetCountdown(),o.__dragged=!0,t.onNodeDrag(o,c)}}),n.addEventListener(`dragend`,function(e){var r=pL(e.object);if(r){delete e.object.__initialPos,delete e.object.__prevPos;var a=r.__data;a.__disposeControlsAfterDrag&&(n.dispose(),delete a.__disposeControlsAfterDrag);var s=a.__initialFixedPos,c=a.__initialPos,l={x:c.x-a.x,y:c.y-a.y,z:c.z-a.z};if(s&&([`x`,`y`,`z`].forEach(function(e){var t=`f${e}`;s[t]===void 0&&delete a[t]}),delete a.__initialFixedPos,delete a.__initialPos,a.__dragged&&(delete a.__dragged,t.onNodeDragEnd(a,l))),t.forceGraph.d3AlphaTarget(0).resetCountdown(),t.enableNavigationControls){var u;o.enabled=!0,o._status&&((u=o._onPointerCancel)==null||u.call(o)),o.domElement&&o.domElement.ownerDocument&&o.domElement.ownerDocument.dispatchEvent(new PointerEvent(`pointerup`,{pointerType:`touch`}))}i.domElement.classList.remove(`grabbable`)}})}}),iL.REVISION<155&&(t.renderObjs.renderer().useLegacyLights=!1),t.renderObjs.hoverOrderComparator(function(e,t){var n=pL(e);if(!n)return 1;var r=pL(t);if(!r)return-1;var i=function(e){return e.__graphObjType===`node`};return i(r)-i(n)}).tooltipContent(function(e){var n=pL(e);return n&&a(t[`${n.__graphObjType}Label`])(n.__data)||``}).hoverDuringDrag(!1).onHover(function(e){var n=pL(e);if(n!==t.hoverObj){var r=t.hoverObj?t.hoverObj.__graphObjType:null,o=t.hoverObj?t.hoverObj.__data:null,s=n?n.__graphObjType:null,c=n?n.__data:null;if(r&&r!==s){var l=t[`on${r===`node`?`Node`:`Link`}Hover`];l&&l(null,o)}if(s){var u=t[`on${s===`node`?`Node`:`Link`}Hover`];u&&u(c,r===s?o:null)}i.domElement.classList[(n&&t[`on${s===`node`?`Node`:`Link`}Click`]||!n&&t.onBackgroundClick)&&a(t.showPointerCursor)(c)?`add`:`remove`](`clickable`),t.hoverObj=n}}).clickAfterDrag(!1).onClick(function(e,n){var r=pL(e);if(r){var i=t[`on${r.__graphObjType===`node`?`Node`:`Link`}Click`];i&&i(r.__data,n)}else t.onBackgroundClick&&t.onBackgroundClick(n)}).onRightClick(function(e,n){var r=pL(e);if(r){var i=t[`on${r.__graphObjType===`node`?`Node`:`Link`}RightClick`];i&&i(r.__data,n)}else t.onBackgroundRightClick&&t.onBackgroundRightClick(n)}),this._animationCycle()}});function pL(e){for(var t=e;t&&!t.hasOwnProperty(`__graphObjType`);)t=t.parent;return t}var $=t(_(),1),mL={width:$.default.number,height:$.default.number,graphData:$.default.shape({nodes:$.default.arrayOf($.default.object).isRequired,links:$.default.arrayOf($.default.object).isRequired}),backgroundColor:$.default.string,nodeRelSize:$.default.number,nodeId:$.default.string,nodeLabel:$.default.oneOfType([$.default.string,$.default.func]),nodeVal:$.default.oneOfType([$.default.number,$.default.string,$.default.func]),nodeVisibility:$.default.oneOfType([$.default.bool,$.default.string,$.default.func]),nodeColor:$.default.oneOfType([$.default.string,$.default.func]),nodeAutoColorBy:$.default.oneOfType([$.default.string,$.default.func]),onNodeHover:$.default.func,onNodeClick:$.default.func,linkSource:$.default.string,linkTarget:$.default.string,linkLabel:$.default.oneOfType([$.default.string,$.default.func]),linkVisibility:$.default.oneOfType([$.default.bool,$.default.string,$.default.func]),linkColor:$.default.oneOfType([$.default.string,$.default.func]),linkAutoColorBy:$.default.oneOfType([$.default.string,$.default.func]),linkWidth:$.default.oneOfType([$.default.number,$.default.string,$.default.func]),linkCurvature:$.default.oneOfType([$.default.number,$.default.string,$.default.func]),linkDirectionalArrowLength:$.default.oneOfType([$.default.number,$.default.string,$.default.func]),linkDirectionalArrowColor:$.default.oneOfType([$.default.string,$.default.func]),linkDirectionalArrowRelPos:$.default.oneOfType([$.default.number,$.default.string,$.default.func]),linkDirectionalParticles:$.default.oneOfType([$.default.number,$.default.string,$.default.func]),linkDirectionalParticleSpeed:$.default.oneOfType([$.default.number,$.default.string,$.default.func]),linkDirectionalParticleOffset:$.default.oneOfType([$.default.number,$.default.string,$.default.func]),linkDirectionalParticleWidth:$.default.oneOfType([$.default.number,$.default.string,$.default.func]),linkDirectionalParticleColor:$.default.oneOfType([$.default.string,$.default.func]),onLinkHover:$.default.func,onLinkClick:$.default.func,dagMode:$.default.oneOf([`td`,`bu`,`lr`,`rl`,`zin`,`zout`,`radialin`,`radialout`]),dagLevelDistance:$.default.number,dagNodeFilter:$.default.func,onDagError:$.default.func,d3AlphaMin:$.default.number,d3AlphaDecay:$.default.number,d3VelocityDecay:$.default.number,warmupTicks:$.default.number,cooldownTicks:$.default.number,cooldownTime:$.default.number,onEngineTick:$.default.func,onEngineStop:$.default.func,getGraphBbox:$.default.func},hL={zoomToFit:$.default.func,onNodeRightClick:$.default.func,onNodeDrag:$.default.func,onNodeDragEnd:$.default.func,onLinkRightClick:$.default.func,linkHoverPrecision:$.default.number,onBackgroundClick:$.default.func,onBackgroundRightClick:$.default.func,showPointerCursor:$.default.oneOfType([$.default.bool,$.default.func]),enablePointerInteraction:$.default.bool,enableNodeDrag:$.default.bool},gL={showNavInfo:$.default.bool,nodeOpacity:$.default.number,nodeResolution:$.default.number,nodeThreeObject:$.default.oneOfType([$.default.object,$.default.string,$.default.func]),nodeThreeObjectExtend:$.default.oneOfType([$.default.bool,$.default.string,$.default.func]),nodePositionUpdate:$.default.func,linkOpacity:$.default.number,linkResolution:$.default.number,linkCurveRotation:$.default.oneOfType([$.default.number,$.default.string,$.default.func]),linkMaterial:$.default.oneOfType([$.default.object,$.default.string,$.default.func]),linkThreeObject:$.default.oneOfType([$.default.object,$.default.string,$.default.func]),linkThreeObjectExtend:$.default.oneOfType([$.default.bool,$.default.string,$.default.func]),linkPositionUpdate:$.default.func,linkDirectionalArrowResolution:$.default.number,linkDirectionalParticleResolution:$.default.number,linkDirectionalParticleThreeObject:$.default.oneOfType([$.default.object,$.default.string,$.default.func]),forceEngine:$.default.oneOf([`d3`,`ngraph`]),ngraphPhysics:$.default.object,numDimensions:$.default.oneOf([1,2,3])};Object.assign({},mL,hL,{linkLineDash:$.default.oneOfType([$.default.arrayOf($.default.number),$.default.string,$.default.func]),nodeCanvasObjectMode:$.default.oneOfType([$.default.string,$.default.func]),nodeCanvasObject:$.default.func,nodePointerAreaPaint:$.default.func,linkCanvasObjectMode:$.default.oneOfType([$.default.string,$.default.func]),linkCanvasObject:$.default.func,linkPointerAreaPaint:$.default.func,linkDirectionalParticleCanvasObject:$.default.func,autoPauseRedraw:$.default.bool,minZoom:$.default.number,maxZoom:$.default.number,enableZoomInteraction:$.default.oneOfType([$.default.bool,$.default.func]),enablePanInteraction:$.default.oneOfType([$.default.bool,$.default.func]),onZoom:$.default.func,onZoomEnd:$.default.func,onRenderFramePre:$.default.func,onRenderFramePost:$.default.func});var _L=Object.assign({},mL,hL,gL,{enableNavigationControls:$.default.bool,controlType:$.default.oneOf([`trackball`,`orbit`,`fly`]),rendererConfig:$.default.object,extraRenderers:$.default.arrayOf($.default.shape({render:$.default.func.isRequired}))});Object.assign({},mL,gL,{nodeDesc:$.default.oneOfType([$.default.string,$.default.func]),linkDesc:$.default.oneOfType([$.default.string,$.default.func])}),Object.assign({},mL,gL,{markerAttrs:$.default.object,yOffset:$.default.number,glScale:$.default.number});var vL=y(fL,{methodNames:[`emitParticle`,`d3Force`,`d3ReheatSimulation`,`stopAnimation`,`pauseAnimation`,`resumeAnimation`,`cameraPosition`,`zoomToFit`,`getGraphBbox`,`screen2GraphCoords`,`graph2ScreenCoords`,`postProcessingComposer`,`lights`,`scene`,`camera`,`renderer`,`controls`,`refresh`],initPropNames:[`controlType`,`rendererConfig`,`extraRenderers`]});vL.displayName=`ForceGraph3D`,vL.propTypes=_L;export{vL as default};