(function(f,uf){typeof exports=="object"&&typeof module<"u"?uf(exports):typeof define=="function"&&define.amd?define(["exports"],uf):(f=typeof globalThis<"u"?globalThis:f||self,uf(f.threepipe={}))})(this,(function(f){"use strict";var Oa,Os,kl,Qr,xo,Hh,Vl,Ua,Js,So,Wh,qh;const Hl={ROTATE:0,DOLLY:1,PAN:2},Ql={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},QP=0,cw=1,jP=2,xA=1,WP=2,qr=3,us=0,In=1,Zi=2,gn=0,Sr=1,df=2,ff=3,pf=4,er=5,Er=100,hw=101,uw=102,dw=103,fw=104,SA=200,EA=201,MA=202,TA=203,jl=204,Wl=205,IA=206,PA=207,DA=208,RA=209,pw=210,Yh=211,$h=212,ql=213,Xl=214,mw=0,gw=1,Aw=2,Yl=3,yw=4,_w=5,vw=6,bw=7,$l=0,qP=1,XP=2,Xr=0,ww=1,Cw=2,xw=3,BA=4,Sw=5,Ew=6,YP=7,Mw="attached",$P="detached",Kh=300,Yr=301,To=302,$r=303,mf=304,Kl=306,Pn=1e3,di=1001,Kr=1002,mi=1003,Jh=1004,Na=1005,at=1006,Io=1007,Dn=1008,Tw=1008,Qt=1009,LA=1010,OA=1011,Jl=1012,gf=1013,tr=1014,Ut=1015,Yt=1016,Af=1017,yf=1018,Po=1020,Iw=35902,Pw=1021,Dw=1022,qt=1023,Rw=1024,Bw=1025,Do=1026,Zl=1027,Jr=1028,_f=1029,Ro=1030,UA=1031,FA=1033,vf=33776,Zh=33777,bf=33778,eu=33779,wf=35840,NA=35841,Cf=35842,kA=35843,xf=36196,Sf=37492,Ef=37496,Mf=37808,GA=37809,zA=37810,VA=37811,tu=37812,HA=37813,QA=37814,jA=37815,WA=37816,qA=37817,XA=37818,YA=37819,$A=37820,KA=37821,iu=36492,JA=36494,ZA=36495,Lw=36283,ey=36284,ty=36285,iy=36286,ny=2200,sy=2201,KP=2202,ec=2300,tc=2301,ry=2302,ic=2400,nc=2401,Tf=2402,ay=2500,Ow=2501,JP=0,Uw=1,oy=2,If=3200,sc=3201,ZP=3202,eD=3203,Us=0,Fw=1,ai="",Ct="srgb",Bt="srgb-linear",nu="display-p3",su="display-p3-linear",Fs="rgbm-16",Pf="linear",Ci="srgb",Df="rec709",Rf="p3",Zr=7680,ly=519,tD=512,iD=513,nD=514,Nw=515,sD=516,rD=517,aD=518,oD=519,Bf=35044,lD="100",cy="300 es",ea=2e3,Lf=2001,kw=3e3,Of=3001;class xi{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){if(this._listeners===void 0)return!1;const i=this._listeners;return i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){if(this._listeners===void 0)return;const n=this._listeners[e];if(n!==void 0){const s=n.indexOf(t);s!==-1&&n.splice(s,1)}}dispatchEvent(e){if(this._listeners===void 0)return;const i=this._listeners[e.type];if(i!==void 0){e.target=this;const n=i.slice(0);for(let s=0,a=n.length;s<a;s++)n[s].call(this,e);e.target=null}}}const kn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let Gw=1234567;const Bo=Math.PI/180,rc=180/Math.PI;function Cs(){const r=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(kn[r&255]+kn[r>>8&255]+kn[r>>16&255]+kn[r>>24&255]+"-"+kn[e&255]+kn[e>>8&255]+"-"+kn[e>>16&15|64]+kn[e>>24&255]+"-"+kn[t&63|128]+kn[t>>8&255]+"-"+kn[t>>16&255]+kn[t>>24&255]+kn[i&255]+kn[i>>8&255]+kn[i>>16&255]+kn[i>>24&255]).toLowerCase()}function Gi(r,e,t){return Math.max(e,Math.min(t,r))}function hy(r,e){return(r%e+e)%e}function cD(r,e,t,i,n){return i+(r-e)*(n-i)/(t-e)}function hD(r,e,t){return r!==e?(t-r)/(e-r):0}function ru(r,e,t){return(1-t)*r+t*e}function uD(r,e,t,i){return ru(r,e,1-Math.exp(-t*i))}function dD(r,e=1){return e-Math.abs(hy(r,e*2)-e)}function fD(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*(3-2*r))}function pD(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*r*(r*(r*6-15)+10))}function mD(r,e){return r+Math.floor(Math.random()*(e-r+1))}function gD(r,e){return r+Math.random()*(e-r)}function AD(r){return r*(.5-Math.random())}function yD(r){r!==void 0&&(Gw=r);let e=Gw+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function _D(r){return r*Bo}function vD(r){return r*rc}function bD(r){return(r&r-1)===0&&r!==0}function wD(r){return Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))}function CD(r){return Math.pow(2,Math.floor(Math.log(r)/Math.LN2))}function xD(r,e,t,i,n){const s=Math.cos,a=Math.sin,o=s(t/2),l=a(t/2),c=s((e+i)/2),h=a((e+i)/2),u=s((e-i)/2),d=a((e-i)/2),p=s((i-e)/2),m=a((i-e)/2);switch(n){case"XYX":r.set(o*h,l*u,l*d,o*c);break;case"YZY":r.set(l*d,o*h,l*u,o*c);break;case"ZXZ":r.set(l*u,l*d,o*h,o*c);break;case"XZX":r.set(o*h,l*m,l*p,o*c);break;case"YXY":r.set(l*p,o*h,l*m,o*c);break;case"ZYZ":r.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function es(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return r/4294967295;case Uint16Array:return r/65535;case Uint8Array:return r/255;case Int32Array:return Math.max(r/2147483647,-1);case Int16Array:return Math.max(r/32767,-1);case Int8Array:return Math.max(r/127,-1);default:throw new Error("Invalid component type.")}}function St(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return Math.round(r*4294967295);case Uint16Array:return Math.round(r*65535);case Uint8Array:return Math.round(r*255);case Int32Array:return Math.round(r*2147483647);case Int16Array:return Math.round(r*32767);case Int8Array:return Math.round(r*127);default:throw new Error("Invalid component type.")}}const Ft={DEG2RAD:Bo,RAD2DEG:rc,generateUUID:Cs,clamp:Gi,euclideanModulo:hy,mapLinear:cD,inverseLerp:hD,lerp:ru,damp:uD,pingpong:dD,smoothstep:fD,smootherstep:pD,randInt:mD,randFloat:gD,randFloatSpread:AD,seededRandom:yD,degToRad:_D,radToDeg:vD,isPowerOfTwo:bD,ceilPowerOfTwo:wD,floorPowerOfTwo:CD,setQuaternionFromProperEuler:xD,normalize:St,denormalize:es};class K{constructor(e=0,t=0){K.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,n=e.elements;return this.x=n[0]*t+n[3]*i+n[6],this.y=n[1]*t+n[4]*i+n[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=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,i)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Gi(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}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,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),n=Math.sin(t),s=this.x-e.x,a=this.y-e.y;return this.x=s*i-a*n+e.x,this.y=s*n+a*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class At{constructor(e,t,i,n,s,a,o,l,c){At.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,n,s,a,o,l,c)}set(e,t,i,n,s,a,o,l,c){const h=this.elements;return h[0]=e,h[1]=n,h[2]=o,h[3]=t,h[4]=s,h[5]=l,h[6]=i,h[7]=a,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,s=this.elements,a=i[0],o=i[3],l=i[6],c=i[1],h=i[4],u=i[7],d=i[2],p=i[5],m=i[8],A=n[0],g=n[3],y=n[6],v=n[1],_=n[4],b=n[7],T=n[2],E=n[5],M=n[8];return s[0]=a*A+o*v+l*T,s[3]=a*g+o*_+l*E,s[6]=a*y+o*b+l*M,s[1]=c*A+h*v+u*T,s[4]=c*g+h*_+u*E,s[7]=c*y+h*b+u*M,s[2]=d*A+p*v+m*T,s[5]=d*g+p*_+m*E,s[8]=d*y+p*b+m*M,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],n=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8];return t*a*h-t*o*c-i*s*h+i*o*l+n*s*c-n*a*l}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=h*a-o*c,d=o*l-h*s,p=c*s-a*l,m=t*u+i*d+n*p;if(m===0)return this.set(0,0,0,0,0,0,0,0,0);const A=1/m;return e[0]=u*A,e[1]=(n*c-h*i)*A,e[2]=(o*i-n*a)*A,e[3]=d*A,e[4]=(h*t-n*l)*A,e[5]=(n*s-o*t)*A,e[6]=p*A,e[7]=(i*l-c*t)*A,e[8]=(a*t-i*s)*A,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,n,s,a,o){const l=Math.cos(s),c=Math.sin(s);return this.set(i*l,i*c,-i*(l*a+c*o)+a+e,-n*c,n*l,-n*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(uy.makeScale(e,t)),this}rotate(e){return this.premultiply(uy.makeRotation(-e)),this}translate(e,t){return this.premultiply(uy.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<9;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const uy=new At;function zw(r){for(let e=r.length-1;e>=0;--e)if(r[e]>=65535)return!0;return!1}const SD={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function ac(r,e){return new SD[r](e)}function au(r){return document.createElementNS("http://www.w3.org/1999/xhtml",r)}function ED(){const r=au("canvas");return r.style.display="block",r}const Vw={};function ta(r){r in Vw||(Vw[r]=!0,console.warn(r))}function MD(r,e,t){return new Promise(function(i,n){function s(){switch(r.clientWaitSync(e,r.SYNC_FLUSH_COMMANDS_BIT,0)){case r.WAIT_FAILED:n();break;case r.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:i()}}setTimeout(s,t)})}const Hw=new At().set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),Qw=new At().set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),ou={[Bt]:{transfer:Pf,primaries:Df,luminanceCoefficients:[.2126,.7152,.0722],toReference:r=>r,fromReference:r=>r},[Ct]:{transfer:Ci,primaries:Df,luminanceCoefficients:[.2126,.7152,.0722],toReference:r=>r.convertSRGBToLinear(),fromReference:r=>r.convertLinearToSRGB()},[su]:{transfer:Pf,primaries:Rf,luminanceCoefficients:[.2289,.6917,.0793],toReference:r=>r.applyMatrix3(Qw),fromReference:r=>r.applyMatrix3(Hw)},[nu]:{transfer:Ci,primaries:Rf,luminanceCoefficients:[.2289,.6917,.0793],toReference:r=>r.convertSRGBToLinear().applyMatrix3(Qw),fromReference:r=>r.applyMatrix3(Hw).convertLinearToSRGB()}},TD=new Set([Bt,su]),Nt={enabled:!0,_workingColorSpace:Bt,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(r){if(!TD.has(r))throw new Error(`Unsupported working color space, "${r}".`);this._workingColorSpace=r},convert:function(r,e,t){if(this.enabled===!1||e===t||!e||!t)return r;const i=ou[e].toReference,n=ou[t].fromReference;return n(i(r))},fromWorkingColorSpace:function(r,e){return this.convert(r,this._workingColorSpace,e)},toWorkingColorSpace:function(r,e){return this.convert(r,e,this._workingColorSpace)},getPrimaries:function(r){return ou[r].primaries},getTransfer:function(r){return r===ai||r===Fs?Pf:ou[r].transfer},getLuminanceCoefficients:function(r,e=this._workingColorSpace){return r.fromArray(ou[e].luminanceCoefficients)}};function oc(r){return r<.04045?r*.0773993808:Math.pow(r*.9478672986+.0521327014,2.4)}function dy(r){return r<.0031308?r*12.92:1.055*Math.pow(r,.41666)-.055}let lc;class fy{static getDataURL(e,t=!1){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{lc===void 0&&(lc=au("canvas")),lc.width=e.width,lc.height=e.height;const n=lc.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),i=lc}return!t&&(i.width>2048||i.height>2048)?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),i.toDataURL("image/jpeg",.6)):i.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=au("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const n=i.getImageData(0,0,e.width,e.height),s=n.data;for(let a=0;a<s.length;a++)s[a]=oc(s[a]/255)*255;return i.putImageData(n,0,0),t}else if(e.data){const t=e.data.slice(0);for(let i=0;i<t.length;i++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[i]=Math.floor(oc(t[i]/255)*255):t[i]=oc(t[i]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let ID=0;class ia{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:ID++}),this.uuid=Cs(),this.data=e,this.dataReady=!0,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const i={uuid:this.uuid,url:""},n=this.data;if(n!==null){let s;if(Array.isArray(n)){s=[];for(let a=0,o=n.length;a<o;a++)n[a].isDataTexture?s.push(py(n[a].image)):s.push(py(n[a]))}else s=py(n);i.url=s}return t||(e.images[this.uuid]=i),i}}function py(r){if(typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&r instanceof ImageBitmap)return fy.getDataURL(r);if(r.data){let e=[];try{e=Array.from(r.data)}catch(t){t.message.includes("Invalid array length")?console.warn("Serializing large texture, might not be saved in JSON structure."):console.error(t),e=r.data}return{data:e,width:r.width,height:r.height,type:r.data.constructor.name}}else return r.url!==void 0?r.url:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let PD=0;class kt extends xi{constructor(e=kt.DEFAULT_IMAGE,t=kt.DEFAULT_MAPPING,i=di,n=di,s=at,a=Dn,o=qt,l=Qt,c=kt.DEFAULT_ANISOTROPY,h=ai){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:PD++}),this.uuid=Cs(),this.name="",this.source=new ia(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=s,this.minFilter=a,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new K(0,0),this.repeat=new K(1,1),this.center=new K(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new At,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,typeof h=="string"?this.colorSpace=h:(ta("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=h===Of?Ct:ai),this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.pmremVersion=0,typeof ImageData<"u"&&e instanceof ImageData&&e!==kt.DEFAULT_IMAGE&&(this.needsUpdate=!0)}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.userData=jw(this.userData,e.userData),this.needsUpdate=!0,this}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,encoding:this.colorSpace===Ct?Of:kw,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&&(i.userData=jw({},this.userData)),!t&&e.textures&&(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Kh)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Pn:e.x=e.x-Math.floor(e.x);break;case di:e.x=e.x<0?0:1;break;case Kr:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Pn:e.y=e.y-Math.floor(e.y);break;case di:e.y=e.y<0?0:1;break;case Kr:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0,this.dispatchEvent({type:"update"}))}get encoding(){return ta("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===Ct?Of:kw}set encoding(e){ta("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===Of?Ct:ai}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}kt.DEFAULT_IMAGE=null,kt.DEFAULT_MAPPING=Kh,kt.DEFAULT_ANISOTROPY=1;const DD=["appliedMaterials","uuid"];function jw(r,e){if(e)for(const t of Object.keys(e))DD.includes(t)||t.startsWith("__")||typeof r[t]=="function"||typeof e[t]=="function"||(r[t]=typeof e[t]=="object"?JSON.parse(JSON.stringify(e[t])):e[t]);return r}class et{constructor(e=0,t=0,i=0,n=1){et.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=n}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,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,s=this.w,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*n+a[12]*s,this.y=a[1]*t+a[5]*i+a[9]*n+a[13]*s,this.z=a[2]*t+a[6]*i+a[10]*n+a[14]*s,this.w=a[3]*t+a[7]*i+a[11]*n+a[15]*s,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,n,s;const l=e.elements,c=l[0],h=l[4],u=l[8],d=l[1],p=l[5],m=l[9],A=l[2],g=l[6],y=l[10];if(Math.abs(h-d)<.01&&Math.abs(u-A)<.01&&Math.abs(m-g)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+A)<.1&&Math.abs(m+g)<.1&&Math.abs(c+p+y-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const _=(c+1)/2,b=(p+1)/2,T=(y+1)/2,E=(h+d)/4,M=(u+A)/4,I=(m+g)/4;return _>b&&_>T?_<.01?(i=0,n=.707106781,s=.707106781):(i=Math.sqrt(_),n=E/i,s=M/i):b>T?b<.01?(i=.707106781,n=0,s=.707106781):(n=Math.sqrt(b),i=E/n,s=I/n):T<.01?(i=.707106781,n=.707106781,s=0):(s=Math.sqrt(T),i=M/s,n=I/s),this.set(i,n,s,t),this}let v=Math.sqrt((g-m)*(g-m)+(u-A)*(u-A)+(d-h)*(d-h));return Math.abs(v)<.001&&(v=1),this.x=(g-m)/v,this.y=(u-A)/v,this.z=(d-h)/v,this.w=Math.acos((c+p+y-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this.w=Math.max(e.w,Math.min(t.w,this.w)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this.w=Math.max(e,Math.min(t,this.w)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,i)))}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,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Ww extends xi{constructor(e=1,t=1,i={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new et(0,0,e,t),this.scissorTest=!1,this.viewport=new et(0,0,e,t);const n={width:e,height:t,depth:1};i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:at,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},i);const s=new kt(n,i.mapping,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.format,i.type,i.anisotropy,i.colorSpace);s.flipY=!1,s.generateMipmaps=i.generateMipmaps,s.internalFormat=i.internalFormat,this.textures=[];const a=i.count;for(let o=0;o<a;o++)this.textures[o]=s.clone(),this.textures[o].isRenderTargetTexture=!0;this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.resolveDepthBuffer=i.resolveDepthBuffer,this.resolveStencilBuffer=i.resolveStencilBuffer,this.depthTexture=i.depthTexture,this.samples=i.samples}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}setSize(e,t,i=1){if(this.width!==e||this.height!==t||this.depth!==i){this.width=e,this.height=t,this.depth=i;for(let n=0,s=this.textures.length;n<s;n++)this.textures[n].image.width=e,this.textures[n].image.height=t,this.textures[n].image.depth=i;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 i=0,n=e.textures.length;i<n;i++)this.textures[i]=e.textures[i].clone(),this.textures[i].isRenderTargetTexture=!0;const t=Object.assign({},e.texture.image);return this.texture.source=new ia(t),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class ds extends Ww{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}}class Uf extends kt{constructor(e=null,t=1,i=1,n=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=mi,this.minFilter=mi,this.wrapR=di,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class RD extends ds{constructor(e=1,t=1,i=1,n={}){super(e,t,n),this.isWebGLArrayRenderTarget=!0,this.depth=i,this.texture=new Uf(null,e,t,i),this.texture.isRenderTargetTexture=!0}}class Ff extends kt{constructor(e=null,t=1,i=1,n=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:i,depth:n},this.magFilter=mi,this.minFilter=mi,this.wrapR=di,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class BD extends ds{constructor(e=1,t=1,i=1,n={}){super(e,t,n),this.isWebGL3DRenderTarget=!0,this.depth=i,this.texture=new Ff(null,e,t,i),this.texture.isRenderTargetTexture=!0}}class $e{constructor(e=0,t=0,i=0,n=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=n}static slerpFlat(e,t,i,n,s,a,o){let l=i[n+0],c=i[n+1],h=i[n+2],u=i[n+3];const d=s[a+0],p=s[a+1],m=s[a+2],A=s[a+3];if(o===0){e[t+0]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u;return}if(o===1){e[t+0]=d,e[t+1]=p,e[t+2]=m,e[t+3]=A;return}if(u!==A||l!==d||c!==p||h!==m){let g=1-o;const y=l*d+c*p+h*m+u*A,v=y>=0?1:-1,_=1-y*y;if(_>Number.EPSILON){const T=Math.sqrt(_),E=Math.atan2(T,y*v);g=Math.sin(g*E)/T,o=Math.sin(o*E)/T}const b=o*v;if(l=l*g+d*b,c=c*g+p*b,h=h*g+m*b,u=u*g+A*b,g===1-o){const T=1/Math.sqrt(l*l+c*c+h*h+u*u);l*=T,c*=T,h*=T,u*=T}}e[t]=l,e[t+1]=c,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,i,n,s,a){const o=i[n],l=i[n+1],c=i[n+2],h=i[n+3],u=s[a],d=s[a+1],p=s[a+2],m=s[a+3];return e[t]=o*m+h*u+l*p-c*d,e[t+1]=l*m+h*d+c*u-o*p,e[t+2]=c*m+h*p+o*d-l*u,e[t+3]=h*m-o*u-l*d-c*p,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,i,n){return this._x=e,this._y=t,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,n=e._y,s=e._z,a=e._order,o=Math.cos,l=Math.sin,c=o(i/2),h=o(n/2),u=o(s/2),d=l(i/2),p=l(n/2),m=l(s/2);switch(a){case"XYZ":this._x=d*h*u+c*p*m,this._y=c*p*u-d*h*m,this._z=c*h*m+d*p*u,this._w=c*h*u-d*p*m;break;case"YXZ":this._x=d*h*u+c*p*m,this._y=c*p*u-d*h*m,this._z=c*h*m-d*p*u,this._w=c*h*u+d*p*m;break;case"ZXY":this._x=d*h*u-c*p*m,this._y=c*p*u+d*h*m,this._z=c*h*m+d*p*u,this._w=c*h*u-d*p*m;break;case"ZYX":this._x=d*h*u-c*p*m,this._y=c*p*u+d*h*m,this._z=c*h*m-d*p*u,this._w=c*h*u+d*p*m;break;case"YZX":this._x=d*h*u+c*p*m,this._y=c*p*u+d*h*m,this._z=c*h*m-d*p*u,this._w=c*h*u-d*p*m;break;case"XZY":this._x=d*h*u-c*p*m,this._y=c*p*u-d*h*m,this._z=c*h*m+d*p*u,this._w=c*h*u+d*p*m;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,n=Math.sin(i);return this._x=e.x*n,this._y=e.y*n,this._z=e.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],n=t[4],s=t[8],a=t[1],o=t[5],l=t[9],c=t[2],h=t[6],u=t[10],d=i+o+u;if(d>0){const p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(h-l)*p,this._y=(s-c)*p,this._z=(a-n)*p}else if(i>o&&i>u){const p=2*Math.sqrt(1+i-o-u);this._w=(h-l)/p,this._x=.25*p,this._y=(n+a)/p,this._z=(s+c)/p}else if(o>u){const p=2*Math.sqrt(1+o-i-u);this._w=(s-c)/p,this._x=(n+a)/p,this._y=.25*p,this._z=(l+h)/p}else{const p=2*Math.sqrt(1+u-i-o);this._w=(a-n)/p,this._x=(s+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<Number.EPSILON?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(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=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Gi(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const n=Math.min(1,t/i);return this.slerp(e,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,n=e._y,s=e._z,a=e._w,o=t._x,l=t._y,c=t._z,h=t._w;return this._x=i*h+a*o+n*c-s*l,this._y=n*h+a*l+s*o-i*c,this._z=s*h+a*c+i*l-n*o,this._w=a*h-i*o-n*l-s*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const i=this._x,n=this._y,s=this._z,a=this._w;let o=a*e._w+i*e._x+n*e._y+s*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=i,this._y=n,this._z=s,this;const l=1-o*o;if(l<=Number.EPSILON){const p=1-t;return this._w=p*a+t*this._w,this._x=p*i+t*this._x,this._y=p*n+t*this._y,this._z=p*s+t*this._z,this.normalize(),this}const c=Math.sqrt(l),h=Math.atan2(c,o),u=Math.sin((1-t)*h)/c,d=Math.sin(t*h)/c;return this._w=a*u+this._w*d,this._x=i*u+this._x*d,this._y=n*u+this._y*d,this._z=s*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),n=Math.sqrt(1-i),s=Math.sqrt(i);return this.set(n*Math.sin(e),n*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class S{constructor(e=0,t=0,i=0){S.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(qw.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(qw.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,n=this.z,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6]*n,this.y=s[1]*t+s[4]*i+s[7]*n,this.z=s[2]*t+s[5]*i+s[8]*n,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,s=e.elements,a=1/(s[3]*t+s[7]*i+s[11]*n+s[15]);return this.x=(s[0]*t+s[4]*i+s[8]*n+s[12])*a,this.y=(s[1]*t+s[5]*i+s[9]*n+s[13])*a,this.z=(s[2]*t+s[6]*i+s[10]*n+s[14])*a,this}applyQuaternion(e){const t=this.x,i=this.y,n=this.z,s=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*n-o*i),h=2*(o*t-s*n),u=2*(s*i-a*t);return this.x=t+l*c+a*u-o*h,this.y=i+l*h+o*c-s*u,this.z=n+l*u+s*h-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){const t=this.x,i=this.y,n=this.z,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*n,this.y=s[1]*t+s[5]*i+s[9]*n,this.z=s[2]*t+s[6]*i+s[10]*n,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=Math.max(e.x,Math.min(t.x,this.x)),this.y=Math.max(e.y,Math.min(t.y,this.y)),this.z=Math.max(e.z,Math.min(t.z,this.z)),this}clampScalar(e,t){return this.x=Math.max(e,Math.min(t,this.x)),this.y=Math.max(e,Math.min(t,this.y)),this.z=Math.max(e,Math.min(t,this.z)),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Math.max(e,Math.min(t,i)))}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,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,n=e.y,s=e.z,a=t.x,o=t.y,l=t.z;return this.x=n*l-s*o,this.y=s*a-i*l,this.z=i*o-n*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return my.copy(this).projectOnVector(e),this.sub(my)}reflect(e){return this.sub(my.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Gi(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,n=this.z-e.z;return t*t+i*i+n*n}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,i){const n=Math.sin(t)*e;return this.x=n*Math.sin(i),this.y=Math.cos(t)*e,this.z=n*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),n=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=n,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const my=new S,qw=new $e;class en{constructor(e=new S(1/0,1/0,1/0),t=new S(-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,i=e.length;t<i;t+=3)this.expandByPoint(ir.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint(ir.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const i=ir.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const i=e.geometry;if(i!==void 0){const s=i.getAttribute("position");if(t===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=s.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,ir):ir.fromBufferAttribute(s,a),ir.applyMatrix4(e.matrixWorld),this.expandByPoint(ir);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Nf.copy(e.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),Nf.copy(i.boundingBox)),Nf.applyMatrix4(e.matrixWorld),this.union(Nf)}const n=e.children;for(let s=0,a=n.length;s<a;s++)this.expandByObject(n[s],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,ir),ir.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(lu),kf.subVectors(this.max,lu),cc.subVectors(e.a,lu),hc.subVectors(e.b,lu),uc.subVectors(e.c,lu),ka.subVectors(hc,cc),Ga.subVectors(uc,hc),Lo.subVectors(cc,uc);let t=[0,-ka.z,ka.y,0,-Ga.z,Ga.y,0,-Lo.z,Lo.y,ka.z,0,-ka.x,Ga.z,0,-Ga.x,Lo.z,0,-Lo.x,-ka.y,ka.x,0,-Ga.y,Ga.x,0,-Lo.y,Lo.x,0];return!gy(t,cc,hc,uc,kf)||(t=[1,0,0,0,1,0,0,0,1],!gy(t,cc,hc,uc,kf))?!1:(Gf.crossVectors(ka,Ga),t=[Gf.x,Gf.y,Gf.z],gy(t,cc,hc,uc,kf))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ir).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ir).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:(na[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),na[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),na[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),na[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),na[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),na[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),na[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),na[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(na),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)}}const na=[new S,new S,new S,new S,new S,new S,new S,new S],ir=new S,Nf=new en,cc=new S,hc=new S,uc=new S,ka=new S,Ga=new S,Lo=new S,lu=new S,kf=new S,Gf=new S,Oo=new S;function gy(r,e,t,i,n){for(let s=0,a=r.length-3;s<=a;s+=3){Oo.fromArray(r,s);const o=n.x*Math.abs(Oo.x)+n.y*Math.abs(Oo.y)+n.z*Math.abs(Oo.z),l=e.dot(Oo),c=t.dot(Oo),h=i.dot(Oo);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>o)return!1}return!0}const LD=new en,cu=new S,Ay=new S;class un{constructor(e=new S,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):LD.setFromPoints(e).getCenter(i);let n=0;for(let s=0,a=e.length;s<a;s++)n=Math.max(n,i.distanceToSquared(e[s]));return this.radius=Math.sqrt(n),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const i=this.center.distanceToSquared(e);return t.copy(e),i>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;cu.subVectors(e,this.center);const t=cu.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),n=(i-this.radius)*.5;this.center.addScaledVector(cu,n/i),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):(Ay.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(cu.copy(e.center).add(Ay)),this.expandByPoint(cu.copy(e.center).sub(Ay))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const sa=new S,yy=new S,zf=new S,za=new S,_y=new S,Vf=new S,vy=new S;class Va{constructor(e=new S,t=new S(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,sa)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=sa.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(sa.copy(this.origin).addScaledVector(this.direction,t),sa.distanceToSquared(e))}distanceSqToSegment(e,t,i,n){yy.copy(e).add(t).multiplyScalar(.5),zf.copy(t).sub(e).normalize(),za.copy(this.origin).sub(yy);const s=e.distanceTo(t)*.5,a=-this.direction.dot(zf),o=za.dot(this.direction),l=-za.dot(zf),c=za.lengthSq(),h=Math.abs(1-a*a);let u,d,p,m;if(h>0)if(u=a*l-o,d=a*o-l,m=s*h,u>=0)if(d>=-m)if(d<=m){const A=1/h;u*=A,d*=A,p=u*(u+a*d+2*o)+d*(a*u+d+2*l)+c}else d=s,u=Math.max(0,-(a*d+o)),p=-u*u+d*(d+2*l)+c;else d=-s,u=Math.max(0,-(a*d+o)),p=-u*u+d*(d+2*l)+c;else d<=-m?(u=Math.max(0,-(-a*s+o)),d=u>0?-s:Math.min(Math.max(-s,-l),s),p=-u*u+d*(d+2*l)+c):d<=m?(u=0,d=Math.min(Math.max(-s,-l),s),p=d*(d+2*l)+c):(u=Math.max(0,-(a*s+o)),d=u>0?s:Math.min(Math.max(-s,-l),s),p=-u*u+d*(d+2*l)+c);else d=a>0?-s:s,u=Math.max(0,-(a*d+o)),p=-u*u+d*(d+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,u),n&&n.copy(yy).addScaledVector(zf,d),p}intersectSphere(e,t){sa.subVectors(e.center,this.origin);const i=sa.dot(this.direction),n=sa.dot(sa)-i*i,s=e.radius*e.radius;if(n>s)return null;const a=Math.sqrt(s-n),o=i-a,l=i+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,n,s,a,o,l;const c=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(i=(e.min.x-d.x)*c,n=(e.max.x-d.x)*c):(i=(e.max.x-d.x)*c,n=(e.min.x-d.x)*c),h>=0?(s=(e.min.y-d.y)*h,a=(e.max.y-d.y)*h):(s=(e.max.y-d.y)*h,a=(e.min.y-d.y)*h),i>a||s>n||((s>i||isNaN(i))&&(i=s),(a<n||isNaN(n))&&(n=a),u>=0?(o=(e.min.z-d.z)*u,l=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,l=(e.min.z-d.z)*u),i>l||o>n)||((o>i||i!==i)&&(i=o),(l<n||n!==n)&&(n=l),n<0)?null:this.at(i>=0?i:n,t)}intersectsBox(e){return this.intersectBox(e,sa)!==null}intersectTriangle(e,t,i,n,s){_y.subVectors(t,e),Vf.subVectors(i,e),vy.crossVectors(_y,Vf);let a=this.direction.dot(vy),o;if(a>0){if(n)return null;o=1}else if(a<0)o=-1,a=-a;else return null;za.subVectors(this.origin,e);const l=o*this.direction.dot(Vf.crossVectors(za,Vf));if(l<0)return null;const c=o*this.direction.dot(_y.cross(za));if(c<0||l+c>a)return null;const h=-o*za.dot(vy);return h<0?null:this.at(h/a,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class fe{constructor(e,t,i,n,s,a,o,l,c,h,u,d,p,m,A,g){fe.prototype.isMatrix4=!0,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,i,n,s,a,o,l,c,h,u,d,p,m,A,g)}set(e,t,i,n,s,a,o,l,c,h,u,d,p,m,A,g){const y=this.elements;return y[0]=e,y[4]=t,y[8]=i,y[12]=n,y[1]=s,y[5]=a,y[9]=o,y[13]=l,y[2]=c,y[6]=h,y[10]=u,y[14]=d,y[3]=p,y[7]=m,y[11]=A,y[15]=g,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 fe().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,n=1/dc.setFromMatrixColumn(e,0).length(),s=1/dc.setFromMatrixColumn(e,1).length(),a=1/dc.setFromMatrixColumn(e,2).length();return t[0]=i[0]*n,t[1]=i[1]*n,t[2]=i[2]*n,t[3]=0,t[4]=i[4]*s,t[5]=i[5]*s,t[6]=i[6]*s,t[7]=0,t[8]=i[8]*a,t[9]=i[9]*a,t[10]=i[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,n=e.y,s=e.z,a=Math.cos(i),o=Math.sin(i),l=Math.cos(n),c=Math.sin(n),h=Math.cos(s),u=Math.sin(s);if(e.order==="XYZ"){const d=a*h,p=a*u,m=o*h,A=o*u;t[0]=l*h,t[4]=-l*u,t[8]=c,t[1]=p+m*c,t[5]=d-A*c,t[9]=-o*l,t[2]=A-d*c,t[6]=m+p*c,t[10]=a*l}else if(e.order==="YXZ"){const d=l*h,p=l*u,m=c*h,A=c*u;t[0]=d+A*o,t[4]=m*o-p,t[8]=a*c,t[1]=a*u,t[5]=a*h,t[9]=-o,t[2]=p*o-m,t[6]=A+d*o,t[10]=a*l}else if(e.order==="ZXY"){const d=l*h,p=l*u,m=c*h,A=c*u;t[0]=d-A*o,t[4]=-a*u,t[8]=m+p*o,t[1]=p+m*o,t[5]=a*h,t[9]=A-d*o,t[2]=-a*c,t[6]=o,t[10]=a*l}else if(e.order==="ZYX"){const d=a*h,p=a*u,m=o*h,A=o*u;t[0]=l*h,t[4]=m*c-p,t[8]=d*c+A,t[1]=l*u,t[5]=A*c+d,t[9]=p*c-m,t[2]=-c,t[6]=o*l,t[10]=a*l}else if(e.order==="YZX"){const d=a*l,p=a*c,m=o*l,A=o*c;t[0]=l*h,t[4]=A-d*u,t[8]=m*u+p,t[1]=u,t[5]=a*h,t[9]=-o*h,t[2]=-c*h,t[6]=p*u+m,t[10]=d-A*u}else if(e.order==="XZY"){const d=a*l,p=a*c,m=o*l,A=o*c;t[0]=l*h,t[4]=-u,t[8]=c*h,t[1]=d*u+A,t[5]=a*h,t[9]=p*u-m,t[2]=m*u-p,t[6]=o*h,t[10]=A*u+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(OD,e,UD)}lookAt(e,t,i){const n=this.elements;return xs.subVectors(e,t),xs.lengthSq()===0&&(xs.z=1),xs.normalize(),Ha.crossVectors(i,xs),Ha.lengthSq()===0&&(Math.abs(i.z)===1?xs.x+=1e-4:xs.z+=1e-4,xs.normalize(),Ha.crossVectors(i,xs)),Ha.normalize(),Hf.crossVectors(xs,Ha),n[0]=Ha.x,n[4]=Hf.x,n[8]=xs.x,n[1]=Ha.y,n[5]=Hf.y,n[9]=xs.y,n[2]=Ha.z,n[6]=Hf.z,n[10]=xs.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,n=t.elements,s=this.elements,a=i[0],o=i[4],l=i[8],c=i[12],h=i[1],u=i[5],d=i[9],p=i[13],m=i[2],A=i[6],g=i[10],y=i[14],v=i[3],_=i[7],b=i[11],T=i[15],E=n[0],M=n[4],I=n[8],C=n[12],x=n[1],D=n[5],U=n[9],O=n[13],N=n[2],H=n[6],V=n[10],X=n[14],W=n[3],ce=n[7],ue=n[11],we=n[15];return s[0]=a*E+o*x+l*N+c*W,s[4]=a*M+o*D+l*H+c*ce,s[8]=a*I+o*U+l*V+c*ue,s[12]=a*C+o*O+l*X+c*we,s[1]=h*E+u*x+d*N+p*W,s[5]=h*M+u*D+d*H+p*ce,s[9]=h*I+u*U+d*V+p*ue,s[13]=h*C+u*O+d*X+p*we,s[2]=m*E+A*x+g*N+y*W,s[6]=m*M+A*D+g*H+y*ce,s[10]=m*I+A*U+g*V+y*ue,s[14]=m*C+A*O+g*X+y*we,s[3]=v*E+_*x+b*N+T*W,s[7]=v*M+_*D+b*H+T*ce,s[11]=v*I+_*U+b*V+T*ue,s[15]=v*C+_*O+b*X+T*we,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],n=e[8],s=e[12],a=e[1],o=e[5],l=e[9],c=e[13],h=e[2],u=e[6],d=e[10],p=e[14],m=e[3],A=e[7],g=e[11],y=e[15];return m*(+s*l*u-n*c*u-s*o*d+i*c*d+n*o*p-i*l*p)+A*(+t*l*p-t*c*d+s*a*d-n*a*p+n*c*h-s*l*h)+g*(+t*c*u-t*o*p-s*a*u+i*a*p+s*o*h-i*c*h)+y*(-n*o*h-t*l*u+t*o*d+n*a*u-i*a*d+i*l*h)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const n=this.elements;return e.isVector3?(n[12]=e.x,n[13]=e.y,n[14]=e.z):(n[12]=e,n[13]=t,n[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],h=e[8],u=e[9],d=e[10],p=e[11],m=e[12],A=e[13],g=e[14],y=e[15],v=u*g*c-A*d*c+A*l*p-o*g*p-u*l*y+o*d*y,_=m*d*c-h*g*c-m*l*p+a*g*p+h*l*y-a*d*y,b=h*A*c-m*u*c+m*o*p-a*A*p-h*o*y+a*u*y,T=m*u*l-h*A*l-m*o*d+a*A*d+h*o*g-a*u*g,E=t*v+i*_+n*b+s*T;if(E===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const M=1/E;return e[0]=v*M,e[1]=(A*d*s-u*g*s-A*n*p+i*g*p+u*n*y-i*d*y)*M,e[2]=(o*g*s-A*l*s+A*n*c-i*g*c-o*n*y+i*l*y)*M,e[3]=(u*l*s-o*d*s-u*n*c+i*d*c+o*n*p-i*l*p)*M,e[4]=_*M,e[5]=(h*g*s-m*d*s+m*n*p-t*g*p-h*n*y+t*d*y)*M,e[6]=(m*l*s-a*g*s-m*n*c+t*g*c+a*n*y-t*l*y)*M,e[7]=(a*d*s-h*l*s+h*n*c-t*d*c-a*n*p+t*l*p)*M,e[8]=b*M,e[9]=(m*u*s-h*A*s-m*i*p+t*A*p+h*i*y-t*u*y)*M,e[10]=(a*A*s-m*o*s+m*i*c-t*A*c-a*i*y+t*o*y)*M,e[11]=(h*o*s-a*u*s-h*i*c+t*u*c+a*i*p-t*o*p)*M,e[12]=T*M,e[13]=(h*A*n-m*u*n+m*i*d-t*A*d-h*i*g+t*u*g)*M,e[14]=(m*o*n-a*A*n-m*i*l+t*A*l+a*i*g-t*o*g)*M,e[15]=(a*u*n-h*o*n+h*i*l-t*u*l-a*i*d+t*o*d)*M,this}scale(e){const t=this.elements,i=e.x,n=e.y,s=e.z;return t[0]*=i,t[4]*=n,t[8]*=s,t[1]*=i,t[5]*=n,t[9]*=s,t[2]*=i,t[6]*=n,t[10]*=s,t[3]*=i,t[7]*=n,t[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],n=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,n))}makeTranslation(e,t,i){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,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),n=Math.sin(t),s=1-i,a=e.x,o=e.y,l=e.z,c=s*a,h=s*o;return this.set(c*a+i,c*o-n*l,c*l+n*o,0,c*o+n*l,h*o+i,h*l-n*a,0,c*l-n*o,h*l+n*a,s*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,n,s,a){return this.set(1,i,s,0,e,1,a,0,t,n,1,0,0,0,0,1),this}compose(e,t,i){const n=this.elements,s=t._x,a=t._y,o=t._z,l=t._w,c=s+s,h=a+a,u=o+o,d=s*c,p=s*h,m=s*u,A=a*h,g=a*u,y=o*u,v=l*c,_=l*h,b=l*u,T=i.x,E=i.y,M=i.z;return n[0]=(1-(A+y))*T,n[1]=(p+b)*T,n[2]=(m-_)*T,n[3]=0,n[4]=(p-b)*E,n[5]=(1-(d+y))*E,n[6]=(g+v)*E,n[7]=0,n[8]=(m+_)*M,n[9]=(g-v)*M,n[10]=(1-(d+A))*M,n[11]=0,n[12]=e.x,n[13]=e.y,n[14]=e.z,n[15]=1,this}decompose(e,t,i){const n=this.elements;let s=dc.set(n[0],n[1],n[2]).length();const a=dc.set(n[4],n[5],n[6]).length(),o=dc.set(n[8],n[9],n[10]).length();this.determinant()<0&&(s=-s),e.x=n[12],e.y=n[13],e.z=n[14],nr.copy(this);const c=1/s,h=1/a,u=1/o;return nr.elements[0]*=c,nr.elements[1]*=c,nr.elements[2]*=c,nr.elements[4]*=h,nr.elements[5]*=h,nr.elements[6]*=h,nr.elements[8]*=u,nr.elements[9]*=u,nr.elements[10]*=u,t.setFromRotationMatrix(nr),i.x=s,i.y=a,i.z=o,this}makePerspective(e,t,i,n,s,a,o=ea){const l=this.elements,c=2*s/(t-e),h=2*s/(i-n),u=(t+e)/(t-e),d=(i+n)/(i-n);let p,m;if(o===ea)p=-(a+s)/(a-s),m=-2*a*s/(a-s);else if(o===Lf)p=-a/(a-s),m=-a*s/(a-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=c,l[4]=0,l[8]=u,l[12]=0,l[1]=0,l[5]=h,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=m,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,i,n,s,a,o=ea){const l=this.elements,c=1/(t-e),h=1/(i-n),u=1/(a-s),d=(t+e)*c,p=(i+n)*h;let m,A;if(o===ea)m=(a+s)*u,A=-2*u;else if(o===Lf)m=s*u,A=-1*u;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-d,l[1]=0,l[5]=2*h,l[9]=0,l[13]=-p,l[2]=0,l[6]=0,l[10]=A,l[14]=-m,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let n=0;n<16;n++)if(t[n]!==i[n])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const dc=new S,nr=new fe,OD=new S(0,0,0),UD=new S(1,1,1),Ha=new S,Hf=new S,xs=new S,Xw=new fe,Yw=new $e;class Pt{constructor(e=0,t=0,i=0,n=Pt.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=n}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,i,n=this._order){return this._x=e,this._y=t,this._z=i,this._order=n,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,i=!0){const n=e.elements,s=n[0],a=n[4],o=n[8],l=n[1],c=n[5],h=n[9],u=n[2],d=n[6],p=n[10];switch(t){case"XYZ":this._y=Math.asin(Gi(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-a,s)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Gi(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,s),this._z=0);break;case"ZXY":this._x=Math.asin(Gi(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,p),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-Gi(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(Gi(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,s)):(this._x=0,this._y=Math.atan2(o,p));break;case"XZY":this._z=Math.asin(-Gi(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,s)):(this._x=Math.atan2(-h,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return Xw.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Xw,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Yw.setFromEuler(this),this.setFromQuaternion(Yw,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}}Pt.DEFAULT_ORDER="XYZ";class Qf{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let FD=0;const $w=new S,fc=new $e,ra=new fe,jf=new S,hu=new S,ND=new S,kD=new $e,Kw=new S(1,0,0),Jw=new S(0,1,0),Zw=new S(0,0,1),eC={type:"added"},GD={type:"removed"},pc={type:"childadded",child:null},by={type:"childremoved",child:null};class ft extends xi{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:FD++}),this.uuid=Cs(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=ft.DEFAULT_UP.clone();const e=new S,t=new Pt,i=new $e,n=new S(1,1,1);function s(){i.setFromEuler(t,!1)}function a(){t.setFromQuaternion(i,void 0,!1)}t._onChange(s),i._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new fe},normalMatrix:{value:new At}}),this.matrix=new fe,this.matrixWorld=new fe,this.matrixAutoUpdate=ft.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=ft.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Qf,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(e,t,i,n,s,a){this.dispatchEvent({type:"beforeRender",renderer:e,scene:t,camera:i,geometry:n,material:s,group:a})}onAfterRender(e,t,i,n,s,a){this.dispatchEvent({type:"afterRender",renderer:e,scene:t,camera:i,geometry:n,material:s,group:a})}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 fc.setFromAxisAngle(e,t),this.quaternion.multiply(fc),this}rotateOnWorldAxis(e,t){return fc.setFromAxisAngle(e,t),this.quaternion.premultiply(fc),this}rotateX(e){return this.rotateOnAxis(Kw,e)}rotateY(e){return this.rotateOnAxis(Jw,e)}rotateZ(e){return this.rotateOnAxis(Zw,e)}translateOnAxis(e,t){return $w.copy(e).applyQuaternion(this.quaternion),this.position.add($w.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Kw,e)}translateY(e){return this.translateOnAxis(Jw,e)}translateZ(e){return this.translateOnAxis(Zw,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(ra.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?jf.copy(e):jf.set(e,t,i);const n=this.parent;this.updateWorldMatrix(!0,!1),hu.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?ra.lookAt(hu,jf,this.up):ra.lookAt(jf,hu,this.up),this.quaternion.setFromRotationMatrix(ra),n&&(ra.extractRotation(n.matrixWorld),fc.setFromRotationMatrix(ra),this.quaternion.premultiply(fc.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(eC),pc.child=e,this.dispatchEvent(pc),pc.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(GD),by.child=e,this.dispatchEvent(by),by.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),ra.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),ra.multiply(e.parent.matrixWorld)),e.applyMatrix4(ra),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(eC),pc.child=e,this.dispatchEvent(pc),pc.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 i=0,n=this.children.length;i<n;i++){const a=this.children[i].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,i=[]){this[e]===t&&i.push(this);const n=this.children;for(let s=0,a=n.length;s<a;s++)n[s].getObjectsByProperty(e,t,i);return i}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(hu,e,ND),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(hu,kD,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let i=0,n=t.length;i<n;i++)t[i].updateMatrixWorld(e)}updateWorldMatrix(e,t){const i=this.parent;if(e===!0&&i!==null&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const n=this.children;for(let s=0,a=n.length;s<a;s++)n[s].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",i={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{},extras:{}},i.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const n={};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.castShadow===!0&&(n.castShadow=!0),this.receiveShadow===!0&&(n.receiveShadow=!0),this.visible===!1&&(n.visible=!1),this.frustumCulled===!1&&(n.frustumCulled=!1),this.renderOrder!==0&&(n.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.visibility=this._visibility,n.active=this._active,n.bounds=this._bounds.map(o=>({boxInitialized:o.boxInitialized,boxMin:o.box.min.toArray(),boxMax:o.box.max.toArray(),sphereInitialized:o.sphereInitialized,sphereRadius:o.sphere.radius,sphereCenter:o.sphere.center.toArray()})),n.maxInstanceCount=this._maxInstanceCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.geometryCount=this._geometryCount,n.matricesTexture=this._matricesTexture.toJSON(e),this._colorsTexture!==null&&(n.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(n.boundingSphere={center:n.boundingSphere.center.toArray(),radius:n.boundingSphere.radius}),this.boundingBox!==null&&(n.boundingBox={min:n.boundingBox.min.toArray(),max:n.boundingBox.max.toArray()}));function s(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=s(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const l=o.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c<h;c++){const u=l[c];s(e.shapes,u)}else s(e.shapes,l)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let l=0,c=this.material.length;l<c;l++)o.push(s(e.materials,this.material[l]));n.material=o}else n.material=s(e.materials,this.material);if(this.children.length>0){n.children=[];for(let o=0;o<this.children.length;o++)n.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){n.animations=[];for(let o=0;o<this.animations.length;o++){const l=this.animations[o];n.animations.push(s(e.animations,l))}}if(t){const o=a(e.geometries),l=a(e.materials),c=a(e.textures),h=a(e.images),u=a(e.shapes),d=a(e.skeletons),p=a(e.animations),m=a(e.nodes);o.length>0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),h.length>0&&(i.images=h),u.length>0&&(i.shapes=u),d.length>0&&(i.skeletons=d),p.length>0&&(i.animations=p),m.length>0&&(i.nodes=m)}return i.object=n,i;function a(o){const l=[];for(const c in o){const h=o[c];delete h.metadata,l.push(h)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData={};for(const[i,n]of Object.entries(e.userData))this.userData[i]=!n||n&&(n.isTexture||n.isObject3D)?n:JSON.parse(JSON.stringify(n));if(t===!0)for(let i=0;i<e.children.length;i++){const n=e.children[i];this.add(n.clone())}return this}}ft.DEFAULT_UP=new S(0,1,0),ft.DEFAULT_MATRIX_AUTO_UPDATE=!0,ft.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const sr=new S,aa=new S,wy=new S,oa=new S,mc=new S,gc=new S,tC=new S,Cy=new S,xy=new S,Sy=new S;class ts{constructor(e=new S,t=new S,i=new S){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,n){n.subVectors(i,t),sr.subVectors(e,t),n.cross(sr);const s=n.lengthSq();return s>0?n.multiplyScalar(1/Math.sqrt(s)):n.set(0,0,0)}static getBarycoord(e,t,i,n,s){sr.subVectors(n,t),aa.subVectors(i,t),wy.subVectors(e,t);const a=sr.dot(sr),o=sr.dot(aa),l=sr.dot(wy),c=aa.dot(aa),h=aa.dot(wy),u=a*c-o*o;if(u===0)return s.set(0,0,0),null;const d=1/u,p=(c*l-o*h)*d,m=(a*h-o*l)*d;return s.set(1-p-m,m,p)}static containsPoint(e,t,i,n){return this.getBarycoord(e,t,i,n,oa)===null?!1:oa.x>=0&&oa.y>=0&&oa.x+oa.y<=1}static getInterpolation(e,t,i,n,s,a,o,l){return this.getBarycoord(e,t,i,n,oa)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,oa.x),l.addScaledVector(a,oa.y),l.addScaledVector(o,oa.z),l)}static isFrontFacing(e,t,i,n){return sr.subVectors(i,t),aa.subVectors(e,t),sr.cross(aa).dot(n)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,n){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[n]),this}setFromAttributeAndIndices(e,t,i,n){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,n),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 sr.subVectors(this.c,this.b),aa.subVectors(this.a,this.b),sr.cross(aa).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return ts.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return ts.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,n,s){return ts.getInterpolation(e,this.a,this.b,this.c,t,i,n,s)}containsPoint(e){return ts.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return ts.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,n=this.b,s=this.c;let a,o;mc.subVectors(n,i),gc.subVectors(s,i),Cy.subVectors(e,i);const l=mc.dot(Cy),c=gc.dot(Cy);if(l<=0&&c<=0)return t.copy(i);xy.subVectors(e,n);const h=mc.dot(xy),u=gc.dot(xy);if(h>=0&&u<=h)return t.copy(n);const d=l*u-h*c;if(d<=0&&l>=0&&h<=0)return a=l/(l-h),t.copy(i).addScaledVector(mc,a);Sy.subVectors(e,s);const p=mc.dot(Sy),m=gc.dot(Sy);if(m>=0&&p<=m)return t.copy(s);const A=p*c-l*m;if(A<=0&&c>=0&&m<=0)return o=c/(c-m),t.copy(i).addScaledVector(gc,o);const g=h*m-p*u;if(g<=0&&u-h>=0&&p-m>=0)return tC.subVectors(s,n),o=(u-h)/(u-h+(p-m)),t.copy(n).addScaledVector(tC,o);const y=1/(g+A+d);return a=A*y,o=d*y,t.copy(i).addScaledVector(mc,a).addScaledVector(gc,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const iC={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},Qa={h:0,s:0,l:0},Wf={h:0,s:0,l:0};function Ey(r,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?r+(e-r)*6*t:t<1/2?e:t<2/3?r+(e-r)*6*(2/3-t):r}class ee{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const n=e;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Ct){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Nt.toWorkingColorSpace(this,t),this}setRGB(e,t,i,n=Nt.workingColorSpace){return this.r=e,this.g=t,this.b=i,Nt.toWorkingColorSpace(this,n),this}setHSL(e,t,i,n=Nt.workingColorSpace){if(e=hy(e,1),t=Gi(t,0,1),i=Gi(i,0,1),t===0)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+t):i+t-i*t,a=2*i-s;this.r=Ey(a,s,e+1/3),this.g=Ey(a,s,e),this.b=Ey(a,s,e-1/3)}return Nt.toWorkingColorSpace(this,n),this}setStyle(e,t=Ct){function i(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const a=n[1],o=n[2];switch(a){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=n[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(s,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Ct){const i=iC[e.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=oc(e.r),this.g=oc(e.g),this.b=oc(e.b),this}copyLinearToSRGB(e){return this.r=dy(e.r),this.g=dy(e.g),this.b=dy(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Ct){return Nt.fromWorkingColorSpace(Gn.copy(this),e),Math.round(Gi(Gn.r*255,0,255))*65536+Math.round(Gi(Gn.g*255,0,255))*256+Math.round(Gi(Gn.b*255,0,255))}getHexString(e=Ct){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Nt.workingColorSpace){Nt.fromWorkingColorSpace(Gn.copy(this),t);const i=Gn.r,n=Gn.g,s=Gn.b,a=Math.max(i,n,s),o=Math.min(i,n,s);let l,c;const h=(o+a)/2;if(o===a)l=0,c=0;else{const u=a-o;switch(c=h<=.5?u/(a+o):u/(2-a-o),a){case i:l=(n-s)/u+(n<s?6:0);break;case n:l=(s-i)/u+2;break;case s:l=(i-n)/u+4;break}l/=6}return e.h=l,e.s=c,e.l=h,e}getRGB(e,t=Nt.workingColorSpace){return Nt.fromWorkingColorSpace(Gn.copy(this),t),e.r=Gn.r,e.g=Gn.g,e.b=Gn.b,e}getStyle(e=Ct){Nt.fromWorkingColorSpace(Gn.copy(this),e);const t=Gn.r,i=Gn.g,n=Gn.b;return e!==Ct?`color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(i*255)},${Math.round(n*255)})`}offsetHSL(e,t,i){return this.getHSL(Qa),this.setHSL(Qa.h+e,Qa.s+t,Qa.l+i)}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,i){return this.r=e.r+(t.r-e.r)*i,this.g=e.g+(t.g-e.g)*i,this.b=e.b+(t.b-e.b)*i,this}lerpHSL(e,t){this.getHSL(Qa),e.getHSL(Wf);const i=ru(Qa.h,Wf.h,t),n=ru(Qa.s,Wf.s,t),s=ru(Qa.l,Wf.l,t);return this.setHSL(i,n,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,i=this.g,n=this.b,s=e.elements;return this.r=s[0]*t+s[3]*i+s[6]*n,this.g=s[1]*t+s[4]*i+s[7]*n,this.b=s[2]*t+s[5]*i+s[8]*n,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Gn=new ee;ee.NAMES=iC;let zD=0;class tn extends xi{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:zD++}),this.uuid=Cs(),this.name="",this.type="Material",this.blending=Sr,this.side=us,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=jl,this.blendDst=Wl,this.blendEquation=Er,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new ee(0,0,0),this.blendAlpha=0,this.depthFunc=Yl,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=ly,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Zr,this.stencilZFail=Zr,this.stencilZPass=Zr,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(){}onAfterRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const n=this[t];n!==void 0&&(n&&n.isColor?n.set(i):n&&n.isVector3&&i&&i.isVector3?n.copy(i):Array.isArray(i)&&n&&typeof n.fromArray=="function"?n.fromArray(i):this[t]=i)}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.6001,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==Sr&&(i.blending=this.blending),this.side!==us&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==jl&&(i.blendSrc=this.blendSrc),this.blendDst!==Wl&&(i.blendDst=this.blendDst),this.blendEquation!==Er&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==Yl&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==ly&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Zr&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Zr&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Zr&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(s){const a=[];for(const o in s){const l=s[o];delete l.metadata,a.push(l)}return a}if(t){const s=n(e.textures),a=n(e.images);s.length>0&&(i.textures=s),a.length>0&&(i.images=a)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const n=t.length;i=new Array(n);for(let s=0;s!==n;++s)i[s]=t[s].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=nC({},e.userData),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}function nC(r,e){if(!e)return r;for(const t of Object.keys(e)){if(t.startsWith("__")||typeof r[t]=="function"||typeof e[t]=="function")continue;const i=e[t],n=!i||i.isTexture||i.isObject3D||i.isMaterial||i.isBufferGeometry||i.userDataSkipClone;!n&&typeof e[t].clone=="function"?r[t]=e[t].clone():!n&&(typeof e[t]=="object"||Array.isArray(e[t]))?r[t]=nC(Array.isArray(e[t])?[]:{},e[t]):r[t]=e[t]}return r}class is extends tn{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ee(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 Pt,this.combine=$l,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const la=VD();function VD(){const r=new ArrayBuffer(4),e=new Float32Array(r),t=new Uint32Array(r),i=new Uint32Array(512),n=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(i[l]=0,i[l|256]=32768,n[l]=24,n[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,n[l]=-c-1,n[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,n[l]=13,n[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,n[l]=24,n[l|256]=24):(i[l]=31744,i[l|256]=64512,n[l]=13,n[l|256]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,h=0;for(;(c&8388608)===0;)c<<=1,h-=8388608;c&=-8388609,h+=947912704,s[l]=c|h}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:n,mantissaTable:s,exponentTable:a,offsetTable:o}}function fs(r){Math.abs(r)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),r=Gi(r,-65504,65504),la.floatView[0]=r;const e=la.uint32View[0],t=e>>23&511;return la.baseTable[t]+((e&8388607)>>la.shiftTable[t])}function uu(r){const e=r>>10;return la.uint32View[0]=la.mantissaTable[la.offsetTable[e]+(r&1023)]+la.exponentTable[e],la.floatView[0]}const zn={toHalfFloat:fs,fromHalfFloat:uu},dn=new S,qf=new K;class Ze{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=Bf,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=Ut,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return ta("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}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,i){e*=this.itemSize,i*=t.itemSize;for(let n=0,s=this.itemSize;n<s;n++)this.array[e+n]=t.array[i+n];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,i=this.count;t<i;t++)qf.fromBufferAttribute(this,t),qf.applyMatrix3(e),this.setXY(t,qf.x,qf.y);else if(this.itemSize===3)for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyMatrix3(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyMatrix4(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyNormalMatrix(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.transformDirection(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let i=this.array[e*this.itemSize+t];return this.normalized&&(i=es(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=St(i,this.array)),this.array[e*this.itemSize+t]=i,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=es(t,this.array)),t}setX(e,t){return this.normalized&&(t=St(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=es(t,this.array)),t}setY(e,t){return this.normalized&&(t=St(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=es(t,this.array)),t}setZ(e,t){return this.normalized&&(t=St(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=es(t,this.array)),t}setW(e,t){return this.normalized&&(t=St(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=St(t,this.array),i=St(i,this.array)),this.array[e+0]=t,this.array[e+1]=i,this}setXYZ(e,t,i,n){return e*=this.itemSize,this.normalized&&(t=St(t,this.array),i=St(i,this.array),n=St(n,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this}setXYZW(e,t,i,n,s){return e*=this.itemSize,this.normalized&&(t=St(t,this.array),i=St(i,this.array),n=St(n,this.array),s=St(s,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Bf&&(e.usage=this.usage),e}}class HD extends Ze{constructor(e,t,i){super(new Int8Array(e),t,i)}}class QD extends Ze{constructor(e,t,i){super(new Uint8Array(e),t,i)}}class jD extends Ze{constructor(e,t,i){super(new Uint8ClampedArray(e),t,i)}}class WD extends Ze{constructor(e,t,i){super(new Int16Array(e),t,i)}}class Xf extends Ze{constructor(e,t,i){super(new Uint16Array(e),t,i)}}class qD extends Ze{constructor(e,t,i){super(new Int32Array(e),t,i)}}class My extends Ze{constructor(e,t,i){super(new Uint32Array(e),t,i)}}class XD extends Ze{constructor(e,t,i){super(new Uint16Array(e),t,i),this.isFloat16BufferAttribute=!0}getX(e){let t=uu(this.array[e*this.itemSize]);return this.normalized&&(t=es(t,this.array)),t}setX(e,t){return this.normalized&&(t=St(t,this.array)),this.array[e*this.itemSize]=fs(t),this}getY(e){let t=uu(this.array[e*this.itemSize+1]);return this.normalized&&(t=es(t,this.array)),t}setY(e,t){return this.normalized&&(t=St(t,this.array)),this.array[e*this.itemSize+1]=fs(t),this}getZ(e){let t=uu(this.array[e*this.itemSize+2]);return this.normalized&&(t=es(t,this.array)),t}setZ(e,t){return this.normalized&&(t=St(t,this.array)),this.array[e*this.itemSize+2]=fs(t),this}getW(e){let t=uu(this.array[e*this.itemSize+3]);return this.normalized&&(t=es(t,this.array)),t}setW(e,t){return this.normalized&&(t=St(t,this.array)),this.array[e*this.itemSize+3]=fs(t),this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=St(t,this.array),i=St(i,this.array)),this.array[e+0]=fs(t),this.array[e+1]=fs(i),this}setXYZ(e,t,i,n){return e*=this.itemSize,this.normalized&&(t=St(t,this.array),i=St(i,this.array),n=St(n,this.array)),this.array[e+0]=fs(t),this.array[e+1]=fs(i),this.array[e+2]=fs(n),this}setXYZW(e,t,i,n,s){return e*=this.itemSize,this.normalized&&(t=St(t,this.array),i=St(i,this.array),n=St(n,this.array),s=St(s,this.array)),this.array[e+0]=fs(t),this.array[e+1]=fs(i),this.array[e+2]=fs(n),this.array[e+3]=fs(s),this}}class Ee extends Ze{constructor(e,t,i){super(new Float32Array(e),t,i)}}let YD=0;const Ns=new fe,Ty=new ft,Uo=new S,Ss=new en,du=new en,wn=new S;class Je extends xi{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:YD++}),this.uuid=Cs(),this.name="",this.type="BufferGeometry",this.index=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(zw(e)?My:Xf)(e,1):this.index=e,this}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,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const s=new At().getNormalMatrix(e);i.applyNormalMatrix(s),i.needsUpdate=!0}const n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(e),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Ns.makeRotationFromQuaternion(e),this.applyMatrix4(Ns),this}rotateX(e){return Ns.makeRotationX(e),this.applyMatrix4(Ns),this}rotateY(e){return Ns.makeRotationY(e),this.applyMatrix4(Ns),this}rotateZ(e){return Ns.makeRotationZ(e),this.applyMatrix4(Ns),this}translate(e,t,i){return Ns.makeTranslation(e,t,i),this.applyMatrix4(Ns),this}scale(e,t,i){return Ns.makeScale(e,t,i),this.applyMatrix4(Ns),this}lookAt(e){return Ty.lookAt(e),Ty.updateMatrix(),this.applyMatrix4(Ty.matrix),this}center(e=void 0){return this.computeBoundingBox(),this.boundingBox.getCenter(Uo).negate(),this.translate(Uo.x,Uo.y,Uo.z),e&&e.copy(Uo),this}setFromPoints(e){const t=[];for(let i=0,n=e.length;i<n;i++){const s=e[i];t.push(s.x,s.y,s.z||0)}return this.setAttribute("position",new Ee(t,3)),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new en);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new S(-1/0,-1/0,-1/0),new S(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,n=t.length;i<n;i++){const s=t[i];Ss.setFromBufferAttribute(s),this.morphTargetsRelative?(wn.addVectors(this.boundingBox.min,Ss.min),this.boundingBox.expandByPoint(wn),wn.addVectors(this.boundingBox.max,Ss.max),this.boundingBox.expandByPoint(wn)):(this.boundingBox.expandByPoint(Ss.min),this.boundingBox.expandByPoint(Ss.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new S,1/0);return}if(e){const i=this.boundingSphere.center;if(Ss.setFromBufferAttribute(e),t)for(let s=0,a=t.length;s<a;s++){const o=t[s];du.setFromBufferAttribute(o),this.morphTargetsRelative?(wn.addVectors(Ss.min,du.min),Ss.expandByPoint(wn),wn.addVectors(Ss.max,du.max),Ss.expandByPoint(wn)):(Ss.expandByPoint(du.min),Ss.expandByPoint(du.max))}Ss.getCenter(i);let n=0;for(let s=0,a=e.count;s<a;s++)wn.fromBufferAttribute(e,s),n=Math.max(n,i.distanceToSquared(wn));if(t)for(let s=0,a=t.length;s<a;s++){const o=t[s],l=this.morphTargetsRelative;for(let c=0,h=o.count;c<h;c++)wn.fromBufferAttribute(o,c),l&&(Uo.fromBufferAttribute(e,c),wn.add(Uo)),n=Math.max(n,i.distanceToSquared(wn))}this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=t.position,n=t.normal,s=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Ze(new Float32Array(4*i.count),4));const a=this.getAttribute("tangent"),o=[],l=[];for(let I=0;I<i.count;I++)o[I]=new S,l[I]=new S;const c=new S,h=new S,u=new S,d=new K,p=new K,m=new K,A=new S,g=new S;function y(I,C,x){c.fromBufferAttribute(i,I),h.fromBufferAttribute(i,C),u.fromBufferAttribute(i,x),d.fromBufferAttribute(s,I),p.fromBufferAttribute(s,C),m.fromBufferAttribute(s,x),h.sub(c),u.sub(c),p.sub(d),m.sub(d);const D=1/(p.x*m.y-m.x*p.y);isFinite(D)&&(A.copy(h).multiplyScalar(m.y).addScaledVector(u,-p.y).multiplyScalar(D),g.copy(u).multiplyScalar(p.x).addScaledVector(h,-m.x).multiplyScalar(D),o[I].add(A),o[C].add(A),o[x].add(A),l[I].add(g),l[C].add(g),l[x].add(g))}let v=this.groups;v.length===0&&(v=[{start:0,count:e.count}]);for(let I=0,C=v.length;I<C;++I){const x=v[I],D=x.start,U=x.count;for(let O=D,N=D+U;O<N;O+=3)y(e.getX(O+0),e.getX(O+1),e.getX(O+2))}const _=new S,b=new S,T=new S,E=new S;function M(I){T.fromBufferAttribute(n,I),E.copy(T);const C=o[I];_.copy(C),_.sub(T.multiplyScalar(T.dot(C))).normalize(),b.crossVectors(E,C);const D=b.dot(l[I])<0?-1:1;a.setXYZW(I,_.x,_.y,_.z,D)}for(let I=0,C=v.length;I<C;++I){const x=v[I],D=x.start,U=x.count;for(let O=D,N=D+U;O<N;O+=3)M(e.getX(O+0)),M(e.getX(O+1)),M(e.getX(O+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let i=this.getAttribute("normal");if(i===void 0)i=new Ze(new Float32Array(t.count*3),3),this.setAttribute("normal",i);else for(let d=0,p=i.count;d<p;d++)i.setXYZ(d,0,0,0);const n=new S,s=new S,a=new S,o=new S,l=new S,c=new S,h=new S,u=new S;if(e)for(let d=0,p=e.count;d<p;d+=3){const m=e.getX(d+0),A=e.getX(d+1),g=e.getX(d+2);n.fromBufferAttribute(t,m),s.fromBufferAttribute(t,A),a.fromBufferAttribute(t,g),h.subVectors(a,s),u.subVectors(n,s),h.cross(u),o.fromBufferAttribute(i,m),l.fromBufferAttribute(i,A),c.fromBufferAttribute(i,g),o.add(h),l.add(h),c.add(h),i.setXYZ(m,o.x,o.y,o.z),i.setXYZ(A,l.x,l.y,l.z),i.setXYZ(g,c.x,c.y,c.z)}else for(let d=0,p=t.count;d<p;d+=3)n.fromBufferAttribute(t,d+0),s.fromBufferAttribute(t,d+1),a.fromBufferAttribute(t,d+2),h.subVectors(a,s),u.subVectors(n,s),h.cross(u),i.setXYZ(d+0,h.x,h.y,h.z),i.setXYZ(d+1,h.x,h.y,h.z),i.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,i=e.count;t<i;t++)wn.fromBufferAttribute(e,t),wn.normalize(),e.setXYZ(t,wn.x,wn.y,wn.z)}toNonIndexed(){function e(o,l){const c=o.array,h=o.itemSize,u=o.normalized,d=new c.constructor(l.length*h);let p=0,m=0;for(let A=0,g=l.length;A<g;A++){o.isInterleavedBufferAttribute?p=l[A]*o.data.stride+o.offset:p=l[A]*h;for(let y=0;y<h;y++)d[m++]=c[p++]}return new Ze(d,h,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Je,i=this.index.array,n=this.attributes;for(const o in n){const l=n[o],c=e(l,i);t.setAttribute(o,c)}const s=this.morphAttributes;for(const o in s){const l=[],c=s[o];for(let h=0,u=c.length;h<u;h++){const d=c[h],p=e(d,i);l.push(p)}t.morphAttributes[o]=l}t.morphTargetsRelative=this.morphTargetsRelative;const a=this.groups;for(let o=0,l=a.length;o<l;o++){const c=a[o];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const e={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const n={};let s=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],h=[];for(let u=0,d=c.length;u<d;u++){const p=c[u];h.push(p.toJSON(e.data))}h.length>0&&(n[l]=h,s=!0)}s&&(e.data.morphAttributes=n,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone(t));const n=e.attributes;for(const c in n){const h=n[c];this.setAttribute(c,h.clone(t))}const s=e.morphAttributes;for(const c in s){const h=[],u=s[c];for(let d=0,p=u.length;d<p;d++)h.push(u[d].clone(t));this.morphAttributes[c]=h}this.morphTargetsRelative=e.morphTargetsRelative;const a=e.groups;for(let c=0,h=a.length;c<h;c++){const u=a[c];this.addGroup(u.start,u.count,u.materialIndex)}const o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const sC=new fe,Fo=new Va,Yf=new un,rC=new S,Ac=new S,yc=new S,_c=new S,Iy=new S,$f=new S,Kf=new K,Jf=new K,Zf=new K,aC=new S,oC=new S,lC=new S,ep=new S,tp=new S;class _e extends ft{constructor(e=new Je,t=new is){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.isMesh?(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):this}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=n.length;s<a;s++){const o=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}getVertexPosition(e,t){const i=this.geometry,n=i.attributes.position,s=i.morphAttributes.position,a=i.morphTargetsRelative;t.fromBufferAttribute(n,e);const o=this.morphTargetInfluences;if(s&&o){$f.set(0,0,0);for(let l=0,c=s.length;l<c;l++){const h=o[l],u=s[l];h!==0&&(Iy.fromBufferAttribute(u,e),a?$f.addScaledVector(Iy,h):$f.addScaledVector(Iy.sub(t),h))}t.add($f)}return t}raycast(e,t){const i=this.geometry,n=this.material,s=this.matrixWorld;n!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),Yf.copy(i.boundingSphere),Yf.applyMatrix4(s),Fo.copy(e.ray).recast(e.near),!(Yf.containsPoint(Fo.origin)===!1&&(Fo.intersectSphere(Yf,rC)===null||Fo.origin.distanceToSquared(rC)>(e.far-e.near)**2))&&(sC.copy(s).invert(),Fo.copy(e.ray).applyMatrix4(sC),!(i.boundingBox!==null&&Fo.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,Fo)))}_computeIntersections(e,t,i){let n;const s=this.geometry,a=this.material,o=s.index,l=s.attributes.position,c=s.attributes.uv,h=s.attributes.uv1,u=s.attributes.normal,d=s.groups,p=s.drawRange;if(o!==null)if(Array.isArray(a))for(let m=0,A=d.length;m<A;m++){const g=d[m],y=a[g.materialIndex],v=Math.max(g.start,p.start),_=Math.min(o.count,Math.min(g.start+g.count,p.start+p.count));for(let b=v,T=_;b<T;b+=3){const E=o.getX(b),M=o.getX(b+1),I=o.getX(b+2);n=ip(this,y,e,i,c,h,u,E,M,I),n&&(n.faceIndex=Math.floor(b/3),n.face.materialIndex=g.materialIndex,t.push(n))}}else{const m=Math.max(0,p.start),A=Math.min(o.count,p.start+p.count);for(let g=m,y=A;g<y;g+=3){const v=o.getX(g),_=o.getX(g+1),b=o.getX(g+2);n=ip(this,a,e,i,c,h,u,v,_,b),n&&(n.faceIndex=Math.floor(g/3),t.push(n))}}else if(l!==void 0)if(Array.isArray(a))for(let m=0,A=d.length;m<A;m++){const g=d[m],y=a[g.materialIndex],v=Math.max(g.start,p.start),_=Math.min(l.count,Math.min(g.start+g.count,p.start+p.count));for(let b=v,T=_;b<T;b+=3){const E=b,M=b+1,I=b+2;n=ip(this,y,e,i,c,h,u,E,M,I),n&&(n.faceIndex=Math.floor(b/3),n.face.materialIndex=g.materialIndex,t.push(n))}}else{const m=Math.max(0,p.start),A=Math.min(l.count,p.start+p.count);for(let g=m,y=A;g<y;g+=3){const v=g,_=g+1,b=g+2;n=ip(this,a,e,i,c,h,u,v,_,b),n&&(n.faceIndex=Math.floor(g/3),t.push(n))}}}}function $D(r,e,t,i,n,s,a,o){let l;if(e.side===In?l=i.intersectTriangle(a,s,n,!0,o):l=i.intersectTriangle(n,s,a,e.side===us,o),l===null)return null;tp.copy(o),tp.applyMatrix4(r.matrixWorld);const c=t.ray.origin.distanceTo(tp);return c<t.near||c>t.far?null:{distance:c,point:tp.clone(),object:r}}function ip(r,e,t,i,n,s,a,o,l,c){r.getVertexPosition(o,Ac),r.getVertexPosition(l,yc),r.getVertexPosition(c,_c);const h=$D(r,e,t,i,Ac,yc,_c,ep);if(h){n&&(Kf.fromBufferAttribute(n,o),Jf.fromBufferAttribute(n,l),Zf.fromBufferAttribute(n,c),h.uv=ts.getInterpolation(ep,Ac,yc,_c,Kf,Jf,Zf,new K)),s&&(Kf.fromBufferAttribute(s,o),Jf.fromBufferAttribute(s,l),Zf.fromBufferAttribute(s,c),h.uv1=ts.getInterpolation(ep,Ac,yc,_c,Kf,Jf,Zf,new K)),a&&(aC.fromBufferAttribute(a,o),oC.fromBufferAttribute(a,l),lC.fromBufferAttribute(a,c),h.normal=ts.getInterpolation(ep,Ac,yc,_c,aC,oC,lC,new S),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const u={a:o,b:l,c,normal:new S,materialIndex:0};ts.getNormal(Ac,yc,_c,u.normal),h.face=u}return h}class gi extends Je{constructor(e=1,t=1,i=1,n=1,s=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:n,heightSegments:s,depthSegments:a};const o=this;n=Math.floor(n),s=Math.floor(s),a=Math.floor(a);const l=[],c=[],h=[],u=[];let d=0,p=0;m("z","y","x",-1,-1,i,t,e,a,s,0),m("z","y","x",1,-1,i,t,-e,a,s,1),m("x","z","y",1,1,e,i,t,n,a,2),m("x","z","y",1,-1,e,i,-t,n,a,3),m("x","y","z",1,-1,e,t,i,n,s,4),m("x","y","z",-1,-1,e,t,-i,n,s,5),this.setIndex(l),this.setAttribute("position",new Ee(c,3)),this.setAttribute("normal",new Ee(h,3)),this.setAttribute("uv",new Ee(u,2));function m(A,g,y,v,_,b,T,E,M,I,C){const x=b/M,D=T/I,U=b/2,O=T/2,N=E/2,H=M+1,V=I+1;let X=0,W=0;const ce=new S;for(let ue=0;ue<V;ue++){const we=ue*D-O;for(let Pe=0;Pe<H;Pe++){const Qe=Pe*x-U;ce[A]=Qe*v,ce[g]=we*_,ce[y]=N,c.push(ce.x,ce.y,ce.z),ce[A]=0,ce[g]=0,ce[y]=E>0?1:-1,h.push(ce.x,ce.y,ce.z),u.push(Pe/M),u.push(1-ue/I),X+=1}}for(let ue=0;ue<I;ue++)for(let we=0;we<M;we++){const Pe=d+we+H*ue,Qe=d+we+H*(ue+1),ie=d+(we+1)+H*(ue+1),oe=d+(we+1)+H*ue;l.push(Pe,Qe,oe),l.push(Qe,ie,oe),W+=6}o.addGroup(p,W,C),p+=W,d+=X}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new gi(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function No(r){const e={};for(const t in r){e[t]={};for(const i in r[t]){const n=r[t][i];n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)?n.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][i]=null):e[t][i]=n.clone():Array.isArray(n)?e[t][i]=n.slice():e[t][i]=n}}return e}function ns(r){const e={};for(let t=0;t<r.length;t++){const i=No(r[t]);for(const n in i)e[n]=i[n]}return e}function KD(r){const e=[];for(let t=0;t<r.length;t++)e.push(r[t].clone());return e}function cC(r){const e=r.getRenderTarget();return e===null?r.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Nt.workingColorSpace}const ko={clone:No,merge:ns};var JD=`void main() {
	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,ZD=`void main() {
	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`;class nn extends tn{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=JD,this.fragmentShader=ZD,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=KD(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const n in this.uniforms){const a=this.uniforms[n].value;a&&a.isTexture?t.uniforms[n]={type:"t",value:a.toJSON(e).uuid}:a&&a.isColor?t.uniforms[n]={type:"c",value:a.getHex()}:a&&a.isVector2?t.uniforms[n]={type:"v2",value:a.toArray()}:a&&a.isVector3?t.uniforms[n]={type:"v3",value:a.toArray()}:a&&a.isVector4?t.uniforms[n]={type:"v4",value:a.toArray()}:a&&a.isMatrix3?t.uniforms[n]={type:"m3",value:a.toArray()}:a&&a.isMatrix4?t.uniforms[n]={type:"m4",value:a.toArray()}:t.uniforms[n]={value:a}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const n in this.extensions)this.extensions[n]===!0&&(i[n]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class fu extends ft{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new fe,this.projectionMatrix=new fe,this.projectionMatrixInverse=new fe,this.coordinateSystem=ea}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const ja=new S,hC=new K,uC=new K;class zi extends fu{constructor(e=50,t=1,i=.1,n=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=n,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=rc*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Bo*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return rc*2*Math.atan(Math.tan(Bo*.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,i){ja.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ja.x,ja.y).multiplyScalar(-e/ja.z),ja.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(ja.x,ja.y).multiplyScalar(-e/ja.z)}getViewSize(e,t){return this.getViewBounds(e,hC,uC),t.subVectors(uC,hC)}setViewOffset(e,t,i,n,s,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=i,this.view.offsetY=n,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Bo*.5*this.fov)/this.zoom,i=2*t,n=this.aspect*i,s=-.5*n;const a=this.view;if(this.view!==null&&this.view.enabled){const l=a.fullWidth,c=a.fullHeight;s+=a.offsetX*n/l,t-=a.offsetY*i/c,n*=a.width/l,i*=a.height/c}const o=this.filmOffset;o!==0&&(s+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+n,t,t-i,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const vc=-90,bc=1;class dC extends ft{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const n=new zi(vc,bc,e,t);n.layers=this.layers,this.add(n);const s=new zi(vc,bc,e,t);s.layers=this.layers,this.add(s);const a=new zi(vc,bc,e,t);a.layers=this.layers,this.add(a);const o=new zi(vc,bc,e,t);o.layers=this.layers,this.add(o);const l=new zi(vc,bc,e,t);l.layers=this.layers,this.add(l);const c=new zi(vc,bc,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,n,s,a,o,l]=t;for(const c of t)this.remove(c);if(e===ea)i.up.set(0,1,0),i.lookAt(1,0,0),n.up.set(0,1,0),n.lookAt(-1,0,0),s.up.set(0,0,-1),s.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),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===Lf)i.up.set(0,-1,0),i.lookAt(-1,0,0),n.up.set(0,-1,0),n.lookAt(1,0,0),s.up.set(0,0,1),s.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),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:n}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,a,o,l,c,h]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),p=e.getActiveMipmapLevel(),m=e.xr.enabled;e.xr.enabled=!1;const A=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,n),e.render(t,s),e.setRenderTarget(i,1,n),e.render(t,a),e.setRenderTarget(i,2,n),e.render(t,o),e.setRenderTarget(i,3,n),e.render(t,l),e.setRenderTarget(i,4,n),e.render(t,c),i.texture.generateMipmaps=A,e.setRenderTarget(i,5,n),e.render(t,h),e.setRenderTarget(u,d,p),e.xr.enabled=m,i.texture.needsPMREMUpdate=!0}}class wc extends kt{constructor(e,t,i,n,s,a,o,l,c,h){e=e!==void 0?e:[],t=t!==void 0?t:Yr,super(e,t,i,n,s,a,o,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Py extends ds{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},n=[i,i,i,i,i,i];this.texture=new wc(n,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:at}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={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 );

				}
			`},n=new gi(5,5,5),s=new nn({name:"CubemapFromEquirect",uniforms:No(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:In,blending:gn});s.uniforms.tEquirect.value=t;const a=new _e(n,s),o=t.minFilter;return t.minFilter===Dn&&(t.minFilter=at),new dC(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t,i,n){const s=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,i,n);e.setRenderTarget(s)}}const Dy=new S,eR=new S,tR=new At;class Es{constructor(e=new S(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,i,n){return this.normal.set(e,t,i),this.constant=n,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,i){const n=Dy.subVectors(i,t).cross(eR.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(n,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const i=e.delta(Dy),n=this.normal.dot(i);if(n===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const s=-(e.start.dot(this.normal)+this.constant)/n;return s<0||s>1?null:t.copy(e.start).addScaledVector(i,s)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||tR.getNormalMatrix(e),n=this.coplanarPoint(Dy).applyMatrix4(e),s=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Go=new un,np=new S;class pu{constructor(e=new Es,t=new Es,i=new Es,n=new Es,s=new Es,a=new Es){this.planes=[e,t,i,n,s,a]}set(e,t,i,n,s,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(n),o[4].copy(s),o[5].copy(a),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=ea){const i=this.planes,n=e.elements,s=n[0],a=n[1],o=n[2],l=n[3],c=n[4],h=n[5],u=n[6],d=n[7],p=n[8],m=n[9],A=n[10],g=n[11],y=n[12],v=n[13],_=n[14],b=n[15];if(i[0].setComponents(l-s,d-c,g-p,b-y).normalize(),i[1].setComponents(l+s,d+c,g+p,b+y).normalize(),i[2].setComponents(l+a,d+h,g+m,b+v).normalize(),i[3].setComponents(l-a,d-h,g-m,b-v).normalize(),i[4].setComponents(l-o,d-u,g-A,b-_).normalize(),t===ea)i[5].setComponents(l+o,d+u,g+A,b+_).normalize();else if(t===Lf)i[5].setComponents(o,u,A,_).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Go.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Go.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Go)}intersectsSprite(e){return Go.center.set(0,0,0),Go.radius=.7071067811865476,Go.applyMatrix4(e.matrixWorld),this.intersectsSphere(Go)}intersectsSphere(e){const t=this.planes,i=e.center,n=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(i)<n)return!1;return!0}intersectsBox(e){const t=this.planes;for(let i=0;i<6;i++){const n=t[i];if(np.x=n.normal.x>0?e.max.x:e.min.x,np.y=n.normal.y>0?e.max.y:e.min.y,np.z=n.normal.z>0?e.max.z:e.min.z,n.distanceToPoint(np)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function fC(){let r=null,e=!1,t=null,i=null;function n(s,a){t(s,a),i=r.requestAnimationFrame(n)}return{start:function(){e!==!0&&t!==null&&(i=r.requestAnimationFrame(n),e=!0)},stop:function(){r.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(s){t=s},setContext:function(s){r=s}}}function iR(r){const e=new WeakMap;function t(o,l){const c=o.array,h=o.usage,u=c.byteLength,d=r.createBuffer();r.bindBuffer(l,d),r.bufferData(l,c,h),o.onUploadCallback();let p;if(c instanceof Float32Array)p=r.FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?p=r.HALF_FLOAT:p=r.UNSIGNED_SHORT;else if(c instanceof Int16Array)p=r.SHORT;else if(c instanceof Uint32Array)p=r.UNSIGNED_INT;else if(c instanceof Int32Array)p=r.INT;else if(c instanceof Int8Array)p=r.BYTE;else if(c instanceof Uint8Array)p=r.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)p=r.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:d,type:p,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:u}}function i(o,l,c){const h=l.array,u=l._updateRange,d=l.updateRanges;if(r.bindBuffer(c,o),u.count===-1&&d.length===0&&r.bufferSubData(c,0,h),d.length!==0){for(let p=0,m=d.length;p<m;p++){const A=d[p];r.bufferSubData(c,A.start*h.BYTES_PER_ELEMENT,h,A.start,A.count)}l.clearUpdateRanges()}u.count!==-1&&(r.bufferSubData(c,u.offset*h.BYTES_PER_ELEMENT,h,u.offset,u.count),u.count=-1),l.onUploadCallback()}function n(o){return o.isInterleavedBufferAttribute&&(o=o.data),e.get(o)}function s(o){o.isInterleavedBufferAttribute&&(o=o.data);const l=e.get(o);l&&(r.deleteBuffer(l.buffer),e.delete(o))}function a(o,l){if(o.isInterleavedBufferAttribute&&(o=o.data),o.isGLBufferAttribute){const h=e.get(o);(!h||h.version<o.version)&&e.set(o,{buffer:o.buffer,type:o.type,bytesPerElement:o.elementSize,version:o.version});return}const c=e.get(o);if(c===void 0)e.set(o,t(o,l));else if(c.version<o.version){if(c.size!==o.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");i(c.buffer,o,l),c.version=o.version}}return{get:n,remove:s,update:a}}class ca extends Je{constructor(e=1,t=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:i,heightSegments:n};const s=e/2,a=t/2,o=Math.floor(i),l=Math.floor(n),c=o+1,h=l+1,u=e/o,d=t/l,p=[],m=[],A=[],g=[];for(let y=0;y<h;y++){const v=y*d-a;for(let _=0;_<c;_++){const b=_*u-s;m.push(b,-v,0),A.push(0,0,1),g.push(_/o),g.push(1-y/l)}}for(let y=0;y<l;y++)for(let v=0;v<o;v++){const _=v+c*y,b=v+c*(y+1),T=v+1+c*(y+1),E=v+1+c*y;p.push(_,b,E),p.push(b,T,E)}this.setIndex(p),this.setAttribute("position",new Ee(m,3)),this.setAttribute("normal",new Ee(A,3)),this.setAttribute("uv",new Ee(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ca(e.width,e.height,e.widthSegments,e.heightSegments)}}var nR=`#ifdef USE_ALPHAHASH
	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,sR=`#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`,rR=`#ifdef USE_ALPHAMAP
	#if defined(INVERSE_ALPHAMAP) && INVERSE_ALPHAMAP >= 1
	diffuseColor.a *= 1.0-texture2D( alphaMap, vAlphaMapUv ).g;
	#else
	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
	#endif
#endif`,aR=`#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,oR=`#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`,lR=`#ifdef USE_ALPHATEST
	uniform float alphaTest;
#endif`,cR=`#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`,hR=`#ifdef USE_AOMAP
	uniform sampler2D aoMap;
	uniform float aoMapIntensity;
#endif`,uR=`#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;
	vec3 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 ).rgb;
	}
#endif`,dR=`#ifdef USE_BATCHING
	mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`,fR=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
	vPosition = vec3( position );
#endif`,pR=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
	vec3 objectTangent = vec3( tangent.xyz );
#endif`,mR=`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`,gR=`#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`,AR=`#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`,yR=`#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`,_R=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,vR=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
#endif`,bR=`#if NUM_CLIPPING_PLANES > 0
	vClipPosition = - mvPosition.xyz;
#endif`,wR=`#if defined( USE_COLOR_ALPHA )
	diffuseColor *= vColor;
#elif defined( USE_COLOR )
	diffuseColor.rgb *= vColor;
#endif`,CR=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR )
	varying vec3 vColor;
#endif`,xR=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	varying vec3 vColor;
#endif`,SR=`#if defined( USE_COLOR_ALPHA )
	vColor = vec4( 1.0 );
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	vColor = vec3( 1.0 );
#endif
#ifdef USE_COLOR
	vColor *= color;
#endif
#ifdef USE_INSTANCING_COLOR
	vColor.xyz *= instanceColor.xyz;
#endif
#ifdef USE_BATCHING_COLOR
	vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
	vColor.xyz *= batchingColor.xyz;
#endif`,ER=`#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
#define RECIPROCAL_PI2 0.15915494309189535
#define EPSILON 1e-6
#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
#define whiteComplement( a ) ( 1.0 - saturate( a ) )
float pow2( const in float x ) { return x*x; }
vec3 pow2( const in vec3 x ) { return x*x; }
float pow3( const in float x ) { return x*x*x; }
float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
highp float rand( const in vec2 uv ) {
	const highp float a = 12.9898, b = 78.233, c = 43758.5453;
	highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
	return fract( sin( sn ) * c );
}
#ifdef HIGH_PRECISION
	float precisionSafeLength( vec3 v ) { return length( v ); }
#else
	float precisionSafeLength( vec3 v ) {
		float maxComponent = max3( abs( v ) );
		return length( v / maxComponent ) * maxComponent;
	}
#endif
struct IncidentLight {
	vec3 color;
	vec3 direction;
	bool visible;
};
struct ReflectedLight {
	vec3 directDiffuse;
	vec3 directSpecular;
	vec3 indirectDiffuse;
	vec3 indirectSpecular;
};
#ifdef USE_ALPHAHASH
	varying vec3 vPosition;
#endif
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
}
mat3 transposeMat3( const in mat3 m ) {
	mat3 tmp;
	tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
	tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
	tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
	return tmp;
}
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`,MR=`#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`,TR=`vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
	vec3 transformedTangent = objectTangent;
#endif
#ifdef USE_BATCHING
	mat3 bm = mat3( batchingMatrix );
	transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
	transformedNormal = bm * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = bm * transformedTangent;
	#endif
#endif
#ifdef USE_INSTANCING
	mat3 im = mat3( instanceMatrix );
	transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
	transformedNormal = im * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = im * transformedTangent;
	#endif
#endif
transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
	transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
	transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
	#ifdef FLIP_SIDED
		transformedTangent = - transformedTangent;
	#endif
#endif`,IR=`#ifdef USE_DISPLACEMENTMAP
	uniform sampler2D displacementMap;
	uniform float displacementScale;
	uniform float displacementBias;
#endif`,PR=`#ifdef USE_DISPLACEMENTMAP
	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,DR=`#ifdef USE_EMISSIVEMAP
	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
	totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,RR=`#ifdef USE_EMISSIVEMAP
	uniform sampler2D emissiveMap;
#endif`,BR="gl_FragColor = linearToOutputTexel( gl_FragColor );",LR=`
const mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(
	vec3( 0.8224621, 0.177538, 0.0 ),
	vec3( 0.0331941, 0.9668058, 0.0 ),
	vec3( 0.0170827, 0.0723974, 0.9105199 )
);
const mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(
	vec3( 1.2249401, - 0.2249404, 0.0 ),
	vec3( - 0.0420569, 1.0420571, 0.0 ),
	vec3( - 0.0196376, - 0.0786361, 1.0982735 )
);
vec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {
	return vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );
}
vec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {
	return vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );
}
vec4 LinearTransferOETF( in vec4 value ) {
	return value;
}
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 );
}
vec4 LinearToLinear( in vec4 value ) {
	return value;
}
vec4 LinearTosRGB( in vec4 value ) {
	return sRGBTransferOETF( value );
}
vec4 sRGBToLinear( 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 RGBM16ToLinear( in vec4 value ) {
	return vec4( value.rgb * value.a * 16.0, 1.0 );
}
vec4 LinearToRGBM16( in vec4 value ) {
	float maxRGB = max( value.r, max( value.g, value.b ) );
	float M = clamp( maxRGB / 16.0, 0.0, 1.0 );
	M = ceil( M * 255.0 ) / 255.0;
	return vec4( value.rgb / ( M * 16.0 ), M );
}`,OR=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vec3 cameraToFrag;
		if ( isOrthographic ) {
			cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToFrag = normalize( vWorldPosition - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vec3 reflectVec = reflect( cameraToFrag, worldNormal );
		#else
			vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
		#endif
	#else
		vec3 reflectVec = vReflect;
	#endif
	#ifdef ENVMAP_TYPE_CUBE
		vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
	#else
		vec4 envColor = vec4( 0.0 );
	#endif
	#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`,UR=`#ifdef USE_ENVMAP
	uniform float envMapIntensity;
	uniform float flipEnvMap;
	uniform mat3 envMapRotation;
	#ifdef ENVMAP_TYPE_CUBE
		uniform samplerCube envMap;
	#else
		uniform sampler2D envMap;
	#endif
#endif`,FR=`#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`,NR=`#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`,kR=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vWorldPosition = worldPosition.xyz;
	#else
		vec3 cameraToVertex;
		if ( isOrthographic ) {
			cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vReflect = reflect( cameraToVertex, worldNormal );
		#else
			vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
		#endif
	#endif
#endif`,GR=`#ifdef USE_FOG
	vFogDepth = - mvPosition.z;
#endif`,zR=`#ifdef USE_FOG
	varying float vFogDepth;
#endif`,VR=`#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`,HR=`#ifdef USE_FOG
	uniform vec3 fogColor;
	varying float vFogDepth;
	#ifdef FOG_EXP2
		uniform float fogDensity;
	#else
		uniform float fogNear;
		uniform float fogFar;
	#endif
#endif`,QR=`#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
}`,jR=`#ifdef USE_LIGHTMAP
	uniform sampler2D lightMap;
	uniform float lightMapIntensity;
#endif`,WR=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,qR=`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`,XR=`uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
	uniform vec3 lightProbe[ 9 ];
#endif
vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
	float x = normal.x, y = normal.y, z = normal.z;
	vec3 result = shCoefficients[ 0 ] * 0.886227;
	result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
	result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
	result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
	result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
	result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
	result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
	result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
	result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
	return result;
}
vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
	vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
	vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
	return irradiance;
}
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
	vec3 irradiance = ambientLightColor;
	return irradiance;
}
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
	float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
	if ( cutoffDistance > 0.0 ) {
		distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
	}
	return distanceFalloff;
}
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
	return smoothstep( coneCosine, penumbraCosine, angleCosine );
}
#if NUM_DIR_LIGHTS > 0
	struct DirectionalLight {
		vec3 direction;
		vec3 color;
	};
	uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
	void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
		light.color = directionalLight.color;
		light.direction = directionalLight.direction;
		light.visible = true;
	}
#endif
#if NUM_POINT_LIGHTS > 0
	struct PointLight {
		vec3 position;
		vec3 color;
		float distance;
		float decay;
	};
	uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
	void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = pointLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float lightDistance = length( lVector );
		light.color = pointLight.color;
		light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
		light.visible = ( light.color != vec3( 0.0 ) );
	}
#endif
#if NUM_SPOT_LIGHTS > 0
	struct SpotLight {
		vec3 position;
		vec3 direction;
		vec3 color;
		float distance;
		float decay;
		float coneCos;
		float penumbraCos;
	};
	uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
	void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = spotLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float angleCos = dot( light.direction, spotLight.direction );
		float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
		if ( spotAttenuation > 0.0 ) {
			float lightDistance = length( lVector );
			light.color = spotLight.color * spotAttenuation;
			light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
			light.visible = ( light.color != vec3( 0.0 ) );
		} else {
			light.color = vec3( 0.0 );
			light.visible = false;
		}
	}
#endif
#if NUM_RECT_AREA_LIGHTS > 0
	struct RectAreaLight {
		vec3 color;
		vec3 position;
		vec3 halfWidth;
		vec3 halfHeight;
	};
	uniform sampler2D ltc_1;	uniform sampler2D ltc_2;
	uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
#endif
#if NUM_HEMI_LIGHTS > 0
	struct HemisphereLight {
		vec3 direction;
		vec3 skyColor;
		vec3 groundColor;
	};
	uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
	vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
		float dotNL = dot( normal, hemiLight.direction );
		float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
		vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
		return irradiance;
	}
#endif`,YR=`#ifdef USE_ENVMAP
	vec3 getIBLIrradiance( const in vec3 normal ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
		#if defined( FIX_ENV_DIRECTION )
			vec3 worldNormal = normal;
		#else
			vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
		#endif
			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, roughness * roughness) );
			#if !defined( FIX_ENV_DIRECTION )
			reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
			#endif
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
			return envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	#ifdef USE_ANISOTROPY
		vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
			#ifdef ENVMAP_TYPE_CUBE_UV
				vec3 bentNormal = cross( bitangent, viewDir );
				bentNormal = normalize( cross( bentNormal, bitangent ) );
				bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
				return getIBLRadiance( viewDir, bentNormal, roughness );
			#else
				return vec3( 0.0 );
			#endif
		}
	#endif
#endif`,$R=`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,KR=`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`,JR=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,ZR=`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`,eB=`PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb * ( 1.0 - 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 = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
#else
	material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
	material.specularF90 = 1.0;
#endif
#ifdef USE_CLEARCOAT
	material.clearcoat = clearcoat;
	material.clearcoatRoughness = clearcoatRoughness;
	material.clearcoatF0 = vec3( 0.04 );
	material.clearcoatF90 = 1.0;
	#ifdef USE_CLEARCOATMAP
		material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
	#endif
	#ifdef USE_CLEARCOAT_ROUGHNESSMAP
		material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
	#endif
	material.clearcoat = saturate( material.clearcoat );	material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
	material.clearcoatRoughness += geometryRoughness;
	material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
#endif
#ifdef USE_DISPERSION
	material.dispersion = dispersion;
#endif
#ifdef USE_IRIDESCENCE
	material.iridescence = iridescence;
	material.iridescenceIOR = iridescenceIOR;
	#ifdef USE_IRIDESCENCEMAP
		material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
	#endif
	#ifdef USE_IRIDESCENCE_THICKNESSMAP
		material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
	#else
		material.iridescenceThickness = iridescenceThicknessMaximum;
	#endif
#endif
#ifdef USE_SHEEN
	material.sheenColor = sheenColor;
	#ifdef USE_SHEEN_COLORMAP
		material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
	#endif
	material.sheenRoughness = clamp( sheenRoughness, 0.07, 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`,tB=`struct PhysicalMaterial {
	vec3 diffuseColor;
	float roughness;
	vec3 specularColor;
	float specularF90;
	float dispersion;
	#ifdef USE_CLEARCOAT
		float clearcoat;
		float clearcoatRoughness;
		vec3 clearcoatF0;
		float clearcoatF90;
	#endif
	#ifdef USE_IRIDESCENCE
		float iridescence;
		float iridescenceIOR;
		float iridescenceThickness;
		vec3 iridescenceFresnel;
		vec3 iridescenceF0;
	#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 );
}
#if defined( USE_ANISOTROPY ) || defined( USE_ANISOTROPY_BRDF )
	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 ) );
		float v = 0.5 / ( gv + gl );
		return saturate(v);
	}
	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.specularColor;
	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 * transposeMat3( 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 a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
	float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
	float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
	return saturate( DG * RECIPROCAL_PI );
}
vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
	const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
	vec4 r = roughness * c0 + c1;
	float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
	vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
	return fab;
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	return specularColor * fab.x + specularF90 * fab.y;
}
#ifdef USE_IRIDESCENCE
void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#else
void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#endif
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	#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.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
		reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
		reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
	}
#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 );
	#endif
	reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
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 ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
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 );
	#endif
	vec3 singleScattering = vec3( 0.0 );
	vec3 multiScattering = vec3( 0.0 );
	vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
	#ifdef USE_IRIDESCENCE
		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
	#else
		computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
	#endif
	vec3 totalScattering = singleScattering + multiScattering;
	vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
	reflectedLight.indirectSpecular += radiance * singleScattering;
	reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
	reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
}
#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 );
}`,iB=`
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
	geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
	float dotNVi = saturate( dot( normal, geometryViewDir ) );
	if ( material.iridescenceThickness == 0.0 ) {
		material.iridescence = 0.0;
	} else {
		material.iridescence = saturate( material.iridescence );
	}
	if ( material.iridescence > 0.0 ) {
		material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
		material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
	}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
	PointLight pointLight;
	#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
		pointLight = pointLights[ i ];
		getPointLightInfo( pointLight, geometryPosition, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
		pointLightShadow = pointLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
	SpotLight spotLight;
	vec4 spotColor;
	vec3 spotLightCoord;
	bool inSpotLightMap;
	#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
		spotLight = spotLights[ i ];
		getSpotLightInfo( spotLight, geometryPosition, directLight );
		#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
		#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
		#else
		#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#endif
		#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
			spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
			inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
			spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
			directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
		#endif
		#undef SPOT_LIGHT_MAP_INDEX
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		spotLightShadow = spotLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
	DirectionalLight directionalLight;
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
		directionalLight = directionalLights[ i ];
		getDirectionalLightInfo( directionalLight, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
		directionalLightShadow = directionalLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
	RectAreaLight rectAreaLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
		rectAreaLight = rectAreaLights[ i ];
		RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
	vec3 iblIrradiance = vec3( 0.0 );
	vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
	#if defined( USE_LIGHT_PROBES )
		irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
	#endif
	#if ( NUM_HEMI_LIGHTS > 0 )
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
			irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
		}
		#pragma unroll_loop_end
	#endif
#endif
#if defined( RE_IndirectSpecular )
	vec3 radiance = vec3( 0.0 );
	vec3 clearcoatRadiance = vec3( 0.0 );
#endif`,nB=`#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( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
		iblIrradiance += getIBLIrradiance( geometryNormal );
	#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
	#ifdef USE_ANISOTROPY
		radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
	#else
		radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
	#endif
	#ifdef USE_CLEARCOAT
		clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
	#endif
#endif`,sB=`#if defined( RE_IndirectDiffuse )
	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`,rB=`#if defined( USE_LOGDEPTHBUF )
	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,aB=`#if defined( USE_LOGDEPTHBUF )
	uniform float logDepthBufFC;
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,oB=`#ifdef USE_LOGDEPTHBUF
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,lB=`#ifdef USE_LOGDEPTHBUF
	vFragDepth = 1.0 + gl_Position.w;
	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,cB=`#ifdef USE_MAP
	vec4 sampledDiffuseColor = texture2D( map, vMapUv );
	#ifdef DECODE_VIDEO_TEXTURE
		sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );
	
	#endif
	diffuseColor *= sampledDiffuseColor;
#endif`,hB=`#ifdef USE_MAP
	uniform sampler2D map;
#endif`,uB=`#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`,dB=`#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`,fB=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
	metalnessFactor *= texelMetalness.b;
#endif`,pB=`#ifdef USE_METALNESSMAP
	uniform sampler2D metalnessMap;
#endif`,mB=`#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`,gB=`#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`,AB=`#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`,yB=`#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`,_B=`#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`,vB=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
	vec3 fdx = dFdx( vViewPosition );
	vec3 fdy = dFdy( vViewPosition );
	vec3 normal = normalize( cross( fdx, fdy ) );
#else
	vec3 normal = normalize( vNormal );
	#ifdef DOUBLE_SIDED
		normal *= faceDirection;
	#endif
#endif
#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
	#ifdef USE_TANGENT
		mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn = getTangentFrame( - vViewPosition, normal,
		#if defined( USE_NORMALMAP )
			vNormalMapUv
		#elif defined( USE_CLEARCOAT_NORMALMAP )
			vClearcoatNormalMapUv
		#else
			vUv
		#endif
		);
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn[0] *= faceDirection;
		tbn[1] *= faceDirection;
	#endif
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	#ifdef USE_TANGENT
		mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn2[0] *= faceDirection;
		tbn2[1] *= faceDirection;
	#endif
#endif
vec3 nonPerturbedNormal = normal;`,bB=`#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;
	mapN.xy *= normalScale;
	normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
	normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`,wB=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,CB=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,xB=`#ifndef FLAT_SHADED
	vNormal = normalize( transformedNormal );
	#ifdef USE_TANGENT
		vTangent = normalize( transformedTangent );
		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
	#endif
#endif`,SB=`#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`,EB=`#ifdef USE_CLEARCOAT
	vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,MB=`#ifdef USE_CLEARCOAT_NORMALMAP
	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
	clearcoatMapN.xy *= clearcoatNormalScale;
	clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,TB=`#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`,IB=`#ifdef USE_IRIDESCENCEMAP
	uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform sampler2D iridescenceThicknessMap;
#endif`,PB=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
diffuseColor.a = min(max(diffuseColor.a, 0.), 1.);
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,DB=`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 ) {
	return depth * ( near - far ) - near;
}
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 ) {
	return ( near * far ) / ( ( far - near ) * depth - far );
}`,RB=`#ifdef PREMULTIPLIED_ALPHA
	gl_FragColor.rgb *= gl_FragColor.a;
#endif`,BB=`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;`,LB=`#ifdef DITHERING
	gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,OB=`#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`,UB=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
	roughnessFactor *= texelRoughness.g;
#endif`,FB=`#ifdef USE_ROUGHNESSMAP
	uniform sampler2D roughnessMap;
#endif`,NB=`#if NUM_SPOT_LIGHT_COORDS > 0
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
	uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform sampler2D directionalShadowMap[ 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
		uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
		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 sampler2D pointShadowMap[ 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
	float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
		return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );
	}
	vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
		return unpackRGBATo2Half( texture2D( shadow, uv ) );
	}
	float VSMShadow (sampler2D shadow, vec2 uv, float compare ){
		float occlusion = 1.0;
		vec2 distribution = texture2DDistribution( shadow, uv );
		float hard_shadow = step( compare , distribution.x );
		if (hard_shadow != 1.0 ) {
			float distance = compare - distribution.x ;
			float variance = max( 0.00000, distribution.y * distribution.y );
			float softness_probability = variance / (variance + distance * distance );			softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );			occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
		}
		return occlusion;
	}
	float getShadow( sampler2D 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 ) {
		#if defined( SHADOWMAP_TYPE_PCF )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx0 = - texelSize.x * shadowRadius;
			float dy0 = - texelSize.y * shadowRadius;
			float dx1 = + texelSize.x * shadowRadius;
			float dy1 = + texelSize.y * shadowRadius;
			float dx2 = dx0 / 2.0;
			float dy2 = dy0 / 2.0;
			float dx3 = dx1 / 2.0;
			float dy3 = dy1 / 2.0;
			shadow = (
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
			) * ( 1.0 / 17.0 );
		#elif defined( SHADOWMAP_TYPE_PCF_SOFT )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx = texelSize.x;
			float dy = texelSize.y;
			vec2 uv = shadowCoord.xy;
			vec2 f = fract( uv * shadowMapSize + 0.5 );
			uv -= f * texelSize;
			shadow = (
				texture2DCompare( shadowMap, uv, shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
						  f.x ),
					 mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
						  f.x ),
					 f.y )
			) * ( 1.0 / 9.0 );
		#elif defined( SHADOWMAP_TYPE_VSM )
			shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
		#else
			shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
		#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
	vec2 cubeToUV( vec3 v, float texelSizeY ) {
		vec3 absV = abs( v );
		float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
		absV *= scaleToCube;
		v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
		vec2 planar = v.xy;
		float almostATexel = 1.5 * texelSizeY;
		float almostOne = 1.0 - almostATexel;
		if ( absV.z >= almostOne ) {
			if ( v.z > 0.0 )
				planar.x = 4.0 - v.x;
		} else if ( absV.x >= almostOne ) {
			float signX = sign( v.x );
			planar.x = v.z * signX + 2.0 * signX;
		} else if ( absV.y >= almostOne ) {
			float signY = sign( v.y );
			planar.x = v.x + 2.0 * signY + 2.0;
			planar.y = v.z * signY - 2.0;
		}
		return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
	}
	float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
		float shadow = 1.0;
		vec3 lightToPosition = shadowCoord.xyz;
		
		float lightToPositionLength = length( lightToPosition );
		if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
			float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );			dp += shadowBias;
			vec3 bd3D = normalize( lightToPosition );
			vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
			#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
				vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
				shadow = (
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
				) * ( 1.0 / 9.0 );
			#else
				shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
			#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
#endif`,kB=`#if NUM_SPOT_LIGHT_COORDS > 0
	uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
#endif`,GB=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
	vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
	vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
	#if NUM_DIR_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
			vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
			vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
#endif
#if NUM_SPOT_LIGHT_COORDS > 0
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
		shadowWorldPosition = worldPosition;
		#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
			shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
		#endif
		vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
	}
	#pragma unroll_loop_end
#endif`,zB=`float getShadowMask() {
	float shadow = 1.0;
	#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
		directionalLight = directionalLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
		spotLight = spotLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
	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;
}`,VB=`#ifdef USE_SKINNING
	mat4 boneMatX = getBoneMatrix( skinIndex.x );
	mat4 boneMatY = getBoneMatrix( skinIndex.y );
	mat4 boneMatZ = getBoneMatrix( skinIndex.z );
	mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,HB=`#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`,QB=`#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`,jB=`#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`,WB=`float specularStrength;
#ifdef USE_SPECULARMAP
	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
	specularStrength = texelSpecular.r;
#else
	specularStrength = 1.0;
#endif`,qB=`#ifdef USE_SPECULARMAP
	uniform sampler2D specularMap;
#endif`,XB=`#if defined( TONE_MAPPING )
	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,YB=`#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; }`,$B=`#ifdef USE_TRANSMISSION
	material.transmission = transmission;
	material.transmissionAlpha = 1.0;
	material.thickness = thickness;
	material.attenuationDistance = attenuationDistance;
	material.attenuationColor = attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
	#endif
	#ifdef USE_THICKNESSMAP
		material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
	#endif
	vec3 pos = vWorldPosition;
	vec3 v = normalize( cameraPosition - pos );
	vec3 n = inverseTransformDirection( normal, viewMatrix );
	vec4 transmitted = getIBLVolumeRefraction(
		n, v, roughnessFactor, material.diffuseColor, material.specularColor, 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`,KB=`#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 ) );
	}
	#ifndef WebGL2Context
	#define textureLod texture2DLodEXT
	#define textureSize(s, lod) vec2(1024./pow(2.,float(lod)),1024./pow(2.,float(lod)))
	#define isinf(x) (x > 1e20 || x < -1e20)
	#endif
	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 ) {
		if(roughness == 0.0) return transmissionSamplerMapTexelToLinear( texture2D( transmissionSamplerMap, fragCoord.xy ) );
		float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
		return transmissionSamplerMapTexelToLinear( textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ) );
	}
	vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
		if ( isinf( attenuationDistance ) || attenuationDistance == 0.0) {
			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`,JB=`#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`,ZB=`#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`,e2=`#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`,t2=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
	vec4 worldPosition = vec4( transformed, 1.0 );
	#ifdef USE_BATCHING
		worldPosition = batchingMatrix * worldPosition;
	#endif
	#ifdef USE_INSTANCING
		worldPosition = instanceMatrix * worldPosition;
	#endif
	worldPosition = modelMatrix * worldPosition;
#endif`;const lt={alphahash_fragment:nR,alphahash_pars_fragment:sR,alphamap_fragment:rR,alphamap_pars_fragment:aR,alphatest_fragment:oR,alphatest_pars_fragment:lR,aomap_fragment:cR,aomap_pars_fragment:hR,batching_pars_vertex:uR,batching_vertex:dR,begin_vertex:fR,beginnormal_vertex:pR,bsdfs:mR,iridescence_fragment:gR,bumpmap_pars_fragment:AR,clipping_planes_fragment:yR,clipping_planes_pars_fragment:_R,clipping_planes_pars_vertex:vR,clipping_planes_vertex:bR,color_fragment:wR,color_pars_fragment:CR,color_pars_vertex:xR,color_vertex:SR,common:ER,cube_uv_reflection_fragment:MR,defaultnormal_vertex:TR,displacementmap_pars_vertex:IR,displacementmap_vertex:PR,emissivemap_fragment:DR,emissivemap_pars_fragment:RR,colorspace_fragment:BR,colorspace_pars_fragment:LR,envmap_fragment:OR,envmap_common_pars_fragment:UR,envmap_pars_fragment:FR,envmap_pars_vertex:NR,envmap_physical_pars_fragment:YR,envmap_vertex:kR,fog_vertex:GR,fog_pars_vertex:zR,fog_fragment:VR,fog_pars_fragment:HR,gradientmap_pars_fragment:QR,lightmap_pars_fragment:jR,lights_lambert_fragment:WR,lights_lambert_pars_fragment:qR,lights_pars_begin:XR,lights_toon_fragment:$R,lights_toon_pars_fragment:KR,lights_phong_fragment:JR,lights_phong_pars_fragment:ZR,lights_physical_fragment:eB,lights_physical_pars_fragment:tB,lights_fragment_begin:iB,lights_fragment_maps:nB,lights_fragment_end:sB,logdepthbuf_fragment:rB,logdepthbuf_pars_fragment:aB,logdepthbuf_pars_vertex:oB,logdepthbuf_vertex:lB,map_fragment:cB,map_pars_fragment:hB,map_particle_fragment:uB,map_particle_pars_fragment:dB,metalnessmap_fragment:fB,metalnessmap_pars_fragment:pB,morphinstance_vertex:mB,morphcolor_vertex:gB,morphnormal_vertex:AB,morphtarget_pars_vertex:yB,morphtarget_vertex:_B,normal_fragment_begin:vB,normal_fragment_maps:bB,normal_pars_fragment:wB,normal_pars_vertex:CB,normal_vertex:xB,normalmap_pars_fragment:SB,clearcoat_normal_fragment_begin:EB,clearcoat_normal_fragment_maps:MB,clearcoat_pars_fragment:TB,iridescence_pars_fragment:IB,opaque_fragment:PB,packing:DB,premultiplied_alpha_fragment:RB,project_vertex:BB,dithering_fragment:LB,dithering_pars_fragment:OB,roughnessmap_fragment:UB,roughnessmap_pars_fragment:FB,shadowmap_pars_fragment:NB,shadowmap_pars_vertex:kB,shadowmap_vertex:GB,shadowmask_pars_fragment:zB,skinbase_vertex:VB,skinning_pars_vertex:HB,skinning_vertex:QB,skinnormal_vertex:jB,specularmap_fragment:WB,specularmap_pars_fragment:qB,tonemapping_fragment:XB,tonemapping_pars_fragment:YB,transmission_fragment:$B,transmission_pars_fragment:KB,uv_pars_fragment:JB,uv_pars_vertex:ZB,uv_vertex:e2,worldpos_vertex:t2,background_vert:`#ifdef HAS_TEXTURE
varying vec2 vUv;
uniform mat3 uvTransform;
uniform bool flipX;
uniform bool flipY;
#endif
void main() {
#ifdef HAS_TEXTURE
	vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
    vUv = flipX ? vec2( 1.0 - vUv.x, vUv.y ) : vUv;
    vUv = flipY ? vec2( vUv.x, 1.0 - vUv.y ) : vUv;
#endif
	gl_Position = vec4( position.xy, 1.0, 1.0 );
}`,background_frag:`#ifdef HAS_TEXTURE
uniform sampler2D t2D;
varying vec2 vUv;
#endif
uniform float backgroundIntensity;
uniform vec3 backgroundColor;
void main() {
#ifdef HAS_TEXTURE
	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
#else
	vec4 texColor = vec4( 1.0 );
#endif
	texColor.rgb *= backgroundColor * 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 flipEnvMap;
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 * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
	#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>
	float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;
	#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
}`,distanceRGBA_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;
}`,distanceRGBA_frag:`#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#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 <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 = packDepthToRGBA( dist );
}`,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 <packing>
#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 <envmap_common_pars_fragment>
#include <envmap_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 <packing>
#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( packNormalToRGB( normal ), 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 <packing>
#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 <envmap_common_pars_fragment>
#include <envmap_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_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 <packing>
#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
		float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
		outgoingLight = outgoingLight * sheenEnergyComp + 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 <packing>
#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 <packing>
#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>
}`,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 * vec4( 0.0, 0.0, 0.0, 1.0 );
	vec2 scale;
	scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );
	scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );
	#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>
}`},De={common:{diffuse:{value:new ee(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new At},alphaMap:{value:null},alphaMapTransform:{value:new At},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new At}},envmap:{envMap:{value:null},envMapRotation:{value:new At},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new At}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new At}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new At},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new At},normalScale:{value:new K(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new At},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new At}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new At}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new At}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ee(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new ee(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new At},alphaTest:{value:0},uvTransform:{value:new At}},sprite:{diffuse:{value:new ee(16777215)},opacity:{value:1},center:{value:new K(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new At},alphaMap:{value:null},alphaMapTransform:{value:new At},alphaTest:{value:0}}},Di={basic:{uniforms:ns([De.common,De.specularmap,De.envmap,De.aomap,De.lightmap,De.fog]),vertexShader:lt.meshbasic_vert,fragmentShader:lt.meshbasic_frag},lambert:{uniforms:ns([De.common,De.specularmap,De.envmap,De.aomap,De.lightmap,De.emissivemap,De.bumpmap,De.normalmap,De.displacementmap,De.fog,De.lights,{emissive:{value:new ee(0)}}]),vertexShader:lt.meshlambert_vert,fragmentShader:lt.meshlambert_frag},phong:{uniforms:ns([De.common,De.specularmap,De.envmap,De.aomap,De.lightmap,De.emissivemap,De.bumpmap,De.normalmap,De.displacementmap,De.fog,De.lights,{emissive:{value:new ee(0)},specular:{value:new ee(1118481)},shininess:{value:30}}]),vertexShader:lt.meshphong_vert,fragmentShader:lt.meshphong_frag},standard:{uniforms:ns([De.common,De.envmap,De.aomap,De.lightmap,De.emissivemap,De.bumpmap,De.normalmap,De.displacementmap,De.roughnessmap,De.metalnessmap,De.fog,De.lights,{emissive:{value:new ee(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:lt.meshphysical_vert,fragmentShader:lt.meshphysical_frag},toon:{uniforms:ns([De.common,De.aomap,De.lightmap,De.emissivemap,De.bumpmap,De.normalmap,De.displacementmap,De.gradientmap,De.fog,De.lights,{emissive:{value:new ee(0)}}]),vertexShader:lt.meshtoon_vert,fragmentShader:lt.meshtoon_frag},matcap:{uniforms:ns([De.common,De.bumpmap,De.normalmap,De.displacementmap,De.fog,{matcap:{value:null}}]),vertexShader:lt.meshmatcap_vert,fragmentShader:lt.meshmatcap_frag},points:{uniforms:ns([De.points,De.fog]),vertexShader:lt.points_vert,fragmentShader:lt.points_frag},dashed:{uniforms:ns([De.common,De.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:lt.linedashed_vert,fragmentShader:lt.linedashed_frag},depth:{uniforms:ns([De.common,De.displacementmap]),vertexShader:lt.depth_vert,fragmentShader:lt.depth_frag},normal:{uniforms:ns([De.common,De.bumpmap,De.normalmap,De.displacementmap,{opacity:{value:1}}]),vertexShader:lt.meshnormal_vert,fragmentShader:lt.meshnormal_frag},sprite:{uniforms:ns([De.sprite,De.fog]),vertexShader:lt.sprite_vert,fragmentShader:lt.sprite_frag},background:{uniforms:{uvTransform:{value:new At},t2D:{value:null},backgroundIntensity:{value:1},backgroundColor:{value:new ee(16777215)},flipX:{value:!1},flipY:{value:!1}},vertexShader:lt.background_vert,fragmentShader:lt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},envMapRotation:{value:0},envMapIntensity:{value:1},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new At}},vertexShader:lt.backgroundCube_vert,fragmentShader:lt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:lt.cube_vert,fragmentShader:lt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:lt.equirect_vert,fragmentShader:lt.equirect_frag},distanceRGBA:{uniforms:ns([De.common,De.displacementmap,{referencePosition:{value:new S},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:lt.distanceRGBA_vert,fragmentShader:lt.distanceRGBA_frag},shadow:{uniforms:ns([De.lights,De.fog,{color:{value:new ee(0)},opacity:{value:1}}]),vertexShader:lt.shadow_vert,fragmentShader:lt.shadow_frag}};Di.physical={uniforms:ns([Di.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new At},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new At},clearcoatNormalScale:{value:new K(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new At},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new At},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new At},sheen:{value:0},sheenColor:{value:new ee(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new At},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new At},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new At},transmissionSamplerSize:{value:new K},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new At},attenuationDistance:{value:0},attenuationColor:{value:new ee(0)},specularColor:{value:new ee(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new At},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new At},anisotropyVector:{value:new K},anisotropyMap:{value:null},anisotropyMapTransform:{value:new At}}]),vertexShader:lt.meshphysical_vert,fragmentShader:lt.meshphysical_frag};const sp={r:0,b:0,g:0},ps=new Pt,pC=new fe,i2=new At;function n2(r,e,t,i,n,s,a){const o=new ee(0);let l=s===!0?0:1,c,h,u=null,d=0,p=null;function m(v){let _=v.isScene===!0?v.background:null;return _==="environment"&&(_=v.environment),_&&_.isTexture&&(_=(v.backgroundBlurriness>0?t:e).get(_)),_}function A(v){let _=!1;const b=m(v);b===null?y(o,l):b&&b.isColor&&(y(b,1),_=!0);const T=r.xr.getEnvironmentBlendMode();T==="additive"?i.buffers.color.setClear(0,0,0,1,a):T==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,a),(r.autoClear||_)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),r.clear(r.autoClearColor,r.autoClearDepth,r.autoClearStencil))}function g(v,_){const b=m(_),T=b&&b===_.environment,E=_.isScene&&_.backgroundColor!==void 0?_.backgroundColor:null;if(b&&(b.isCubeTexture||b.mapping===Kl))h===void 0&&(h=new _e(new gi(1,1,1),new nn({name:"BackgroundCubeMaterial",uniforms:No(Di.backgroundCube.uniforms),vertexShader:Di.backgroundCube.vertexShader,fragmentShader:Di.backgroundCube.fragmentShader,side:In,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(M,I,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(h)),ps.copy(_.backgroundRotation),ps.x*=-1,ps.y*=-1,ps.z*=-1,b.isCubeTexture&&b.isRenderTargetTexture===!1&&(ps.y*=-1,ps.z*=-1),h.material.uniforms.envMap.value=b,h.material.uniforms.flipEnvMap.value=b.isCubeTexture&&b.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=_.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(pC.makeRotationFromEuler(ps)),h.material.toneMapped=Nt.getTransfer(b.colorSpace)!==Ci,T&&(h.material.uniforms.backgroundIntensity.value*=_.environmentIntensity,ps.copy(_.environmentRotation),ps.x*=-1,ps.y*=-1,ps.z*=-1,b.isCubeTexture&&b.isRenderTargetTexture===!1&&(ps.y*=-1,ps.z*=-1),h.material.uniforms.backgroundRotation.value.premultiply(i2.setFromMatrix4(pC.makeRotationFromEuler(ps)))),(u!==b||d!==b.version||p!==r.toneMapping)&&(h.material.needsUpdate=!0,u=b,d=b.version,p=r.toneMapping),h.layers.enableAll(),v.unshift(h,h.geometry,h.material,0,0,null);else if(b&&b.isTexture||!b&&E){c===void 0&&(c=new _e(new ca(2,2),new nn({name:"BackgroundMaterial",uniforms:No(Di.background.uniforms),vertexShader:Di.background.vertexShader,fragmentShader:Di.background.fragmentShader,side:us,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(c)),c.material.uniforms.backgroundColor.value.set(E||16777215),c.material.uniforms.t2D.value=b,c.material.uniforms.backgroundIntensity.value=_.backgroundIntensity,b?(c.material.toneMapped=Nt.getTransfer(b.colorSpace)!==Ci,c.material.uniforms.flipX.value=b.userData.flipX||!1,c.material.uniforms.flipY.value=b.userData.flipY||!1,b.matrixAutoUpdate===!0&&b.updateMatrix(),c.material.uniforms.uvTransform.value.copy(b.matrix),c.material.defines.HAS_TEXTURE="1"):c.material.defines.HAS_TEXTURE&&delete c.material.defines.HAS_TEXTURE;const M=b?b.version:-1;(u!==b||d!==M||p!==r.toneMapping)&&(c.material.needsUpdate=!0,u=b,d=M,p=r.toneMapping),c.layers.enableAll(),v.unshift(c,c.geometry,c.material,0,0,null)}}function y(v,_){v.getRGB(sp,cC(r)),i.buffers.color.setClear(sp.r,sp.g,sp.b,_,a)}return{getClearColor:function(){return o},setClearColor:function(v,_=1){o.set(v),l=_,y(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(v){l=v,y(o,l)},getPlaneMesh:function(){return c},getBoxMesh:function(){return h},getBoxMesh2:function(){return h===void 0&&(h=new _e(new gi(1,1,1),new nn({name:"BackgroundCubeMaterial",uniforms:No(Di.backgroundCube.uniforms),vertexShader:Di.backgroundCube.vertexShader,fragmentShader:Di.backgroundCube.fragmentShader,side:In,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(v,_,b){this.matrixWorld.copyPosition(b.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(h)),h},render:A,addToRenderList:g}}function s2(r,e){const t=r.getParameter(r.MAX_VERTEX_ATTRIBS),i={},n=d(null);let s=n,a=!1;function o(x,D,U,O,N){let H=!1;const V=u(O,U,D);s!==V&&(s=V,c(s.object)),H=p(x,O,U,N),H&&m(x,O,U,N),N!==null&&e.update(N,r.ELEMENT_ARRAY_BUFFER),(H||a)&&(a=!1,b(x,D,U,O),N!==null&&r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.get(N).buffer))}function l(){return r.createVertexArray()}function c(x){return r.bindVertexArray(x)}function h(x){return r.deleteVertexArray(x)}function u(x,D,U){const O=U.wireframe===!0;let N=i[x.id];N===void 0&&(N={},i[x.id]=N);let H=N[D.id];H===void 0&&(H={},N[D.id]=H);let V=H[O];return V===void 0&&(V=d(l()),H[O]=V),V}function d(x){const D=[],U=[],O=[];for(let N=0;N<t;N++)D[N]=0,U[N]=0,O[N]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:D,enabledAttributes:U,attributeDivisors:O,object:x,attributes:{},index:null}}function p(x,D,U,O){const N=s.attributes,H=D.attributes;let V=0;const X=U.getAttributes();for(const W in X)if(X[W].location>=0){const ue=N[W];let we=H[W];if(we===void 0&&(W==="instanceMatrix"&&x.instanceMatrix&&(we=x.instanceMatrix),W==="instanceColor"&&x.instanceColor&&(we=x.instanceColor)),ue===void 0||ue.attribute!==we||we&&ue.data!==we.data)return!0;V++}return s.attributesNum!==V||s.index!==O}function m(x,D,U,O){const N={},H=D.attributes;let V=0;const X=U.getAttributes();for(const W in X)if(X[W].location>=0){let ue=H[W];ue===void 0&&(W==="instanceMatrix"&&x.instanceMatrix&&(ue=x.instanceMatrix),W==="instanceColor"&&x.instanceColor&&(ue=x.instanceColor));const we={};we.attribute=ue,ue&&ue.data&&(we.data=ue.data),N[W]=we,V++}s.attributes=N,s.attributesNum=V,s.index=O}function A(){const x=s.newAttributes;for(let D=0,U=x.length;D<U;D++)x[D]=0}function g(x){y(x,0)}function y(x,D){const U=s.newAttributes,O=s.enabledAttributes,N=s.attributeDivisors;U[x]=1,O[x]===0&&(r.enableVertexAttribArray(x),O[x]=1),N[x]!==D&&(r.vertexAttribDivisor(x,D),N[x]=D)}function v(){const x=s.newAttributes,D=s.enabledAttributes;for(let U=0,O=D.length;U<O;U++)D[U]!==x[U]&&(r.disableVertexAttribArray(U),D[U]=0)}function _(x,D,U,O,N,H,V){V===!0?r.vertexAttribIPointer(x,D,U,N,H):r.vertexAttribPointer(x,D,U,O,N,H)}function b(x,D,U,O){A();const N=O.attributes,H=U.getAttributes(),V=D.defaultAttributeValues;for(const X in H){const W=H[X];if(W.location>=0){let ce=N[X];if(ce===void 0&&(X==="instanceMatrix"&&x.instanceMatrix&&(ce=x.instanceMatrix),X==="instanceColor"&&x.instanceColor&&(ce=x.instanceColor)),ce!==void 0){const ue=ce.normalized,we=ce.itemSize,Pe=e.get(ce);if(Pe===void 0)continue;const Qe=Pe.buffer,ie=Pe.type,oe=Pe.bytesPerElement,me=ie===r.INT||ie===r.UNSIGNED_INT||ce.gpuType===gf;if(ce.isInterleavedBufferAttribute){const Ce=ce.data,Xe=Ce.stride,dt=ce.offset;if(Ce.isInstancedInterleavedBuffer){for(let Ke=0;Ke<W.locationSize;Ke++)y(W.location+Ke,Ce.meshPerAttribute);x.isInstancedMesh!==!0&&O._maxInstanceCount===void 0&&(O._maxInstanceCount=Ce.meshPerAttribute*Ce.count)}else for(let Ke=0;Ke<W.locationSize;Ke++)g(W.location+Ke);r.bindBuffer(r.ARRAY_BUFFER,Qe);for(let Ke=0;Ke<W.locationSize;Ke++)_(W.location+Ke,we/W.locationSize,ie,ue,Xe*oe,(dt+we/W.locationSize*Ke)*oe,me)}else{if(ce.isInstancedBufferAttribute){for(let Ce=0;Ce<W.locationSize;Ce++)y(W.location+Ce,ce.meshPerAttribute);x.isInstancedMesh!==!0&&O._maxInstanceCount===void 0&&(O._maxInstanceCount=ce.meshPerAttribute*ce.count)}else for(let Ce=0;Ce<W.locationSize;Ce++)g(W.location+Ce);r.bindBuffer(r.ARRAY_BUFFER,Qe);for(let Ce=0;Ce<W.locationSize;Ce++)_(W.location+Ce,we/W.locationSize,ie,ue,we*oe,we/W.locationSize*Ce*oe,me)}}else if(V!==void 0){const ue=V[X];if(ue!==void 0)switch(ue.length){case 2:r.vertexAttrib2fv(W.location,ue);break;case 3:r.vertexAttrib3fv(W.location,ue);break;case 4:r.vertexAttrib4fv(W.location,ue);break;default:r.vertexAttrib1fv(W.location,ue)}}}}v()}function T(){I();for(const x in i){const D=i[x];for(const U in D){const O=D[U];for(const N in O)h(O[N].object),delete O[N];delete D[U]}delete i[x]}}function E(x){if(i[x.id]===void 0)return;const D=i[x.id];for(const U in D){const O=D[U];for(const N in O)h(O[N].object),delete O[N];delete D[U]}delete i[x.id]}function M(x){for(const D in i){const U=i[D];if(U[x.id]===void 0)continue;const O=U[x.id];for(const N in O)h(O[N].object),delete O[N];delete U[x.id]}}function I(){C(),a=!0,s!==n&&(s=n,c(s.object))}function C(){n.geometry=null,n.program=null,n.wireframe=!1}return{setup:o,reset:I,resetDefaultState:C,dispose:T,releaseStatesOfGeometry:E,releaseStatesOfProgram:M,initAttributes:A,enableAttribute:g,disableUnusedAttributes:v}}function r2(r,e,t){let i;function n(c){i=c}function s(c,h){r.drawArrays(i,c,h),t.update(h,i,1)}function a(c,h,u){u!==0&&(r.drawArraysInstanced(i,c,h,u),t.update(h,i,u))}function o(c,h,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,c,0,h,0,u);let p=0;for(let m=0;m<u;m++)p+=h[m];t.update(p,i,1)}function l(c,h,u,d){if(u===0)return;const p=e.get("WEBGL_multi_draw");if(p===null)for(let m=0;m<c.length;m++)a(c[m],h[m],d[m]);else{p.multiDrawArraysInstancedWEBGL(i,c,0,h,0,d,0,u);let m=0;for(let A=0;A<u;A++)m+=h[A];for(let A=0;A<d.length;A++)t.update(m,i,d[A])}}this.setMode=n,this.render=s,this.renderInstances=a,this.renderMultiDraw=o,this.renderMultiDrawInstances=l}function a2(r,e,t,i){let n;function s(){if(n!==void 0)return n;if(e.has("EXT_texture_filter_anisotropic")===!0){const E=e.get("EXT_texture_filter_anisotropic");n=r.getParameter(E.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else n=0;return n}function a(E){return!(E!==qt&&i.convert(E)!==r.getParameter(r.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(E){const M=E===Yt&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(E!==Qt&&i.convert(E)!==r.getParameter(r.IMPLEMENTATION_COLOR_READ_TYPE)&&E!==Ut&&!M)}function l(E){if(E==="highp"){if(r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.HIGH_FLOAT).precision>0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).precision>0)return"highp";E="mediump"}return E==="mediump"&&r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_FLOAT).precision>0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp";const h=l(c);h!==c&&(console.warn("THREE.WebGLRenderer:",c,"not supported, using",h,"instead."),c=h);const u=t.logarithmicDepthBuffer===!0,d=r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS),p=r.getParameter(r.MAX_VERTEX_TEXTURE_IMAGE_UNITS),m=r.getParameter(r.MAX_TEXTURE_SIZE),A=r.getParameter(r.MAX_CUBE_MAP_TEXTURE_SIZE),g=r.getParameter(r.MAX_VERTEX_ATTRIBS),y=r.getParameter(r.MAX_VERTEX_UNIFORM_VECTORS),v=r.getParameter(r.MAX_VARYING_VECTORS),_=r.getParameter(r.MAX_FRAGMENT_UNIFORM_VECTORS),b=p>0,T=r.getParameter(r.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:l,textureFormatReadable:a,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:u,maxTextures:d,maxVertexTextures:p,maxTextureSize:m,maxCubemapSize:A,maxAttributes:g,maxVertexUniforms:y,maxVaryings:v,maxFragmentUniforms:_,vertexTextures:b,maxSamples:T}}function o2(r){const e=this;let t=null,i=0,n=!1,s=!1;const a=new Es,o=new At,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){const p=u.length!==0||d||i!==0||n;return n=d,i=u.length,p},this.beginShadows=function(){s=!0,h(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(u,d){t=h(u,d,0)},this.setState=function(u,d,p){const m=u.clippingPlanes,A=u.clipIntersection,g=u.clipShadows,y=r.get(u);if(!n||m===null||m.length===0||s&&!g)s?h(null):c();else{const v=s?0:i,_=v*4;let b=y.clippingState||null;l.value=b,b=h(m,d,_,p);for(let T=0;T!==_;++T)b[T]=t[T];y.clippingState=b,this.numIntersection=A?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function h(u,d,p,m){const A=u!==null?u.length:0;let g=null;if(A!==0){if(g=l.value,m!==!0||g===null){const y=p+A*4,v=d.matrixWorldInverse;o.getNormalMatrix(v),(g===null||g.length<y)&&(g=new Float32Array(y));for(let _=0,b=p;_!==A;++_,b+=4)a.copy(u[_]).applyMatrix4(v,o),a.normal.toArray(g,b),g[b+3]=a.constant}l.value=g,l.needsUpdate=!0}return e.numPlanes=A,e.numIntersection=0,g}}function l2(r){let e=new WeakMap;function t(a,o){return o===$r?a.mapping=Yr:o===mf&&(a.mapping=To),a}function i(a){if(a&&a.isTexture){const o=a.mapping;if(o===$r||o===mf)if(e.has(a)){const l=e.get(a).texture;return t(l,a.mapping)}else{const l=a.image;if(l&&l.height>0){const c=new Py(l.height);return c.fromEquirectangularTexture(r,a),e.set(a,c),a.addEventListener("dispose",n),t(c.texture,a.mapping)}else return null}}return a}function n(a){const o=a.target;o.removeEventListener("dispose",n);const l=e.get(o);l!==void 0&&(e.delete(o),l.dispose())}function s(){e=new WeakMap}return{get:i,dispose:s}}class Mr extends fu{constructor(e=-1,t=1,i=1,n=-1,s=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=i,this.bottom=n,this.near=s,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,i,n,s,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=i,this.view.offsetY=n,this.view.width=s,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,n=(this.top+this.bottom)/2;let s=i-e,a=i+e,o=n+t,l=n-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=c*this.view.offsetX,a=s+c*this.view.width,o-=h*this.view.offsetY,l=o-h*this.view.height}this.projectionMatrix.makeOrthographic(s,a,o,l,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}const Cc=4,mC=[.125,.215,.35,.446,.526,.582],zo=20,Ry=new Mr,gC=new ee;let By=null,Ly=0,Oy=0,Uy=!1;const Vo=(1+Math.sqrt(5))/2,xc=1/Vo,AC=[new S(-Vo,xc,0),new S(Vo,xc,0),new S(-xc,0,Vo),new S(xc,0,Vo),new S(0,Vo,-xc),new S(0,Vo,xc),new S(-1,1,-1),new S(1,1,-1),new S(-1,1,1),new S(1,1,1)];class Fy{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,i=.1,n=100){By=this._renderer.getRenderTarget(),Ly=this._renderer.getActiveCubeFace(),Oy=this._renderer.getActiveMipmapLevel(),Uy=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,i,n,s),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=vC(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=_C(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(By,Ly,Oy),this._renderer.xr.enabled=Uy,e.scissorTest=!1,rp(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===Yr||e.mapping===To?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),By=this._renderer.getRenderTarget(),Ly=this._renderer.getActiveCubeFace(),Oy=this._renderer.getActiveMipmapLevel(),Uy=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const i=t||this._allocateTargets();return this._textureToCubeUV(e,i),this._applyPMREM(i),this._cleanup(i),i}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,i={magFilter:at,minFilter:at,generateMipmaps:!1,type:Yt,format:qt,colorSpace:Bt,depthBuffer:!1},n=yC(e,t,i);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=yC(e,t,i);const{_lodMax:s}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=c2(s)),this._blurMaterial=h2(s,e,t)}return n}_compileMaterial(e){const t=new _e(this._lodPlanes[0],e);this._renderer.compile(t,Ry)}_sceneToCubeUV(e,t,i,n){const o=new zi(90,1,t,i),l=[1,-1,1,1,1,1],c=[1,1,1,-1,-1,-1],h=this._renderer,u=h.autoClear,d=h.toneMapping;h.getClearColor(gC),h.toneMapping=Xr,h.autoClear=!1;const p=new is({name:"PMREM.Background",side:In,depthWrite:!1,depthTest:!1}),m=new _e(new gi,p);let A=!1;const g=e.background;g?g.isColor&&(p.color.copy(g),e.background=null,A=!0):(p.color.copy(gC),A=!0);for(let y=0;y<6;y++){const v=y%3;v===0?(o.up.set(0,l[y],0),o.lookAt(c[y],0,0)):v===1?(o.up.set(0,0,l[y]),o.lookAt(0,c[y],0)):(o.up.set(0,l[y],0),o.lookAt(0,0,c[y]));const _=this._cubeSize;rp(n,v*_,y>2?_:0,_,_),h.setRenderTarget(n),A&&h.render(m,o),h.render(e,o)}m.geometry.dispose(),m.material.dispose(),h.toneMapping=d,h.autoClear=u,e.background=g}_textureToCubeUV(e,t){const i=this._renderer,n=e.mapping===Yr||e.mapping===To;n?(this._cubemapMaterial===null&&(this._cubemapMaterial=vC()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=_C());const s=n?this._cubemapMaterial:this._equirectMaterial,a=new _e(this._lodPlanes[0],s),o=s.uniforms;o.envMap.value=e;const l=this._cubeSize;rp(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(a,Ry)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const n=this._lodPlanes.length;for(let s=1;s<n;s++){const a=Math.sqrt(this._sigmas[s]*this._sigmas[s]-this._sigmas[s-1]*this._sigmas[s-1]),o=AC[(n-s-1)%AC.length];this._blur(e,s-1,s,a,o)}t.autoClear=i}_blur(e,t,i,n,s){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,i,n,"latitudinal",s),this._halfBlur(a,e,i,i,n,"longitudinal",s)}_halfBlur(e,t,i,n,s,a,o){const l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");const h=3,u=new _e(this._lodPlanes[n],c),d=c.uniforms,p=this._sizeLods[i]-1,m=isFinite(s)?Math.PI/(2*p):2*Math.PI/(2*zo-1),A=s/m,g=isFinite(s)?1+Math.floor(h*A):zo;g>zo&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${zo}`);const y=[];let v=0;for(let M=0;M<zo;++M){const I=M/A,C=Math.exp(-I*I/2);y.push(C),M===0?v+=C:M<g&&(v+=2*C)}for(let M=0;M<y.length;M++)y[M]=y[M]/v;d.envMap.value=e.texture,d.samples.value=g,d.weights.value=y,d.latitudinal.value=a==="latitudinal",o&&(d.poleAxis.value=o);const{_lodMax:_}=this;d.dTheta.value=m,d.mipInt.value=_-i;const b=this._sizeLods[n],T=3*b*(n>_-Cc?n-_+Cc:0),E=4*(this._cubeSize-b);rp(t,T,E,3*b,2*b),l.setRenderTarget(t),l.render(u,Ry)}}function c2(r){const e=[],t=[],i=[];let n=r;const s=r-Cc+1+mC.length;for(let a=0;a<s;a++){const o=Math.pow(2,n);t.push(o);let l=1/o;a>r-Cc?l=mC[a-r+Cc-1]:a===0&&(l=0),i.push(l);const c=1/(o-2),h=-c,u=1+c,d=[h,h,u,h,u,u,h,h,u,u,h,u],p=6,m=6,A=3,g=2,y=1,v=new Float32Array(A*m*p),_=new Float32Array(g*m*p),b=new Float32Array(y*m*p);for(let E=0;E<p;E++){const M=E%3*2/3-1,I=E>2?0:-1,C=[M,I,0,M+2/3,I,0,M+2/3,I+1,0,M,I,0,M+2/3,I+1,0,M,I+1,0];v.set(C,A*m*E),_.set(d,g*m*E);const x=[E,E,E,E,E,E];b.set(x,y*m*E)}const T=new Je;T.setAttribute("position",new Ze(v,A)),T.setAttribute("uv",new Ze(_,g)),T.setAttribute("faceIndex",new Ze(b,y)),e.push(T),n>Cc&&n--}return{lodPlanes:e,sizeLods:t,sigmas:i}}function yC(r,e,t){const i=new ds(r,e,t);return i.texture.mapping=Kl,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function rp(r,e,t,i,n){r.viewport.set(e,t,i,n),r.scissor.set(e,t,i,n)}function h2(r,e,t){const i=new Float32Array(zo),n=new S(0,1,0);return new nn({name:"SphericalGaussianBlur",defines:{n:zo,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${r}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:Ny(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;
			uniform int samples;
			uniform float weights[ n ];
			uniform bool latitudinal;
			uniform float dTheta;
			uniform float mipInt;
			uniform vec3 poleAxis;

			#define ENVMAP_TYPE_CUBE_UV
			#include <cube_uv_reflection_fragment>

			vec3 getSample( float theta, vec3 axis ) {

				float cosTheta = cos( theta );
				// Rodrigues' axis-angle rotation
				vec3 sampleDirection = vOutputDirection * cosTheta
					+ cross( axis, vOutputDirection ) * sin( theta )
					+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );

				return bilinearCubeUV( envMap, sampleDirection, mipInt );

			}

			void main() {

				vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );

				if ( all( equal( axis, vec3( 0.0 ) ) ) ) {

					axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );

				}

				axis = normalize( axis );

				gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
				gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );

				for ( int i = 1; i < n; i++ ) {

					if ( i >= samples ) {

						break;

					}

					float theta = dTheta * float( i );
					gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
					gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );

				}

			}
		`,blending:gn,depthTest:!1,depthWrite:!1})}function _C(){return new nn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Ny(),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:gn,depthTest:!1,depthWrite:!1})}function vC(){return new nn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ny(),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:gn,depthTest:!1,depthWrite:!1})}function Ny(){return`

		precision mediump float;
		precision mediump int;

		attribute float faceIndex;

		varying vec3 vOutputDirection;

		// RH coordinate system; PMREM face-indexing convention
		vec3 getDirection( vec2 uv, float face ) {

			uv = 2.0 * uv - 1.0;

			vec3 direction = vec3( uv, 1.0 );

			if ( face == 0.0 ) {

				direction = direction.zyx; // ( 1, v, u ) pos x

			} else if ( face == 1.0 ) {

				direction = direction.xzy;
				direction.xz *= -1.0; // ( -u, 1, -v ) pos y

			} else if ( face == 2.0 ) {

				direction.x *= -1.0; // ( -u, v, 1 ) pos z

			} else if ( face == 3.0 ) {

				direction = direction.zyx;
				direction.xz *= -1.0; // ( -1, v, -u ) neg x

			} else if ( face == 4.0 ) {

				direction = direction.xzy;
				direction.xy *= -1.0; // ( -u, -1, v ) neg y

			} else if ( face == 5.0 ) {

				direction.z *= -1.0; // ( u, v, -1 ) neg z

			}

			return direction;

		}

		void main() {

			vOutputDirection = getDirection( uv, faceIndex );
			gl_Position = vec4( position, 1.0 );

		}
	`}function u2(r){let e=new WeakMap,t=null;function i(o){if(o&&o.isTexture){const l=o.mapping,c=l===$r||l===mf,h=l===Yr||l===To;if(c||h){let u=e.get(o);const d=u!==void 0?u.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==d)return t===null&&(t=new Fy(r)),u=c?t.fromEquirectangular(o,u):t.fromCubemap(o,u),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),u.texture;if(u!==void 0)return u.texture;{const p=o.image;return c&&p&&p.height>0||h&&p&&n(p)?(t===null&&(t=new Fy(r)),u=c?t.fromEquirectangular(o):t.fromCubemap(o),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),o.addEventListener("dispose",s),u.texture):null}}}return o}function n(o){let l=0;const c=6;for(let h=0;h<c;h++)o[h]!==void 0&&l++;return l===c}function s(o){const l=o.target;l.removeEventListener("dispose",s);const c=e.get(l);c!==void 0&&(e.delete(l),c.dispose())}function a(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:i,dispose:a}}function d2(r){const e={};function t(i){if(e[i]!==void 0)return e[i];let n;switch(i){case"WEBGL_depth_texture":n=r.getExtension("WEBGL_depth_texture")||r.getExtension("MOZ_WEBGL_depth_texture")||r.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=r.getExtension("EXT_texture_filter_anisotropic")||r.getExtension("MOZ_EXT_texture_filter_anisotropic")||r.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=r.getExtension("WEBGL_compressed_texture_s3tc")||r.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||r.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=r.getExtension("WEBGL_compressed_texture_pvrtc")||r.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:n=r.getExtension(i)}return e[i]=n,n}return{has:function(i){return t(i)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(i){const n=t(i);return n===null&&ta("THREE.WebGLRenderer: "+i+" extension not supported."),n}}}function f2(r,e,t,i){const n={},s=new WeakMap;function a(u){const d=u.target;d.index!==null&&e.remove(d.index);for(const m in d.attributes)e.remove(d.attributes[m]);for(const m in d.morphAttributes){const A=d.morphAttributes[m];for(let g=0,y=A.length;g<y;g++)e.remove(A[g])}d.removeEventListener("dispose",a),delete n[d.id];const p=s.get(d);p&&(e.remove(p),s.delete(d)),i.releaseStatesOfGeometry(d),d.isInstancedBufferGeometry===!0&&delete d._maxInstanceCount,t.memory.geometries--}function o(u,d){return n[d.id]===!0||(d.addEventListener("dispose",a),n[d.id]=!0,t.memory.geometries++),d}function l(u){const d=u.attributes;for(const m in d)e.update(d[m],r.ARRAY_BUFFER);const p=u.morphAttributes;for(const m in p){const A=p[m];for(let g=0,y=A.length;g<y;g++)e.update(A[g],r.ARRAY_BUFFER)}}function c(u){const d=[],p=u.index,m=u.attributes.position;let A=0;if(p!==null){const v=p.array;A=p.version;for(let _=0,b=v.length;_<b;_+=3){const T=v[_+0],E=v[_+1],M=v[_+2];d.push(T,E,E,M,M,T)}}else if(m!==void 0){const v=m.array;A=m.version;for(let _=0,b=v.length/3-1;_<b;_+=3){const T=_+0,E=_+1,M=_+2;d.push(T,E,E,M,M,T)}}else return;const g=new(zw(d)?My:Xf)(d,1);g.version=A;const y=s.get(u);y&&e.remove(y),s.set(u,g)}function h(u){const d=s.get(u);if(d){const p=u.index;p!==null&&d.version<p.version&&c(u)}else c(u);return s.get(u)}return{get:o,update:l,getWireframeAttribute:h}}function p2(r,e,t){let i;function n(d){i=d}let s,a;function o(d){s=d.type,a=d.bytesPerElement}function l(d,p){r.drawElements(i,p,s,d*a),t.update(p,i,1)}function c(d,p,m){m!==0&&(r.drawElementsInstanced(i,p,s,d*a,m),t.update(p,i,m))}function h(d,p,m){if(m===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,p,0,s,d,0,m);let g=0;for(let y=0;y<m;y++)g+=p[y];t.update(g,i,1)}function u(d,p,m,A){if(m===0)return;const g=e.get("WEBGL_multi_draw");if(g===null)for(let y=0;y<d.length;y++)c(d[y]/a,p[y],A[y]);else{g.multiDrawElementsInstancedWEBGL(i,p,0,s,d,0,A,0,m);let y=0;for(let v=0;v<m;v++)y+=p[v];for(let v=0;v<A.length;v++)t.update(y,i,A[v])}}this.setMode=n,this.setIndex=o,this.render=l,this.renderInstances=c,this.renderMultiDraw=h,this.renderMultiDrawInstances=u}function m2(r){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function i(s,a,o){switch(t.calls++,a){case r.TRIANGLES:t.triangles+=o*(s/3);break;case r.LINES:t.lines+=o*(s/2);break;case r.LINE_STRIP:t.lines+=o*(s-1);break;case r.LINE_LOOP:t.lines+=o*s;break;case r.POINTS:t.points+=o*s;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",a);break}}function n(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:n,update:i}}function g2(r,e,t){const i=new WeakMap,n=new et;function s(a,o,l){const c=a.morphTargetInfluences,h=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=h!==void 0?h.length:0;let d=i.get(o);if(d===void 0||d.count!==u){let C=function(){M.dispose(),i.delete(o),o.removeEventListener("dispose",C)};d!==void 0&&d.texture.dispose();const p=o.morphAttributes.position!==void 0,m=o.morphAttributes.normal!==void 0,A=o.morphAttributes.color!==void 0,g=o.morphAttributes.position||[],y=o.morphAttributes.normal||[],v=o.morphAttributes.color||[];let _=0;p===!0&&(_=1),m===!0&&(_=2),A===!0&&(_=3);let b=o.attributes.position.count*_,T=1;b>e.maxTextureSize&&(T=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const E=new Float32Array(b*T*4*u),M=new Uf(E,b,T,u);M.type=Ut,M.needsUpdate=!0;const I=_*4;for(let x=0;x<u;x++){const D=g[x],U=y[x],O=v[x],N=b*T*4*x;for(let H=0;H<D.count;H++){const V=H*I;p===!0&&(n.fromBufferAttribute(D,H),E[N+V+0]=n.x,E[N+V+1]=n.y,E[N+V+2]=n.z,E[N+V+3]=0),m===!0&&(n.fromBufferAttribute(U,H),E[N+V+4]=n.x,E[N+V+5]=n.y,E[N+V+6]=n.z,E[N+V+7]=0),A===!0&&(n.fromBufferAttribute(O,H),E[N+V+8]=n.x,E[N+V+9]=n.y,E[N+V+10]=n.z,E[N+V+11]=O.itemSize===4?n.w:1)}}d={count:u,texture:M,size:new K(b,T)},i.set(o,d),o.addEventListener("dispose",C)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)l.getUniforms().setValue(r,"morphTexture",a.morphTexture,t);else{let p=0;for(let A=0;A<c.length;A++)p+=c[A];const m=o.morphTargetsRelative?1:1-p;l.getUniforms().setValue(r,"morphTargetBaseInfluence",m),l.getUniforms().setValue(r,"morphTargetInfluences",c)}l.getUniforms().setValue(r,"morphTargetsTexture",d.texture,t),l.getUniforms().setValue(r,"morphTargetsTextureSize",d.size)}return{update:s}}function A2(r,e,t,i){let n=new WeakMap;function s(l){const c=i.render.frame,h=l.geometry,u=e.get(l,h);if(n.get(u)!==c&&(e.update(u),n.set(u,c)),l.isInstancedMesh&&(l.hasEventListener("dispose",o)===!1&&l.addEventListener("dispose",o),n.get(l)!==c&&(t.update(l.instanceMatrix,r.ARRAY_BUFFER),l.instanceColor!==null&&t.update(l.instanceColor,r.ARRAY_BUFFER),n.set(l,c))),l.isSkinnedMesh){const d=l.skeleton;n.get(d)!==c&&(d.update(),n.set(d,c))}return u}function a(){n=new WeakMap}function o(l){const c=l.target;c.removeEventListener("dispose",o),t.remove(c.instanceMatrix),c.instanceColor!==null&&t.remove(c.instanceColor)}return{update:s,dispose:a}}class ap extends kt{constructor(e,t,i,n,s,a,o,l,c,h=Do){if(h!==Do&&h!==Zl)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");i===void 0&&h===Do&&(i=tr),i===void 0&&h===Zl&&(i=Po),super(null,n,s,a,o,l,h,i,c),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=o!==void 0?o:mi,this.minFilter=l!==void 0?l:mi,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}const bC=new kt,wC=new ap(1,1),CC=new Uf,xC=new Ff,SC=new wc,EC=[],MC=[],TC=new Float32Array(16),IC=new Float32Array(9),PC=new Float32Array(4);function Sc(r,e,t){const i=r[0];if(i<=0||i>0)return r;const n=e*t;let s=EC[n];if(s===void 0&&(s=new Float32Array(n),EC[n]=s),e!==0){i.toArray(s,0);for(let a=1,o=0;a!==e;++a)o+=t,r[a].toArray(s,o)}return s}function An(r,e){if(r.length!==e.length)return!1;for(let t=0,i=r.length;t<i;t++)if(r[t]!==e[t])return!1;return!0}function yn(r,e){for(let t=0,i=e.length;t<i;t++)r[t]=e[t]}function op(r,e){let t=MC[e];t===void 0&&(t=new Int32Array(e),MC[e]=t);for(let i=0;i!==e;++i)t[i]=r.allocateTextureUnit();return t}function y2(r,e){const t=this.cache;t[0]!==e&&(r.uniform1f(this.addr,e),t[0]=e)}function _2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(An(t,e))return;r.uniform2fv(this.addr,e),yn(t,e)}}function v2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(r.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(An(t,e))return;r.uniform3fv(this.addr,e),yn(t,e)}}function b2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(An(t,e))return;r.uniform4fv(this.addr,e),yn(t,e)}}function w2(r,e){const t=this.cache,i=e.elements;if(i===void 0){if(An(t,e))return;r.uniformMatrix2fv(this.addr,!1,e),yn(t,e)}else{if(An(t,i))return;PC.set(i),r.uniformMatrix2fv(this.addr,!1,PC),yn(t,i)}}function C2(r,e){const t=this.cache,i=e.elements;if(i===void 0){if(An(t,e))return;r.uniformMatrix3fv(this.addr,!1,e),yn(t,e)}else{if(An(t,i))return;IC.set(i),r.uniformMatrix3fv(this.addr,!1,IC),yn(t,i)}}function x2(r,e){const t=this.cache,i=e.elements;if(i===void 0){if(An(t,e))return;r.uniformMatrix4fv(this.addr,!1,e),yn(t,e)}else{if(An(t,i))return;TC.set(i),r.uniformMatrix4fv(this.addr,!1,TC),yn(t,i)}}function S2(r,e){const t=this.cache;t[0]!==e&&(r.uniform1i(this.addr,e),t[0]=e)}function E2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(An(t,e))return;r.uniform2iv(this.addr,e),yn(t,e)}}function M2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(An(t,e))return;r.uniform3iv(this.addr,e),yn(t,e)}}function T2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(An(t,e))return;r.uniform4iv(this.addr,e),yn(t,e)}}function I2(r,e){const t=this.cache;t[0]!==e&&(r.uniform1ui(this.addr,e),t[0]=e)}function P2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(An(t,e))return;r.uniform2uiv(this.addr,e),yn(t,e)}}function D2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(An(t,e))return;r.uniform3uiv(this.addr,e),yn(t,e)}}function R2(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(An(t,e))return;r.uniform4uiv(this.addr,e),yn(t,e)}}function B2(r,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(r.uniform1i(this.addr,n),i[0]=n);let s;this.type===r.SAMPLER_2D_SHADOW?(wC.compareFunction=Nw,s=wC):s=bC,t.setTexture2D(e||s,n)}function L2(r,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(r.uniform1i(this.addr,n),i[0]=n),t.setTexture3D(e||xC,n)}function O2(r,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(r.uniform1i(this.addr,n),i[0]=n),t.setTextureCube(e||SC,n)}function U2(r,e,t){const i=this.cache,n=t.allocateTextureUnit();i[0]!==n&&(r.uniform1i(this.addr,n),i[0]=n),t.setTexture2DArray(e||CC,n)}function F2(r){switch(r){case 5126:return y2;case 35664:return _2;case 35665:return v2;case 35666:return b2;case 35674:return w2;case 35675:return C2;case 35676:return x2;case 5124:case 35670:return S2;case 35667:case 35671:return E2;case 35668:case 35672:return M2;case 35669:case 35673:return T2;case 5125:return I2;case 36294:return P2;case 36295:return D2;case 36296:return R2;case 35678:case 36198:case 36298:case 36306:case 35682:return B2;case 35679:case 36299:case 36307:return L2;case 35680:case 36300:case 36308:case 36293:return O2;case 36289:case 36303:case 36311:case 36292:return U2}}function N2(r,e){r.uniform1fv(this.addr,e)}function k2(r,e){const t=Sc(e,this.size,2);r.uniform2fv(this.addr,t)}function G2(r,e){const t=Sc(e,this.size,3);r.uniform3fv(this.addr,t)}function z2(r,e){const t=Sc(e,this.size,4);r.uniform4fv(this.addr,t)}function V2(r,e){const t=Sc(e,this.size,4);r.uniformMatrix2fv(this.addr,!1,t)}function H2(r,e){const t=Sc(e,this.size,9);r.uniformMatrix3fv(this.addr,!1,t)}function Q2(r,e){const t=Sc(e,this.size,16);r.uniformMatrix4fv(this.addr,!1,t)}function j2(r,e){r.uniform1iv(this.addr,e)}function W2(r,e){r.uniform2iv(this.addr,e)}function q2(r,e){r.uniform3iv(this.addr,e)}function X2(r,e){r.uniform4iv(this.addr,e)}function Y2(r,e){r.uniform1uiv(this.addr,e)}function $2(r,e){r.uniform2uiv(this.addr,e)}function K2(r,e){r.uniform3uiv(this.addr,e)}function J2(r,e){r.uniform4uiv(this.addr,e)}function Z2(r,e,t){const i=this.cache,n=e.length,s=op(t,n);An(i,s)||(r.uniform1iv(this.addr,s),yn(i,s));for(let a=0;a!==n;++a)t.setTexture2D(e[a]||bC,s[a])}function eL(r,e,t){const i=this.cache,n=e.length,s=op(t,n);An(i,s)||(r.uniform1iv(this.addr,s),yn(i,s));for(let a=0;a!==n;++a)t.setTexture3D(e[a]||xC,s[a])}function tL(r,e,t){const i=this.cache,n=e.length,s=op(t,n);An(i,s)||(r.uniform1iv(this.addr,s),yn(i,s));for(let a=0;a!==n;++a)t.setTextureCube(e[a]||SC,s[a])}function iL(r,e,t){const i=this.cache,n=e.length,s=op(t,n);An(i,s)||(r.uniform1iv(this.addr,s),yn(i,s));for(let a=0;a!==n;++a)t.setTexture2DArray(e[a]||CC,s[a])}function nL(r){switch(r){case 5126:return N2;case 35664:return k2;case 35665:return G2;case 35666:return z2;case 35674:return V2;case 35675:return H2;case 35676:return Q2;case 5124:case 35670:return j2;case 35667:case 35671:return W2;case 35668:case 35672:return q2;case 35669:case 35673:return X2;case 5125:return Y2;case 36294:return $2;case 36295:return K2;case 36296:return J2;case 35678:case 36198:case 36298:case 36306:case 35682:return Z2;case 35679:case 36299:case 36307:return eL;case 35680:case 36300:case 36308:case 36293:return tL;case 36289:case 36303:case 36311:case 36292:return iL}}class sL{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.setValue=F2(t.type)}}class rL{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=nL(t.type)}}class aL{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,i){const n=this.seq;for(let s=0,a=n.length;s!==a;++s){const o=n[s];o.setValue(e,t[o.id],i)}}}const ky=/(\w+)(\])?(\[|\.)?/g;function DC(r,e){r.seq.push(e),r.map[e.id]=e}function oL(r,e,t){const i=r.name,n=i.length;for(ky.lastIndex=0;;){const s=ky.exec(i),a=ky.lastIndex;let o=s[1];const l=s[2]==="]",c=s[3];if(l&&(o=o|0),c===void 0||c==="["&&a+2===n){DC(t,c===void 0?new sL(o,r,e):new rL(o,r,e));break}else{let u=t.map[o];u===void 0&&(u=new aL(o),DC(t,u)),t=u}}}class lp{constructor(e,t){this.seq=[],this.map={};const i=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let n=0;n<i;++n){const s=e.getActiveUniform(t,n),a=e.getUniformLocation(t,s.name);oL(s,a,this)}}setValue(e,t,i,n){const s=this.map[t];s!==void 0&&s.setValue(e,i,n)}setOptional(e,t,i){const n=t[i];n!==void 0&&this.setValue(e,i,n)}static upload(e,t,i,n){for(let s=0,a=t.length;s!==a;++s){const o=t[s],l=i[o.id];l.needsUpdate!==!1&&o.setValue(e,l.value,n)}}static seqWithValue(e,t){const i=[];for(let n=0,s=e.length;n!==s;++n){const a=e[n];a.id in t&&i.push(a)}return i}}function RC(r,e,t){const i=r.createShader(e);return r.shaderSource(i,t),r.compileShader(i),i}const lL=37297;let cL=0;function hL(r,e){const t=r.split(`
`),i=[],n=Math.max(e-6,0),s=Math.min(e+6,t.length);for(let a=n;a<s;a++){const o=a+1;i.push(`${o===e?">":" "} ${o}: ${t[a]}`)}return i.join(`
`)}function uL(r){const e=Nt.getPrimaries(Nt.workingColorSpace),t=r===ai||r===Fs?null:Nt.getPrimaries(r);let i;switch(e===t||!t?i="":e===Rf&&t===Df?i="LinearDisplayP3ToLinearSRGB":e===Df&&t===Rf&&(i="LinearSRGBToLinearDisplayP3"),r){case ai:return["",""];case Bt:case su:return[i,"LinearTransferOETF"];case Ct:case nu:return[i,"sRGBTransferOETF"];case Fs:return["","LinearToRGBM16"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",r),[i,"LinearTransferOETF"]}}function BC(r,e,t){const i=r.getShaderParameter(e,r.COMPILE_STATUS),n=r.getShaderInfoLog(e).trim();if(i&&n==="")return"";const s=/ERROR: 0:(\d+)/.exec(n);if(s){const a=parseInt(s[1]);return t.toUpperCase()+`

`+n+`

`+hL(r.getShaderSource(e),a)}else return n}function dL(r,e){let t;switch(e){case Bt:t="";break;case Ct:t="sRGBToLinear";break;case Fs:t="RGBM16ToLinear";break;default:console.warn("THREE.WebGLProgram: Unsupported color space:",e),t="";break}return`vec4 ${r}( vec4 value ) { return ${t} ( value ); }`}function fL(r,e){const t=uL(e);return`vec4 ${r}( vec4 value ) { return ${t[0]}( ${t[1]}( value ) ); }`}function pL(r,e){let t;switch(e){case ww:t="Linear";break;case Cw:t="Reinhard";break;case xw:t="Cineon";break;case BA:t="ACESFilmic";break;case Ew:t="AgX";break;case YP:t="Neutral";break;case Sw:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+r+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const cp=new S;function mL(){Nt.getLuminanceCoefficients(cp);const r=cp.x.toFixed(4),e=cp.y.toFixed(4),t=cp.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",`	const vec3 weights = vec3( ${r}, ${e}, ${t} );`,"	return dot( weights, rgb );","}"].join(`
`)}function gL(r){return[r.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",r.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(mu).join(`
`)}function AL(r){const e=[];for(const t in r){const i=r[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(`
`)}function yL(r,e){const t={},i=r.getProgramParameter(e,r.ACTIVE_ATTRIBUTES);for(let n=0;n<i;n++){const s=r.getActiveAttrib(e,n),a=s.name;let o=1;s.type===r.FLOAT_MAT2&&(o=2),s.type===r.FLOAT_MAT3&&(o=3),s.type===r.FLOAT_MAT4&&(o=4),t[a]={type:s.type,location:r.getAttribLocation(e,a),locationSize:o}}return t}function mu(r){return r!==""}function LC(r,e){const t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return r.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function OC(r,e){return r.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const _L=/^[ \t]*#include +<([\w\d./]+)>/gm;function Gy(r){return r.replace(_L,bL)}const vL=new Map;function bL(r,e){let t=lt[e];if(t===void 0){const i=vL.get(e);if(i!==void 0)t=lt[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return Gy(t)}const wL=/#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 UC(r){return r.replace(wL,CL)}function CL(r,e,t,i){let n="";for(let s=parseInt(e);s<parseInt(t);s++)n+=i.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return n}function FC(r){let e=`precision ${r.precision} float;
	precision ${r.precision} int;
	precision ${r.precision} sampler2D;
	precision ${r.precision} samplerCube;
	precision ${r.precision} sampler3D;
	precision ${r.precision} sampler2DArray;
	precision ${r.precision} sampler2DShadow;
	precision ${r.precision} samplerCubeShadow;
	precision ${r.precision} sampler2DArrayShadow;
	precision ${r.precision} isampler2D;
	precision ${r.precision} isampler3D;
	precision ${r.precision} isamplerCube;
	precision ${r.precision} isampler2DArray;
	precision ${r.precision} usampler2D;
	precision ${r.precision} usampler3D;
	precision ${r.precision} usamplerCube;
	precision ${r.precision} usampler2DArray;
	`;return r.precision==="highp"?e+=`
#define HIGH_PRECISION`:r.precision==="mediump"?e+=`
#define MEDIUM_PRECISION`:r.precision==="lowp"&&(e+=`
#define LOW_PRECISION`),e}function xL(r){let e="SHADOWMAP_TYPE_BASIC";return r.shadowMapType===xA?e="SHADOWMAP_TYPE_PCF":r.shadowMapType===WP?e="SHADOWMAP_TYPE_PCF_SOFT":r.shadowMapType===qr&&(e="SHADOWMAP_TYPE_VSM"),e}function SL(r){let e="ENVMAP_TYPE_CUBE";if(r.envMap)switch(r.envMapMode){case Yr:case To:e="ENVMAP_TYPE_CUBE";break;case Kl:e="ENVMAP_TYPE_CUBE_UV";break}return e}function EL(r){let e="ENVMAP_MODE_REFLECTION";return r.envMap&&r.envMapMode===To&&(e="ENVMAP_MODE_REFRACTION"),e}function ML(r){let e="ENVMAP_BLENDING_NONE";if(r.envMap)switch(r.combine){case $l:e="ENVMAP_BLENDING_MULTIPLY";break;case qP:e="ENVMAP_BLENDING_MIX";break;case XP:e="ENVMAP_BLENDING_ADD";break}return e}function TL(r){const e=r.envMapCubeUVHeight;if(e===null)return null;const t=Math.log2(e)-2,i=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:i,maxMip:t}}function IL(r,e,t,i){const n=r.getContext(),s=t.defines;let a=t.vertexShader,o=t.fragmentShader;const l=xL(t),c=SL(t),h=EL(t),u=ML(t),d=TL(t),p=gL(t),m=AL(s),A=n.createProgram();let g,y,v=t.glslVersion?"#version "+t.glslVersion+`
`:"";t.isRawShaderMaterial?(g=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m].filter(mu).join(`
`),g.length>0&&(g+=`
`),y=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m].filter(mu).join(`
`),y.length>0&&(y+=`
`)):(g=[FC(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"","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(mu).join(`
`),y=[FC(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+h:"",t.envMap?"#define "+u:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Xr?"#define TONE_MAPPING":"",t.toneMapping!==Xr?lt.tonemapping_pars_fragment:"",t.toneMapping!==Xr?pL("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",lt.colorspace_pars_fragment,fL("linearToOutputTexel",t.outputColorSpace),mL(),t.transmissionSamplerMapEncoding?dL("transmissionSamplerMapTexelToLinear",t.transmissionSamplerMapEncoding):"",t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
`].filter(mu).join(`
`)),a=Gy(a),a=LC(a,t),a=OC(a,t),o=Gy(o),o=LC(o,t),o=OC(o,t),a=UC(a),o=UC(o),t.isRawShaderMaterial!==!0&&(v=`#version 300 es
`,g=[p,"#define attribute in","#define varying out","#define texture2D texture"].join(`
`)+`
`+g,y=["#define varying in",t.glslVersion===cy?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===cy?"":"#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","#define WebGL2Context 1"].join(`
`)+`
`+y);const _=v+g+a,b=v+y+o,T=RC(n,n.VERTEX_SHADER,_),E=RC(n,n.FRAGMENT_SHADER,b);n.attachShader(A,T),n.attachShader(A,E),t.index0AttributeName!==void 0?n.bindAttribLocation(A,0,t.index0AttributeName):t.morphTargets===!0&&n.bindAttribLocation(A,0,"position"),n.linkProgram(A);function M(D){if(r.debug.checkShaderErrors){const U=n.getProgramInfoLog(A).trim(),O=n.getShaderInfoLog(T).trim(),N=n.getShaderInfoLog(E).trim();let H=!0,V=!0;if(n.getProgramParameter(A,n.LINK_STATUS)===!1)if(H=!1,typeof r.debug.onShaderError=="function")r.debug.onShaderError(n,A,T,E);else{const X=BC(n,T,"vertex"),W=BC(n,E,"fragment");console.error("THREE.WebGLProgram: Shader Error "+n.getError()+" - VALIDATE_STATUS "+n.getProgramParameter(A,n.VALIDATE_STATUS)+`

Material Name: `+D.name+`
Material Type: `+D.type+`

Program Info Log: `+U+`
`+X+`
`+W)}else U!==""?console.warn("THREE.WebGLProgram: Program Info Log:",U):(O===""||N==="")&&(V=!1);V&&(D.diagnostics={runnable:H,programLog:U,vertexShader:{log:O,prefix:g},fragmentShader:{log:N,prefix:y}})}n.deleteShader(T),n.deleteShader(E),I=new lp(n,A),C=yL(n,A)}let I;this.getUniforms=function(){return I===void 0&&M(this),I};let C;this.getAttributes=function(){return C===void 0&&M(this),C};let x=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return x===!1&&(x=n.getProgramParameter(A,lL)),x},this.destroy=function(){i.releaseStatesOfProgram(this),n.deleteProgram(A),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=cL++,this.cacheKey=e,this.usedTimes=1,this.program=A,this.vertexShader=T,this.fragmentShader=E,this}let PL=0;class DL{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,n=this._getShaderStage(t),s=this._getShaderStage(i),a=this._getShaderCacheForMaterial(e);return a.has(n)===!1&&(a.add(n),n.usedTimes++),a.has(s)===!1&&(a.add(s),s.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new RL(e),t.set(e,i)),i}}class RL{constructor(e){this.id=PL++,this.code=e,this.usedTimes=0}}function BL(r,e,t,i,n,s,a){const o=new Qf,l=new DL,c=new Set,h=[],u=n.logarithmicDepthBuffer,d=n.vertexTextures;let p=n.precision;const m={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function A(C){return c.add(C),C===0?"uv":`uv${C}`}function g(C,x,D,U,O){const N=U.fog,H=O.geometry,V=C.isMeshStandardMaterial?U.environment:null,X=(C.isMeshStandardMaterial?t:e).get(C.envMap||V),W=X&&X.mapping===Kl?X.image.height:null,ce=m[C.type];C.precision!==null&&(p=n.getMaxPrecision(C.precision),p!==C.precision&&console.warn("THREE.WebGLProgram.getParameters:",C.precision,"not supported, using",p,"instead."));const ue=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,we=ue!==void 0?ue.length:0;let Pe=0;H.morphAttributes.position!==void 0&&(Pe=1),H.morphAttributes.normal!==void 0&&(Pe=2),H.morphAttributes.color!==void 0&&(Pe=3);let Qe,ie,oe,me;if(ce){const bs=Di[ce];Qe=bs.vertexShader,ie=bs.fragmentShader}else Qe=C.vertexShader,ie=C.fragmentShader,l.update(C),oe=l.getVertexShaderID(C),me=l.getFragmentShaderID(C);const Ce=r.getRenderTarget(),Xe=r.userData&&r.userData.transmissionRenderTarget,dt=O.isInstancedMesh===!0,Ke=O.isBatchedMesh===!0,gt=!!C.map,F=!!C.matcap,xe=!!X,be=!!C.aoMap,Ne=!!C.lightMap,ge=!!C.bumpMap,ut=!!C.normalMap,ke=!!C.displacementMap,Ve=!!C.emissiveMap,z=!!C.metalnessMap,B=!!C.roughnessMap,ne=C.anisotropy>0,de=C.clearcoat>0,ye=C.dispersion>0,pe=C.iridescence>0,nt=C.sheen>0,Le=C.transmission>0,Ye=ne&&!!C.anisotropyMap,yt=de&&!!C.clearcoatMap,Me=de&&!!C.clearcoatNormalMap,je=de&&!!C.clearcoatRoughnessMap,Wt=pe&&!!C.iridescenceMap,st=pe&&!!C.iridescenceThicknessMap,Ge=nt&&!!C.sheenColorMap,wt=nt&&!!C.sheenRoughnessMap,_t=!!C.specularMap,Ht=!!C.specularColorMap,j=!!C.specularIntensityMap,Ie=Le&&!!C.transmissionMap,$=Le&&!!C.thicknessMap,Ae=!!C.gradientMap,Be=!!C.alphaMap,pt=C.alphaTest>0,Kt=!!C.alphaHash,Ji=!!C.extensions;let Nn=Xr;C.toneMapped&&(Ce===null||Ce.isXRRenderTarget===!0)&&(Nn=r.toneMapping);const Jt={shaderID:ce,shaderType:C.type,shaderName:C.name,vertexShader:Qe,fragmentShader:ie,defines:C.defines,customVertexShaderID:oe,customFragmentShaderID:me,isRawShaderMaterial:C.isRawShaderMaterial===!0,glslVersion:C.glslVersion,precision:p,batching:Ke,batchingColor:Ke&&O._colorsTexture!==null,instancing:dt,instancingColor:dt&&O.instanceColor!==null,instancingMorph:dt&&O.morphTexture!==null,supportsVertexTextures:d,outputColorSpace:Ce===null?r.outputColorSpace:Ce.isXRRenderTarget===!0||Ce.texture.colorSpace&&Ce.texture.colorSpace!==Ct?Ce.texture.colorSpace:Bt,alphaToCoverage:!!C.alphaToCoverage,map:gt,matcap:F,envMap:xe,envMapMode:xe&&X.mapping,envMapCubeUVHeight:W,aoMap:be,lightMap:Ne,bumpMap:ge,normalMap:ut,displacementMap:d&&ke,emissiveMap:Ve,normalMapObjectSpace:ut&&C.normalMapType===Fw,normalMapTangentSpace:ut&&C.normalMapType===Us,metalnessMap:z,roughnessMap:B,anisotropy:ne,anisotropyMap:Ye,clearcoat:de,clearcoatMap:yt,clearcoatNormalMap:Me,clearcoatRoughnessMap:je,dispersion:ye,iridescence:pe,iridescenceMap:Wt,iridescenceThicknessMap:st,sheen:nt,sheenColorMap:Ge,sheenRoughnessMap:wt,specularMap:_t,specularColorMap:Ht,specularIntensityMap:j,transmission:Le,transmissionMap:Ie,thicknessMap:$,transmissionSamplerMapEncoding:Xe&&Xe.texture.colorSpace||Bt,gradientMap:Ae,opaque:C.transparent===!1&&C.blending===Sr&&C.alphaToCoverage===!1&&!(C.transmission>0),alphaMap:Be,alphaTest:pt,alphaHash:Kt,combine:C.combine,mapUv:gt&&A(C.map.channel),aoMapUv:be&&A(C.aoMap.channel),lightMapUv:Ne&&A(C.lightMap.channel),bumpMapUv:ge&&A(C.bumpMap.channel),normalMapUv:ut&&A(C.normalMap.channel),displacementMapUv:ke&&A(C.displacementMap.channel),emissiveMapUv:Ve&&A(C.emissiveMap.channel),metalnessMapUv:z&&A(C.metalnessMap.channel),roughnessMapUv:B&&A(C.roughnessMap.channel),anisotropyMapUv:Ye&&A(C.anisotropyMap.channel),clearcoatMapUv:yt&&A(C.clearcoatMap.channel),clearcoatNormalMapUv:Me&&A(C.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:je&&A(C.clearcoatRoughnessMap.channel),iridescenceMapUv:Wt&&A(C.iridescenceMap.channel),iridescenceThicknessMapUv:st&&A(C.iridescenceThicknessMap.channel),sheenColorMapUv:Ge&&A(C.sheenColorMap.channel),sheenRoughnessMapUv:wt&&A(C.sheenRoughnessMap.channel),specularMapUv:_t&&A(C.specularMap.channel),specularColorMapUv:Ht&&A(C.specularColorMap.channel),specularIntensityMapUv:j&&A(C.specularIntensityMap.channel),transmissionMapUv:Ie&&A(C.transmissionMap.channel),thicknessMapUv:$&&A(C.thicknessMap.channel),alphaMapUv:Be&&A(C.alphaMap.channel),vertexTangents:!!H.attributes.tangent&&(ut||ne||H.userData.__forceUseTangent),vertexColors:C.vertexColors,vertexAlphas:C.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,pointsUvs:O.isPoints===!0&&!!H.attributes.uv&&(gt||Be),fog:!!N,useFog:C.fog===!0,fogExp2:!!N&&N.isFogExp2,flatShading:C.flatShading===!0,sizeAttenuation:C.sizeAttenuation===!0,logarithmicDepthBuffer:u,skinning:O.isSkinnedMesh===!0,morphTargets:H.morphAttributes.position!==void 0,morphNormals:H.morphAttributes.normal!==void 0,morphColors:H.morphAttributes.color!==void 0,morphTargetsCount:we,morphTextureStride:Pe,numDirLights:x.directional.length,numPointLights:x.point.length,numSpotLights:x.spot.length,numSpotLightMaps:x.spotLightMap.length,numRectAreaLights:x.rectArea.length,numHemiLights:x.hemi.length,numDirLightShadows:x.directionalShadowMap.length,numPointLightShadows:x.pointShadowMap.length,numSpotLightShadows:x.spotShadowMap.length,numSpotLightShadowsWithMaps:x.numSpotLightShadowsWithMaps,numLightProbes:x.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:C.dithering,shadowMapEnabled:r.shadowMap.enabled&&D.length>0,shadowMapType:r.shadowMap.type,toneMapping:Nn,decodeVideoTexture:gt&&C.map.isVideoTexture===!0&&Nt.getTransfer(C.map.colorSpace)===Ci,premultipliedAlpha:C.premultipliedAlpha,doubleSided:C.side===Zi,flipSided:C.side===In,useDepthPacking:C.depthPacking>=0,depthPacking:C.depthPacking||0,index0AttributeName:C.index0AttributeName,extensionClipCullDistance:Ji&&C.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Ji&&C.extensions.multiDraw===!0||Ke)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:C.customProgramCacheKey()};return Jt.vertexUv1s=c.has(1),Jt.vertexUv2s=c.has(2),Jt.vertexUv3s=c.has(3),c.clear(),Jt}function y(C){const x=[];if(C.shaderID?x.push(C.shaderID):(x.push(C.customVertexShaderID),x.push(C.customFragmentShaderID)),C.defines!==void 0)for(const D in C.defines)x.push(D),x.push(C.defines[D]);return C.isRawShaderMaterial===!1&&(v(x,C),_(x,C),x.push(r.outputColorSpace)),x.push(C.customProgramCacheKey),x.join()}function v(C,x){C.push(x.precision),C.push(x.outputColorSpace),C.push(x.envMapMode),C.push(x.envMapCubeUVHeight),C.push(x.mapUv),C.push(x.alphaMapUv),C.push(x.lightMapUv),C.push(x.aoMapUv),C.push(x.bumpMapUv),C.push(x.normalMapUv),C.push(x.displacementMapUv),C.push(x.emissiveMapUv),C.push(x.metalnessMapUv),C.push(x.roughnessMapUv),C.push(x.anisotropyMapUv),C.push(x.clearcoatMapUv),C.push(x.clearcoatNormalMapUv),C.push(x.clearcoatRoughnessMapUv),C.push(x.iridescenceMapUv),C.push(x.iridescenceThicknessMapUv),C.push(x.sheenColorMapUv),C.push(x.sheenRoughnessMapUv),C.push(x.specularMapUv),C.push(x.specularColorMapUv),C.push(x.specularIntensityMapUv),C.push(x.transmissionMapUv),C.push(x.thicknessMapUv),C.push(x.combine),C.push(x.fogExp2),C.push(x.sizeAttenuation),C.push(x.morphTargetsCount),C.push(x.morphAttributeCount),C.push(x.numDirLights),C.push(x.numPointLights),C.push(x.numSpotLights),C.push(x.numSpotLightMaps),C.push(x.numHemiLights),C.push(x.numRectAreaLights),C.push(x.numDirLightShadows),C.push(x.numPointLightShadows),C.push(x.numSpotLightShadows),C.push(x.numSpotLightShadowsWithMaps),C.push(x.numLightProbes),C.push(x.shadowMapType),C.push(x.toneMapping),C.push(x.numClippingPlanes),C.push(x.numClipIntersection),C.push(x.depthPacking)}function _(C,x){o.disableAll(),x.supportsVertexTextures&&o.enable(0),x.instancing&&o.enable(1),x.instancingColor&&o.enable(2),x.instancingMorph&&o.enable(3),x.matcap&&o.enable(4),x.envMap&&o.enable(5),x.normalMapObjectSpace&&o.enable(6),x.normalMapTangentSpace&&o.enable(7),x.clearcoat&&o.enable(8),x.iridescence&&o.enable(9),x.alphaTest&&o.enable(10),x.vertexColors&&o.enable(11),x.vertexAlphas&&o.enable(12),x.vertexUv1s&&o.enable(13),x.vertexUv2s&&o.enable(14),x.vertexUv3s&&o.enable(15),x.vertexTangents&&o.enable(16),x.anisotropy&&o.enable(17),x.alphaHash&&o.enable(18),x.batching&&o.enable(19),x.dispersion&&o.enable(20),x.batchingColor&&o.enable(21),C.push(o.mask),o.disableAll(),x.fog&&o.enable(0),x.useFog&&o.enable(1),x.flatShading&&o.enable(2),x.logarithmicDepthBuffer&&o.enable(3),x.skinning&&o.enable(4),x.morphTargets&&o.enable(5),x.morphNormals&&o.enable(6),x.morphColors&&o.enable(7),x.premultipliedAlpha&&o.enable(8),x.shadowMapEnabled&&o.enable(9),x.doubleSided&&o.enable(10),x.flipSided&&o.enable(11),x.useDepthPacking&&o.enable(12),x.dithering&&o.enable(13),x.transmission&&o.enable(14),x.sheen&&o.enable(15),x.opaque&&o.enable(16),x.pointsUvs&&o.enable(17),x.decodeVideoTexture&&o.enable(18),x.alphaToCoverage&&o.enable(19),C.push(o.mask)}function b(C){const x=m[C.type];let D;if(x){const U=Di[x];D=ko.clone(U.uniforms)}else D=C.uniforms;return D}function T(C,x){let D;for(let U=0,O=h.length;U<O;U++){const N=h[U];if(N.cacheKey===x){D=N,++D.usedTimes;break}}return D===void 0&&(D=new IL(r,x,C,s),h.push(D)),D}function E(C){if(--C.usedTimes===0){const x=h.indexOf(C);h[x]=h[h.length-1],h.pop(),C.destroy()}}function M(C){l.remove(C)}function I(){l.dispose()}return{getParameters:g,getProgramCacheKey:y,getUniforms:b,acquireProgram:T,releaseProgram:E,releaseShaderCache:M,programs:h,dispose:I}}function LL(){let r=new WeakMap;function e(a){return r.has(a)}function t(a){let o=r.get(a);return o===void 0&&(o={},r.set(a,o)),o}function i(a){r.delete(a)}function n(a,o,l){r.get(a)[o]=l}function s(){r=new WeakMap}return{has:e,get:t,remove:i,update:n,dispose:s}}function OL(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.material.id!==e.material.id?r.material.id-e.material.id:r.z!==e.z?r.z-e.z:r.id-e.id}function NC(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?e.z-r.z:r.id-e.id}function kC(){const r=[];let e=0;const t=[],i=[],n=[];function s(){e=0,t.length=0,i.length=0,n.length=0}function a(u,d,p,m,A,g){let y=r[e];return y===void 0?(y={id:u.id,object:u,geometry:d,material:p,groupOrder:m,renderOrder:u.renderOrder,z:A,group:g},r[e]=y):(y.id=u.id,y.object=u,y.geometry=d,y.material=p,y.groupOrder=m,y.renderOrder=u.renderOrder,y.z=A,y.group=g),e++,y}function o(u,d,p,m,A,g){const y=a(u,d,p,m,A,g);p.transmission>0?i.push(y):p.transparent===!0?n.push(y):t.push(y)}function l(u,d,p,m,A,g){const y=a(u,d,p,m,A,g);p.transmission>0?i.unshift(y):p.transparent===!0?n.unshift(y):t.unshift(y)}function c(u,d){t.length>1&&t.sort(u||OL),i.length>1&&i.sort(d||NC),n.length>1&&n.sort(d||NC)}function h(){for(let u=e,d=r.length;u<d;u++){const p=r[u];if(p.id===null)break;p.id=null,p.object=null,p.geometry=null,p.material=null,p.group=null}}return{opaque:t,transmissive:i,transparent:n,init:s,push:o,unshift:l,finish:h,sort:c}}function UL(){let r=new WeakMap;function e(i,n){const s=r.get(i);let a;return s===void 0?(a=new kC,r.set(i,[a])):n>=s.length?(a=new kC,s.push(a)):a=s[n],a}function t(){r=new WeakMap}return{get:e,dispose:t}}function FL(){const r={};return{get:function(e){if(r[e.id]!==void 0)return r[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new S,color:new ee};break;case"SpotLight":t={position:new S,direction:new S,color:new ee,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new S,color:new ee,distance:0,decay:0};break;case"HemisphereLight":t={direction:new S,skyColor:new ee,groundColor:new ee};break;case"RectAreaLight":t={color:new ee,position:new S,halfWidth:new S,halfHeight:new S};break}return r[e.id]=t,t}}}function NL(){const r={};return{get:function(e){if(r[e.id]!==void 0)return r[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new K};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new K};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new K,shadowCameraNear:1,shadowCameraFar:1e3};break}return r[e.id]=t,t}}}let kL=0;function GL(r,e){return(e.castShadow?2:0)-(r.castShadow?2:0)+(e.map?1:0)-(r.map?1:0)}function zL(r){const e=new FL,t=NL(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new S);const n=new S,s=new fe,a=new fe;function o(c){let h=0,u=0,d=0;for(let C=0;C<9;C++)i.probe[C].set(0,0,0);let p=0,m=0,A=0,g=0,y=0,v=0,_=0,b=0,T=0,E=0,M=0;c.sort(GL);for(let C=0,x=c.length;C<x;C++){const D=c[C],U=D.color,O=D.intensity,N=D.distance,H=D.shadow&&D.shadow.map?D.shadow.map.texture:null;if(D.isAmbientLight)h+=U.r*O,u+=U.g*O,d+=U.b*O;else if(D.isLightProbe){for(let V=0;V<9;V++)i.probe[V].addScaledVector(D.sh.coefficients[V],O);M++}else if(D.isDirectionalLight){const V=e.get(D);if(V.color.copy(D.color).multiplyScalar(D.intensity),D.castShadow){const X=D.shadow,W=t.get(D);W.shadowIntensity=X.intensity,W.shadowBias=X.bias,W.shadowNormalBias=X.normalBias,W.shadowRadius=X.radius,W.shadowMapSize=X.mapSize,i.directionalShadow[p]=W,i.directionalShadowMap[p]=H,i.directionalShadowMatrix[p]=D.shadow.matrix,v++}i.directional[p]=V,p++}else if(D.isSpotLight){const V=e.get(D);V.position.setFromMatrixPosition(D.matrixWorld),V.color.copy(U).multiplyScalar(O),V.distance=N,V.coneCos=Math.cos(D.angle),V.penumbraCos=Math.cos(D.angle*(1-D.penumbra)),V.decay=D.decay,i.spot[A]=V;const X=D.shadow;if(D.map&&(i.spotLightMap[T]=D.map,T++,X.updateMatrices(D),D.castShadow&&E++),i.spotLightMatrix[A]=X.matrix,D.castShadow){const W=t.get(D);W.shadowIntensity=X.intensity,W.shadowBias=X.bias,W.shadowNormalBias=X.normalBias,W.shadowRadius=X.radius,W.shadowMapSize=X.mapSize,i.spotShadow[A]=W,i.spotShadowMap[A]=H,b++}A++}else if(D.isRectAreaLight){const V=e.get(D);V.color.copy(U).multiplyScalar(O),V.halfWidth.set(D.width*.5,0,0),V.halfHeight.set(0,D.height*.5,0),i.rectArea[g]=V,g++}else if(D.isPointLight){const V=e.get(D);if(V.color.copy(D.color).multiplyScalar(D.intensity),V.distance=D.distance,V.decay=D.decay,D.castShadow){const X=D.shadow,W=t.get(D);W.shadowIntensity=X.intensity,W.shadowBias=X.bias,W.shadowNormalBias=X.normalBias,W.shadowRadius=X.radius,W.shadowMapSize=X.mapSize,W.shadowCameraNear=X.camera.near,W.shadowCameraFar=X.camera.far,i.pointShadow[m]=W,i.pointShadowMap[m]=H,i.pointShadowMatrix[m]=D.shadow.matrix,_++}i.point[m]=V,m++}else if(D.isHemisphereLight){const V=e.get(D);V.skyColor.copy(D.color).multiplyScalar(O),V.groundColor.copy(D.groundColor).multiplyScalar(O),i.hemi[y]=V,y++}}g>0&&(r.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=De.LTC_FLOAT_1,i.rectAreaLTC2=De.LTC_FLOAT_2):(i.rectAreaLTC1=De.LTC_HALF_1,i.rectAreaLTC2=De.LTC_HALF_2)),i.ambient[0]=h,i.ambient[1]=u,i.ambient[2]=d;const I=i.hash;(I.directionalLength!==p||I.pointLength!==m||I.spotLength!==A||I.rectAreaLength!==g||I.hemiLength!==y||I.numDirectionalShadows!==v||I.numPointShadows!==_||I.numSpotShadows!==b||I.numSpotMaps!==T||I.numLightProbes!==M)&&(i.directional.length=p,i.spot.length=A,i.rectArea.length=g,i.point.length=m,i.hemi.length=y,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=_,i.pointShadowMap.length=_,i.spotShadow.length=b,i.spotShadowMap.length=b,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=_,i.spotLightMatrix.length=b+T-E,i.spotLightMap.length=T,i.numSpotLightShadowsWithMaps=E,i.numLightProbes=M,I.directionalLength=p,I.pointLength=m,I.spotLength=A,I.rectAreaLength=g,I.hemiLength=y,I.numDirectionalShadows=v,I.numPointShadows=_,I.numSpotShadows=b,I.numSpotMaps=T,I.numLightProbes=M,i.version=kL++)}function l(c,h){let u=0,d=0,p=0,m=0,A=0;const g=h.matrixWorldInverse;for(let y=0,v=c.length;y<v;y++){const _=c[y];if(_.isDirectionalLight){const b=i.directional[u];b.direction.setFromMatrixPosition(_.matrixWorld),n.setFromMatrixPosition(_.target.matrixWorld),b.direction.sub(n),b.direction.transformDirection(g),u++}else if(_.isSpotLight){const b=i.spot[p];b.position.setFromMatrixPosition(_.matrixWorld),b.position.applyMatrix4(g),b.direction.setFromMatrixPosition(_.matrixWorld),n.setFromMatrixPosition(_.target.matrixWorld),b.direction.sub(n),b.direction.transformDirection(g),p++}else if(_.isRectAreaLight){const b=i.rectArea[m];b.position.setFromMatrixPosition(_.matrixWorld),b.position.applyMatrix4(g),a.identity(),s.copy(_.matrixWorld),s.premultiply(g),a.extractRotation(s),b.halfWidth.set(_.width*.5,0,0),b.halfHeight.set(0,_.height*.5,0),b.halfWidth.applyMatrix4(a),b.halfHeight.applyMatrix4(a),m++}else if(_.isPointLight){const b=i.point[d];b.position.setFromMatrixPosition(_.matrixWorld),b.position.applyMatrix4(g),d++}else if(_.isHemisphereLight){const b=i.hemi[A];b.direction.setFromMatrixPosition(_.matrixWorld),b.direction.transformDirection(g),A++}}}return{setup:o,setupView:l,state:i}}function GC(r){const e=new zL(r),t=[],i=[];function n(h){c.camera=h,t.length=0,i.length=0}function s(h){t.push(h)}function a(h){i.push(h)}function o(){e.setup(t)}function l(h){e.setupView(t,h)}const c={lightsArray:t,shadowsArray:i,camera:null,lights:e,transmissionRenderTarget:{}};return{init:n,state:c,setupLights:o,setupLightsView:l,pushLight:s,pushShadow:a}}function VL(r){let e=new WeakMap;function t(n,s=0){const a=e.get(n);let o;return a===void 0?(o=new GC(r),e.set(n,[o])):s>=a.length?(o=new GC(r),a.push(o)):o=a[s],o}function i(){e=new WeakMap}return{get:t,dispose:i}}class Ec extends tn{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=If,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class zy extends tn{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}}const HL=`void main() {
	gl_Position = vec4( position, 1.0 );
}`,QL=`uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
#include <packing>
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 = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
			mean += distribution.x;
			squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
		#else
			float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
			mean += depth;
			squared_mean += depth * depth;
		#endif
	}
	mean = mean / samples;
	squared_mean = squared_mean / samples;
	float std_dev = sqrt( squared_mean - mean * mean );
	gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
}`;function jL(r,e,t){let i=new pu;const n=new K,s=new K,a=new et,o=new Ec({depthPacking:sc}),l=new zy,c={},h=t.maxTextureSize,u={[us]:In,[In]:us,[Zi]:Zi},d=new nn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new K},radius:{value:4}},vertexShader:HL,fragmentShader:QL}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const m=new Je;m.setAttribute("position",new Ze(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const A=new _e(m,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=xA;let y=this.type;this.render=function(E,M,I){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||E.length===0)return;const C=r.getRenderTarget(),x=r.getActiveCubeFace(),D=r.getActiveMipmapLevel(),U=r.state;U.setBlending(gn),U.buffers.color.setClear(1,1,1,1),U.buffers.depth.setTest(!0),U.setScissorTest(!1);const O=y!==qr&&this.type===qr,N=y===qr&&this.type!==qr;for(let H=0,V=E.length;H<V;H++){const X=E[H],W=X.shadow;if(W===void 0){console.warn("THREE.WebGLShadowMap:",X,"has no shadow.");continue}if(W.autoUpdate===!1&&W.needsUpdate===!1)continue;n.copy(W.mapSize);const ce=W.getFrameExtents();if(n.multiply(ce),s.copy(W.mapSize),(n.x>h||n.y>h)&&(n.x>h&&(s.x=Math.floor(h/ce.x),n.x=s.x*ce.x,W.mapSize.x=s.x),n.y>h&&(s.y=Math.floor(h/ce.y),n.y=s.y*ce.y,W.mapSize.y=s.y)),W.map===null||O===!0||N===!0){const we=this.type!==qr?{minFilter:mi,magFilter:mi}:{};W.map!==null&&W.map.dispose(),W.map=new ds(n.x,n.y,we),W.map.texture.name=X.name+".shadowMap",W.camera.updateProjectionMatrix()}r.setRenderTarget(W.map),r.clear();const ue=W.getViewportCount();for(let we=0;we<ue;we++){const Pe=W.getViewport(we);a.set(s.x*Pe.x,s.y*Pe.y,s.x*Pe.z,s.y*Pe.w),U.viewport(a),W.updateMatrices(X,we),i=W.getFrustum(),b(M,I,W.camera,X,this.type)}W.isPointLightShadow!==!0&&this.type===qr&&v(W,I),W.needsUpdate=!1}y=this.type,g.needsUpdate=!1,r.setRenderTarget(C,x,D)};function v(E,M){const I=e.update(A);d.defines.VSM_SAMPLES!==E.blurSamples&&(d.defines.VSM_SAMPLES=E.blurSamples,p.defines.VSM_SAMPLES=E.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),E.mapPass===null&&(E.mapPass=new ds(n.x,n.y)),d.uniforms.shadow_pass.value=E.map.texture,d.uniforms.resolution.value=E.mapSize,d.uniforms.radius.value=E.radius,r.setRenderTarget(E.mapPass),r.clear(),r.renderBufferDirect(M,null,I,d,A,null),p.uniforms.shadow_pass.value=E.mapPass.texture,p.uniforms.resolution.value=E.mapSize,p.uniforms.radius.value=E.radius,r.setRenderTarget(E.map),r.clear(),r.renderBufferDirect(M,null,I,p,A,null)}function _(E,M,I,C){let x=null;const D=I.isPointLight===!0?E.customDistanceMaterial:E.customDepthMaterial;if(D!==void 0)x=D;else if(x=I.isPointLight===!0?l:o,r.localClippingEnabled&&M.clipShadows===!0&&Array.isArray(M.clippingPlanes)&&M.clippingPlanes.length!==0||M.displacementMap&&M.displacementScale!==0||M.alphaMap&&M.alphaTest>0||M.map&&M.alphaTest>0){const U=x.uuid,O=M.uuid;let N=c[U];N===void 0&&(N={},c[U]=N);let H=N[O];H===void 0&&(H=x.clone(),N[O]=H,M.addEventListener("dispose",T)),x=H}if(x.visible=M.visible,x.wireframe=M.wireframe,C===qr?x.side=M.shadowSide!==null?M.shadowSide:M.side:x.side=M.shadowSide!==null?M.shadowSide:u[M.side],x.alphaMap=M.alphaMap,x.alphaTest=M.alphaTest,x.map=M.map,x.clipShadows=M.clipShadows,x.clippingPlanes=M.clippingPlanes,x.clipIntersection=M.clipIntersection,x.displacementMap=M.displacementMap,x.displacementScale=M.displacementScale,x.displacementBias=M.displacementBias,x.wireframeLinewidth=M.wireframeLinewidth,x.linewidth=M.linewidth,I.isPointLight===!0&&x.isMeshDistanceMaterial===!0){const U=r.properties.get(x);U.light=I}return x}function b(E,M,I,C,x){if(E.visible===!1)return;if(E.layers.test(M.layers)&&(E.isMesh||E.isLine||E.isPoints)&&(E.castShadow||E.receiveShadow&&x===qr)&&(!E.frustumCulled||i.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(I.matrixWorldInverse,E.matrixWorld);const O=e.update(E),N=E.material;if(Array.isArray(N)){const H=O.groups;for(let V=0,X=H.length;V<X;V++){const W=H[V],ce=N[W.materialIndex];if(ce&&ce.visible){const ue=_(E,ce,C,x);E.onBeforeShadow(r,E,M,I,O,ue,W),r.renderBufferDirect(I,null,O,ue,E,W),E.onAfterShadow(r,E,M,I,O,ue,W)}}}else if(N.visible){const H=_(E,N,C,x);E.onBeforeShadow(r,E,M,I,O,H,null),r.renderBufferDirect(I,null,O,H,E,null),E.onAfterShadow(r,E,M,I,O,H,null)}}const U=E.children;for(let O=0,N=U.length;O<N;O++)b(U[O],M,I,C,x)}function T(E){E.target.removeEventListener("dispose",T);for(const I in c){const C=c[I],x=E.target.uuid;x in C&&(C[x].dispose(),delete C[x])}}}function WL(r){function e(){let j=!1;const Ie=new et;let $=null;const Ae=new et(0,0,0,0);return{setMask:function(Be){$!==Be&&!j&&(r.colorMask(Be,Be,Be,Be),$=Be)},setLocked:function(Be){j=Be},setClear:function(Be,pt,Kt,Ji,Nn){Nn===!0&&(Be*=Ji,pt*=Ji,Kt*=Ji),Ie.set(Be,pt,Kt,Ji),Ae.equals(Ie)===!1&&(r.clearColor(Be,pt,Kt,Ji),Ae.copy(Ie))},reset:function(){j=!1,$=null,Ae.set(-1,0,0,0)}}}function t(){let j=!1,Ie=null,$=null,Ae=null;return{setTest:function(Be){Be?me(r.DEPTH_TEST):Ce(r.DEPTH_TEST)},setMask:function(Be){Ie!==Be&&!j&&(r.depthMask(Be),Ie=Be)},setFunc:function(Be){if($!==Be){switch(Be){case mw:r.depthFunc(r.NEVER);break;case gw:r.depthFunc(r.ALWAYS);break;case Aw:r.depthFunc(r.LESS);break;case Yl:r.depthFunc(r.LEQUAL);break;case yw:r.depthFunc(r.EQUAL);break;case _w:r.depthFunc(r.GEQUAL);break;case vw:r.depthFunc(r.GREATER);break;case bw:r.depthFunc(r.NOTEQUAL);break;default:r.depthFunc(r.LEQUAL)}$=Be}},setLocked:function(Be){j=Be},setClear:function(Be){Ae!==Be&&(r.clearDepth(Be),Ae=Be)},reset:function(){j=!1,Ie=null,$=null,Ae=null}}}function i(){let j=!1,Ie=null,$=null,Ae=null,Be=null,pt=null,Kt=null,Ji=null,Nn=null;return{setTest:function(Jt){j||(Jt?me(r.STENCIL_TEST):Ce(r.STENCIL_TEST))},setMask:function(Jt){Ie!==Jt&&!j&&(r.stencilMask(Jt),Ie=Jt)},setFunc:function(Jt,bs,Zs){($!==Jt||Ae!==bs||Be!==Zs)&&(r.stencilFunc(Jt,bs,Zs),$=Jt,Ae=bs,Be=Zs)},setOp:function(Jt,bs,Zs){(pt!==Jt||Kt!==bs||Ji!==Zs)&&(r.stencilOp(Jt,bs,Zs),pt=Jt,Kt=bs,Ji=Zs)},setLocked:function(Jt){j=Jt},setClear:function(Jt){Nn!==Jt&&(r.clearStencil(Jt),Nn=Jt)},reset:function(){j=!1,Ie=null,$=null,Ae=null,Be=null,pt=null,Kt=null,Ji=null,Nn=null}}}const n=new e,s=new t,a=new i,o=new WeakMap,l=new WeakMap;let c={},h={},u=new WeakMap,d=[],p=null,m=!1,A=null,g=null,y=null,v=null,_=null,b=null,T=null,E=new ee(0,0,0),M=0,I=!1,C=null,x=null,D=null,U=null,O=null;const N=r.getParameter(r.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let H=!1,V=0;const X=r.getParameter(r.VERSION);X.indexOf("WebGL")!==-1?(V=parseFloat(/^WebGL (\d)/.exec(X)[1]),H=V>=1):X.indexOf("OpenGL ES")!==-1&&(V=parseFloat(/^OpenGL ES (\d)/.exec(X)[1]),H=V>=2);let W=null,ce={};const ue=r.getParameter(r.SCISSOR_BOX),we=r.getParameter(r.VIEWPORT),Pe=new et().fromArray(ue),Qe=new et().fromArray(we);function ie(j,Ie,$,Ae){const Be=new Uint8Array(4),pt=r.createTexture();r.bindTexture(j,pt),r.texParameteri(j,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(j,r.TEXTURE_MAG_FILTER,r.NEAREST);for(let Kt=0;Kt<$;Kt++)j===r.TEXTURE_3D||j===r.TEXTURE_2D_ARRAY?r.texImage3D(Ie,0,r.RGBA,1,1,Ae,0,r.RGBA,r.UNSIGNED_BYTE,Be):r.texImage2D(Ie+Kt,0,r.RGBA,1,1,0,r.RGBA,r.UNSIGNED_BYTE,Be);return pt}const oe={};oe[r.TEXTURE_2D]=ie(r.TEXTURE_2D,r.TEXTURE_2D,1),oe[r.TEXTURE_CUBE_MAP]=ie(r.TEXTURE_CUBE_MAP,r.TEXTURE_CUBE_MAP_POSITIVE_X,6),oe[r.TEXTURE_2D_ARRAY]=ie(r.TEXTURE_2D_ARRAY,r.TEXTURE_2D_ARRAY,1,1),oe[r.TEXTURE_3D]=ie(r.TEXTURE_3D,r.TEXTURE_3D,1,1),n.setClear(0,0,0,1),s.setClear(1),a.setClear(0),me(r.DEPTH_TEST),s.setFunc(Yl),Ne(!1),ge(cw),me(r.CULL_FACE),xe(gn);function me(j){c[j]!==!0&&(r.enable(j),c[j]=!0)}function Ce(j){c[j]!==!1&&(r.disable(j),c[j]=!1)}function Xe(j,Ie){return h[j]!==Ie?(r.bindFramebuffer(j,Ie),h[j]=Ie,j===r.DRAW_FRAMEBUFFER&&(h[r.FRAMEBUFFER]=Ie),j===r.FRAMEBUFFER&&(h[r.DRAW_FRAMEBUFFER]=Ie),!0):!1}function dt(j,Ie){let $=d,Ae=!1;if(j){$=u.get(Ie),$===void 0&&($=[],u.set(Ie,$));const Be=j.textures;if($.length!==Be.length||$[0]!==r.COLOR_ATTACHMENT0){for(let pt=0,Kt=Be.length;pt<Kt;pt++)$[pt]=r.COLOR_ATTACHMENT0+pt;$.length=Be.length,Ae=!0}}else $[0]!==r.BACK&&($[0]=r.BACK,Ae=!0);Ae&&r.drawBuffers($)}function Ke(j){return p!==j?(r.useProgram(j),p=j,!0):!1}const gt={[Er]:r.FUNC_ADD,[hw]:r.FUNC_SUBTRACT,[uw]:r.FUNC_REVERSE_SUBTRACT};gt[dw]=r.MIN,gt[fw]=r.MAX;const F={[SA]:r.ZERO,[EA]:r.ONE,[MA]:r.SRC_COLOR,[jl]:r.SRC_ALPHA,[pw]:r.SRC_ALPHA_SATURATE,[DA]:r.DST_COLOR,[IA]:r.DST_ALPHA,[TA]:r.ONE_MINUS_SRC_COLOR,[Wl]:r.ONE_MINUS_SRC_ALPHA,[RA]:r.ONE_MINUS_DST_COLOR,[PA]:r.ONE_MINUS_DST_ALPHA,[Yh]:r.CONSTANT_COLOR,[$h]:r.ONE_MINUS_CONSTANT_COLOR,[ql]:r.CONSTANT_ALPHA,[Xl]:r.ONE_MINUS_CONSTANT_ALPHA};function xe(j,Ie,$,Ae,Be,pt,Kt,Ji,Nn,Jt){if(j===gn){m===!0&&(Ce(r.BLEND),m=!1);return}if(m===!1&&(me(r.BLEND),m=!0),j!==er){if(j!==A||Jt!==I){if((g!==Er||_!==Er)&&(r.blendEquation(r.FUNC_ADD),g=Er,_=Er),Jt)switch(j){case Sr:r.blendFuncSeparate(r.ONE,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA);break;case df:r.blendFunc(r.ONE,r.ONE);break;case ff:r.blendFuncSeparate(r.ZERO,r.ONE_MINUS_SRC_COLOR,r.ZERO,r.ONE);break;case pf:r.blendFuncSeparate(r.ZERO,r.SRC_COLOR,r.ZERO,r.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",j);break}else switch(j){case Sr:r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA);break;case df:r.blendFunc(r.SRC_ALPHA,r.ONE);break;case ff:r.blendFuncSeparate(r.ZERO,r.ONE_MINUS_SRC_COLOR,r.ZERO,r.ONE);break;case pf:r.blendFunc(r.ZERO,r.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",j);break}y=null,v=null,b=null,T=null,E.set(0,0,0),M=0,A=j,I=Jt}return}Be=Be||Ie,pt=pt||$,Kt=Kt||Ae,(Ie!==g||Be!==_)&&(r.blendEquationSeparate(gt[Ie],gt[Be]),g=Ie,_=Be),($!==y||Ae!==v||pt!==b||Kt!==T)&&(r.blendFuncSeparate(F[$],F[Ae],F[pt],F[Kt]),y=$,v=Ae,b=pt,T=Kt),(Ji.equals(E)===!1||Nn!==M)&&(r.blendColor(Ji.r,Ji.g,Ji.b,Nn),E.copy(Ji),M=Nn),A=j,I=!1}function be(j,Ie){j.side===Zi?Ce(r.CULL_FACE):me(r.CULL_FACE);let $=j.side===In;Ie&&($=!$),Ne($),j.blending===Sr&&j.transparent===!1?xe(gn):xe(j.blending,j.blendEquation,j.blendSrc,j.blendDst,j.blendEquationAlpha,j.blendSrcAlpha,j.blendDstAlpha,j.blendColor,j.blendAlpha,j.premultipliedAlpha),s.setFunc(j.depthFunc),s.setTest(j.depthTest),s.setMask(j.depthWrite),n.setMask(j.colorWrite);const Ae=j.stencilWrite;a.setTest(Ae),Ae&&(a.setMask(j.stencilWriteMask),a.setFunc(j.stencilFunc,j.stencilRef,j.stencilFuncMask),a.setOp(j.stencilFail,j.stencilZFail,j.stencilZPass)),ke(j.polygonOffset,j.polygonOffsetFactor,j.polygonOffsetUnits),j.alphaToCoverage===!0?me(r.SAMPLE_ALPHA_TO_COVERAGE):Ce(r.SAMPLE_ALPHA_TO_COVERAGE)}function Ne(j){C!==j&&(j?r.frontFace(r.CW):r.frontFace(r.CCW),C=j)}function ge(j){j!==QP?(me(r.CULL_FACE),j!==x&&(j===cw?r.cullFace(r.BACK):j===jP?r.cullFace(r.FRONT):r.cullFace(r.FRONT_AND_BACK))):Ce(r.CULL_FACE),x=j}function ut(j){j!==D&&(H&&r.lineWidth(j),D=j)}function ke(j,Ie,$){j?(me(r.POLYGON_OFFSET_FILL),(U!==Ie||O!==$)&&(r.polygonOffset(Ie,$),U=Ie,O=$)):Ce(r.POLYGON_OFFSET_FILL)}function Ve(j){j?me(r.SCISSOR_TEST):Ce(r.SCISSOR_TEST)}function z(j){j===void 0&&(j=r.TEXTURE0+N-1),W!==j&&(r.activeTexture(j),W=j)}function B(j,Ie,$){$===void 0&&(W===null?$=r.TEXTURE0+N-1:$=W);let Ae=ce[$];Ae===void 0&&(Ae={type:void 0,texture:void 0},ce[$]=Ae),(Ae.type!==j||Ae.texture!==Ie)&&(W!==$&&(r.activeTexture($),W=$),r.bindTexture(j,Ie||oe[j]),Ae.type=j,Ae.texture=Ie)}function ne(){const j=ce[W];j!==void 0&&j.type!==void 0&&(r.bindTexture(j.type,null),j.type=void 0,j.texture=void 0)}function de(){try{r.compressedTexImage2D.apply(r,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function ye(){try{r.compressedTexImage3D.apply(r,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function pe(){try{r.texSubImage2D.apply(r,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function nt(){try{r.texSubImage3D.apply(r,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function Le(){try{r.compressedTexSubImage2D.apply(r,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function Ye(){try{r.compressedTexSubImage3D.apply(r,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function yt(){try{r.texStorage2D.apply(r,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function Me(){try{r.texStorage3D.apply(r,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function je(){try{r.texImage2D.apply(r,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function Wt(){try{r.texImage3D.apply(r,arguments)}catch(j){console.error("THREE.WebGLState:",j)}}function st(j){Pe.equals(j)===!1&&(r.scissor(j.x,j.y,j.z,j.w),Pe.copy(j))}function Ge(j){Qe.equals(j)===!1&&(r.viewport(j.x,j.y,j.z,j.w),Qe.copy(j))}function wt(j,Ie){let $=l.get(Ie);$===void 0&&($=new WeakMap,l.set(Ie,$));let Ae=$.get(j);Ae===void 0&&(Ae=r.getUniformBlockIndex(Ie,j.name),$.set(j,Ae))}function _t(j,Ie){const Ae=l.get(Ie).get(j);o.get(Ie)!==Ae&&(r.uniformBlockBinding(Ie,Ae,j.__bindingPointIndex),o.set(Ie,Ae))}function Ht(){r.disable(r.BLEND),r.disable(r.CULL_FACE),r.disable(r.DEPTH_TEST),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SCISSOR_TEST),r.disable(r.STENCIL_TEST),r.disable(r.SAMPLE_ALPHA_TO_COVERAGE),r.blendEquation(r.FUNC_ADD),r.blendFunc(r.ONE,r.ZERO),r.blendFuncSeparate(r.ONE,r.ZERO,r.ONE,r.ZERO),r.blendColor(0,0,0,0),r.colorMask(!0,!0,!0,!0),r.clearColor(0,0,0,0),r.depthMask(!0),r.depthFunc(r.LESS),r.clearDepth(1),r.stencilMask(4294967295),r.stencilFunc(r.ALWAYS,0,4294967295),r.stencilOp(r.KEEP,r.KEEP,r.KEEP),r.clearStencil(0),r.cullFace(r.BACK),r.frontFace(r.CCW),r.polygonOffset(0,0),r.activeTexture(r.TEXTURE0),r.bindFramebuffer(r.FRAMEBUFFER,null),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,null),r.bindFramebuffer(r.READ_FRAMEBUFFER,null),r.useProgram(null),r.lineWidth(1),r.scissor(0,0,r.canvas.width,r.canvas.height),r.viewport(0,0,r.canvas.width,r.canvas.height),c={},W=null,ce={},h={},u=new WeakMap,d=[],p=null,m=!1,A=null,g=null,y=null,v=null,_=null,b=null,T=null,E=new ee(0,0,0),M=0,I=!1,C=null,x=null,D=null,U=null,O=null,Pe.set(0,0,r.canvas.width,r.canvas.height),Qe.set(0,0,r.canvas.width,r.canvas.height),n.reset(),s.reset(),a.reset()}return{buffers:{color:n,depth:s,stencil:a},enable:me,disable:Ce,bindFramebuffer:Xe,drawBuffers:dt,useProgram:Ke,setBlending:xe,setMaterial:be,setFlipSided:Ne,setCullFace:ge,setLineWidth:ut,setPolygonOffset:ke,setScissorTest:Ve,activeTexture:z,bindTexture:B,unbindTexture:ne,compressedTexImage2D:de,compressedTexImage3D:ye,texImage2D:je,texImage3D:Wt,updateUBOMapping:wt,uniformBlockBinding:_t,texStorage2D:yt,texStorage3D:Me,texSubImage2D:pe,texSubImage3D:nt,compressedTexSubImage2D:Le,compressedTexSubImage3D:Ye,scissor:st,viewport:Ge,reset:Ht}}function zC(r,e,t,i){const n=qL(i);switch(t){case Pw:return r*e;case Rw:return r*e;case Bw:return r*e*2;case Jr:return r*e/n.components*n.byteLength;case _f:return r*e/n.components*n.byteLength;case Ro:return r*e*2/n.components*n.byteLength;case UA:return r*e*2/n.components*n.byteLength;case Dw:return r*e*3/n.components*n.byteLength;case qt:return r*e*4/n.components*n.byteLength;case FA:return r*e*4/n.components*n.byteLength;case vf:case Zh:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*8;case bf:case eu:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case NA:case kA:return Math.max(r,16)*Math.max(e,8)/4;case wf:case Cf:return Math.max(r,8)*Math.max(e,8)/2;case xf:case Sf:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*8;case Ef:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case Mf:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case GA:return Math.floor((r+4)/5)*Math.floor((e+3)/4)*16;case zA:return Math.floor((r+4)/5)*Math.floor((e+4)/5)*16;case VA:return Math.floor((r+5)/6)*Math.floor((e+4)/5)*16;case tu:return Math.floor((r+5)/6)*Math.floor((e+5)/6)*16;case HA:return Math.floor((r+7)/8)*Math.floor((e+4)/5)*16;case QA:return Math.floor((r+7)/8)*Math.floor((e+5)/6)*16;case jA:return Math.floor((r+7)/8)*Math.floor((e+7)/8)*16;case WA:return Math.floor((r+9)/10)*Math.floor((e+4)/5)*16;case qA:return Math.floor((r+9)/10)*Math.floor((e+5)/6)*16;case XA:return Math.floor((r+9)/10)*Math.floor((e+7)/8)*16;case YA:return Math.floor((r+9)/10)*Math.floor((e+9)/10)*16;case $A:return Math.floor((r+11)/12)*Math.floor((e+9)/10)*16;case KA:return Math.floor((r+11)/12)*Math.floor((e+11)/12)*16;case iu:case JA:case ZA:return Math.ceil(r/4)*Math.ceil(e/4)*16;case Lw:case ey:return Math.ceil(r/4)*Math.ceil(e/4)*8;case ty:case iy:return Math.ceil(r/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function qL(r){switch(r){case Qt:case LA:return{byteLength:1,components:1};case Jl:case OA:case Yt:return{byteLength:2,components:1};case Af:case yf:return{byteLength:2,components:4};case tr:case gf:case Ut:return{byteLength:4,components:1};case Iw:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${r}.`)}function XL(r,e,t,i,n,s,a){const o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new K,h=new WeakMap;let u;const d=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function m(z,B){return p?new OffscreenCanvas(z,B):au("canvas")}function A(z,B,ne){let de=1;const ye=Ve(z);if((ye.width>ne||ye.height>ne)&&(de=ne/Math.max(ye.width,ye.height)),de<1)if(typeof HTMLImageElement<"u"&&z instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&z instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&z instanceof ImageBitmap||typeof VideoFrame<"u"&&z instanceof VideoFrame){const pe=Math.floor(de*ye.width),nt=Math.floor(de*ye.height);u===void 0&&(u=m(pe,nt));const Le=B?m(pe,nt):u;return Le.width=pe,Le.height=nt,Le.getContext("2d").drawImage(z,0,0,pe,nt),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+ye.width+"x"+ye.height+") to ("+pe+"x"+nt+")."),Le}else return"data"in z&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+ye.width+"x"+ye.height+")."),z;return z}function g(z){return z.generateMipmaps&&z.minFilter!==mi&&z.minFilter!==at}function y(z){r.generateMipmap(z)}function v(z,B,ne,de,ye=!1){if(z!==null){if(r[z]!==void 0)return r[z];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+z+"'")}let pe=B;if(B===r.RED&&(ne===r.FLOAT&&(pe=r.R32F),ne===r.HALF_FLOAT&&(pe=r.R16F),ne===r.UNSIGNED_BYTE&&(pe=r.R8)),B===r.RED_INTEGER&&(ne===r.UNSIGNED_BYTE&&(pe=r.R8UI),ne===r.UNSIGNED_SHORT&&(pe=r.R16UI),ne===r.UNSIGNED_INT&&(pe=r.R32UI),ne===r.BYTE&&(pe=r.R8I),ne===r.SHORT&&(pe=r.R16I),ne===r.INT&&(pe=r.R32I)),B===r.RG&&(ne===r.FLOAT&&(pe=r.RG32F),ne===r.HALF_FLOAT&&(pe=r.RG16F),ne===r.UNSIGNED_BYTE&&(pe=r.RG8)),B===r.RG_INTEGER&&(ne===r.UNSIGNED_BYTE&&(pe=r.RG8UI),ne===r.UNSIGNED_SHORT&&(pe=r.RG16UI),ne===r.UNSIGNED_INT&&(pe=r.RG32UI),ne===r.BYTE&&(pe=r.RG8I),ne===r.SHORT&&(pe=r.RG16I),ne===r.INT&&(pe=r.RG32I)),B===r.RGB&&ne===r.UNSIGNED_INT_5_9_9_9_REV&&(pe=r.RGB9_E5),B===r.RGBA){const nt=ye?Pf:Nt.getTransfer(de);ne===r.FLOAT&&(pe=r.RGBA32F),ne===r.HALF_FLOAT&&(pe=r.RGBA16F),ne===r.UNSIGNED_BYTE&&(pe=nt===Ci?r.SRGB8_ALPHA8:r.RGBA8),ne===r.UNSIGNED_SHORT_4_4_4_4&&(pe=r.RGBA4),ne===r.UNSIGNED_SHORT_5_5_5_1&&(pe=r.RGB5_A1)}return(pe===r.R16F||pe===r.R32F||pe===r.RG16F||pe===r.RG32F||pe===r.RGBA16F||pe===r.RGBA32F)&&e.get("EXT_color_buffer_float"),pe}function _(z,B){let ne;return z?B===null||B===tr||B===Po?ne=r.DEPTH24_STENCIL8:B===Ut?ne=r.DEPTH32F_STENCIL8:B===Jl&&(ne=r.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):B===null||B===tr||B===Po?ne=r.DEPTH_COMPONENT24:B===Ut?ne=r.DEPTH_COMPONENT32F:B===Jl&&(ne=r.DEPTH_COMPONENT16),ne}function b(z,B){return g(z)===!0||z.isFramebufferTexture&&z.minFilter!==mi&&z.minFilter!==at?Math.log2(Math.max(B.width,B.height))+1:z.mipmaps!==void 0&&z.mipmaps.length>0?z.mipmaps.length:z.isCompressedTexture&&Array.isArray(z.image)?B.mipmaps.length:1}function T(z){const B=z.target;B.removeEventListener("dispose",T),M(B),B.isVideoTexture&&h.delete(B)}function E(z){const B=z.target;B.removeEventListener("dispose",E),C(B)}function M(z){const B=i.get(z);if(B.__webglInit===void 0)return;const ne=z.source,de=d.get(ne);if(de){const ye=de[B.__cacheKey];ye.usedTimes--,ye.usedTimes===0&&I(z),Object.keys(de).length===0&&d.delete(ne)}i.remove(z)}function I(z){const B=i.get(z);r.deleteTexture(B.__webglTexture);const ne=z.source,de=d.get(ne);delete de[B.__cacheKey],a.memory.textures--}function C(z){const B=i.get(z);if(z.depthTexture&&z.depthTexture.dispose(),z.isWebGLCubeRenderTarget)for(let de=0;de<6;de++){if(Array.isArray(B.__webglFramebuffer[de]))for(let ye=0;ye<B.__webglFramebuffer[de].length;ye++)r.deleteFramebuffer(B.__webglFramebuffer[de][ye]);else r.deleteFramebuffer(B.__webglFramebuffer[de]);B.__webglDepthbuffer&&r.deleteRenderbuffer(B.__webglDepthbuffer[de])}else{if(Array.isArray(B.__webglFramebuffer))for(let de=0;de<B.__webglFramebuffer.length;de++)r.deleteFramebuffer(B.__webglFramebuffer[de]);else r.deleteFramebuffer(B.__webglFramebuffer);if(B.__webglDepthbuffer&&r.deleteRenderbuffer(B.__webglDepthbuffer),B.__webglMultisampledFramebuffer&&r.deleteFramebuffer(B.__webglMultisampledFramebuffer),B.__webglColorRenderbuffer)for(let de=0;de<B.__webglColorRenderbuffer.length;de++)B.__webglColorRenderbuffer[de]&&r.deleteRenderbuffer(B.__webglColorRenderbuffer[de]);B.__webglDepthRenderbuffer&&r.deleteRenderbuffer(B.__webglDepthRenderbuffer)}const ne=z.textures;for(let de=0,ye=ne.length;de<ye;de++){const pe=i.get(ne[de]);pe.__webglTexture&&(r.deleteTexture(pe.__webglTexture),a.memory.textures--),i.remove(ne[de])}i.remove(z)}let x=0;function D(){x=0}function U(){const z=x;return z>=n.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+z+" texture units while this GPU supports only "+n.maxTextures),x+=1,z}function O(z){const B=[];return B.push(z.wrapS),B.push(z.wrapT),B.push(z.wrapR||0),B.push(z.magFilter),B.push(z.minFilter),B.push(z.anisotropy),B.push(z.internalFormat),B.push(z.format),B.push(z.type),B.push(z.generateMipmaps),B.push(z.premultiplyAlpha),B.push(z.flipY),B.push(z.unpackAlignment),B.push(z.colorSpace),B.join()}function N(z,B){const ne=i.get(z);if(z.isVideoTexture&&ut(z),z.isRenderTargetTexture===!1&&z.version>0&&ne.__version!==z.version){const de=z.image;if(de===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(de.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Qe(ne,z,B);return}}t.bindTexture(r.TEXTURE_2D,ne.__webglTexture,r.TEXTURE0+B)}function H(z,B){const ne=i.get(z);if(z.version>0&&ne.__version!==z.version){Qe(ne,z,B);return}t.bindTexture(r.TEXTURE_2D_ARRAY,ne.__webglTexture,r.TEXTURE0+B)}function V(z,B){const ne=i.get(z);if(z.version>0&&ne.__version!==z.version){Qe(ne,z,B);return}t.bindTexture(r.TEXTURE_3D,ne.__webglTexture,r.TEXTURE0+B)}function X(z,B){const ne=i.get(z);if(z.version>0&&ne.__version!==z.version){ie(ne,z,B);return}t.bindTexture(r.TEXTURE_CUBE_MAP,ne.__webglTexture,r.TEXTURE0+B)}const W={[Pn]:r.REPEAT,[di]:r.CLAMP_TO_EDGE,[Kr]:r.MIRRORED_REPEAT},ce={[mi]:r.NEAREST,[Jh]:r.NEAREST_MIPMAP_NEAREST,[Na]:r.NEAREST_MIPMAP_LINEAR,[at]:r.LINEAR,[Io]:r.LINEAR_MIPMAP_NEAREST,[Dn]:r.LINEAR_MIPMAP_LINEAR},ue={[tD]:r.NEVER,[oD]:r.ALWAYS,[iD]:r.LESS,[Nw]:r.LEQUAL,[nD]:r.EQUAL,[aD]:r.GEQUAL,[sD]:r.GREATER,[rD]:r.NOTEQUAL};function we(z,B){if(B.type===Ut&&e.has("OES_texture_float_linear")===!1&&(B.magFilter===at||B.magFilter===Io||B.magFilter===Na||B.magFilter===Dn||B.minFilter===at||B.minFilter===Io||B.minFilter===Na||B.minFilter===Dn)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),r.texParameteri(z,r.TEXTURE_WRAP_S,W[B.wrapS]),r.texParameteri(z,r.TEXTURE_WRAP_T,W[B.wrapT]),(z===r.TEXTURE_3D||z===r.TEXTURE_2D_ARRAY)&&r.texParameteri(z,r.TEXTURE_WRAP_R,W[B.wrapR]),r.texParameteri(z,r.TEXTURE_MAG_FILTER,ce[B.magFilter]),r.texParameteri(z,r.TEXTURE_MIN_FILTER,ce[B.minFilter]),B.compareFunction&&(r.texParameteri(z,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(z,r.TEXTURE_COMPARE_FUNC,ue[B.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(B.magFilter===mi||B.minFilter!==Na&&B.minFilter!==Dn||B.type===Ut&&e.has("OES_texture_float_linear")===!1)return;if(B.anisotropy>1||i.get(B).__currentAnisotropy){const ne=e.get("EXT_texture_filter_anisotropic");r.texParameterf(z,ne.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(B.anisotropy,n.getMaxAnisotropy())),i.get(B).__currentAnisotropy=B.anisotropy}}}function Pe(z,B){let ne=!1;z.__webglInit===void 0&&(z.__webglInit=!0,B.addEventListener("dispose",T));const de=B.source;let ye=d.get(de);ye===void 0&&(ye={},d.set(de,ye));const pe=O(B);if(pe!==z.__cacheKey){ye[pe]===void 0&&(ye[pe]={texture:r.createTexture(),usedTimes:0},a.memory.textures++,ne=!0),ye[pe].usedTimes++;const nt=ye[z.__cacheKey];nt!==void 0&&(ye[z.__cacheKey].usedTimes--,nt.usedTimes===0&&I(B)),z.__cacheKey=pe,z.__webglTexture=ye[pe].texture}return ne}function Qe(z,B,ne){let de=r.TEXTURE_2D;(B.isDataArrayTexture||B.isCompressedArrayTexture)&&(de=r.TEXTURE_2D_ARRAY),B.isData3DTexture&&(de=r.TEXTURE_3D);const ye=Pe(z,B),pe=B.source;t.bindTexture(de,z.__webglTexture,r.TEXTURE0+ne);const nt=i.get(pe);if(pe.version!==nt.__version||ye===!0){t.activeTexture(r.TEXTURE0+ne);const Le=Nt.getPrimaries(Nt.workingColorSpace),Ye=B.colorSpace===ai||B.colorSpace===Fs?null:Nt.getPrimaries(B.colorSpace),yt=B.colorSpace===ai||B.colorSpace===Fs||Le===Ye?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,B.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,B.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,yt);let Me=A(B.image,!1,n.maxTextureSize);Me=ke(B,Me);const je=s.convert(B.format,B.colorSpace),Wt=s.convert(B.type);let st=v(B.internalFormat,je,Wt,B.colorSpace,B.isVideoTexture);we(de,B);let Ge;const wt=B.mipmaps,_t=B.isVideoTexture!==!0,Ht=nt.__version===void 0||ye===!0,j=pe.dataReady,Ie=b(B,Me);if(B.isDepthTexture)st=_(B.format===Zl,B.type),Ht&&(_t?t.texStorage2D(r.TEXTURE_2D,1,st,Me.width,Me.height):t.texImage2D(r.TEXTURE_2D,0,st,Me.width,Me.height,0,je,Wt,null));else if(B.isDataTexture)if(wt.length>0){_t&&Ht&&t.texStorage2D(r.TEXTURE_2D,Ie,st,wt[0].width,wt[0].height);for(let $=0,Ae=wt.length;$<Ae;$++)Ge=wt[$],_t?j&&t.texSubImage2D(r.TEXTURE_2D,$,0,0,Ge.width,Ge.height,je,Wt,Ge.data):t.texImage2D(r.TEXTURE_2D,$,st,Ge.width,Ge.height,0,je,Wt,Ge.data);B.generateMipmaps=!1}else _t?(Ht&&t.texStorage2D(r.TEXTURE_2D,Ie,st,Me.width,Me.height),j&&t.texSubImage2D(r.TEXTURE_2D,0,0,0,Me.width,Me.height,je,Wt,Me.data)):t.texImage2D(r.TEXTURE_2D,0,st,Me.width,Me.height,0,je,Wt,Me.data);else if(B.isCompressedTexture)if(B.isCompressedArrayTexture){_t&&Ht&&t.texStorage3D(r.TEXTURE_2D_ARRAY,Ie,st,wt[0].width,wt[0].height,Me.depth);for(let $=0,Ae=wt.length;$<Ae;$++)if(Ge=wt[$],B.format!==qt)if(je!==null)if(_t){if(j)if(B.layerUpdates.size>0){const Be=zC(Ge.width,Ge.height,B.format,B.type);for(const pt of B.layerUpdates){const Kt=Ge.data.subarray(pt*Be/Ge.data.BYTES_PER_ELEMENT,(pt+1)*Be/Ge.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,$,0,0,pt,Ge.width,Ge.height,1,je,Kt,0,0)}B.clearLayerUpdates()}else t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,$,0,0,0,Ge.width,Ge.height,Me.depth,je,Ge.data,0,0)}else t.compressedTexImage3D(r.TEXTURE_2D_ARRAY,$,st,Ge.width,Ge.height,Me.depth,0,Ge.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else _t?j&&t.texSubImage3D(r.TEXTURE_2D_ARRAY,$,0,0,0,Ge.width,Ge.height,Me.depth,je,Wt,Ge.data):t.texImage3D(r.TEXTURE_2D_ARRAY,$,st,Ge.width,Ge.height,Me.depth,0,je,Wt,Ge.data)}else{_t&&Ht&&t.texStorage2D(r.TEXTURE_2D,Ie,st,wt[0].width,wt[0].height);for(let $=0,Ae=wt.length;$<Ae;$++)Ge=wt[$],B.format!==qt?je!==null?_t?j&&t.compressedTexSubImage2D(r.TEXTURE_2D,$,0,0,Ge.width,Ge.height,je,Ge.data):t.compressedTexImage2D(r.TEXTURE_2D,$,st,Ge.width,Ge.height,0,Ge.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):_t?j&&t.texSubImage2D(r.TEXTURE_2D,$,0,0,Ge.width,Ge.height,je,Wt,Ge.data):t.texImage2D(r.TEXTURE_2D,$,st,Ge.width,Ge.height,0,je,Wt,Ge.data)}else if(B.isDataArrayTexture)if(_t){if(Ht&&t.texStorage3D(r.TEXTURE_2D_ARRAY,Ie,st,Me.width,Me.height,Me.depth),j)if(B.layerUpdates.size>0){const $=zC(Me.width,Me.height,B.format,B.type);for(const Ae of B.layerUpdates){const Be=Me.data.subarray(Ae*$/Me.data.BYTES_PER_ELEMENT,(Ae+1)*$/Me.data.BYTES_PER_ELEMENT);t.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,Ae,Me.width,Me.height,1,je,Wt,Be)}B.clearLayerUpdates()}else t.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,Me.width,Me.height,Me.depth,je,Wt,Me.data)}else t.texImage3D(r.TEXTURE_2D_ARRAY,0,st,Me.width,Me.height,Me.depth,0,je,Wt,Me.data);else if(B.isData3DTexture)_t?(Ht&&t.texStorage3D(r.TEXTURE_3D,Ie,st,Me.width,Me.height,Me.depth),j&&t.texSubImage3D(r.TEXTURE_3D,0,0,0,0,Me.width,Me.height,Me.depth,je,Wt,Me.data)):t.texImage3D(r.TEXTURE_3D,0,st,Me.width,Me.height,Me.depth,0,je,Wt,Me.data);else if(B.isFramebufferTexture){if(Ht)if(_t)t.texStorage2D(r.TEXTURE_2D,Ie,st,Me.width,Me.height);else{let $=Me.width,Ae=Me.height;for(let Be=0;Be<Ie;Be++)t.texImage2D(r.TEXTURE_2D,Be,st,$,Ae,0,je,Wt,null),$>>=1,Ae>>=1}}else if(wt.length>0){if(_t&&Ht){const $=Ve(wt[0]);t.texStorage2D(r.TEXTURE_2D,Ie,st,$.width,$.height)}for(let $=0,Ae=wt.length;$<Ae;$++)Ge=wt[$],_t?j&&t.texSubImage2D(r.TEXTURE_2D,$,0,0,je,Wt,Ge):t.texImage2D(r.TEXTURE_2D,$,st,je,Wt,Ge);B.generateMipmaps=!1}else if(_t){if(Ht){const $=Ve(Me);t.texStorage2D(r.TEXTURE_2D,Ie,st,$.width,$.height)}j&&t.texSubImage2D(r.TEXTURE_2D,0,0,0,je,Wt,Me)}else t.texImage2D(r.TEXTURE_2D,0,st,je,Wt,Me);g(B)&&y(de),nt.__version=pe.version,B.onUpdate&&B.onUpdate(B)}z.__version=B.version}function ie(z,B,ne){if(B.image.length!==6)return;const de=Pe(z,B),ye=B.source;t.bindTexture(r.TEXTURE_CUBE_MAP,z.__webglTexture,r.TEXTURE0+ne);const pe=i.get(ye);if(ye.version!==pe.__version||de===!0){t.activeTexture(r.TEXTURE0+ne);const nt=Nt.getPrimaries(Nt.workingColorSpace),Le=B.colorSpace===ai||B.colorSpace===Fs?null:Nt.getPrimaries(B.colorSpace),Ye=B.colorSpace===ai||B.colorSpace===Fs||nt===Le?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,B.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,B.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ye);const yt=B.isCompressedTexture||B.image[0].isCompressedTexture,Me=B.image[0]&&B.image[0].isDataTexture,je=[];for(let Ae=0;Ae<6;Ae++)!yt&&!Me?je[Ae]=A(B.image[Ae],!0,n.maxCubemapSize):je[Ae]=Me?B.image[Ae].image:B.image[Ae],je[Ae]=ke(B,je[Ae]);const Wt=je[0],st=s.convert(B.format,B.colorSpace),Ge=s.convert(B.type),wt=v(B.internalFormat,st,Ge,B.colorSpace),_t=B.isVideoTexture!==!0,Ht=pe.__version===void 0||de===!0,j=ye.dataReady;let Ie=b(B,Wt);we(r.TEXTURE_CUBE_MAP,B);let $;if(yt){_t&&Ht&&t.texStorage2D(r.TEXTURE_CUBE_MAP,Ie,wt,Wt.width,Wt.height);for(let Ae=0;Ae<6;Ae++){$=je[Ae].mipmaps;for(let Be=0;Be<$.length;Be++){const pt=$[Be];B.format!==qt?st!==null?_t?j&&t.compressedTexSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,Be,0,0,pt.width,pt.height,st,pt.data):t.compressedTexImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,Be,wt,pt.width,pt.height,0,pt.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):_t?j&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,Be,0,0,pt.width,pt.height,st,Ge,pt.data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,Be,wt,pt.width,pt.height,0,st,Ge,pt.data)}}}else{if($=B.mipmaps,_t&&Ht){$.length>0&&Ie++;const Ae=Ve(je[0]);t.texStorage2D(r.TEXTURE_CUBE_MAP,Ie,wt,Ae.width,Ae.height)}for(let Ae=0;Ae<6;Ae++)if(Me){_t?j&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,0,0,0,je[Ae].width,je[Ae].height,st,Ge,je[Ae].data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,0,wt,je[Ae].width,je[Ae].height,0,st,Ge,je[Ae].data);for(let Be=0;Be<$.length;Be++){const Kt=$[Be].image[Ae].image;_t?j&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,Be+1,0,0,Kt.width,Kt.height,st,Ge,Kt.data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,Be+1,wt,Kt.width,Kt.height,0,st,Ge,Kt.data)}}else{_t?j&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,0,0,0,st,Ge,je[Ae]):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,0,wt,st,Ge,je[Ae]);for(let Be=0;Be<$.length;Be++){const pt=$[Be];_t?j&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,Be+1,0,0,st,Ge,pt.image[Ae]):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+Ae,Be+1,wt,st,Ge,pt.image[Ae])}}}g(B)&&y(r.TEXTURE_CUBE_MAP),pe.__version=ye.version,B.onUpdate&&B.onUpdate(B)}z.__version=B.version}function oe(z,B,ne,de,ye,pe){const nt=s.convert(ne.format,ne.colorSpace),Le=s.convert(ne.type),Ye=v(ne.internalFormat,nt,Le,ne.colorSpace);if(!i.get(B).__hasExternalTextures){const Me=Math.max(1,B.width>>pe),je=Math.max(1,B.height>>pe);ye===r.TEXTURE_3D||ye===r.TEXTURE_2D_ARRAY?t.texImage3D(ye,pe,Ye,Me,je,B.depth,0,nt,Le,null):t.texImage2D(ye,pe,Ye,Me,je,0,nt,Le,null)}t.bindFramebuffer(r.FRAMEBUFFER,z),ge(B)?o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,de,ye,i.get(ne).__webglTexture,0,Ne(B)):(ye===r.TEXTURE_2D||ye>=r.TEXTURE_CUBE_MAP_POSITIVE_X&&ye<=r.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&r.framebufferTexture2D(r.FRAMEBUFFER,de,ye,i.get(ne).__webglTexture,pe),t.bindFramebuffer(r.FRAMEBUFFER,null)}function me(z,B,ne){if(r.bindRenderbuffer(r.RENDERBUFFER,z),B.depthBuffer){const de=B.depthTexture,ye=de&&de.isDepthTexture?de.type:null,pe=_(B.stencilBuffer,ye),nt=B.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,Le=Ne(B);ge(B)?o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,Le,pe,B.width,B.height):ne?r.renderbufferStorageMultisample(r.RENDERBUFFER,Le,pe,B.width,B.height):r.renderbufferStorage(r.RENDERBUFFER,pe,B.width,B.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,nt,r.RENDERBUFFER,z)}else{const de=B.textures;for(let ye=0;ye<de.length;ye++){const pe=de[ye],nt=s.convert(pe.format,pe.colorSpace),Le=s.convert(pe.type),Ye=v(pe.internalFormat,nt,Le,pe.colorSpace),yt=Ne(B);ne&&ge(B)===!1?r.renderbufferStorageMultisample(r.RENDERBUFFER,yt,Ye,B.width,B.height):ge(B)?o.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,yt,Ye,B.width,B.height):r.renderbufferStorage(r.RENDERBUFFER,Ye,B.width,B.height)}}r.bindRenderbuffer(r.RENDERBUFFER,null)}function Ce(z,B){if(B&&B.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(r.FRAMEBUFFER,z),!(B.depthTexture&&B.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");(!i.get(B.depthTexture).__webglTexture||B.depthTexture.image.width!==B.width||B.depthTexture.image.height!==B.height)&&(B.depthTexture.image.width=B.width,B.depthTexture.image.height=B.height,B.depthTexture.needsUpdate=!0),N(B.depthTexture,0);const de=i.get(B.depthTexture).__webglTexture,ye=Ne(B);if(B.depthTexture.format===Do)ge(B)?o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,de,0,ye):r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,de,0);else if(B.depthTexture.format===Zl)ge(B)?o.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.TEXTURE_2D,de,0,ye):r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.TEXTURE_2D,de,0);else throw new Error("Unknown depthTexture format")}function Xe(z){const B=i.get(z),ne=z.isWebGLCubeRenderTarget===!0;if(B.__boundDepthTexture!==z.depthTexture){const de=z.depthTexture;if(B.__depthDisposeCallback&&B.__depthDisposeCallback(),de){const ye=()=>{delete B.__boundDepthTexture,delete B.__depthDisposeCallback,de.removeEventListener("dispose",ye)};de.addEventListener("dispose",ye),B.__depthDisposeCallback=ye}B.__boundDepthTexture=de}if(z.depthTexture&&!B.__autoAllocateDepthBuffer){if(ne)throw new Error("target.depthTexture not supported in Cube render targets");Ce(B.__webglFramebuffer,z)}else if(ne){B.__webglDepthbuffer=[];for(let de=0;de<6;de++)if(t.bindFramebuffer(r.FRAMEBUFFER,B.__webglFramebuffer[de]),B.__webglDepthbuffer[de]===void 0)B.__webglDepthbuffer[de]=r.createRenderbuffer(),me(B.__webglDepthbuffer[de],z,!1);else{const ye=z.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,pe=B.__webglDepthbuffer[de];r.bindRenderbuffer(r.RENDERBUFFER,pe),r.framebufferRenderbuffer(r.FRAMEBUFFER,ye,r.RENDERBUFFER,pe)}}else if(t.bindFramebuffer(r.FRAMEBUFFER,B.__webglFramebuffer),B.__webglDepthbuffer===void 0)B.__webglDepthbuffer=r.createRenderbuffer(),me(B.__webglDepthbuffer,z,!1);else{const de=z.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,ye=B.__webglDepthbuffer;r.bindRenderbuffer(r.RENDERBUFFER,ye),r.framebufferRenderbuffer(r.FRAMEBUFFER,de,r.RENDERBUFFER,ye)}t.bindFramebuffer(r.FRAMEBUFFER,null)}function dt(z,B,ne){const de=i.get(z);B!==void 0&&oe(de.__webglFramebuffer,z,z.texture,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,0),ne!==void 0&&Xe(z)}function Ke(z){const B=z.texture,ne=i.get(z),de=i.get(B);z.addEventListener("dispose",E);const ye=z.textures,pe=z.isWebGLCubeRenderTarget===!0,nt=ye.length>1;if(nt||(de.__webglTexture===void 0&&(de.__webglTexture=r.createTexture()),de.__version=B.version,a.memory.textures++),pe){ne.__webglFramebuffer=[];for(let Le=0;Le<6;Le++)if(B.mipmaps&&B.mipmaps.length>0){ne.__webglFramebuffer[Le]=[];for(let Ye=0;Ye<B.mipmaps.length;Ye++)ne.__webglFramebuffer[Le][Ye]=r.createFramebuffer()}else ne.__webglFramebuffer[Le]=r.createFramebuffer()}else{if(B.mipmaps&&B.mipmaps.length>0){ne.__webglFramebuffer=[];for(let Le=0;Le<B.mipmaps.length;Le++)ne.__webglFramebuffer[Le]=r.createFramebuffer()}else ne.__webglFramebuffer=r.createFramebuffer();if(nt)for(let Le=0,Ye=ye.length;Le<Ye;Le++){const yt=i.get(ye[Le]);yt.__webglTexture===void 0&&(yt.__webglTexture=r.createTexture(),a.memory.textures++)}if(z.samples>0&&ge(z)===!1){ne.__webglMultisampledFramebuffer=r.createFramebuffer(),ne.__webglColorRenderbuffer=[],t.bindFramebuffer(r.FRAMEBUFFER,ne.__webglMultisampledFramebuffer);for(let Le=0;Le<ye.length;Le++){const Ye=ye[Le];ne.__webglColorRenderbuffer[Le]=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,ne.__webglColorRenderbuffer[Le]);const yt=s.convert(Ye.format,Ye.colorSpace),Me=s.convert(Ye.type),je=v(Ye.internalFormat,yt,Me,Ye.colorSpace,z.isXRRenderTarget===!0),Wt=Ne(z);r.renderbufferStorageMultisample(r.RENDERBUFFER,Wt,je,z.width,z.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+Le,r.RENDERBUFFER,ne.__webglColorRenderbuffer[Le])}r.bindRenderbuffer(r.RENDERBUFFER,null),z.depthBuffer&&(ne.__webglDepthRenderbuffer=r.createRenderbuffer(),me(ne.__webglDepthRenderbuffer,z,!0)),t.bindFramebuffer(r.FRAMEBUFFER,null)}}if(pe){t.bindTexture(r.TEXTURE_CUBE_MAP,de.__webglTexture),we(r.TEXTURE_CUBE_MAP,B);for(let Le=0;Le<6;Le++)if(B.mipmaps&&B.mipmaps.length>0)for(let Ye=0;Ye<B.mipmaps.length;Ye++)oe(ne.__webglFramebuffer[Le][Ye],z,B,r.COLOR_ATTACHMENT0,r.TEXTURE_CUBE_MAP_POSITIVE_X+Le,Ye);else oe(ne.__webglFramebuffer[Le],z,B,r.COLOR_ATTACHMENT0,r.TEXTURE_CUBE_MAP_POSITIVE_X+Le,0);g(B)&&y(r.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(nt){for(let Le=0,Ye=ye.length;Le<Ye;Le++){const yt=ye[Le],Me=i.get(yt);t.bindTexture(r.TEXTURE_2D,Me.__webglTexture),we(r.TEXTURE_2D,yt),oe(ne.__webglFramebuffer,z,yt,r.COLOR_ATTACHMENT0+Le,r.TEXTURE_2D,0),g(yt)&&y(r.TEXTURE_2D)}t.unbindTexture()}else{let Le=r.TEXTURE_2D;if((z.isWebGL3DRenderTarget||z.isWebGLArrayRenderTarget)&&(Le=z.isWebGL3DRenderTarget?r.TEXTURE_3D:r.TEXTURE_2D_ARRAY),t.bindTexture(Le,de.__webglTexture),we(Le,B),B.mipmaps&&B.mipmaps.length>0)for(let Ye=0;Ye<B.mipmaps.length;Ye++)oe(ne.__webglFramebuffer[Ye],z,B,r.COLOR_ATTACHMENT0,Le,Ye);else oe(ne.__webglFramebuffer,z,B,r.COLOR_ATTACHMENT0,Le,0);g(B)&&y(Le),t.unbindTexture()}z.depthBuffer&&Xe(z)}function gt(z){const B=z.isWebGLMultipleRenderTargets===!0&&Array.isArray(z.texture)?z.texture:z.textures||[z.texture],ne=z.isWebGLCubeRenderTarget?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;for(let de=0,ye=B.length;de<ye;de++){const pe=B[de],nt=i.get(pe),Le=nt.__webglTexture;nt.__version!==pe.version&&(t.bindTexture(ne,Le),we(ne,pe),t.unbindTexture(),nt.__version=pe.version),g(pe)&&(t.bindTexture(ne,Le),y(ne),t.unbindTexture())}}const F=[],xe=[];function be(z){if(z.samples>0){if(ge(z)===!1){const B=z.textures,ne=z.width,de=z.height;let ye=r.COLOR_BUFFER_BIT;const pe=z.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,nt=i.get(z),Le=B.length>1;if(Le)for(let Ye=0;Ye<B.length;Ye++)t.bindFramebuffer(r.FRAMEBUFFER,nt.__webglMultisampledFramebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+Ye,r.RENDERBUFFER,null),t.bindFramebuffer(r.FRAMEBUFFER,nt.__webglFramebuffer),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0+Ye,r.TEXTURE_2D,null,0);t.bindFramebuffer(r.READ_FRAMEBUFFER,nt.__webglMultisampledFramebuffer),t.bindFramebuffer(r.DRAW_FRAMEBUFFER,nt.__webglFramebuffer);for(let Ye=0;Ye<B.length;Ye++){if(z.resolveDepthBuffer&&(z.depthBuffer&&(ye|=r.DEPTH_BUFFER_BIT),z.stencilBuffer&&z.resolveStencilBuffer&&(ye|=r.STENCIL_BUFFER_BIT)),Le){r.framebufferRenderbuffer(r.READ_FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.RENDERBUFFER,nt.__webglColorRenderbuffer[Ye]);const yt=i.get(B[Ye]).__webglTexture;r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,yt,0)}r.blitFramebuffer(0,0,ne,de,0,0,ne,de,ye,r.NEAREST),l===!0&&(F.length=0,xe.length=0,F.push(r.COLOR_ATTACHMENT0+Ye),z.depthBuffer&&z.resolveDepthBuffer===!1&&(F.push(pe),xe.push(pe),r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER,xe)),r.invalidateFramebuffer(r.READ_FRAMEBUFFER,F))}if(t.bindFramebuffer(r.READ_FRAMEBUFFER,null),t.bindFramebuffer(r.DRAW_FRAMEBUFFER,null),Le)for(let Ye=0;Ye<B.length;Ye++){t.bindFramebuffer(r.FRAMEBUFFER,nt.__webglMultisampledFramebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+Ye,r.RENDERBUFFER,nt.__webglColorRenderbuffer[Ye]);const yt=i.get(B[Ye]).__webglTexture;t.bindFramebuffer(r.FRAMEBUFFER,nt.__webglFramebuffer),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0+Ye,r.TEXTURE_2D,yt,0)}t.bindFramebuffer(r.DRAW_FRAMEBUFFER,nt.__webglMultisampledFramebuffer)}else if(z.depthBuffer&&z.resolveDepthBuffer===!1&&l){const B=z.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT;r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER,[B])}}}function Ne(z){return Math.min(n.maxSamples,z.samples)}function ge(z){const B=i.get(z);return z.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&B.__useRenderToTexture!==!1}function ut(z){const B=a.render.frame;h.get(z)!==B&&(h.set(z,B),z.update())}function ke(z,B){const ne=z.colorSpace,de=z.format,ye=z.type;return z.isCompressedTexture===!0||z.isVideoTexture===!0||ne!==Bt&&ne!==ai&&(Nt.getTransfer(ne)===Ci?(de!==qt||ye!==Qt)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):ne===Fs||console.error("THREE.WebGLTextures: Unsupported texture color space:",ne)),B}function Ve(z){return typeof HTMLImageElement<"u"&&z instanceof HTMLImageElement?(c.width=z.naturalWidth||z.width,c.height=z.naturalHeight||z.height):typeof VideoFrame<"u"&&z instanceof VideoFrame?(c.width=z.displayWidth,c.height=z.displayHeight):(c.width=z.width,c.height=z.height),c}this.allocateTextureUnit=U,this.resetTextureUnits=D,this.setTexture2D=N,this.setTexture2DArray=H,this.setTexture3D=V,this.setTextureCube=X,this.rebindTextures=dt,this.setupRenderTarget=Ke,this.updateRenderTargetMipmap=gt,this.updateMultisampleRenderTarget=be,this.setupDepthRenderbuffer=Xe,this.setupFrameBufferTexture=oe,this.useMultisampledRTT=ge}function VC(r,e){function t(i,n=ai){let s;const a=Nt.getTransfer(n);if(i===Qt)return r.UNSIGNED_BYTE;if(i===Af)return r.UNSIGNED_SHORT_4_4_4_4;if(i===yf)return r.UNSIGNED_SHORT_5_5_5_1;if(i===Iw)return r.UNSIGNED_INT_5_9_9_9_REV;if(i===LA)return r.BYTE;if(i===OA)return r.SHORT;if(i===Jl)return r.UNSIGNED_SHORT;if(i===gf)return r.INT;if(i===tr)return r.UNSIGNED_INT;if(i===Ut)return r.FLOAT;if(i===Yt)return r.HALF_FLOAT;if(i===Pw)return r.ALPHA;if(i===Dw)return r.RGB;if(i===qt)return r.RGBA;if(i===Rw)return r.LUMINANCE;if(i===Bw)return r.LUMINANCE_ALPHA;if(i===Do)return r.DEPTH_COMPONENT;if(i===Zl)return r.DEPTH_STENCIL;if(i===Jr)return r.RED;if(i===_f)return r.RED_INTEGER;if(i===Ro)return r.RG;if(i===UA)return r.RG_INTEGER;if(i===FA)return r.RGBA_INTEGER;if(i===vf||i===Zh||i===bf||i===eu)if(a===Ci)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===vf)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Zh)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===bf)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===eu)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===vf)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Zh)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===bf)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===eu)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===wf||i===NA||i===Cf||i===kA)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===wf)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===NA)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Cf)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===kA)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===xf||i===Sf||i===Ef)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(i===xf||i===Sf)return a===Ci?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===Ef)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===Mf||i===GA||i===zA||i===VA||i===tu||i===HA||i===QA||i===jA||i===WA||i===qA||i===XA||i===YA||i===$A||i===KA)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(i===Mf)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===GA)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===zA)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===VA)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===tu)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===HA)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===QA)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===jA)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===WA)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===qA)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===XA)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===YA)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===$A)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===KA)return a===Ci?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===iu||i===JA||i===ZA)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(i===iu)return a===Ci?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===JA)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===ZA)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===Lw||i===ey||i===ty||i===iy)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(i===iu)return s.COMPRESSED_RED_RGTC1_EXT;if(i===ey)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===ty)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===iy)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===Po?r.UNSIGNED_INT_24_8:r[i]!==void 0?r[i]:null}return{convert:t}}class HC extends zi{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class Vi extends ft{constructor(){super(),this.isGroup=!0,this.type="Group"}}const YL={type:"move"};class Vy{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Vi,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 Vi,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new S,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new S),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Vi,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new S,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new S),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}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,i){let n=null,s=null,a=null;const o=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){a=!0;for(const A of e.hand.values()){const g=t.getJointPose(A,i),y=this._getHandJoint(c,A);g!==null&&(y.matrix.fromArray(g.transform.matrix),y.matrix.decompose(y.position,y.rotation,y.scale),y.matrixWorldNeedsUpdate=!0,y.jointRadius=g.radius),y.visible=g!==null}const h=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],d=h.position.distanceTo(u.position),p=.02,m=.005;c.inputState.pinching&&d>p+m?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=p-m&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,i),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1));o!==null&&(n=t.getPose(e.targetRaySpace,i),n===null&&s!==null&&(n=s),n!==null&&(o.matrix.fromArray(n.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,n.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(n.linearVelocity)):o.hasLinearVelocity=!1,n.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(n.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(YL)))}return o!==null&&(o.visible=n!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Vi;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}const $L=`
void main() {

	gl_Position = vec4( position, 1.0 );

}`,KL=`
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;

void main() {

	vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );

	if ( coord.x >= 1.0 ) {

		gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;

	} else {

		gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;

	}

}`;class JL{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,i){if(this.texture===null){const n=new kt,s=e.properties.get(n);s.__webglTexture=t.texture,(t.depthNear!=i.depthNear||t.depthFar!=i.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new nn({vertexShader:$L,fragmentShader:KL,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new _e(new ca(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class ZL extends xi{constructor(e,t){super();const i=this;let n=null,s=1,a=null,o="local-floor",l=1,c=null,h=null,u=null,d=null,p=null,m=null;const A=new JL,g=t.getContextAttributes();let y=null,v=null;const _=[],b=[],T=new K;let E=null;const M=new zi;M.layers.enable(1),M.viewport=new et;const I=new zi;I.layers.enable(2),I.viewport=new et;const C=[M,I],x=new HC;x.layers.enable(1),x.layers.enable(2);let D=null,U=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(ie){let oe=_[ie];return oe===void 0&&(oe=new Vy,_[ie]=oe),oe.getTargetRaySpace()},this.getControllerGrip=function(ie){let oe=_[ie];return oe===void 0&&(oe=new Vy,_[ie]=oe),oe.getGripSpace()},this.getHand=function(ie){let oe=_[ie];return oe===void 0&&(oe=new Vy,_[ie]=oe),oe.getHandSpace()};function O(ie){const oe=b.indexOf(ie.inputSource);if(oe===-1)return;const me=_[oe];me!==void 0&&(me.update(ie.inputSource,ie.frame,c||a),me.dispatchEvent({type:ie.type,data:ie.inputSource}))}function N(){n.removeEventListener("select",O),n.removeEventListener("selectstart",O),n.removeEventListener("selectend",O),n.removeEventListener("squeeze",O),n.removeEventListener("squeezestart",O),n.removeEventListener("squeezeend",O),n.removeEventListener("end",N),n.removeEventListener("inputsourceschange",H);for(let ie=0;ie<_.length;ie++){const oe=b[ie];oe!==null&&(b[ie]=null,_[ie].disconnect(oe))}D=null,U=null,A.reset(),e.setRenderTarget(y),p=null,d=null,u=null,n=null,v=null,Qe.stop(),i.isPresenting=!1,e.setPixelRatio(E),e.setSize(T.width,T.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(ie){s=ie,i.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(ie){o=ie,i.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(ie){c=ie},this.getBaseLayer=function(){return d!==null?d:p},this.getBinding=function(){return u},this.getFrame=function(){return m},this.getSession=function(){return n},this.setSession=async function(ie){if(n=ie,n!==null){if(y=e.getRenderTarget(),n.addEventListener("select",O),n.addEventListener("selectstart",O),n.addEventListener("selectend",O),n.addEventListener("squeeze",O),n.addEventListener("squeezestart",O),n.addEventListener("squeezeend",O),n.addEventListener("end",N),n.addEventListener("inputsourceschange",H),g.xrCompatible!==!0&&await t.makeXRCompatible(),E=e.getPixelRatio(),e.getSize(T),n.renderState.layers===void 0){const oe={antialias:g.antialias,alpha:!0,depth:g.depth,stencil:g.stencil,framebufferScaleFactor:s};p=new XRWebGLLayer(n,t,oe),n.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),v=new ds(p.framebufferWidth,p.framebufferHeight,{format:qt,type:Qt,colorSpace:e.outputColorSpace,stencilBuffer:g.stencil})}else{let oe=null,me=null,Ce=null;g.depth&&(Ce=g.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,oe=g.stencil?Zl:Do,me=g.stencil?Po:tr);const Xe={colorFormat:t.RGBA8,depthFormat:Ce,scaleFactor:s};u=new XRWebGLBinding(n,t),d=u.createProjectionLayer(Xe),n.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),v=new ds(d.textureWidth,d.textureHeight,{format:qt,type:Qt,depthTexture:new ap(d.textureWidth,d.textureHeight,me,void 0,void 0,void 0,void 0,void 0,void 0,oe),stencilBuffer:g.stencil,colorSpace:e.outputColorSpace,samples:g.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1})}v.isXRRenderTarget=!0,this.setFoveation(l),c=null,a=await n.requestReferenceSpace(o),Qe.setContext(n),Qe.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(n!==null)return n.environmentBlendMode},this.getDepthTexture=function(){return A.getDepthTexture()};function H(ie){for(let oe=0;oe<ie.removed.length;oe++){const me=ie.removed[oe],Ce=b.indexOf(me);Ce>=0&&(b[Ce]=null,_[Ce].disconnect(me))}for(let oe=0;oe<ie.added.length;oe++){const me=ie.added[oe];let Ce=b.indexOf(me);if(Ce===-1){for(let dt=0;dt<_.length;dt++)if(dt>=b.length){b.push(me),Ce=dt;break}else if(b[dt]===null){b[dt]=me,Ce=dt;break}if(Ce===-1)break}const Xe=_[Ce];Xe&&Xe.connect(me)}}const V=new S,X=new S;function W(ie,oe,me){V.setFromMatrixPosition(oe.matrixWorld),X.setFromMatrixPosition(me.matrixWorld);const Ce=V.distanceTo(X),Xe=oe.projectionMatrix.elements,dt=me.projectionMatrix.elements,Ke=Xe[14]/(Xe[10]-1),gt=Xe[14]/(Xe[10]+1),F=(Xe[9]+1)/Xe[5],xe=(Xe[9]-1)/Xe[5],be=(Xe[8]-1)/Xe[0],Ne=(dt[8]+1)/dt[0],ge=Ke*be,ut=Ke*Ne,ke=Ce/(-be+Ne),Ve=ke*-be;if(oe.matrixWorld.decompose(ie.position,ie.quaternion,ie.scale),ie.translateX(Ve),ie.translateZ(ke),ie.matrixWorld.compose(ie.position,ie.quaternion,ie.scale),ie.matrixWorldInverse.copy(ie.matrixWorld).invert(),Xe[10]===-1)ie.projectionMatrix.copy(oe.projectionMatrix),ie.projectionMatrixInverse.copy(oe.projectionMatrixInverse);else{const z=Ke+ke,B=gt+ke,ne=ge-Ve,de=ut+(Ce-Ve),ye=F*gt/B*z,pe=xe*gt/B*z;ie.projectionMatrix.makePerspective(ne,de,ye,pe,z,B),ie.projectionMatrixInverse.copy(ie.projectionMatrix).invert()}}function ce(ie,oe){oe===null?ie.matrixWorld.copy(ie.matrix):ie.matrixWorld.multiplyMatrices(oe.matrixWorld,ie.matrix),ie.matrixWorldInverse.copy(ie.matrixWorld).invert()}this.updateCamera=function(ie){if(n===null)return;let oe=ie.near,me=ie.far;A.texture!==null&&(A.depthNear>0&&(oe=A.depthNear),A.depthFar>0&&(me=A.depthFar)),x.near=I.near=M.near=oe,x.far=I.far=M.far=me,(D!==x.near||U!==x.far)&&(n.updateRenderState({depthNear:x.near,depthFar:x.far}),D=x.near,U=x.far);const Ce=ie.parent,Xe=x.cameras;ce(x,Ce);for(let dt=0;dt<Xe.length;dt++)ce(Xe[dt],Ce);Xe.length===2?W(x,M,I):x.projectionMatrix.copy(M.projectionMatrix),ue(ie,x,Ce)};function ue(ie,oe,me){me===null?ie.matrix.copy(oe.matrixWorld):(ie.matrix.copy(me.matrixWorld),ie.matrix.invert(),ie.matrix.multiply(oe.matrixWorld)),ie.matrix.decompose(ie.position,ie.quaternion,ie.scale),ie.updateMatrixWorld(!0),ie.projectionMatrix.copy(oe.projectionMatrix),ie.projectionMatrixInverse.copy(oe.projectionMatrixInverse),ie.isPerspectiveCamera&&(ie.fov=rc*2*Math.atan(1/ie.projectionMatrix.elements[5]),ie.zoom=1)}this.getCamera=function(){return x},this.getFoveation=function(){if(!(d===null&&p===null))return l},this.setFoveation=function(ie){l=ie,d!==null&&(d.fixedFoveation=ie),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=ie)},this.hasDepthSensing=function(){return A.texture!==null},this.getDepthSensingMesh=function(){return A.getMesh(x)};let we=null;this.onPreAnimationFrameCallback=null;function Pe(ie,oe){if(i.onPreAnimationFrameCallback&&i.onPreAnimationFrameCallback(ie,oe),h=oe.getViewerPose(c||a),m=oe,h!==null){const me=h.views;p!==null&&(e.setRenderTargetFramebuffer(v,p.framebuffer),e.setRenderTarget(v));let Ce=!1;me.length!==x.cameras.length&&(x.cameras.length=0,Ce=!0);for(let dt=0;dt<me.length;dt++){const Ke=me[dt];let gt=null;if(p!==null)gt=p.getViewport(Ke);else{const xe=u.getViewSubImage(d,Ke);gt=xe.viewport,dt===0&&(e.setRenderTargetTextures(v,xe.colorTexture,d.ignoreDepthValues?void 0:xe.depthStencilTexture),e.setRenderTarget(v))}let F=C[dt];F===void 0&&(F=new zi,F.layers.enable(dt),F.viewport=new et,C[dt]=F),F.matrix.fromArray(Ke.transform.matrix),F.matrix.decompose(F.position,F.quaternion,F.scale),F.projectionMatrix.fromArray(Ke.projectionMatrix),F.projectionMatrixInverse.copy(F.projectionMatrix).invert(),F.viewport.set(gt.x,gt.y,gt.width,gt.height),dt===0&&(x.matrix.copy(F.matrix),x.matrix.decompose(x.position,x.quaternion,x.scale)),Ce===!0&&x.cameras.push(F)}const Xe=n.enabledFeatures;if(Xe&&Xe.includes("depth-sensing")){const dt=u.getDepthInformation(me[0]);dt&&dt.isValid&&dt.texture&&A.init(e,dt,n.renderState)}}for(let me=0;me<_.length;me++){const Ce=b[me],Xe=_[me];Ce!==null&&Xe!==void 0&&Xe.update(Ce,oe,c||a)}we&&we(ie,oe),oe.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:oe}),m=null}const Qe=new fC;Qe.setAnimationLoop(Pe),this.setAnimationLoop=function(ie){we=ie},this.dispose=function(){}}}const Ho=new Pt,eO=new fe;function tO(r,e){function t(g,y){g.matrixAutoUpdate===!0&&g.updateMatrix(),y.value.copy(g.matrix)}function i(g,y){y.color.getRGB(g.fogColor.value,cC(r)),y.isFog?(g.fogNear.value=y.near,g.fogFar.value=y.far):y.isFogExp2&&(g.fogDensity.value=y.density)}function n(g,y,v,_,b){y.isMeshBasicMaterial||y.isMeshLambertMaterial?s(g,y):y.isMeshToonMaterial?(s(g,y),u(g,y)):y.isMeshPhongMaterial?(s(g,y),h(g,y)):y.isMeshStandardMaterial?(s(g,y),d(g,y),y.isMeshPhysicalMaterial&&p(g,y,b)):y.isMeshMatcapMaterial?(s(g,y),m(g,y)):y.isMeshDepthMaterial?s(g,y):y.isMeshDistanceMaterial?(s(g,y),A(g,y)):y.isMeshNormalMaterial?s(g,y):y.isLineBasicMaterial?(a(g,y),y.isLineDashedMaterial&&o(g,y)):y.isPointsMaterial?l(g,y,v,_):y.isSpriteMaterial?c(g,y):y.isShadowMaterial?(g.color.value.copy(y.color),g.opacity.value=y.opacity):y.isShaderMaterial&&(y.transmission!==void 0&&(g.transmission&&(g.transmission.value=y.transmission),g.transmissionSamplerMap&&b&&(g.transmissionSamplerMap.value=b?b.texture:null),g.transmissionSamplerSize&&b&&g.transmissionSamplerSize.value.set(b.width,b.height)),y.uniformsNeedUpdate=!1)}function s(g,y){g.opacity.value=y.opacity,y.color&&g.diffuse.value.copy(y.color),y.emissive&&g.emissive.value.copy(y.emissive).multiplyScalar(y.emissiveIntensity),y.map&&(g.map.value=y.map,t(y.map,g.mapTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,t(y.alphaMap,g.alphaMapTransform)),y.bumpMap&&(g.bumpMap.value=y.bumpMap,t(y.bumpMap,g.bumpMapTransform),g.bumpScale.value=y.bumpScale,y.side===In&&(g.bumpScale.value*=-1)),y.normalMap&&(g.normalMap.value=y.normalMap,t(y.normalMap,g.normalMapTransform),g.normalScale.value.copy(y.normalScale),y.side===In&&g.normalScale.value.negate()),y.displacementMap&&(g.displacementMap.value=y.displacementMap,t(y.displacementMap,g.displacementMapTransform),g.displacementScale.value=y.displacementScale,g.displacementBias.value=y.displacementBias),y.emissiveMap&&(g.emissiveMap.value=y.emissiveMap,t(y.emissiveMap,g.emissiveMapTransform)),y.specularMap&&(g.specularMap.value=y.specularMap,t(y.specularMap,g.specularMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest);const v=e.get(y),_=v.envMap,b=v.envMapRotation;_&&(g.envMap.value=_,Ho.copy(b),Ho.x*=-1,Ho.y*=-1,Ho.z*=-1,_.isCubeTexture&&_.isRenderTargetTexture===!1&&(Ho.y*=-1,Ho.z*=-1),g.envMapRotation.value.setFromMatrix4(eO.makeRotationFromEuler(Ho)),g.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=y.reflectivity,g.ior.value=y.ior,g.refractionRatio.value=y.refractionRatio),y.lightMap&&(g.lightMap.value=y.lightMap,g.lightMapIntensity.value=y.lightMapIntensity,t(y.lightMap,g.lightMapTransform)),y.aoMap&&(g.aoMap.value=y.aoMap,g.aoMapIntensity.value=y.aoMapIntensity,t(y.aoMap,g.aoMapTransform))}function a(g,y){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,y.map&&(g.map.value=y.map,t(y.map,g.mapTransform))}function o(g,y){g.dashSize.value=y.dashSize,g.totalSize.value=y.dashSize+y.gapSize,g.scale.value=y.scale}function l(g,y,v,_){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,g.size.value=y.size*v,g.scale.value=_*.5,y.map&&(g.map.value=y.map,t(y.map,g.uvTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,t(y.alphaMap,g.alphaMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest)}function c(g,y){g.diffuse.value.copy(y.color),g.opacity.value=y.opacity,g.rotation.value=y.rotation,y.map&&(g.map.value=y.map,t(y.map,g.mapTransform)),y.alphaMap&&(g.alphaMap.value=y.alphaMap,t(y.alphaMap,g.alphaMapTransform)),y.alphaTest>0&&(g.alphaTest.value=y.alphaTest)}function h(g,y){g.specular.value.copy(y.specular),g.shininess.value=Math.max(y.shininess,1e-4)}function u(g,y){y.gradientMap&&(g.gradientMap.value=y.gradientMap)}function d(g,y){g.metalness.value=y.metalness,y.metalnessMap&&(g.metalnessMap.value=y.metalnessMap,t(y.metalnessMap,g.metalnessMapTransform)),g.roughness.value=y.roughness,y.roughnessMap&&(g.roughnessMap.value=y.roughnessMap,t(y.roughnessMap,g.roughnessMapTransform)),y.envMap&&(g.envMapIntensity.value=y.envMapIntensity)}function p(g,y,v){g.ior.value=y.ior,y.sheen>0&&(g.sheenColor.value.copy(y.sheenColor).multiplyScalar(y.sheen),g.sheenRoughness.value=y.sheenRoughness,y.sheenColorMap&&(g.sheenColorMap.value=y.sheenColorMap,t(y.sheenColorMap,g.sheenColorMapTransform)),y.sheenRoughnessMap&&(g.sheenRoughnessMap.value=y.sheenRoughnessMap,t(y.sheenRoughnessMap,g.sheenRoughnessMapTransform))),y.clearcoat>0&&(g.clearcoat.value=y.clearcoat,g.clearcoatRoughness.value=y.clearcoatRoughness,y.clearcoatMap&&(g.clearcoatMap.value=y.clearcoatMap,t(y.clearcoatMap,g.clearcoatMapTransform)),y.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=y.clearcoatRoughnessMap,t(y.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),y.clearcoatNormalMap&&(g.clearcoatNormalMap.value=y.clearcoatNormalMap,t(y.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(y.clearcoatNormalScale),y.side===In&&g.clearcoatNormalScale.value.negate())),y.dispersion>0&&(g.dispersion.value=y.dispersion),y.iridescence>0&&(g.iridescence.value=y.iridescence,g.iridescenceIOR.value=y.iridescenceIOR,g.iridescenceThicknessMinimum.value=y.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=y.iridescenceThicknessRange[1],y.iridescenceMap&&(g.iridescenceMap.value=y.iridescenceMap,t(y.iridescenceMap,g.iridescenceMapTransform)),y.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=y.iridescenceThicknessMap,t(y.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),y.transmission>0&&(g.transmission.value=y.transmission,g.transmissionSamplerMap.value=v.texture,g.transmissionSamplerSize.value.set(v.width,v.height),y.transmissionMap&&(g.transmissionMap.value=y.transmissionMap,t(y.transmissionMap,g.transmissionMapTransform)),g.thickness.value=y.thickness,y.thicknessMap&&(g.thicknessMap.value=y.thicknessMap,t(y.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=y.attenuationDistance,g.attenuationColor.value.copy(y.attenuationColor)),y.anisotropy>0&&(g.anisotropyVector.value.set(y.anisotropy*Math.cos(y.anisotropyRotation),y.anisotropy*Math.sin(y.anisotropyRotation)),y.anisotropyMap&&(g.anisotropyMap.value=y.anisotropyMap,t(y.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=y.specularIntensity,g.specularColor.value.copy(y.specularColor),y.specularColorMap&&(g.specularColorMap.value=y.specularColorMap,t(y.specularColorMap,g.specularColorMapTransform)),y.specularIntensityMap&&(g.specularIntensityMap.value=y.specularIntensityMap,t(y.specularIntensityMap,g.specularIntensityMapTransform))}function m(g,y){y.matcap&&(g.matcap.value=y.matcap)}function A(g,y){const v=e.get(y).light;g.referencePosition.value.setFromMatrixPosition(v.matrixWorld),g.nearDistance.value=v.shadow.camera.near,g.farDistance.value=v.shadow.camera.far}return{refreshTransformUniform:t,refreshFogUniforms:i,refreshMaterialUniforms:n}}function iO(r,e,t,i){let n={},s={},a=[];const o=r.getParameter(r.MAX_UNIFORM_BUFFER_BINDINGS);function l(v,_){const b=_.program;i.uniformBlockBinding(v,b)}function c(v,_){let b=n[v.id];b===void 0&&(m(v),b=h(v),n[v.id]=b,v.addEventListener("dispose",g));const T=_.program;i.updateUBOMapping(v,T);const E=e.render.frame;s[v.id]!==E&&(d(v),s[v.id]=E)}function h(v){const _=u();v.__bindingPointIndex=_;const b=r.createBuffer(),T=v.__size,E=v.usage;return r.bindBuffer(r.UNIFORM_BUFFER,b),r.bufferData(r.UNIFORM_BUFFER,T,E),r.bindBuffer(r.UNIFORM_BUFFER,null),r.bindBufferBase(r.UNIFORM_BUFFER,_,b),b}function u(){for(let v=0;v<o;v++)if(a.indexOf(v)===-1)return a.push(v),v;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(v){const _=n[v.id],b=v.uniforms,T=v.__cache;r.bindBuffer(r.UNIFORM_BUFFER,_);for(let E=0,M=b.length;E<M;E++){const I=Array.isArray(b[E])?b[E]:[b[E]];for(let C=0,x=I.length;C<x;C++){const D=I[C];if(p(D,E,C,T)===!0){const U=D.__offset,O=Array.isArray(D.value)?D.value:[D.value];let N=0;for(let H=0;H<O.length;H++){const V=O[H],X=A(V);typeof V=="number"||typeof V=="boolean"?(D.__data[0]=V,r.bufferSubData(r.UNIFORM_BUFFER,U+N,D.__data)):V.isMatrix3?(D.__data[0]=V.elements[0],D.__data[1]=V.elements[1],D.__data[2]=V.elements[2],D.__data[3]=0,D.__data[4]=V.elements[3],D.__data[5]=V.elements[4],D.__data[6]=V.elements[5],D.__data[7]=0,D.__data[8]=V.elements[6],D.__data[9]=V.elements[7],D.__data[10]=V.elements[8],D.__data[11]=0):(V.toArray(D.__data,N),N+=X.storage/Float32Array.BYTES_PER_ELEMENT)}r.bufferSubData(r.UNIFORM_BUFFER,U,D.__data)}}}r.bindBuffer(r.UNIFORM_BUFFER,null)}function p(v,_,b,T){const E=v.value,M=_+"_"+b;if(T[M]===void 0)return typeof E=="number"||typeof E=="boolean"?T[M]=E:T[M]=E.clone(),!0;{const I=T[M];if(typeof E=="number"||typeof E=="boolean"){if(I!==E)return T[M]=E,!0}else if(I.equals(E)===!1)return I.copy(E),!0}return!1}function m(v){const _=v.uniforms;let b=0;const T=16;for(let M=0,I=_.length;M<I;M++){const C=Array.isArray(_[M])?_[M]:[_[M]];for(let x=0,D=C.length;x<D;x++){const U=C[x],O=Array.isArray(U.value)?U.value:[U.value];for(let N=0,H=O.length;N<H;N++){const V=O[N],X=A(V),W=b%T,ce=W%X.boundary,ue=W+ce;b+=ce,ue!==0&&T-ue<X.storage&&(b+=T-ue),U.__data=new Float32Array(X.storage/Float32Array.BYTES_PER_ELEMENT),U.__offset=b,b+=X.storage}}}const E=b%T;return E>0&&(b+=T-E),v.__size=b,v.__cache={},this}function A(v){const _={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(_.boundary=4,_.storage=4):v.isVector2?(_.boundary=8,_.storage=8):v.isVector3||v.isColor?(_.boundary=16,_.storage=12):v.isVector4?(_.boundary=16,_.storage=16):v.isMatrix3?(_.boundary=48,_.storage=48):v.isMatrix4?(_.boundary=64,_.storage=64):v.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",v),_}function g(v){const _=v.target;_.removeEventListener("dispose",g);const b=a.indexOf(_.__bindingPointIndex);a.splice(b,1),r.deleteBuffer(n[_.id]),delete n[_.id],delete s[_.id]}function y(){for(const v in n)r.deleteBuffer(n[v]);a=[],n={},s={}}return{bind:l,update:c,dispose:y}}class hp{constructor(e={}){const{canvas:t=ED(),context:i=null,depth:n=!0,stencil:s=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1}=e;this.isWebGLRenderer=!0;let d;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");d=i.getContextAttributes().alpha}else d=a;const p=new Uint32Array(4),m=new Int32Array(4);let A=null,g=null;const y=[],v=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=Ct,this.toneMapping=Xr,this.toneMappingExposure=1,this.userData={},this.onContextLost=()=>{},this.onContextRestore=()=>{},this.onContextCreationError=()=>{};const _=this;let b=!1,T=0,E=0,M=null,I=-1,C=null;const x=new et,D=new et;let U=null;const O=new ee(0);let N=0,H=t.width,V=t.height,X=1,W=null,ce=null;const ue=new et(0,0,H,V),we=new et(0,0,H,V);let Pe=!1;const Qe=new pu;let ie=!1,oe=!1;const me=new fe,Ce=new S,Xe=new et,dt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Ke=!1;function gt(){return M===null?X:1}let F=i;function xe(L,q){return t.getContext(L,q)}try{const L={alpha:!0,depth:n,stencil:s,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine","three.js r168"),t.addEventListener("webglcontextlost",$,!1),t.addEventListener("webglcontextrestored",Ae,!1),t.addEventListener("webglcontextcreationerror",Be,!1),F===null){const q="webgl2";if(F=xe(q,L),F===null)throw xe(q)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(L){throw console.error("THREE.WebGLRenderer: "+L.message),L}let be,Ne,ge,ut,ke,Ve,z,B,ne,de,ye,pe,nt,Le,Ye,yt,Me,je,Wt,st,Ge,wt,_t,Ht;function j(){be=new d2(F),be.init(),wt=new VC(F,be),Ne=new a2(F,be,e,wt),ge=new WL(F),ut=new m2(F),ke=new LL,Ve=new XL(F,be,ge,ke,Ne,wt,ut),z=new l2(_),B=new u2(_),ne=new iR(F),_t=new s2(F,ne),de=new f2(F,ne,ut,_t),ye=new A2(F,de,ne,ut),Wt=new g2(F,Ne,Ve),yt=new o2(ke),pe=new BL(_,z,B,be,Ne,_t,yt),nt=new tO(_,ke),Le=new UL,Ye=new VL(be),je=new n2(_,z,B,ge,ye,d,l),Me=new jL(_,ye,Ne),Ht=new iO(F,ut,Ne,ge),st=new r2(F,be,ut),Ge=new p2(F,be,ut),ut.programs=pe.programs,_.capabilities=Ne,_.extensions=be,_.properties=ke,_.renderLists=Le,_.shadowMap=Me,_.state=ge,_.info=ut,_.background=je,_.cubemaps=z,_.cubeuvmaps=B,_.materials=nt}j();const Ie=new ZL(_,F);this.xr=Ie,this.getContext=function(){return F},this.getContextAttributes=function(){return F.getContextAttributes()},this.forceContextLoss=function(){const L=be.get("WEBGL_lose_context");L&&L.loseContext()},this.forceContextRestore=function(){const L=be.get("WEBGL_lose_context");L&&L.restoreContext()},this.getPixelRatio=function(){return X},this.setPixelRatio=function(L){L!==void 0&&(X=L,this.setSize(H,V,!1))},this.getSize=function(L){return L.set(H,V)},this.setSize=function(L,q,w=!0){if(Ie.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}H=L,V=q,t.width=Math.floor(L*X),t.height=Math.floor(q*X),w===!0&&(t.style.width=L+"px",t.style.height=q+"px"),this.setViewport(0,0,L,q)},this.getDrawingBufferSize=function(L){return L.set(H*X,V*X).floor()},this.setDrawingBufferSize=function(L,q,w){H=L,V=q,X=w,t.width=Math.floor(L*w),t.height=Math.floor(q*w),this.setViewport(0,0,L,q)},this.getCurrentViewport=function(L){return L.copy(x)},this.getViewport=function(L){return L.copy(ue)},this.setViewport=function(L,q,w,P){L.isVector4?ue.set(L.x,L.y,L.z,L.w):ue.set(L,q,w,P),ge.viewport(x.copy(ue).multiplyScalar(X).round())},this.getScissor=function(L){return L.copy(we)},this.setScissor=function(L,q,w,P){L.isVector4?we.set(L.x,L.y,L.z,L.w):we.set(L,q,w,P),ge.scissor(D.copy(we).multiplyScalar(X).round())},this.getScissorTest=function(){return Pe},this.setScissorTest=function(L){ge.setScissorTest(Pe=L)},this.setOpaqueSort=function(L){W=L},this.setTransparentSort=function(L){ce=L},this.getClearColor=function(L){return L.copy(je.getClearColor())},this.setClearColor=function(){je.setClearColor.apply(je,arguments)},this.getClearAlpha=function(){return je.getClearAlpha()},this.setClearAlpha=function(){je.setClearAlpha.apply(je,arguments)},this.clear=function(L=!0,q=!0,w=!0){let P=0;if(L){let R=!1;if(M!==null){const k=M.texture.format;R=k===FA||k===UA||k===_f}if(R){const k=M.texture.type,Y=k===Qt||k===tr||k===Jl||k===Po||k===Af||k===yf,Q=je.getClearColor(),Z=je.getClearAlpha(),ae=Q.r,te=Q.g,J=Q.b;Y?(p[0]=ae,p[1]=te,p[2]=J,p[3]=Z,F.clearBufferuiv(F.COLOR,0,p)):(m[0]=ae,m[1]=te,m[2]=J,m[3]=Z,F.clearBufferiv(F.COLOR,0,m))}else P|=F.COLOR_BUFFER_BIT}q&&(P|=F.DEPTH_BUFFER_BIT),w&&(P|=F.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),F.clear(P)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",$,!1),t.removeEventListener("webglcontextrestored",Ae,!1),t.removeEventListener("webglcontextcreationerror",Be,!1),Le.dispose(),Ye.dispose(),ke.dispose(),z.dispose(),B.dispose(),ye.dispose(),_t.dispose(),Ht.dispose(),pe.dispose(),Ie.dispose(),Ie.removeEventListener("sessionstart",Zs),Ie.removeEventListener("sessionend",pA),Fa.stop()};function $(L){L.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),b=!0,_.onContextLost(L)}function Ae(){console.log("THREE.WebGLRenderer: Context Restored."),b=!1;const L=_.info?_.info.autoReset:void 0,q=Me.enabled,w=Me.autoUpdate,P=Me.needsUpdate,R=Me.type;j(),_.info&&L!==void 0&&(_.info.autoReset=L),Me.enabled=q,Me.autoUpdate=w,Me.needsUpdate=P,Me.type=R,_.onContextRestore&&_.onContextRestore()}function Be(L){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",L.statusMessage),_.onContextCreationError(L)}function pt(L){const q=L.target;q.removeEventListener("dispose",pt),Kt(q)}function Kt(L){Ji(L),ke.remove(L)}function Ji(L){const q=ke.get(L).programs;q!==void 0&&(q.forEach(function(w){pe.releaseProgram(w)}),L.isShaderMaterial&&pe.releaseShaderCache(L))}this.renderBufferDirect=function(L,q,w,P,R,k){q===null&&(q=dt);const Y=R.isMesh&&R.matrixWorld.determinant()<0,Q=vA(L,q,w,P,R);ge.setMaterial(P,Y);let Z=w.index,ae=1;if(P.wireframe===!0){if(Z=de.getWireframeAttribute(w),Z===void 0)return;ae=2}const te=w.drawRange,J=w.attributes.position;let re=te.start*ae,Se=(te.start+te.count)*ae;k!==null&&(re=Math.max(re,k.start*ae),Se=Math.min(Se,(k.start+k.count)*ae)),Z!==null?(re=Math.max(re,0),Se=Math.min(Se,Z.count)):J!=null&&(re=Math.max(re,0),Se=Math.min(Se,J.count));const Te=Se-re;if(Te<0||Te===1/0)return;_t.setup(R,P,Q,w,Z);let Oe,Re=st;if(Z!==null&&(Oe=ne.get(Z),Re=Ge,Re.setIndex(Oe)),R.isMesh)P.wireframe===!0?(ge.setLineWidth(P.wireframeLinewidth*gt()),Re.setMode(F.LINES)):Re.setMode(F.TRIANGLES);else if(R.isLine){let le=P.linewidth;le===void 0&&(le=1),ge.setLineWidth(le*gt()),R.isLineSegments?Re.setMode(F.LINES):R.isLineLoop?Re.setMode(F.LINE_LOOP):Re.setMode(F.LINE_STRIP)}else R.isPoints?Re.setMode(F.POINTS):R.isSprite&&Re.setMode(F.TRIANGLES);if(R.isBatchedMesh)if(R._multiDrawInstances!==null)Re.renderMultiDrawInstances(R._multiDrawStarts,R._multiDrawCounts,R._multiDrawCount,R._multiDrawInstances);else if(be.get("WEBGL_multi_draw"))Re.renderMultiDraw(R._multiDrawStarts,R._multiDrawCounts,R._multiDrawCount);else{const le=R._multiDrawStarts,Ue=R._multiDrawCounts,ze=R._multiDrawCount,Rt=Z?ne.get(Z).bytesPerElement:1,ci=ke.get(P).currentProgram.getUniforms();for(let vi=0;vi<ze;vi++)ci.setValue(F,"_gl_DrawID",vi),Re.render(le[vi]/Rt,Ue[vi])}else if(R.isInstancedMesh)Re.renderInstances(re,Te,R.count);else if(w.isInstancedBufferGeometry){const le=w._maxInstanceCount!==void 0?w._maxInstanceCount:1/0,Ue=Math.min(w.instanceCount,le);Re.renderInstances(re,Te,Ue)}else Re.render(re,Te)};function Nn(L,q,w){L.transparent===!0&&L.side===Zi&&L.forceSinglePass===!1?(L.side=In,L.needsUpdate=!0,Xh(L,q,w),L.side=us,L.needsUpdate=!0,Xh(L,q,w),L.side=Zi):Xh(L,q,w)}this.compile=function(L,q,w=null){w===null&&(w=L),g=Ye.get(w),g.init(q),v.push(g),w.traverseVisible(function(R){R.isLight&&R.layers.test(q.layers)&&(g.pushLight(R),R.castShadow&&g.pushShadow(R))}),L!==w&&L.traverseVisible(function(R){R.isLight&&R.layers.test(q.layers)&&(g.pushLight(R),R.castShadow&&g.pushShadow(R))}),g.setupLights();const P=new Set;return L.traverse(function(R){const k=R.material;if(k)if(Array.isArray(k))for(let Y=0;Y<k.length;Y++){const Q=k[Y];Nn(Q,w,R),P.add(Q)}else Nn(k,w,R),P.add(k)}),v.pop(),g=null,P},this.compileAsync=function(L,q,w=null){const P=this.compile(L,q,w);return new Promise(R=>{function k(){if(P.forEach(function(Y){ke.get(Y).currentProgram.isReady()&&P.delete(Y)}),P.size===0){R(L);return}setTimeout(k,10)}be.get("KHR_parallel_shader_compile")!==null?k():setTimeout(k,10)})};let Jt=null;function bs(L){Jt&&Jt(L)}function Zs(){Fa.stop()}function pA(){Fa.start()}const Fa=new fC;Fa.setAnimationLoop(bs),typeof self<"u"&&Fa.setContext(self),this.setAnimationLoop=function(L){Jt=L,Ie.setAnimationLoop(L),L===null?Fa.stop():Fa.start()},Ie.addEventListener("sessionstart",Zs),Ie.addEventListener("sessionend",pA),this.render=function(L,q){if(q!==void 0&&q.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(b!==!0){if(L.matrixWorldAutoUpdate===!0&&L.updateMatrixWorld(),q.parent===null&&q.matrixWorldAutoUpdate===!0&&q.updateMatrixWorld(),Ie.enabled===!0&&Ie.isPresenting===!0&&(Ie.cameraAutoUpdate===!0&&Ie.updateCamera(q),q=Ie.getCamera()),L.isScene===!0&&L.onBeforeRender(_,L,q,M),g=Ye.get(L,v.length),g.init(q),v.push(g),me.multiplyMatrices(q.projectionMatrix,q.matrixWorldInverse),Qe.setFromProjectionMatrix(me),oe=this.localClippingEnabled,ie=yt.init(this.clippingPlanes,oe),A=Le.get(L,y.length),A.init(),y.push(A),Ie.enabled===!0&&Ie.isPresenting===!0){const w=_.xr.getDepthSensingMesh();w!==null&&hf(w,q,-1/0,_.sortObjects)}if(hf(L,q,0,_.sortObjects),A.finish(),_.sortObjects===!0&&A.sort(W,ce),Ke=Ie.enabled===!1||Ie.isPresenting===!1||Ie.hasDepthSensing()===!1,Ke=Ke&&_.userData.backgroundRender!==!1,Ke&&je.addToRenderList(A,L),this.info.render.frame++,_.userData.shadowMapRender!==!1){ie===!0&&yt.beginShadows();const w=g.state.shadowsArray;w.length>0&&Me.render(w,L,q),ie===!0&&yt.endShadows()}if(this.info.autoReset===!0&&this.info.reset(),_.userData.sceneRender!==!1){const w=A.opaque,P=A.transmissive;if(g.setupLights(),q.isArrayCamera){const R=q.cameras;if(P.length>0)for(let k=0,Y=R.length;k<Y;k++){const Q=R[k];gA(w,P,L,Q)}Ke&&je.render(L);for(let k=0,Y=R.length;k<Y;k++){const Q=R[k];mA(A,L,Q,Q.viewport)}}else _.userData.transmissionRender===void 0&&_.userData.renderTransmissionPass!==!1&&P.length>0&&gA(w,P,L,q),Ke&&je.render(L),mA(A,L,q)}M!==null&&(Ve.updateMultisampleRenderTarget(M),Ve.updateRenderTargetMipmap(M)),L.isScene===!0&&L.onAfterRender(_,L,q),_t.resetDefaultState(),I=-1,C=null,v.pop(),v.length>0?(g=v[v.length-1],ie===!0&&yt.setGlobalState(_.clippingPlanes,g.state.camera)):g=null,y.pop(),y.length>0?A=y[y.length-1]:A=null}};function hf(L,q,w,P){if(L.visible===!1)return;if(L.layers.test(q.layers)){if(L.isGroup)w=L.renderOrder;else if(L.isLOD)L.autoUpdate===!0&&L.update(q);else if(L.isLight)g.pushLight(L),L.castShadow&&g.pushShadow(L);else if(L.isSprite){if(!L.frustumCulled||Qe.intersectsSprite(L)){P&&Xe.setFromMatrixPosition(L.matrixWorld).applyMatrix4(me);const Y=ye.update(L),Q=L.material;Q.visible&&A.push(L,Y,Q,w,Xe.z,null)}}else if((L.isMesh||L.isLine||L.isPoints)&&(!L.frustumCulled||Qe.intersectsObject(L))){const Y=ye.update(L),Q=L.material;if(P&&(L.boundingSphere!==void 0?(L.boundingSphere===null&&L.computeBoundingSphere(),Xe.copy(L.boundingSphere.center)):(Y.boundingSphere===null&&Y.computeBoundingSphere(),Xe.copy(Y.boundingSphere.center)),Xe.applyMatrix4(L.matrixWorld).applyMatrix4(me)),Array.isArray(Q)){const Z=Y.groups;for(let ae=0,te=Z.length;ae<te;ae++){const J=Z[ae],re=Q[J.materialIndex];re&&re.visible&&A.push(L,Y,re,w,Xe.z,J)}}else Q.visible&&A.push(L,Y,Q,w,Xe.z,null)}}const k=L.children;for(let Y=0,Q=k.length;Y<Q;Y++)hf(k[Y],q,w,P)}function mA(L,q,w,P){const R=L.opaque,k=L.transmissive,Y=L.transparent;if(g.setupLightsView(w),ie===!0&&yt.setGlobalState(_.clippingPlanes,w),P&&ge.viewport(x.copy(P)),_.userData.opaqueRender!==!1&&R.length>0&&Eo(R,q,w),_.userData.transparentRender!==!1&&Y.length>0&&Eo(Y,q,w),_.userData.transmissionRender!==!1){if(_.userData.transmissionRender===void 0&&_.userData.renderTransmissionPass!==!1)k.length>0&&Eo(k,q,w);else if(k.length>0){g.state.transmissionRenderTarget||(g.state.transmissionRenderTarget={}),g.state.transmissionRenderTarget[w.id]||(g.state.transmissionRenderTarget[w.id]=new ds(1,1));const Q=(_.userData.transmissionRenderTarget||g.state.transmissionRenderTarget[w.id]).texture,Z=Ne.isWebGL2,ae=Q.generateMipmaps,te=Q.minFilter;Z&&_.userData.blurTransmissionTarget&&_.userData.transmissionRenderTarget&&(Q.generateMipmaps=!0,Q.minFilter=Dn,Q.needsUpdate=!0,Ve.updateMultisampleRenderTarget(_.userData.transmissionRenderTarget),Ve.updateRenderTargetMipmap(_.userData.transmissionRenderTarget)),Eo(k,q,w),Z&&_.userData.blurTransmissionTarget&&_.userData.transmissionRenderTarget&&(Q.generateMipmaps=ae,Q.minFilter=te,Q.needsUpdate=!0,Ve.updateMultisampleRenderTarget(_.userData.transmissionRenderTarget),Ve.updateRenderTargetMipmap(_.userData.transmissionRenderTarget))}}ge.buffers.depth.setTest(!0),ge.buffers.depth.setMask(!0),ge.buffers.color.setMask(!0),ge.setPolygonOffset(!1)}function gA(L,q,w,P){if((w.isScene===!0?w.overrideMaterial:null)!==null)return;g.state.transmissionRenderTarget[P.id]===void 0&&(g.state.transmissionRenderTarget[P.id]=new ds(1,1,{generateMipmaps:!0,type:be.has("EXT_color_buffer_half_float")||be.has("EXT_color_buffer_float")?Yt:Qt,minFilter:Dn,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Nt.workingColorSpace}));const k=g.state.transmissionRenderTarget[P.id],Y=P.viewport||x;k.setSize(Y.z,Y.w);const Q=_.getRenderTarget();_.setRenderTarget(k),_.getClearColor(O),N=_.getClearAlpha(),N<1&&_.setClearColor(16777215,.5),_.clear(),Ke&&je.render(w);const Z=_.toneMapping;_.toneMapping=Xr;const ae=P.viewport;if(P.viewport!==void 0&&(P.viewport=void 0),g.setupLightsView(P),ie===!0&&yt.setGlobalState(_.clippingPlanes,P),Eo(L,w,P),Ve.updateMultisampleRenderTarget(k),Ve.updateRenderTargetMipmap(k),be.has("WEBGL_multisampled_render_to_texture")===!1){let te=!1;for(let J=0,re=q.length;J<re;J++){const Se=q[J],Te=Se.object,Oe=Se.geometry,Re=Se.material,le=Se.group;if(Re.side===Zi&&Te.layers.test(P.layers)){const Ue=Re.side;Re.side=In,Re.needsUpdate=!0,AA(Te,w,P,Oe,Re,le),Re.side=Ue,Re.needsUpdate=!0,te=!0}}te===!0&&(Ve.updateMultisampleRenderTarget(k),Ve.updateRenderTargetMipmap(k))}_.setRenderTarget(Q),_.setClearColor(O,N),ae!==void 0&&(P.viewport=ae),_.toneMapping=Z}function Eo(L,q,w){const P={..._.userData};_.userData.opaqueRender=void 0,_.userData.transparentRender=void 0,_.userData.transmissionRender=void 0,_.userData.backgroundRender=void 0;const R=q.isScene===!0?q.overrideMaterial:null;for(let k=0,Y=L.length;k<Y;k++){const Q=L[k],Z=Q.object,ae=Q.geometry,te=Q.group;let J=Q.material;J.allowOverride===!0&&R!==null&&(J=R),Z.layers.test(w.layers)&&AA(Z,q,w,ae,J,te)}Object.assign(_.userData,P)}function AA(L,q,w,P,R,k){L.onBeforeRender(_,q,w,P,R,k),L.modelViewMatrix.multiplyMatrices(w.matrixWorldInverse,L.matrixWorld),L.normalMatrix.getNormalMatrix(L.modelViewMatrix),R.onBeforeRender(_,q,w,P,L,k),R.transparent===!0&&R.side===Zi&&R.forceSinglePass===!1?(R.side=In,R.needsUpdate=!0,_.renderBufferDirect(w,q,P,R,L,k),R.side=us,R.needsUpdate=!0,_.renderBufferDirect(w,q,P,R,L,k),R.side=Zi):_.renderBufferDirect(w,q,P,R,L,k),L.onAfterRender(_,q,w,P,R,k),R.onAfterRender(_,q,w,P,L,k)}function Xh(L,q,w){q.isScene!==!0&&(q=dt);const P=ke.get(L),R=g.state.lights,k=g.state.shadowsArray,Y=R.state.version,Q=pe.getParameters(L,R.state,k,q,w),Z=pe.getProgramCacheKey(Q);let ae=P.programs;P.environment=L.userData&&L.userData.envMapSlotKey&&q.textureSlots&&q.textureSlots[L.userData.envMapSlotKey]?q.textureSlots[L.userData.envMapSlotKey]:L.isMeshStandardMaterial?q.environment:null,P.fog=q.fog,P.envMap=(L.isMeshStandardMaterial?B:z).get(L.envMap||P.environment),P.envMapRotation=P.environment!==null&&L.envMap===null?q.environmentRotation:L.envMapRotation,ae===void 0&&(L.addEventListener("dispose",pt),ae=new Map,P.programs=ae);let te=ae.get(Z);if(te!==void 0){if(P.currentProgram===te&&P.lightsStateVersion===Y)return _A(L,Q),te}else Q.uniforms=pe.getUniforms(L),L.onBeforeCompile(Q,_),te=pe.acquireProgram(Q,Z),ae.set(Z,te),P.uniforms=Q.uniforms;const J=P.uniforms;return(!L.isShaderMaterial&&!L.isRawShaderMaterial||L.clipping===!0)&&(J.clippingPlanes=yt.uniform),_A(L,Q),P.needsLights=ow(L),P.lightsStateVersion=Y,P.needsLights&&(J.ambientLightColor.value=R.state.ambient,J.lightProbe.value=R.state.probe,J.directionalLights.value=R.state.directional,J.directionalLightShadows.value=R.state.directionalShadow,J.spotLights.value=R.state.spot,J.spotLightShadows.value=R.state.spotShadow,J.rectAreaLights.value=R.state.rectArea,J.ltc_1.value=R.state.rectAreaLTC1,J.ltc_2.value=R.state.rectAreaLTC2,J.pointLights.value=R.state.point,J.pointLightShadows.value=R.state.pointShadow,J.hemisphereLights.value=R.state.hemi,J.directionalShadowMap.value=R.state.directionalShadowMap,J.directionalShadowMatrix.value=R.state.directionalShadowMatrix,J.spotShadowMap.value=R.state.spotShadowMap,J.spotLightMatrix.value=R.state.spotLightMatrix,J.spotLightMap.value=R.state.spotLightMap,J.pointShadowMap.value=R.state.pointShadowMap,J.pointShadowMatrix.value=R.state.pointShadowMatrix),P.currentProgram=te,P.uniformsList=null,te}function yA(L){if(L.uniformsList===null){const q=L.currentProgram.getUniforms();L.uniformsList=lp.seqWithValue(q.seq,L.uniforms)}return L.uniformsList}function _A(L,q){const w=ke.get(L);w.outputColorSpace=q.outputColorSpace,w.batching=q.batching,w.batchingColor=q.batchingColor,w.instancing=q.instancing,w.instancingColor=q.instancingColor,w.instancingMorph=q.instancingMorph,w.skinning=q.skinning,w.morphTargets=q.morphTargets,w.morphNormals=q.morphNormals,w.morphColors=q.morphColors,w.morphTargetsCount=q.morphTargetsCount,w.numClippingPlanes=q.numClippingPlanes,w.numIntersection=q.numClipIntersection,w.vertexAlphas=q.vertexAlphas,w.vertexTangents=q.vertexTangents,w.toneMapping=q.toneMapping}function vA(L,q,w,P,R){q.isScene!==!0&&(q=dt),Ve.resetTextureUnits();const k=q.fog,Y=P.userData&&P.userData.envMapSlotKey&&q.textureSlots&&q.textureSlots[P.userData.envMapSlotKey]?q.textureSlots[P.userData.envMapSlotKey]:P.isMeshStandardMaterial?q.environment:null,Q=M===null?_.outputColorSpace:M.isXRRenderTarget===!0||M.texture.colorSpace&&M.texture.colorSpace!==Ct?M.texture.colorSpace:Bt,Z=(P.isMeshStandardMaterial?B:z).get(P.envMap||Y),ae=P.vertexColors===!0&&!!w.attributes.color&&w.attributes.color.itemSize===4,te=!!w.attributes.tangent&&(!!P.normalMap||P.anisotropy>0||w.userData.__forceUseTangent),J=!!w.morphAttributes.position,re=!!w.morphAttributes.normal,Se=!!w.morphAttributes.color;let Te=Xr;P.toneMapped&&(M===null||M.isXRRenderTarget===!0)&&(Te=_.toneMapping);const Oe=w.morphAttributes.position||w.morphAttributes.normal||w.morphAttributes.color,Re=Oe!==void 0?Oe.length:0,le=ke.get(P),Ue=g.state.lights;if(ie===!0&&(oe===!0||L!==C)){const xt=L===C&&P.id===I;yt.setState(P,L,xt)}let ze=!1;P.version===le.__version?(le.needsLights&&le.lightsStateVersion!==Ue.state.version||le.outputColorSpace!==Q||R.isBatchedMesh&&le.batching===!1||!R.isBatchedMesh&&le.batching===!0||R.isBatchedMesh&&le.batchingColor===!0&&R.colorTexture===null||R.isBatchedMesh&&le.batchingColor===!1&&R.colorTexture!==null||R.isInstancedMesh&&le.instancing===!1||!R.isInstancedMesh&&le.instancing===!0||R.isSkinnedMesh&&le.skinning===!1||!R.isSkinnedMesh&&le.skinning===!0||R.isInstancedMesh&&le.instancingColor===!0&&R.instanceColor===null||R.isInstancedMesh&&le.instancingColor===!1&&R.instanceColor!==null||R.isInstancedMesh&&le.instancingMorph===!0&&R.morphTexture===null||R.isInstancedMesh&&le.instancingMorph===!1&&R.morphTexture!==null||le.envMap!==Z||P.fog===!0&&le.fog!==k||le.numClippingPlanes!==void 0&&(le.numClippingPlanes!==yt.numPlanes||le.numIntersection!==yt.numIntersection)||le.vertexAlphas!==ae||le.vertexTangents!==te||le.morphTargets!==J||le.morphNormals!==re||le.morphColors!==Se||le.toneMapping!==Te||le.morphTargetsCount!==Re)&&(ze=!0):(ze=!0,le.__version=P.version);let Rt=le.currentProgram;ze===!0&&(Rt=Xh(P,q,R));let ci=!1,vi=!1,hi=!1;const ot=Rt.getUniforms(),ui=le.uniforms;if(ge.useProgram(Rt.program)&&(ci=!0,vi=!0,hi=!0),P.id!==I&&(I=P.id,vi=!0),ci||C!==L){ot.setValue(F,"projectionMatrix",L.projectionMatrix),ot.setValue(F,"viewMatrix",L.matrixWorldInverse);const xt=ot.map.cameraPosition;xt!==void 0&&xt.setValue(F,Ce.setFromMatrixPosition(L.matrixWorld)),Ne.logarithmicDepthBuffer&&ot.setValue(F,"logDepthBufFC",2/(Math.log(L.far+1)/Math.LN2)),(P.isMeshPhongMaterial||P.isMeshToonMaterial||P.isMeshLambertMaterial||P.isMeshBasicMaterial||P.isMeshStandardMaterial||P.isShaderMaterial)&&ot.setValue(F,"isOrthographic",L.isOrthographicCamera===!0),C!==L&&(C=L,vi=!0,hi=!0)}if(R.isSkinnedMesh){ot.setOptional(F,R,"bindMatrix"),ot.setOptional(F,R,"bindMatrixInverse");const xt=R.skeleton;xt&&(xt.boneTexture===null&&xt.computeBoneTexture(),ot.setValue(F,"boneTexture",xt.boneTexture,Ve))}R.isBatchedMesh&&(ot.setOptional(F,R,"batchingTexture"),ot.setValue(F,"batchingTexture",R._matricesTexture,Ve),ot.setOptional(F,R,"batchingIdTexture"),ot.setValue(F,"batchingIdTexture",R._indirectTexture,Ve),ot.setOptional(F,R,"batchingColorTexture"),R._colorsTexture!==null&&ot.setValue(F,"batchingColorTexture",R._colorsTexture,Ve));const Zn=w.morphAttributes;(Zn.position!==void 0||Zn.normal!==void 0||Zn.color!==void 0)&&Wt.update(R,w,Rt),(vi||le.receiveShadow!==R.receiveShadow)&&(le.receiveShadow=R.receiveShadow,ot.setValue(F,"receiveShadow",R.receiveShadow)),P.isMeshGouraudMaterial&&P.envMap!==null&&(ui.envMap.value=Z,ui.flipEnvMap.value=Z.isCubeTexture&&Z.isRenderTargetTexture===!1?-1:1),P.isMeshStandardMaterial&&P.envMap===null&&q.environment!==null&&(P.userData&&P.userData.separateEnvMapIntensity?ui.envMapIntensity.value=P.envMapIntensity:ui.envMapIntensity.value=q.environmentIntensity),vi&&(ot.setValue(F,"toneMappingExposure",_.toneMappingExposure),le.needsLights&&bA(ui,hi),k&&P.fog===!0&&nt.refreshFogUniforms(ui,k),nt.refreshMaterialUniforms(ui,P,X,V,_.userData.transmissionRenderTarget||g.state.transmissionRenderTarget[L.id]),lp.upload(F,yA(le),ui,Ve)),P.isShaderMaterial&&P.uniformsNeedUpdate===!0&&(lp.upload(F,yA(le),ui,Ve),P.uniformsNeedUpdate=!1),P.isSpriteMaterial&&ot.setValue(F,"center",R.center),ot.setValue(F,"modelViewMatrix",R.modelViewMatrix),ot.setValue(F,"normalMatrix",R.normalMatrix),ot.setValue(F,"modelMatrix",R.matrixWorld);const hn=P.extraUniformsToUpload;if(hn&&Object.entries(hn).forEach(([xt,ei])=>{ei.needsUpdate!==!1&&ot.setValue(F,xt,ei.value,Ve)}),P.isShaderMaterial||P.isRawShaderMaterial){const xt=P.uniformsGroups;for(let ei=0,xr=xt.length;ei<xr;ei++){const Mo=xt[ei];Ht.update(Mo,Rt),Ht.bind(Mo,Rt)}}return Rt}function bA(L,q){L.ambientLightColor.needsUpdate=q,L.lightProbe.needsUpdate=q,L.directionalLights.needsUpdate=q,L.directionalLightShadows.needsUpdate=q,L.pointLights.needsUpdate=q,L.pointLightShadows.needsUpdate=q,L.spotLights.needsUpdate=q,L.spotLightShadows.needsUpdate=q,L.rectAreaLights.needsUpdate=q,L.hemisphereLights.needsUpdate=q}function ow(L){return L.isMeshLambertMaterial||L.isMeshToonMaterial||L.isMeshPhongMaterial||L.isMeshStandardMaterial||L.isShadowMaterial||L.isShaderMaterial&&L.lights===!0}this.getActiveCubeFace=function(){return T},this.getActiveMipmapLevel=function(){return E},this.getRenderTarget=function(){return M},this.setRenderTargetTextures=function(L,q,w){ke.get(L.texture).__webglTexture=q,ke.get(L.depthTexture).__webglTexture=w;const P=ke.get(L);P.__hasExternalTextures=!0,P.__autoAllocateDepthBuffer=w===void 0,P.__autoAllocateDepthBuffer||be.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),P.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(L,q){const w=ke.get(L);w.__webglFramebuffer=q,w.__useDefaultFramebuffer=q===void 0},this.setRenderTarget=function(L,q=0,w=0){M=L,T=q,E=w;let P=!0,R=null,k=!1,Y=!1;if(L){const Z=ke.get(L);if(Z.__useDefaultFramebuffer!==void 0)ge.bindFramebuffer(F.FRAMEBUFFER,null),P=!1;else if(Z.__webglFramebuffer===void 0)Ve.setupRenderTarget(L);else if(Z.__hasExternalTextures)Ve.rebindTextures(L,ke.get(L.texture).__webglTexture,ke.get(L.depthTexture).__webglTexture);else if(L.depthBuffer){const J=L.depthTexture;if(Z.__boundDepthTexture!==J){if(J!==null&&ke.has(J)&&(L.width!==J.image.width||L.height!==J.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");Ve.setupDepthRenderbuffer(L)}}const ae=L.texture;(ae.isData3DTexture||ae.isDataArrayTexture||ae.isCompressedArrayTexture)&&(Y=!0);const te=ke.get(L).__webglFramebuffer;L.isWebGLCubeRenderTarget?(Array.isArray(te[q])?R=te[q][w]:R=te[q],k=!0):L.samples>0&&Ve.useMultisampledRTT(L)===!1?R=ke.get(L).__webglMultisampledFramebuffer:Array.isArray(te)?R=te[w]:R=te,x.copy(L.viewport),D.copy(L.scissor),U=L.scissorTest}else x.copy(ue).multiplyScalar(X).floor(),D.copy(we).multiplyScalar(X).floor(),U=Pe;if(ge.bindFramebuffer(F.FRAMEBUFFER,R)&&P&&ge.drawBuffers(L,R),ge.viewport(x),ge.scissor(D),ge.setScissorTest(U),k){const Z=ke.get(L.texture);F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_CUBE_MAP_POSITIVE_X+q,Z.__webglTexture,w)}else if(Y){const Z=ke.get(L.texture),ae=q||0;F.framebufferTextureLayer(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,Z.__webglTexture,w||0,ae)}I=-1},this.readRenderTargetPixels=function(L,q,w,P,R,k,Y,Q){if(!(L&&L.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Z=ke.get(L).__webglFramebuffer;if(L.isWebGLCubeRenderTarget&&Y!==void 0&&(Z=Z[Y]),Z){ge.bindFramebuffer(F.FRAMEBUFFER,Z);try{const ae=Array.isArray(L.textures)?L.textures[Q||0]:L.texture,te=ae.format,J=ae.type;if(!Ne.textureFormatReadable(te)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!Ne.textureTypeReadable(J)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}q>=0&&q<=L.width-P&&w>=0&&w<=L.height-R&&((L.isWebGLMultipleRenderTargets||L.textures.length>1)&&F.readBuffer(F.COLOR_ATTACHMENT0+(Q||0)),F.readPixels(q,w,P,R,wt.convert(te),wt.convert(J),k))}finally{const ae=M?ke.get(M).__webglFramebuffer:null;ge.bindFramebuffer(F.FRAMEBUFFER,ae)}}},this.readRenderTargetPixelsAsync=async function(L,q,w,P,R,k,Y){if(!(L&&L.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Q=ke.get(L).__webglFramebuffer;if(L.isWebGLCubeRenderTarget&&Y!==void 0&&(Q=Q[Y]),Q){ge.bindFramebuffer(F.FRAMEBUFFER,Q);try{const Z=L.texture,ae=Z.format,te=Z.type;if(!Ne.textureFormatReadable(ae))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Ne.textureTypeReadable(te))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(q>=0&&q<=L.width-P&&w>=0&&w<=L.height-R){const J=F.createBuffer();F.bindBuffer(F.PIXEL_PACK_BUFFER,J),F.bufferData(F.PIXEL_PACK_BUFFER,k.byteLength,F.STREAM_READ),F.readPixels(q,w,P,R,wt.convert(ae),wt.convert(te),0),F.flush();const re=F.fenceSync(F.SYNC_GPU_COMMANDS_COMPLETE,0);await MD(F,re,4);try{F.bindBuffer(F.PIXEL_PACK_BUFFER,J),F.getBufferSubData(F.PIXEL_PACK_BUFFER,0,k)}finally{F.deleteBuffer(J),F.deleteSync(re)}return k}}finally{const Z=M!==null?ke.get(M).__webglFramebuffer:null;ge.bindFramebuffer(F.FRAMEBUFFER,Z)}}},this.copyFramebufferToTexture=function(L,q=null,w=0){L.isTexture!==!0&&(ta("WebGLRenderer: copyFramebufferToTexture function signature has changed."),q=arguments[0]||null,L=arguments[1]);const P=Math.pow(2,-w),R=Math.floor(L.image.width*P),k=Math.floor(L.image.height*P),Y=q!==null?q.x:0,Q=q!==null?q.y:0;Ve.setTexture2D(L,0),F.copyTexSubImage2D(F.TEXTURE_2D,w,0,0,Y,Q,R,k),ge.unbindTexture()},this.copyTextureToTexture=function(L,q,w=null,P=null,R=0){L.isTexture!==!0&&(ta("WebGLRenderer: copyTextureToTexture function signature has changed."),P=arguments[0]||null,L=arguments[1],q=arguments[2],R=arguments[3]||0,w=null);let k,Y,Q,Z,ae,te;w!==null?(k=w.max.x-w.min.x,Y=w.max.y-w.min.y,Q=w.min.x,Z=w.min.y):(k=L.image.width,Y=L.image.height,Q=0,Z=0),P!==null?(ae=P.x,te=P.y):(ae=0,te=0);const J=wt.convert(q.format),re=wt.convert(q.type);Ve.setTexture2D(q,0),F.pixelStorei(F.UNPACK_FLIP_Y_WEBGL,q.flipY),F.pixelStorei(F.UNPACK_PREMULTIPLY_ALPHA_WEBGL,q.premultiplyAlpha),F.pixelStorei(F.UNPACK_ALIGNMENT,q.unpackAlignment);const Se=F.getParameter(F.UNPACK_ROW_LENGTH),Te=F.getParameter(F.UNPACK_IMAGE_HEIGHT),Oe=F.getParameter(F.UNPACK_SKIP_PIXELS),Re=F.getParameter(F.UNPACK_SKIP_ROWS),le=F.getParameter(F.UNPACK_SKIP_IMAGES),Ue=L.isCompressedTexture?L.mipmaps[R]:L.image;F.pixelStorei(F.UNPACK_ROW_LENGTH,Ue.width),F.pixelStorei(F.UNPACK_IMAGE_HEIGHT,Ue.height),F.pixelStorei(F.UNPACK_SKIP_PIXELS,Q),F.pixelStorei(F.UNPACK_SKIP_ROWS,Z),L.isDataTexture?F.texSubImage2D(F.TEXTURE_2D,R,ae,te,k,Y,J,re,Ue.data):L.isCompressedTexture?F.compressedTexSubImage2D(F.TEXTURE_2D,R,ae,te,Ue.width,Ue.height,J,Ue.data):F.texSubImage2D(F.TEXTURE_2D,R,ae,te,k,Y,J,re,Ue),F.pixelStorei(F.UNPACK_ROW_LENGTH,Se),F.pixelStorei(F.UNPACK_IMAGE_HEIGHT,Te),F.pixelStorei(F.UNPACK_SKIP_PIXELS,Oe),F.pixelStorei(F.UNPACK_SKIP_ROWS,Re),F.pixelStorei(F.UNPACK_SKIP_IMAGES,le),R===0&&q.generateMipmaps&&F.generateMipmap(F.TEXTURE_2D),ge.unbindTexture()},this.copyTextureToTexture3D=function(L,q,w=null,P=null,R=0){L.isTexture!==!0&&(ta("WebGLRenderer: copyTextureToTexture3D function signature has changed."),w=arguments[0]||null,P=arguments[1]||null,L=arguments[2],q=arguments[3],R=arguments[4]||0);let k,Y,Q,Z,ae,te,J,re,Se;const Te=L.isCompressedTexture?L.mipmaps[R]:L.image;w!==null?(k=w.max.x-w.min.x,Y=w.max.y-w.min.y,Q=w.max.z-w.min.z,Z=w.min.x,ae=w.min.y,te=w.min.z):(k=Te.width,Y=Te.height,Q=Te.depth,Z=0,ae=0,te=0),P!==null?(J=P.x,re=P.y,Se=P.z):(J=0,re=0,Se=0);const Oe=wt.convert(q.format),Re=wt.convert(q.type);let le;if(q.isData3DTexture)Ve.setTexture3D(q,0),le=F.TEXTURE_3D;else if(q.isDataArrayTexture||q.isCompressedArrayTexture)Ve.setTexture2DArray(q,0),le=F.TEXTURE_2D_ARRAY;else{console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");return}F.pixelStorei(F.UNPACK_FLIP_Y_WEBGL,q.flipY),F.pixelStorei(F.UNPACK_PREMULTIPLY_ALPHA_WEBGL,q.premultiplyAlpha),F.pixelStorei(F.UNPACK_ALIGNMENT,q.unpackAlignment);const Ue=F.getParameter(F.UNPACK_ROW_LENGTH),ze=F.getParameter(F.UNPACK_IMAGE_HEIGHT),Rt=F.getParameter(F.UNPACK_SKIP_PIXELS),ci=F.getParameter(F.UNPACK_SKIP_ROWS),vi=F.getParameter(F.UNPACK_SKIP_IMAGES);F.pixelStorei(F.UNPACK_ROW_LENGTH,Te.width),F.pixelStorei(F.UNPACK_IMAGE_HEIGHT,Te.height),F.pixelStorei(F.UNPACK_SKIP_PIXELS,Z),F.pixelStorei(F.UNPACK_SKIP_ROWS,ae),F.pixelStorei(F.UNPACK_SKIP_IMAGES,te),L.isDataTexture||L.isData3DTexture?F.texSubImage3D(le,R,J,re,Se,k,Y,Q,Oe,Re,Te.data):q.isCompressedArrayTexture?F.compressedTexSubImage3D(le,R,J,re,Se,k,Y,Q,Oe,Te.data):F.texSubImage3D(le,R,J,re,Se,k,Y,Q,Oe,Re,Te),F.pixelStorei(F.UNPACK_ROW_LENGTH,Ue),F.pixelStorei(F.UNPACK_IMAGE_HEIGHT,ze),F.pixelStorei(F.UNPACK_SKIP_PIXELS,Rt),F.pixelStorei(F.UNPACK_SKIP_ROWS,ci),F.pixelStorei(F.UNPACK_SKIP_IMAGES,vi),R===0&&q.generateMipmaps&&F.generateMipmap(le),ge.unbindTexture()},this.initRenderTarget=function(L){ke.get(L).__webglFramebuffer===void 0&&Ve.setupRenderTarget(L)},this.initTexture=function(L){L.isCubeTexture?Ve.setTextureCube(L,0):L.isData3DTexture?Ve.setTexture3D(L,0):L.isDataArrayTexture||L.isCompressedArrayTexture?Ve.setTexture2DArray(L,0):Ve.setTexture2D(L,0),ge.unbindTexture()},this.resetState=function(){T=0,E=0,M=null,ge.reset(),_t.reset()},this.resetCurrentMaterial=function(){I=-1},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ea}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=e===nu?"display-p3":"srgb",t.unpackColorSpace=Nt.workingColorSpace===su?"display-p3":"srgb"}get useLegacyLights(){return this._useLegacyLights}set useLegacyLights(e){this._useLegacyLights=e}}class up{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new ee(e),this.density=t}clone(){return new up(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class dp{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new ee(e),this.near=t,this.far=i}clone(){return new dp(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Qo extends ft{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 Pt,this.environmentIntensity=1,this.environmentRotation=new Pt,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Mc{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Bf,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=Cs()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}get updateRange(){return ta("THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}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,i){e*=this.stride,i*=t.stride;for(let n=0,s=this.stride;n<s;n++)this.array[e+n]=t.array[i+n];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=Cs()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),i=new this.constructor(t,this.stride);return i.setUsage(this.usage),i}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Cs()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const ss=new S;class Rn{constructor(e,t,i,n=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=i,this.normalized=n}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,i=this.data.count;t<i;t++)ss.fromBufferAttribute(this,t),ss.applyMatrix4(e),this.setXYZ(t,ss.x,ss.y,ss.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)ss.fromBufferAttribute(this,t),ss.applyNormalMatrix(e),this.setXYZ(t,ss.x,ss.y,ss.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)ss.fromBufferAttribute(this,t),ss.transformDirection(e),this.setXYZ(t,ss.x,ss.y,ss.z);return this}getComponent(e,t){let i=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(i=es(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=St(i,this.array)),this.data.array[e*this.data.stride+this.offset+t]=i,this}setX(e,t){return this.normalized&&(t=St(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=St(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=St(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=St(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=es(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=es(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=es(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=es(t,this.array)),t}setXY(e,t,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=St(t,this.array),i=St(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this}setXYZ(e,t,i,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=St(t,this.array),i=St(i,this.array),n=St(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=n,this}setXYZW(e,t,i,n,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=St(t,this.array),i=St(i,this.array),n=St(n,this.array),s=St(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=i,this.data.array[e+2]=n,this.data.array[e+3]=s,this}clone(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[n+s])}return new Ze(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new Rn(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[n+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}class gu extends tn{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new ee(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}}let Tc;const Au=new S,Ic=new S,Pc=new S,Dc=new K,yu=new K,QC=new fe,fp=new S,_u=new S,pp=new S,jC=new K,Hy=new K,WC=new K;class mp extends ft{constructor(e=new gu){if(super(),this.isSprite=!0,this.type="Sprite",Tc===void 0){Tc=new Je;const t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new Mc(t,5);Tc.setIndex([0,1,2,0,2,3]),Tc.setAttribute("position",new Rn(i,3,0,!1)),Tc.setAttribute("uv",new Rn(i,2,3,!1))}this.geometry=Tc,this.material=e,this.center=new K(.5,.5)}raycast(e,t){e.camera===null&&console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),Ic.setFromMatrixScale(this.matrixWorld),QC.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),Pc.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&Ic.multiplyScalar(-Pc.z);const i=this.material.rotation;let n,s;i!==0&&(s=Math.cos(i),n=Math.sin(i));const a=this.center;gp(fp.set(-.5,-.5,0),Pc,a,Ic,n,s),gp(_u.set(.5,-.5,0),Pc,a,Ic,n,s),gp(pp.set(.5,.5,0),Pc,a,Ic,n,s),jC.set(0,0),Hy.set(1,0),WC.set(1,1);let o=e.ray.intersectTriangle(fp,_u,pp,!1,Au);if(o===null&&(gp(_u.set(-.5,.5,0),Pc,a,Ic,n,s),Hy.set(0,1),o=e.ray.intersectTriangle(fp,pp,_u,!1,Au),o===null))return;const l=e.ray.origin.distanceTo(Au);l<e.near||l>e.far||t.push({distance:l,point:Au.clone(),uv:ts.getInterpolation(Au,fp,_u,pp,jC,Hy,WC,new K),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}}function gp(r,e,t,i,n,s){Dc.subVectors(r,t).addScalar(.5).multiply(i),n!==void 0?(yu.x=s*Dc.x-n*Dc.y,yu.y=n*Dc.x+s*Dc.y):yu.copy(Dc),r.copy(e),r.x+=yu.x,r.y+=yu.y,r.applyMatrix4(QC)}const Ap=new S,qC=new S;class XC extends ft{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);const t=e.levels;for(let i=0,n=t.length;i<n;i++){const s=t[i];this.addLevel(s.object.clone(),s.distance,s.hysteresis)}return this.autoUpdate=e.autoUpdate,this}addLevel(e,t=0,i=0){t=Math.abs(t);const n=this.levels;let s;for(s=0;s<n.length&&!(t<n[s].distance);s++);return n.splice(s,0,{distance:t,hysteresis:i,object:e}),this.add(e),this}getCurrentLevel(){return this._currentLevel}getObjectForDistance(e){const t=this.levels;if(t.length>0){let i,n;for(i=1,n=t.length;i<n;i++){let s=t[i].distance;if(t[i].object.visible&&(s-=s*t[i].hysteresis),e<s)break}return t[i-1].object}return null}raycast(e,t){if(this.levels.length>0){Ap.setFromMatrixPosition(this.matrixWorld);const n=e.ray.origin.distanceTo(Ap);this.getObjectForDistance(n).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){Ap.setFromMatrixPosition(e.matrixWorld),qC.setFromMatrixPosition(this.matrixWorld);const i=Ap.distanceTo(qC)/e.zoom;t[0].object.visible=!0;let n,s;for(n=1,s=t.length;n<s;n++){let a=t[n].distance;if(t[n].object.visible&&(a-=a*t[n].hysteresis),i>=a)t[n-1].object.visible=!1,t[n].object.visible=!0;else break}for(this._currentLevel=n-1;n<s;n++)t[n].object.visible=!1}}toJSON(e){const t=super.toJSON(e);this.autoUpdate===!1&&(t.object.autoUpdate=!1),t.object.levels=[];const i=this.levels;for(let n=0,s=i.length;n<s;n++){const a=i[n];t.object.levels.push({object:a.object.uuid,distance:a.distance,hysteresis:a.hysteresis})}return t}}const YC=new S,$C=new et,KC=new et,nO=new S,JC=new fe,yp=new S,Qy=new un,ZC=new fe,jy=new Va;class _p extends _e{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=Mw,this.bindMatrix=new fe,this.bindMatrixInverse=new fe,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const e=this.geometry;this.boundingBox===null&&(this.boundingBox=new en),this.boundingBox.makeEmpty();const t=e.getAttribute("position");for(let i=0;i<t.count;i++)this.getVertexPosition(i,yp),this.boundingBox.expandByPoint(yp)}computeBoundingSphere(){const e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new un),this.boundingSphere.makeEmpty();const t=e.getAttribute("position");for(let i=0;i<t.count;i++)this.getVertexPosition(i,yp),this.boundingSphere.expandByPoint(yp)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){const i=this.material,n=this.matrixWorld;i!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Qy.copy(this.boundingSphere),Qy.applyMatrix4(n),e.ray.intersectsSphere(Qy)!==!1&&(ZC.copy(n).invert(),jy.copy(e.ray).applyMatrix4(ZC),!(this.boundingBox!==null&&jy.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,jy)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const e=new et,t=this.geometry.attributes.skinWeight;for(let i=0,n=t.count;i<n;i++){e.fromBufferAttribute(t,i);const s=1/e.manhattanLength();s!==1/0?e.multiplyScalar(s):e.set(1,0,0,0),t.setXYZW(i,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===Mw?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===$P?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){const i=this.skeleton,n=this.geometry;$C.fromBufferAttribute(n.attributes.skinIndex,e),KC.fromBufferAttribute(n.attributes.skinWeight,e),YC.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let s=0;s<4;s++){const a=KC.getComponent(s);if(a!==0){const o=$C.getComponent(s);JC.multiplyMatrices(i.bones[o].matrixWorld,i.boneInverses[o]),t.addScaledVector(nO.copy(YC).applyMatrix4(JC),a)}}return t.applyMatrix4(this.bindMatrixInverse)}}class Rc extends ft{constructor(){super(),this.isBone=!0,this.type="Bone"}}class Vn extends kt{constructor(e=null,t=1,i=1,n,s,a,o,l,c=mi,h=mi,u,d){super(null,a,o,l,c,h,n,s,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const ex=new fe,sO=new fe;class Bc{constructor(e=[],t=[]){this.uuid=Cs(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){const e=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(e.length*16),t.length===0)this.calculateInverses();else if(e.length!==t.length){console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let i=0,n=this.bones.length;i<n;i++)this.boneInverses.push(new fe)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){const i=new fe;this.bones[e]&&i.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(i)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){const i=this.bones[e];i&&i.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){const i=this.bones[e];i&&(i.parent&&i.parent.isBone?(i.matrix.copy(i.parent.matrixWorld).invert(),i.matrix.multiply(i.matrixWorld)):i.matrix.copy(i.matrixWorld),i.matrix.decompose(i.position,i.quaternion,i.scale))}}update(){const e=this.bones,t=this.boneInverses,i=this.boneMatrices,n=this.boneTexture;for(let s=0,a=e.length;s<a;s++){const o=e[s]?e[s].matrixWorld:sO;ex.multiplyMatrices(o,t[s]),ex.toArray(i,s*16)}n!==null&&(n.needsUpdate=!0)}clone(){return new Bc(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(this.bones.length*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);const t=new Float32Array(e*e*4);t.set(this.boneMatrices);const i=new Vn(t,e,e,qt,Ut);return i.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=i,this}getBoneByName(e){for(let t=0,i=this.bones.length;t<i;t++){const n=this.bones[t];if(n.name===e)return n}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let i=0,n=e.bones.length;i<n;i++){const s=e.bones[i];let a=t[s];a===void 0&&(console.warn("THREE.Skeleton: No bone found with UUID:",s),a=new Rc),this.bones.push(a),this.boneInverses.push(new fe().fromArray(e.boneInverses[i]))}return this.init(),this}toJSON(){const e={metadata:{version:4.6,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};e.uuid=this.uuid;const t=this.bones,i=this.boneInverses;for(let n=0,s=t.length;n<s;n++){const a=t[n];e.bones.push(a.uuid);const o=i[n];e.boneInverses.push(o.toArray())}return e}}class ha extends Ze{constructor(e,t,i,n=1){super(e,t,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const Lc=new fe,tx=new fe,vp=[],ix=new en,rO=new fe,vu=new _e,bu=new un;class Oc extends _e{constructor(e,t,i){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new ha(new Float32Array(i*16),16),this.instanceColor=null,this.morphTexture=null,this.sourceTrs=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let n=0;n<i;n++)this.setMatrixAt(n,rO)}computeBoundingBox(){const e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new en),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,Lc),ix.copy(e.boundingBox).applyMatrix4(Lc),this.boundingBox.union(ix)}computeBoundingSphere(){const e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new un),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,Lc),bu.copy(e.boundingSphere).applyMatrix4(Lc),this.boundingSphere.union(bu)}copy(e,t){return super.copy(e,t),e.isInstancedMesh?(this.instanceMatrix.copy(e.instanceMatrix),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this):this}getColorAt(e,t){t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){const i=t.morphTargetInfluences,n=this.morphTexture.source.data.data,s=i.length+1,a=e*s+1;for(let o=0;o<i.length;o++)i[o]=n[a+o]}raycast(e,t){const i=this.matrixWorld,n=this.count;if(vu.geometry=this.geometry,vu.material=this.material,vu.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),bu.copy(this.boundingSphere),bu.applyMatrix4(i),e.ray.intersectsSphere(bu)!==!1))for(let s=0;s<n;s++){this.getMatrixAt(s,Lc),tx.multiplyMatrices(i,Lc),vu.matrixWorld=tx,vu.raycast(e,vp);for(let a=0,o=vp.length;a<o;a++){const l=vp[a];l.instanceId=s,l.object=this,t.push(l)}vp.length=0}}setColorAt(e,t){this.instanceColor===null&&(this.instanceColor=new ha(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3)}setMatrixAt(e,t){t.toArray(this.instanceMatrix.array,e*16)}setMorphAt(e,t){const i=t.morphTargetInfluences,n=i.length+1;this.morphTexture===null&&(this.morphTexture=new Vn(new Float32Array(n*this.count),n,this.count,Jr,Ut));const s=this.morphTexture.source.data.data;let a=0;for(let c=0;c<i.length;c++)a+=i[c];const o=this.geometry.morphTargetsRelative?1:1-a,l=n*e;s[l]=o,s.set(i,l+1)}updateMorphTargets(){}dispose(){return this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null),this}}function aO(r,e){return r.z-e.z}function oO(r,e){return e.z-r.z}class lO{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,t,i){const n=this.pool,s=this.list;this.index>=n.length&&n.push({start:-1,count:-1,z:-1,index:-1});const a=n[this.index];s.push(a),this.index++,a.start=e.start,a.count=e.count,a.z=t,a.index=i}reset(){this.list.length=0,this.index=0}}const Wa=new fe,Wy=new fe,cO=new fe,hO=new ee(1,1,1),nx=new fe,qy=new pu,bp=new en,jo=new un,wu=new S,sx=new S,uO=new S,Xy=new lO,Hn=new _e,wp=[];function dO(r,e,t=0){const i=e.itemSize;if(r.isInterleavedBufferAttribute||r.array.constructor!==e.array.constructor){const n=r.count;for(let s=0;s<n;s++)for(let a=0;a<i;a++)e.setComponent(s+t,a,r.getComponent(s,a))}else e.array.set(r.array,t*i);e.needsUpdate=!0}class rx extends _e{get maxInstanceCount(){return this._maxInstanceCount}constructor(e,t,i=t*2,n){super(new Je,n),this.isBatchedMesh=!0,this.perObjectFrustumCulled=!0,this.sortObjects=!0,this.boundingBox=null,this.boundingSphere=null,this.customSort=null,this._drawInfo=[],this._drawRanges=[],this._reservedRanges=[],this._bounds=[],this._maxInstanceCount=e,this._maxVertexCount=t,this._maxIndexCount=i,this._geometryInitialized=!1,this._geometryCount=0,this._multiDrawCounts=new Int32Array(e),this._multiDrawStarts=new Int32Array(e),this._multiDrawCount=0,this._multiDrawInstances=null,this._visibilityChanged=!0,this._matricesTexture=null,this._indirectTexture=null,this._colorsTexture=null,this._initMatricesTexture(),this._initIndirectTexture()}_initMatricesTexture(){let e=Math.sqrt(this._maxInstanceCount*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);const t=new Float32Array(e*e*4),i=new Vn(t,e,e,qt,Ut);this._matricesTexture=i}_initIndirectTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);const t=new Uint32Array(e*e),i=new Vn(t,e,e,_f,tr);this._indirectTexture=i}_initColorsTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);const t=new Float32Array(e*e*4).fill(1),i=new Vn(t,e,e,qt,Ut);i.colorSpace=Nt.workingColorSpace,this._colorsTexture=i}_initializeGeometry(e){const t=this.geometry,i=this._maxVertexCount,n=this._maxIndexCount;if(this._geometryInitialized===!1){for(const s in e.attributes){const a=e.getAttribute(s),{array:o,itemSize:l,normalized:c}=a,h=new o.constructor(i*l),u=new Ze(h,l,c);t.setAttribute(s,u)}if(e.getIndex()!==null){const s=i>65535?new Uint32Array(n):new Uint16Array(n);t.setIndex(new Ze(s,1))}this._geometryInitialized=!0}}_validateGeometry(e){const t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const i in t.attributes){if(!e.hasAttribute(i))throw new Error(`BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);const n=e.getAttribute(i),s=t.getAttribute(i);if(n.itemSize!==s.itemSize||n.normalized!==s.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new en);const e=this.boundingBox,t=this._drawInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){if(t[i].active===!1)continue;const s=t[i].geometryIndex;this.getMatrixAt(i,Wa),this.getBoundingBoxAt(s,bp).applyMatrix4(Wa),e.union(bp)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un);const e=this.boundingSphere,t=this._drawInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){if(t[i].active===!1)continue;const s=t[i].geometryIndex;this.getMatrixAt(i,Wa),this.getBoundingSphereAt(s,jo).applyMatrix4(Wa),e.union(jo)}}addInstance(e){if(this._drawInfo.length>=this._maxInstanceCount)throw new Error("BatchedMesh: Maximum item count reached.");this._drawInfo.push({visible:!0,active:!0,geometryIndex:e});const t=this._drawInfo.length-1,i=this._matricesTexture,n=i.image.data;cO.toArray(n,t*16),i.needsUpdate=!0;const s=this._colorsTexture;return s&&(hO.toArray(s.image.data,t*4),s.needsUpdate=!0),t}addGeometry(e,t=-1,i=-1){if(this._initializeGeometry(e),this._validateGeometry(e),this._drawInfo.length>=this._maxInstanceCount)throw new Error("BatchedMesh: Maximum item count reached.");const n={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let s=null;const a=this._reservedRanges,o=this._drawRanges,l=this._bounds;this._geometryCount!==0&&(s=a[a.length-1]),t===-1?n.vertexCount=e.getAttribute("position").count:n.vertexCount=t,s===null?n.vertexStart=0:n.vertexStart=s.vertexStart+s.vertexCount;const c=e.getIndex(),h=c!==null;if(h&&(i===-1?n.indexCount=c.count:n.indexCount=i,s===null?n.indexStart=0:n.indexStart=s.indexStart+s.indexCount),n.indexStart!==-1&&n.indexStart+n.indexCount>this._maxIndexCount||n.vertexStart+n.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const u=this._geometryCount;return this._geometryCount++,a.push(n),o.push({start:h?n.indexStart:n.vertexStart,count:-1}),l.push({boxInitialized:!1,box:new en,sphereInitialized:!1,sphere:new un}),this.setGeometryAt(u,e),u}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=i.getIndex()!==null,s=i.getIndex(),a=t.getIndex(),o=this._reservedRanges[e];if(n&&a.count>o.indexCount||t.attributes.position.count>o.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const l=o.vertexStart,c=o.vertexCount;for(const p in i.attributes){const m=t.getAttribute(p),A=i.getAttribute(p);dO(m,A,l);const g=m.itemSize;for(let y=m.count,v=c;y<v;y++){const _=l+y;for(let b=0;b<g;b++)A.setComponent(_,b,0)}A.needsUpdate=!0,A.addUpdateRange(l*g,c*g)}if(n){const p=o.indexStart;for(let m=0;m<a.count;m++)s.setX(p+m,l+a.getX(m));for(let m=a.count,A=o.indexCount;m<A;m++)s.setX(p+m,l);s.needsUpdate=!0,s.addUpdateRange(p,o.indexCount)}const h=this._bounds[e];t.boundingBox!==null?(h.box.copy(t.boundingBox),h.boxInitialized=!0):h.boxInitialized=!1,t.boundingSphere!==null?(h.sphere.copy(t.boundingSphere),h.sphereInitialized=!0):h.sphereInitialized=!1;const u=this._drawRanges[e],d=t.getAttribute("position");return u.count=n?a.count:d.count,this._visibilityChanged=!0,e}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;const i=this._bounds[e],n=i.box,s=this.geometry;if(i.boxInitialized===!1){n.makeEmpty();const a=s.index,o=s.attributes.position,l=this._drawRanges[e];for(let c=l.start,h=l.start+l.count;c<h;c++){let u=c;a&&(u=a.getX(u)),n.expandByPoint(wu.fromBufferAttribute(o,u))}i.boxInitialized=!0}return t.copy(n),t}getBoundingSphereAt(e,t){if(e>=this._geometryCount)return null;const i=this._bounds[e],n=i.sphere,s=this.geometry;if(i.sphereInitialized===!1){n.makeEmpty(),this.getBoundingBoxAt(e,bp),bp.getCenter(n.center);const a=s.index,o=s.attributes.position,l=this._drawRanges[e];let c=0;for(let h=l.start,u=l.start+l.count;h<u;h++){let d=h;a&&(d=a.getX(d)),wu.fromBufferAttribute(o,d),c=Math.max(c,n.center.distanceToSquared(wu))}n.radius=Math.sqrt(c),i.sphereInitialized=!0}return t.copy(n),t}setMatrixAt(e,t){const i=this._drawInfo,n=this._matricesTexture,s=this._matricesTexture.image.data;return e>=i.length||i[e].active===!1?this:(t.toArray(s,e*16),n.needsUpdate=!0,this)}getMatrixAt(e,t){const i=this._drawInfo,n=this._matricesTexture.image.data;return e>=i.length||i[e].active===!1?null:t.fromArray(n,e*16)}setColorAt(e,t){this._colorsTexture===null&&this._initColorsTexture();const i=this._colorsTexture,n=this._colorsTexture.image.data,s=this._drawInfo;return e>=s.length||s[e].active===!1?this:(t.toArray(n,e*4),i.needsUpdate=!0,this)}getColorAt(e,t){const i=this._colorsTexture.image.data,n=this._drawInfo;return e>=n.length||n[e].active===!1?null:t.fromArray(i,e*4)}setVisibleAt(e,t){const i=this._drawInfo;return e>=i.length||i[e].active===!1||i[e].visible===t?this:(i[e].visible=t,this._visibilityChanged=!0,this)}getVisibleAt(e){const t=this._drawInfo;return e>=t.length||t[e].active===!1?!1:t[e].visible}raycast(e,t){const i=this._drawInfo,n=this._drawRanges,s=this.matrixWorld,a=this.geometry;Hn.material=this.material,Hn.geometry.index=a.index,Hn.geometry.attributes=a.attributes,Hn.geometry.boundingBox===null&&(Hn.geometry.boundingBox=new en),Hn.geometry.boundingSphere===null&&(Hn.geometry.boundingSphere=new un);for(let o=0,l=i.length;o<l;o++){if(!i[o].visible||!i[o].active)continue;const c=i[o].geometryIndex,h=n[c];Hn.geometry.setDrawRange(h.start,h.count),this.getMatrixAt(o,Hn.matrixWorld).premultiply(s),this.getBoundingBoxAt(c,Hn.geometry.boundingBox),this.getBoundingSphereAt(c,Hn.geometry.boundingSphere),Hn.raycast(e,wp);for(let u=0,d=wp.length;u<d;u++){const p=wp[u];p.object=this,p.batchId=o,t.push(p)}wp.length=0}Hn.material=null,Hn.geometry.index=null,Hn.geometry.attributes={},Hn.geometry.setDrawRange(0,1/0)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.perObjectFrustumCulled=e.perObjectFrustumCulled,this.sortObjects=e.sortObjects,this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._drawRanges=e._drawRanges.map(t=>({...t})),this._reservedRanges=e._reservedRanges.map(t=>({...t})),this._drawInfo=e._drawInfo.map(t=>({...t})),this._bounds=e._bounds.map(t=>({boxInitialized:t.boxInitialized,box:t.box.clone(),sphereInitialized:t.sphereInitialized,sphere:t.sphere.clone()})),this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null),this}onBeforeRender(e,t,i,n,s){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const a=n.getIndex(),o=a===null?1:a.array.BYTES_PER_ELEMENT,l=this._drawInfo,c=this._multiDrawStarts,h=this._multiDrawCounts,u=this._drawRanges,d=this.perObjectFrustumCulled,p=this._indirectTexture,m=p.image.data;d&&(nx.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),qy.setFromProjectionMatrix(nx,e.coordinateSystem));let A=0;if(this.sortObjects){Wy.copy(this.matrixWorld).invert(),wu.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Wy),sx.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(Wy);for(let v=0,_=l.length;v<_;v++)if(l[v].visible&&l[v].active){const b=l[v].geometryIndex;this.getMatrixAt(v,Wa),this.getBoundingSphereAt(b,jo).applyMatrix4(Wa);let T=!1;if(d&&(T=!qy.intersectsSphere(jo)),!T){const E=uO.subVectors(jo.center,wu).dot(sx);Xy.push(u[b],E,v)}}const g=Xy.list,y=this.customSort;y===null?g.sort(s.transparent?oO:aO):y.call(this,g,i);for(let v=0,_=g.length;v<_;v++){const b=g[v];c[A]=b.start*o,h[A]=b.count,m[A]=b.index,A++}Xy.reset()}else for(let g=0,y=l.length;g<y;g++)if(l[g].visible&&l[g].active){const v=l[g].geometryIndex;let _=!1;if(d&&(this.getMatrixAt(g,Wa),this.getBoundingSphereAt(v,jo).applyMatrix4(Wa),_=!qy.intersectsSphere(jo)),!_){const b=u[v];c[A]=b.start*o,h[A]=b.count,m[A]=g,A++}}p.needsUpdate=!0,this._multiDrawCount=A,this._visibilityChanged=!1}onBeforeShadow(e,t,i,n,s,a){this.onBeforeRender(e,null,n,s,a)}}class Mi extends tn{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new ee(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const Cp=new S,xp=new S,ax=new fe,Cu=new Va,Sp=new un,Yy=new S,ox=new S;class fn extends ft{constructor(e=new Je,t=new Mi){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[0];for(let n=1,s=t.count;n<s;n++)Cp.fromBufferAttribute(t,n-1),xp.fromBufferAttribute(t,n),i[n]=i[n-1],i[n]+=Cp.distanceTo(xp);e.setAttribute("lineDistance",new Ee(i,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const i=this.geometry,n=this.matrixWorld,s=e.params.Line.threshold,a=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),Sp.copy(i.boundingSphere),Sp.applyMatrix4(n),Sp.radius+=s,e.ray.intersectsSphere(Sp)===!1)return;ax.copy(n).invert(),Cu.copy(e.ray).applyMatrix4(ax);const o=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=o*o,c=this.isLineSegments?2:1,h=i.index,d=i.attributes.position;if(h!==null){const p=Math.max(0,a.start),m=Math.min(h.count,a.start+a.count);for(let A=p,g=m-1;A<g;A+=c){const y=h.getX(A),v=h.getX(A+1),_=Ep(this,e,Cu,l,y,v);_&&t.push(_)}if(this.isLineLoop){const A=h.getX(m-1),g=h.getX(p),y=Ep(this,e,Cu,l,A,g);y&&t.push(y)}}else{const p=Math.max(0,a.start),m=Math.min(d.count,a.start+a.count);for(let A=p,g=m-1;A<g;A+=c){const y=Ep(this,e,Cu,l,A,A+1);y&&t.push(y)}if(this.isLineLoop){const A=Ep(this,e,Cu,l,m-1,p);A&&t.push(A)}}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=n.length;s<a;s++){const o=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}}function Ep(r,e,t,i,n,s){const a=r.geometry.attributes.position;if(Cp.fromBufferAttribute(a,n),xp.fromBufferAttribute(a,s),t.distanceSqToSegment(Cp,xp,Yy,ox)>i)return;Yy.applyMatrix4(r.matrixWorld);const l=e.ray.origin.distanceTo(Yy);if(!(l<e.near||l>e.far))return{distance:l,point:ox.clone().applyMatrix4(r.matrixWorld),index:n,face:null,faceIndex:null,object:r}}const lx=new S,cx=new S;class Ms extends fn{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let n=0,s=t.count;n<s;n+=2)lx.fromBufferAttribute(t,n),cx.fromBufferAttribute(t,n+1),i[n]=n===0?0:i[n-1],i[n+1]=i[n]+lx.distanceTo(cx);e.setAttribute("lineDistance",new Ee(i,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class $y extends fn{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}}class Tr extends tn{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new ee(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}}const hx=new fe,Ky=new Va,Mp=new un,Tp=new S;class Wo extends ft{constructor(e=new Je,t=new Tr){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,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}raycast(e,t){const i=this.geometry,n=this.matrixWorld,s=e.params.Points.threshold,a=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),Mp.copy(i.boundingSphere),Mp.applyMatrix4(n),Mp.radius+=s,e.ray.intersectsSphere(Mp)===!1)return;hx.copy(n).invert(),Ky.copy(e.ray).applyMatrix4(hx);const o=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=o*o,c=i.index,u=i.attributes.position;if(c!==null){const d=Math.max(0,a.start),p=Math.min(c.count,a.start+a.count);for(let m=d,A=p;m<A;m++){const g=c.getX(m);Tp.fromBufferAttribute(u,g),ux(Tp,g,l,n,e,t,this)}}else{const d=Math.max(0,a.start),p=Math.min(u.count,a.start+a.count);for(let m=d,A=p;m<A;m++)Tp.fromBufferAttribute(u,m),ux(Tp,m,l,n,e,t,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const n=t[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=n.length;s<a;s++){const o=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=s}}}}}function ux(r,e,t,i,n,s,a){const o=Ky.distanceSqToPoint(r);if(o<t){const l=new S;Ky.closestPointToPoint(r,l),l.applyMatrix4(i);const c=n.ray.origin.distanceTo(l);if(c<n.near||c>n.far)return;s.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,object:a})}}class Jy extends kt{constructor(e,t,i,n,s,a,o,l,c){super(e,t,i,n,s,a,o,l,c),this.isVideoTexture=!0,this.minFilter=a!==void 0?a:at,this.magFilter=s!==void 0?s:at,this.generateMipmaps=!1;const h=this;function u(){h.needsUpdate=!0,e.requestVideoFrameCallback(u)}"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback(u)}clone(){return new this.constructor(this.image).copy(this)}update(){const e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class fO extends kt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=mi,this.minFilter=mi,this.generateMipmaps=!1,this.needsUpdate=!0}}class ua extends kt{constructor(e,t,i,n,s,a,o,l,c,h,u,d){super(null,a,o,l,c,h,n,s,u,d),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class dx extends ua{constructor(e,t,i,n,s,a){super(e,t,i,s,a),this.isCompressedArrayTexture=!0,this.image.depth=n,this.wrapR=di,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class fx extends ua{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,Yr),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class qo extends kt{constructor(e,t,i,n,s,a,o,l,c){super(e,t,i,n,s,a,o,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Ts{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(e,t){const i=this.getUtoTmapping(e);return this.getPoint(i,t)}getPoints(e=5){const t=[];for(let i=0;i<=e;i++)t.push(this.getPoint(i/e));return t}getSpacedPoints(e=5){const t=[];for(let i=0;i<=e;i++)t.push(this.getPointAt(i/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let i,n=this.getPoint(0),s=0;t.push(0);for(let a=1;a<=e;a++)i=this.getPoint(a/e),s+=i.distanceTo(n),t.push(s),n=i;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t){const i=this.getLengths();let n=0;const s=i.length;let a;t?a=t:a=e*i[s-1];let o=0,l=s-1,c;for(;o<=l;)if(n=Math.floor(o+(l-o)/2),c=i[n]-a,c<0)o=n+1;else if(c>0)l=n-1;else{l=n;break}if(n=l,i[n]===a)return n/(s-1);const h=i[n],d=i[n+1]-h,p=(a-h)/d;return(n+p)/(s-1)}getTangent(e,t){let n=e-1e-4,s=e+1e-4;n<0&&(n=0),s>1&&(s=1);const a=this.getPoint(n),o=this.getPoint(s),l=t||(a.isVector2?new K:new S);return l.copy(o).sub(a).normalize(),l}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t){const i=new S,n=[],s=[],a=[],o=new S,l=new fe;for(let p=0;p<=e;p++){const m=p/e;n[p]=this.getTangentAt(m,new S)}s[0]=new S,a[0]=new S;let c=Number.MAX_VALUE;const h=Math.abs(n[0].x),u=Math.abs(n[0].y),d=Math.abs(n[0].z);h<=c&&(c=h,i.set(1,0,0)),u<=c&&(c=u,i.set(0,1,0)),d<=c&&i.set(0,0,1),o.crossVectors(n[0],i).normalize(),s[0].crossVectors(n[0],o),a[0].crossVectors(n[0],s[0]);for(let p=1;p<=e;p++){if(s[p]=s[p-1].clone(),a[p]=a[p-1].clone(),o.crossVectors(n[p-1],n[p]),o.length()>Number.EPSILON){o.normalize();const m=Math.acos(Gi(n[p-1].dot(n[p]),-1,1));s[p].applyMatrix4(l.makeRotationAxis(o,m))}a[p].crossVectors(n[p],s[p])}if(t===!0){let p=Math.acos(Gi(s[0].dot(s[e]),-1,1));p/=e,n[0].dot(o.crossVectors(s[0],s[e]))>0&&(p=-p);for(let m=1;m<=e;m++)s[m].applyMatrix4(l.makeRotationAxis(n[m],p*m)),a[m].crossVectors(n[m],s[m])}return{tangents:n,normals:s,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Xo extends Ts{constructor(e=0,t=0,i=1,n=1,s=0,a=Math.PI*2,o=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=n,this.aStartAngle=s,this.aEndAngle=a,this.aClockwise=o,this.aRotation=l}getPoint(e,t=new K){const i=t,n=Math.PI*2;let s=this.aEndAngle-this.aStartAngle;const a=Math.abs(s)<Number.EPSILON;for(;s<0;)s+=n;for(;s>n;)s-=n;s<Number.EPSILON&&(a?s=0:s=n),this.aClockwise===!0&&!a&&(s===n?s=-n:s=s-n);const o=this.aStartAngle+e*s;let l=this.aX+this.xRadius*Math.cos(o),c=this.aY+this.yRadius*Math.sin(o);if(this.aRotation!==0){const h=Math.cos(this.aRotation),u=Math.sin(this.aRotation),d=l-this.aX,p=c-this.aY;l=d*h-p*u+this.aX,c=d*u+p*h+this.aY}return i.set(l,c)}copy(e){return super.copy(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}toJSON(){const e=super.toJSON();return e.aX=this.aX,e.aY=this.aY,e.xRadius=this.xRadius,e.yRadius=this.yRadius,e.aStartAngle=this.aStartAngle,e.aEndAngle=this.aEndAngle,e.aClockwise=this.aClockwise,e.aRotation=this.aRotation,e}fromJSON(e){return super.fromJSON(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}}class Ip extends Xo{constructor(e,t,i,n,s,a){super(e,t,i,i,n,s,a),this.isArcCurve=!0,this.type="ArcCurve"}}function Zy(){let r=0,e=0,t=0,i=0;function n(s,a,o,l){r=s,e=o,t=-3*s+3*a-2*o-l,i=2*s-2*a+o+l}return{initCatmullRom:function(s,a,o,l,c){n(a,o,c*(o-s),c*(l-a))},initNonuniformCatmullRom:function(s,a,o,l,c,h,u){let d=(a-s)/c-(o-s)/(c+h)+(o-a)/h,p=(o-a)/h-(l-a)/(h+u)+(l-o)/u;d*=h,p*=h,n(a,o,d,p)},calc:function(s){const a=s*s,o=a*s;return r+e*s+t*a+i*o}}}const Pp=new S,e_=new Zy,t_=new Zy,i_=new Zy;class Uc extends Ts{constructor(e=[],t=!1,i="centripetal",n=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=e,this.closed=t,this.curveType=i,this.tension=n}getPoint(e,t=new S){const i=t,n=this.points,s=n.length,a=(s-(this.closed?0:1))*e;let o=Math.floor(a),l=a-o;this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/s)+1)*s:l===0&&o===s-1&&(o=s-2,l=1);let c,h;this.closed||o>0?c=n[(o-1)%s]:(Pp.subVectors(n[0],n[1]).add(n[0]),c=Pp);const u=n[o%s],d=n[(o+1)%s];if(this.closed||o+2<s?h=n[(o+2)%s]:(Pp.subVectors(n[s-1],n[s-2]).add(n[s-1]),h=Pp),this.curveType==="centripetal"||this.curveType==="chordal"){const p=this.curveType==="chordal"?.5:.25;let m=Math.pow(c.distanceToSquared(u),p),A=Math.pow(u.distanceToSquared(d),p),g=Math.pow(d.distanceToSquared(h),p);A<1e-4&&(A=1),m<1e-4&&(m=A),g<1e-4&&(g=A),e_.initNonuniformCatmullRom(c.x,u.x,d.x,h.x,m,A,g),t_.initNonuniformCatmullRom(c.y,u.y,d.y,h.y,m,A,g),i_.initNonuniformCatmullRom(c.z,u.z,d.z,h.z,m,A,g)}else this.curveType==="catmullrom"&&(e_.initCatmullRom(c.x,u.x,d.x,h.x,this.tension),t_.initCatmullRom(c.y,u.y,d.y,h.y,this.tension),i_.initCatmullRom(c.z,u.z,d.z,h.z,this.tension));return i.set(e_.calc(l),t_.calc(l),i_.calc(l)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const n=e.points[t];this.points.push(n.clone())}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,i=this.points.length;t<i;t++){const n=this.points[t];e.points.push(n.toArray())}return e.closed=this.closed,e.curveType=this.curveType,e.tension=this.tension,e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const n=e.points[t];this.points.push(new S().fromArray(n))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}}function px(r,e,t,i,n){const s=(i-e)*.5,a=(n-t)*.5,o=r*r,l=r*o;return(2*t-2*i+s+a)*l+(-3*t+3*i-2*s-a)*o+s*r+t}function pO(r,e){const t=1-r;return t*t*e}function mO(r,e){return 2*(1-r)*r*e}function gO(r,e){return r*r*e}function xu(r,e,t,i){return pO(r,e)+mO(r,t)+gO(r,i)}function AO(r,e){const t=1-r;return t*t*t*e}function yO(r,e){const t=1-r;return 3*t*t*r*e}function _O(r,e){return 3*(1-r)*r*r*e}function vO(r,e){return r*r*r*e}function Su(r,e,t,i,n){return AO(r,e)+yO(r,t)+_O(r,i)+vO(r,n)}class Eu extends Ts{constructor(e=new K,t=new K,i=new K,n=new K){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=i,this.v3=n}getPoint(e,t=new K){const i=t,n=this.v0,s=this.v1,a=this.v2,o=this.v3;return i.set(Su(e,n.x,s.x,a.x,o.x),Su(e,n.y,s.y,a.y,o.y)),i}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}}class Dp extends Ts{constructor(e=new S,t=new S,i=new S,n=new S){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=i,this.v3=n}getPoint(e,t=new S){const i=t,n=this.v0,s=this.v1,a=this.v2,o=this.v3;return i.set(Su(e,n.x,s.x,a.x,o.x),Su(e,n.y,s.y,a.y,o.y),Su(e,n.z,s.z,a.z,o.z)),i}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}}class Yo extends Ts{constructor(e=new K,t=new K){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new K){const i=t;return e===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(e).add(this.v1)),i}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new K){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class $o extends Ts{constructor(e=new S,t=new S){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new S){const i=t;return e===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(e).add(this.v1)),i}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new S){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class Mu extends Ts{constructor(e=new K,t=new K,i=new K){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=i}getPoint(e,t=new K){const i=t,n=this.v0,s=this.v1,a=this.v2;return i.set(xu(e,n.x,s.x,a.x),xu(e,n.y,s.y,a.y)),i}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class Tu extends Ts{constructor(e=new S,t=new S,i=new S){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=i}getPoint(e,t=new S){const i=t,n=this.v0,s=this.v1,a=this.v2;return i.set(xu(e,n.x,s.x,a.x),xu(e,n.y,s.y,a.y),xu(e,n.z,s.z,a.z)),i}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class Iu extends Ts{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new K){const i=t,n=this.points,s=(n.length-1)*e,a=Math.floor(s),o=s-a,l=n[a===0?a:a-1],c=n[a],h=n[a>n.length-2?n.length-1:a+1],u=n[a>n.length-3?n.length-1:a+2];return i.set(px(o,l.x,c.x,h.x,u.x),px(o,l.y,c.y,h.y,u.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const n=e.points[t];this.points.push(n.clone())}return this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,i=this.points.length;t<i;t++){const n=this.points[t];e.points.push(n.toArray())}return e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const n=e.points[t];this.points.push(new K().fromArray(n))}return this}}var Rp=Object.freeze({__proto__:null,ArcCurve:Ip,CatmullRomCurve3:Uc,CubicBezierCurve:Eu,CubicBezierCurve3:Dp,EllipseCurve:Xo,LineCurve:Yo,LineCurve3:$o,QuadraticBezierCurve:Mu,QuadraticBezierCurve3:Tu,SplineCurve:Iu});class Pu extends Ts{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(e){this.curves.push(e)}closePath(){const e=this.curves[0].getPoint(0),t=this.curves[this.curves.length-1].getPoint(1);if(!e.equals(t)){const i=e.isVector2===!0?"LineCurve":"LineCurve3";this.curves.push(new Rp[i](t,e))}return this}getPoint(e,t){const i=e*this.getLength(),n=this.getCurveLengths();let s=0;for(;s<n.length;){if(n[s]>=i){const a=n[s]-i,o=this.curves[s],l=o.getLength(),c=l===0?0:1-a/l;return o.getPointAt(c,t)}s++}return null}getLength(){const e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const e=[];let t=0;for(let i=0,n=this.curves.length;i<n;i++)t+=this.curves[i].getLength(),e.push(t);return this.cacheLengths=e,e}getSpacedPoints(e=40){const t=[];for(let i=0;i<=e;i++)t.push(this.getPoint(i/e));return this.autoClose&&t.push(t[0]),t}getPoints(e=12){const t=[];let i;for(let n=0,s=this.curves;n<s.length;n++){const a=s[n],o=a.isEllipseCurve?e*2:a.isLineCurve||a.isLineCurve3?1:a.isSplineCurve?e*a.points.length:e,l=a.getPoints(o);for(let c=0;c<l.length;c++){const h=l[c];i&&i.equals(h)||(t.push(h),i=h)}}return this.autoClose&&t.length>1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,i=e.curves.length;t<i;t++){const n=e.curves[t];this.curves.push(n.clone())}return this.autoClose=e.autoClose,this}toJSON(){const e=super.toJSON();e.autoClose=this.autoClose,e.curves=[];for(let t=0,i=this.curves.length;t<i;t++){const n=this.curves[t];e.curves.push(n.toJSON())}return e}fromJSON(e){super.fromJSON(e),this.autoClose=e.autoClose,this.curves=[];for(let t=0,i=e.curves.length;t<i;t++){const n=e.curves[t];this.curves.push(new Rp[n.type]().fromJSON(n))}return this}}class Fc extends Pu{constructor(e){super(),this.type="Path",this.currentPoint=new K,e&&this.setFromPoints(e)}setFromPoints(e){this.moveTo(e[0].x,e[0].y);for(let t=1,i=e.length;t<i;t++)this.lineTo(e[t].x,e[t].y);return this}moveTo(e,t){return this.currentPoint.set(e,t),this}lineTo(e,t){const i=new Yo(this.currentPoint.clone(),new K(e,t));return this.curves.push(i),this.currentPoint.set(e,t),this}quadraticCurveTo(e,t,i,n){const s=new Mu(this.currentPoint.clone(),new K(e,t),new K(i,n));return this.curves.push(s),this.currentPoint.set(i,n),this}bezierCurveTo(e,t,i,n,s,a){const o=new Eu(this.currentPoint.clone(),new K(e,t),new K(i,n),new K(s,a));return this.curves.push(o),this.currentPoint.set(s,a),this}splineThru(e){const t=[this.currentPoint.clone()].concat(e),i=new Iu(t);return this.curves.push(i),this.currentPoint.copy(e[e.length-1]),this}arc(e,t,i,n,s,a){const o=this.currentPoint.x,l=this.currentPoint.y;return this.absarc(e+o,t+l,i,n,s,a),this}absarc(e,t,i,n,s,a){return this.absellipse(e,t,i,i,n,s,a),this}ellipse(e,t,i,n,s,a,o,l){const c=this.currentPoint.x,h=this.currentPoint.y;return this.absellipse(e+c,t+h,i,n,s,a,o,l),this}absellipse(e,t,i,n,s,a,o,l){const c=new Xo(e,t,i,n,s,a,o,l);if(this.curves.length>0){const u=c.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.y)}this.curves.push(c);const h=c.getPoint(1);return this.currentPoint.copy(h),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){const e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}}class Du extends Je{constructor(e=[new K(0,-.5),new K(.5,0),new K(0,.5)],t=12,i=0,n=Math.PI*2){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:i,phiLength:n},t=Math.floor(t),n=Gi(n,0,Math.PI*2);const s=[],a=[],o=[],l=[],c=[],h=1/t,u=new S,d=new K,p=new S,m=new S,A=new S;let g=0,y=0;for(let v=0;v<=e.length-1;v++)switch(v){case 0:g=e[v+1].x-e[v].x,y=e[v+1].y-e[v].y,p.x=y*1,p.y=-g,p.z=y*0,A.copy(p),p.normalize(),l.push(p.x,p.y,p.z);break;case e.length-1:l.push(A.x,A.y,A.z);break;default:g=e[v+1].x-e[v].x,y=e[v+1].y-e[v].y,p.x=y*1,p.y=-g,p.z=y*0,m.copy(p),p.x+=A.x,p.y+=A.y,p.z+=A.z,p.normalize(),l.push(p.x,p.y,p.z),A.copy(m)}for(let v=0;v<=t;v++){const _=i+v*h*n,b=Math.sin(_),T=Math.cos(_);for(let E=0;E<=e.length-1;E++){u.x=e[E].x*b,u.y=e[E].y,u.z=e[E].x*T,a.push(u.x,u.y,u.z),d.x=v/t,d.y=E/(e.length-1),o.push(d.x,d.y);const M=l[3*E+0]*b,I=l[3*E+1],C=l[3*E+0]*T;c.push(M,I,C)}}for(let v=0;v<t;v++)for(let _=0;_<e.length-1;_++){const b=_+v*e.length,T=b,E=b+e.length,M=b+e.length+1,I=b+1;s.push(T,E,I),s.push(M,I,E)}this.setIndex(s),this.setAttribute("position",new Ee(a,3)),this.setAttribute("uv",new Ee(o,2)),this.setAttribute("normal",new Ee(c,3))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Du(e.points,e.segments,e.phiStart,e.phiLength)}}class Bp extends Du{constructor(e=1,t=1,i=4,n=8){const s=new Fc;s.absarc(0,-t/2,e,Math.PI*1.5,0),s.absarc(0,t/2,e,0,Math.PI*.5),super(s.getPoints(i),n),this.type="CapsuleGeometry",this.parameters={radius:e,length:t,capSegments:i,radialSegments:n}}static fromJSON(e){return new Bp(e.radius,e.length,e.capSegments,e.radialSegments)}}class Lp extends Je{constructor(e=1,t=32,i=0,n=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:e,segments:t,thetaStart:i,thetaLength:n},t=Math.max(3,t);const s=[],a=[],o=[],l=[],c=new S,h=new K;a.push(0,0,0),o.push(0,0,1),l.push(.5,.5);for(let u=0,d=3;u<=t;u++,d+=3){const p=i+u/t*n;c.x=e*Math.cos(p),c.y=e*Math.sin(p),a.push(c.x,c.y,c.z),o.push(0,0,1),h.x=(a[d]/e+1)/2,h.y=(a[d+1]/e+1)/2,l.push(h.x,h.y)}for(let u=1;u<=t;u++)s.push(u,u+1,0);this.setIndex(s),this.setAttribute("position",new Ee(a,3)),this.setAttribute("normal",new Ee(o,3)),this.setAttribute("uv",new Ee(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Lp(e.radius,e.segments,e.thetaStart,e.thetaLength)}}class sn extends Je{constructor(e=1,t=1,i=1,n=32,s=1,a=!1,o=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:i,radialSegments:n,heightSegments:s,openEnded:a,thetaStart:o,thetaLength:l};const c=this;n=Math.floor(n),s=Math.floor(s);const h=[],u=[],d=[],p=[];let m=0;const A=[],g=i/2;let y=0;v(),a===!1&&(e>0&&_(!0),t>0&&_(!1)),this.setIndex(h),this.setAttribute("position",new Ee(u,3)),this.setAttribute("normal",new Ee(d,3)),this.setAttribute("uv",new Ee(p,2));function v(){const b=new S,T=new S;let E=0;const M=(t-e)/i;for(let I=0;I<=s;I++){const C=[],x=I/s,D=x*(t-e)+e;for(let U=0;U<=n;U++){const O=U/n,N=O*l+o,H=Math.sin(N),V=Math.cos(N);T.x=D*H,T.y=-x*i+g,T.z=D*V,u.push(T.x,T.y,T.z),b.set(H,M,V).normalize(),d.push(b.x,b.y,b.z),p.push(O,1-x),C.push(m++)}A.push(C)}for(let I=0;I<n;I++)for(let C=0;C<s;C++){const x=A[C][I],D=A[C+1][I],U=A[C+1][I+1],O=A[C][I+1];h.push(x,D,O),h.push(D,U,O),E+=6}c.addGroup(y,E,0),y+=E}function _(b){const T=m,E=new K,M=new S;let I=0;const C=b===!0?e:t,x=b===!0?1:-1;for(let U=1;U<=n;U++)u.push(0,g*x,0),d.push(0,x,0),p.push(.5,.5),m++;const D=m;for(let U=0;U<=n;U++){const N=U/n*l+o,H=Math.cos(N),V=Math.sin(N);M.x=C*V,M.y=g*x,M.z=C*H,u.push(M.x,M.y,M.z),d.push(0,x,0),E.x=H*.5+.5,E.y=V*.5*x+.5,p.push(E.x,E.y),m++}for(let U=0;U<n;U++){const O=T+U,N=D+U;b===!0?h.push(N,N+1,O):h.push(N+1,N,O),I+=3}c.addGroup(y,I,b===!0?1:2),y+=I}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new sn(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Op extends sn{constructor(e=1,t=1,i=32,n=1,s=!1,a=0,o=Math.PI*2){super(0,e,t,i,n,s,a,o),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:i,heightSegments:n,openEnded:s,thetaStart:a,thetaLength:o}}static fromJSON(e){return new Op(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class qa extends Je{constructor(e=[],t=[],i=1,n=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:i,detail:n};const s=[],a=[];o(n),c(i),h(),this.setAttribute("position",new Ee(s,3)),this.setAttribute("normal",new Ee(s.slice(),3)),this.setAttribute("uv",new Ee(a,2)),n===0?this.computeVertexNormals():this.normalizeNormals();function o(v){const _=new S,b=new S,T=new S;for(let E=0;E<t.length;E+=3)p(t[E+0],_),p(t[E+1],b),p(t[E+2],T),l(_,b,T,v)}function l(v,_,b,T){const E=T+1,M=[];for(let I=0;I<=E;I++){M[I]=[];const C=v.clone().lerp(b,I/E),x=_.clone().lerp(b,I/E),D=E-I;for(let U=0;U<=D;U++)U===0&&I===E?M[I][U]=C:M[I][U]=C.clone().lerp(x,U/D)}for(let I=0;I<E;I++)for(let C=0;C<2*(E-I)-1;C++){const x=Math.floor(C/2);C%2===0?(d(M[I][x+1]),d(M[I+1][x]),d(M[I][x])):(d(M[I][x+1]),d(M[I+1][x+1]),d(M[I+1][x]))}}function c(v){const _=new S;for(let b=0;b<s.length;b+=3)_.x=s[b+0],_.y=s[b+1],_.z=s[b+2],_.normalize().multiplyScalar(v),s[b+0]=_.x,s[b+1]=_.y,s[b+2]=_.z}function h(){const v=new S;for(let _=0;_<s.length;_+=3){v.x=s[_+0],v.y=s[_+1],v.z=s[_+2];const b=g(v)/2/Math.PI+.5,T=y(v)/Math.PI+.5;a.push(b,1-T)}m(),u()}function u(){for(let v=0;v<a.length;v+=6){const _=a[v+0],b=a[v+2],T=a[v+4],E=Math.max(_,b,T),M=Math.min(_,b,T);E>.9&&M<.1&&(_<.2&&(a[v+0]+=1),b<.2&&(a[v+2]+=1),T<.2&&(a[v+4]+=1))}}function d(v){s.push(v.x,v.y,v.z)}function p(v,_){const b=v*3;_.x=e[b+0],_.y=e[b+1],_.z=e[b+2]}function m(){const v=new S,_=new S,b=new S,T=new S,E=new K,M=new K,I=new K;for(let C=0,x=0;C<s.length;C+=9,x+=6){v.set(s[C+0],s[C+1],s[C+2]),_.set(s[C+3],s[C+4],s[C+5]),b.set(s[C+6],s[C+7],s[C+8]),E.set(a[x+0],a[x+1]),M.set(a[x+2],a[x+3]),I.set(a[x+4],a[x+5]),T.copy(v).add(_).add(b).divideScalar(3);const D=g(T);A(E,x+0,v,D),A(M,x+2,_,D),A(I,x+4,b,D)}}function A(v,_,b,T){T<0&&v.x===1&&(a[_]=v.x-1),b.x===0&&b.z===0&&(a[_]=T/2/Math.PI+.5)}function g(v){return Math.atan2(v.z,-v.x)}function y(v){return Math.atan2(-v.y,Math.sqrt(v.x*v.x+v.z*v.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new qa(e.vertices,e.indices,e.radius,e.details)}}class Up extends qa{constructor(e=1,t=0){const i=(1+Math.sqrt(5))/2,n=1/i,s=[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-n,-i,0,-n,i,0,n,-i,0,n,i,-n,-i,0,-n,i,0,n,-i,0,n,i,0,-i,0,-n,i,0,-n,-i,0,n,i,0,n],a=[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9];super(s,a,e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Up(e.radius,e.detail)}}const Fp=new S,Np=new S,n_=new S,kp=new ts;class mx extends Je{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},e!==null){const n=Math.pow(10,4),s=Math.cos(Bo*t),a=e.getIndex(),o=e.getAttribute("position"),l=a?a.count:o.count,c=[0,0,0],h=["a","b","c"],u=new Array(3),d={},p=[];for(let m=0;m<l;m+=3){a?(c[0]=a.getX(m),c[1]=a.getX(m+1),c[2]=a.getX(m+2)):(c[0]=m,c[1]=m+1,c[2]=m+2);const{a:A,b:g,c:y}=kp;if(A.fromBufferAttribute(o,c[0]),g.fromBufferAttribute(o,c[1]),y.fromBufferAttribute(o,c[2]),kp.getNormal(n_),u[0]=`${Math.round(A.x*n)},${Math.round(A.y*n)},${Math.round(A.z*n)}`,u[1]=`${Math.round(g.x*n)},${Math.round(g.y*n)},${Math.round(g.z*n)}`,u[2]=`${Math.round(y.x*n)},${Math.round(y.y*n)},${Math.round(y.z*n)}`,!(u[0]===u[1]||u[1]===u[2]||u[2]===u[0]))for(let v=0;v<3;v++){const _=(v+1)%3,b=u[v],T=u[_],E=kp[h[v]],M=kp[h[_]],I=`${b}_${T}`,C=`${T}_${b}`;C in d&&d[C]?(n_.dot(d[C].normal)<=s&&(p.push(E.x,E.y,E.z),p.push(M.x,M.y,M.z)),d[C]=null):I in d||(d[I]={index0:c[v],index1:c[_],normal:n_.clone()})}}for(const m in d)if(d[m]){const{index0:A,index1:g}=d[m];Fp.fromBufferAttribute(o,A),Np.fromBufferAttribute(o,g),p.push(Fp.x,Fp.y,Fp.z),p.push(Np.x,Np.y,Np.z)}this.setAttribute("position",new Ee(p,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}class rr extends Fc{constructor(e){super(e),this.uuid=Cs(),this.type="Shape",this.holes=[]}getPointsHoles(e){const t=[];for(let i=0,n=this.holes.length;i<n;i++)t[i]=this.holes[i].getPoints(e);return t}extractPoints(e){return{shape:this.getPoints(e),holes:this.getPointsHoles(e)}}copy(e){super.copy(e),this.holes=[];for(let t=0,i=e.holes.length;t<i;t++){const n=e.holes[t];this.holes.push(n.clone())}return this}toJSON(){const e=super.toJSON();e.uuid=this.uuid,e.holes=[];for(let t=0,i=this.holes.length;t<i;t++){const n=this.holes[t];e.holes.push(n.toJSON())}return e}fromJSON(e){super.fromJSON(e),this.uuid=e.uuid,this.holes=[];for(let t=0,i=e.holes.length;t<i;t++){const n=e.holes[t];this.holes.push(new Fc().fromJSON(n))}return this}}const bO={triangulate:function(r,e,t=2){const i=e&&e.length,n=i?e[0]*t:r.length;let s=gx(r,0,n,t,!0);const a=[];if(!s||s.next===s.prev)return a;let o,l,c,h,u,d,p;if(i&&(s=EO(r,e,s,t)),r.length>80*t){o=c=r[0],l=h=r[1];for(let m=t;m<n;m+=t)u=r[m],d=r[m+1],u<o&&(o=u),d<l&&(l=d),u>c&&(c=u),d>h&&(h=d);p=Math.max(c-o,h-l),p=p!==0?32767/p:0}return Ru(s,a,t,o,l,p,0),a}};function gx(r,e,t,i,n){let s,a;if(n===FO(r,e,t,i)>0)for(s=e;s<t;s+=i)a=_x(s,r[s],r[s+1],a);else for(s=t-i;s>=e;s-=i)a=_x(s,r[s],r[s+1],a);return a&&Gp(a,a.next)&&(Lu(a),a=a.next),a}function Ko(r,e){if(!r)return r;e||(e=r);let t=r,i;do if(i=!1,!t.steiner&&(Gp(t,t.next)||Ri(t.prev,t,t.next)===0)){if(Lu(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function Ru(r,e,t,i,n,s,a){if(!r)return;!a&&s&&DO(r,i,n,s);let o=r,l,c;for(;r.prev!==r.next;){if(l=r.prev,c=r.next,s?CO(r,i,n,s):wO(r)){e.push(l.i/t|0),e.push(r.i/t|0),e.push(c.i/t|0),Lu(r),r=c.next,o=c.next;continue}if(r=c,r===o){a?a===1?(r=xO(Ko(r),e,t),Ru(r,e,t,i,n,s,2)):a===2&&SO(r,e,t,i,n,s):Ru(Ko(r),e,t,i,n,s,1);break}}}function wO(r){const e=r.prev,t=r,i=r.next;if(Ri(e,t,i)>=0)return!1;const n=e.x,s=t.x,a=i.x,o=e.y,l=t.y,c=i.y,h=n<s?n<a?n:a:s<a?s:a,u=o<l?o<c?o:c:l<c?l:c,d=n>s?n>a?n:a:s>a?s:a,p=o>l?o>c?o:c:l>c?l:c;let m=i.next;for(;m!==e;){if(m.x>=h&&m.x<=d&&m.y>=u&&m.y<=p&&Nc(n,o,s,l,a,c,m.x,m.y)&&Ri(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function CO(r,e,t,i){const n=r.prev,s=r,a=r.next;if(Ri(n,s,a)>=0)return!1;const o=n.x,l=s.x,c=a.x,h=n.y,u=s.y,d=a.y,p=o<l?o<c?o:c:l<c?l:c,m=h<u?h<d?h:d:u<d?u:d,A=o>l?o>c?o:c:l>c?l:c,g=h>u?h>d?h:d:u>d?u:d,y=s_(p,m,e,t,i),v=s_(A,g,e,t,i);let _=r.prevZ,b=r.nextZ;for(;_&&_.z>=y&&b&&b.z<=v;){if(_.x>=p&&_.x<=A&&_.y>=m&&_.y<=g&&_!==n&&_!==a&&Nc(o,h,l,u,c,d,_.x,_.y)&&Ri(_.prev,_,_.next)>=0||(_=_.prevZ,b.x>=p&&b.x<=A&&b.y>=m&&b.y<=g&&b!==n&&b!==a&&Nc(o,h,l,u,c,d,b.x,b.y)&&Ri(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;_&&_.z>=y;){if(_.x>=p&&_.x<=A&&_.y>=m&&_.y<=g&&_!==n&&_!==a&&Nc(o,h,l,u,c,d,_.x,_.y)&&Ri(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;b&&b.z<=v;){if(b.x>=p&&b.x<=A&&b.y>=m&&b.y<=g&&b!==n&&b!==a&&Nc(o,h,l,u,c,d,b.x,b.y)&&Ri(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function xO(r,e,t){let i=r;do{const n=i.prev,s=i.next.next;!Gp(n,s)&&Ax(n,i,i.next,s)&&Bu(n,s)&&Bu(s,n)&&(e.push(n.i/t|0),e.push(i.i/t|0),e.push(s.i/t|0),Lu(i),Lu(i.next),i=r=s),i=i.next}while(i!==r);return Ko(i)}function SO(r,e,t,i,n,s){let a=r;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&LO(a,o)){let l=yx(a,o);a=Ko(a,a.next),l=Ko(l,l.next),Ru(a,e,t,i,n,s,0),Ru(l,e,t,i,n,s,0);return}o=o.next}a=a.next}while(a!==r)}function EO(r,e,t,i){const n=[];let s,a,o,l,c;for(s=0,a=e.length;s<a;s++)o=e[s]*i,l=s<a-1?e[s+1]*i:r.length,c=gx(r,o,l,i,!1),c===c.next&&(c.steiner=!0),n.push(BO(c));for(n.sort(MO),s=0;s<n.length;s++)t=TO(n[s],t);return t}function MO(r,e){return r.x-e.x}function TO(r,e){const t=IO(r,e);if(!t)return e;const i=yx(t,r);return Ko(i,i.next),Ko(t,t.next)}function IO(r,e){let t=e,i=-1/0,n;const s=r.x,a=r.y;do{if(a<=t.y&&a>=t.next.y&&t.next.y!==t.y){const d=t.x+(a-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=s&&d>i&&(i=d,n=t.x<t.next.x?t:t.next,d===s))return n}t=t.next}while(t!==e);if(!n)return null;const o=n,l=n.x,c=n.y;let h=1/0,u;t=n;do s>=t.x&&t.x>=l&&s!==t.x&&Nc(a<c?s:i,a,l,c,a<c?i:s,a,t.x,t.y)&&(u=Math.abs(a-t.y)/(s-t.x),Bu(t,r)&&(u<h||u===h&&(t.x>n.x||t.x===n.x&&PO(n,t)))&&(n=t,h=u)),t=t.next;while(t!==o);return n}function PO(r,e){return Ri(r.prev,r,e.prev)<0&&Ri(e.next,r,r.next)<0}function DO(r,e,t,i){let n=r;do n.z===0&&(n.z=s_(n.x,n.y,e,t,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==r);n.prevZ.nextZ=null,n.prevZ=null,RO(n)}function RO(r){let e,t,i,n,s,a,o,l,c=1;do{for(t=r,r=null,s=null,a=0;t;){for(a++,i=t,o=0,e=0;e<c&&(o++,i=i.nextZ,!!i);e++);for(l=c;o>0||l>0&&i;)o!==0&&(l===0||!i||t.z<=i.z)?(n=t,t=t.nextZ,o--):(n=i,i=i.nextZ,l--),s?s.nextZ=n:r=n,n.prevZ=s,s=n;t=i}s.nextZ=null,c*=2}while(a>1);return r}function s_(r,e,t,i,n){return r=(r-t)*n|0,e=(e-i)*n|0,r=(r|r<<8)&16711935,r=(r|r<<4)&252645135,r=(r|r<<2)&858993459,r=(r|r<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,r|e<<1}function BO(r){let e=r,t=r;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==r);return t}function Nc(r,e,t,i,n,s,a,o){return(n-a)*(e-o)>=(r-a)*(s-o)&&(r-a)*(i-o)>=(t-a)*(e-o)&&(t-a)*(s-o)>=(n-a)*(i-o)}function LO(r,e){return r.next.i!==e.i&&r.prev.i!==e.i&&!OO(r,e)&&(Bu(r,e)&&Bu(e,r)&&UO(r,e)&&(Ri(r.prev,r,e.prev)||Ri(r,e.prev,e))||Gp(r,e)&&Ri(r.prev,r,r.next)>0&&Ri(e.prev,e,e.next)>0)}function Ri(r,e,t){return(e.y-r.y)*(t.x-e.x)-(e.x-r.x)*(t.y-e.y)}function Gp(r,e){return r.x===e.x&&r.y===e.y}function Ax(r,e,t,i){const n=Vp(Ri(r,e,t)),s=Vp(Ri(r,e,i)),a=Vp(Ri(t,i,r)),o=Vp(Ri(t,i,e));return!!(n!==s&&a!==o||n===0&&zp(r,t,e)||s===0&&zp(r,i,e)||a===0&&zp(t,r,i)||o===0&&zp(t,e,i))}function zp(r,e,t){return e.x<=Math.max(r.x,t.x)&&e.x>=Math.min(r.x,t.x)&&e.y<=Math.max(r.y,t.y)&&e.y>=Math.min(r.y,t.y)}function Vp(r){return r>0?1:r<0?-1:0}function OO(r,e){let t=r;do{if(t.i!==r.i&&t.next.i!==r.i&&t.i!==e.i&&t.next.i!==e.i&&Ax(t,t.next,r,e))return!0;t=t.next}while(t!==r);return!1}function Bu(r,e){return Ri(r.prev,r,r.next)<0?Ri(r,e,r.next)>=0&&Ri(r,r.prev,e)>=0:Ri(r,e,r.prev)<0||Ri(r,r.next,e)<0}function UO(r,e){let t=r,i=!1;const n=(r.x+e.x)/2,s=(r.y+e.y)/2;do t.y>s!=t.next.y>s&&t.next.y!==t.y&&n<(t.next.x-t.x)*(s-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==r);return i}function yx(r,e){const t=new r_(r.i,r.x,r.y),i=new r_(e.i,e.x,e.y),n=r.next,s=e.prev;return r.next=e,e.prev=r,t.next=n,n.prev=t,i.next=t,t.prev=i,s.next=i,i.prev=s,i}function _x(r,e,t,i){const n=new r_(r,e,t);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function Lu(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ)}function r_(r,e,t){this.i=r,this.x=e,this.y=t,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function FO(r,e,t,i){let n=0;for(let s=e,a=t-i;s<t;s+=i)n+=(r[a]-r[s])*(r[s+1]+r[a+1]),a=s;return n}class ar{static area(e){const t=e.length;let i=0;for(let n=t-1,s=0;s<t;n=s++)i+=e[n].x*e[s].y-e[s].x*e[n].y;return i*.5}static isClockWise(e){return ar.area(e)<0}static triangulateShape(e,t){const i=[],n=[],s=[];vx(e),bx(i,e);let a=e.length;t.forEach(vx);for(let l=0;l<t.length;l++)n.push(a),a+=t[l].length,bx(i,t[l]);const o=bO.triangulate(i,n);for(let l=0;l<o.length;l+=3)s.push(o.slice(l,l+3));return s}}function vx(r){const e=r.length;e>2&&r[e-1].equals(r[0])&&r.pop()}function bx(r,e){for(let t=0;t<e.length;t++)r.push(e[t].x),r.push(e[t].y)}class Hp extends Je{constructor(e=new rr([new K(.5,.5),new K(-.5,.5),new K(-.5,-.5),new K(.5,-.5)]),t={}){super(),this.type="ExtrudeGeometry",this.parameters={shapes:e,options:t},e=Array.isArray(e)?e:[e];const i=this,n=[],s=[];for(let o=0,l=e.length;o<l;o++){const c=e[o];a(c)}this.setAttribute("position",new Ee(n,3)),this.setAttribute("uv",new Ee(s,2)),this.computeVertexNormals();function a(o){const l=[],c=t.curveSegments!==void 0?t.curveSegments:12,h=t.steps!==void 0?t.steps:1,u=t.depth!==void 0?t.depth:1;let d=t.bevelEnabled!==void 0?t.bevelEnabled:!0,p=t.bevelThickness!==void 0?t.bevelThickness:.2,m=t.bevelSize!==void 0?t.bevelSize:p-.1,A=t.bevelOffset!==void 0?t.bevelOffset:0,g=t.bevelSegments!==void 0?t.bevelSegments:3;const y=t.extrudePath,v=t.UVGenerator!==void 0?t.UVGenerator:NO;let _,b=!1,T,E,M,I;y&&(_=y.getSpacedPoints(h),b=!0,d=!1,T=y.computeFrenetFrames(h,!1),E=new S,M=new S,I=new S),d||(g=0,p=0,m=0,A=0);const C=o.extractPoints(c);let x=C.shape;const D=C.holes;if(!ar.isClockWise(x)){x=x.reverse();for(let F=0,xe=D.length;F<xe;F++){const be=D[F];ar.isClockWise(be)&&(D[F]=be.reverse())}}const O=ar.triangulateShape(x,D),N=x;for(let F=0,xe=D.length;F<xe;F++){const be=D[F];x=x.concat(be)}function H(F,xe,be){return xe||console.error("THREE.ExtrudeGeometry: vec does not exist"),F.clone().addScaledVector(xe,be)}const V=x.length,X=O.length;function W(F,xe,be){let Ne,ge,ut;const ke=F.x-xe.x,Ve=F.y-xe.y,z=be.x-F.x,B=be.y-F.y,ne=ke*ke+Ve*Ve,de=ke*B-Ve*z;if(Math.abs(de)>Number.EPSILON){const ye=Math.sqrt(ne),pe=Math.sqrt(z*z+B*B),nt=xe.x-Ve/ye,Le=xe.y+ke/ye,Ye=be.x-B/pe,yt=be.y+z/pe,Me=((Ye-nt)*B-(yt-Le)*z)/(ke*B-Ve*z);Ne=nt+ke*Me-F.x,ge=Le+Ve*Me-F.y;const je=Ne*Ne+ge*ge;if(je<=2)return new K(Ne,ge);ut=Math.sqrt(je/2)}else{let ye=!1;ke>Number.EPSILON?z>Number.EPSILON&&(ye=!0):ke<-Number.EPSILON?z<-Number.EPSILON&&(ye=!0):Math.sign(Ve)===Math.sign(B)&&(ye=!0),ye?(Ne=-Ve,ge=ke,ut=Math.sqrt(ne)):(Ne=ke,ge=Ve,ut=Math.sqrt(ne/2))}return new K(Ne/ut,ge/ut)}const ce=[];for(let F=0,xe=N.length,be=xe-1,Ne=F+1;F<xe;F++,be++,Ne++)be===xe&&(be=0),Ne===xe&&(Ne=0),ce[F]=W(N[F],N[be],N[Ne]);const ue=[];let we,Pe=ce.concat();for(let F=0,xe=D.length;F<xe;F++){const be=D[F];we=[];for(let Ne=0,ge=be.length,ut=ge-1,ke=Ne+1;Ne<ge;Ne++,ut++,ke++)ut===ge&&(ut=0),ke===ge&&(ke=0),we[Ne]=W(be[Ne],be[ut],be[ke]);ue.push(we),Pe=Pe.concat(we)}for(let F=0;F<g;F++){const xe=F/g,be=p*Math.cos(xe*Math.PI/2),Ne=m*Math.sin(xe*Math.PI/2)+A;for(let ge=0,ut=N.length;ge<ut;ge++){const ke=H(N[ge],ce[ge],Ne);Ce(ke.x,ke.y,-be)}for(let ge=0,ut=D.length;ge<ut;ge++){const ke=D[ge];we=ue[ge];for(let Ve=0,z=ke.length;Ve<z;Ve++){const B=H(ke[Ve],we[Ve],Ne);Ce(B.x,B.y,-be)}}}const Qe=m+A;for(let F=0;F<V;F++){const xe=d?H(x[F],Pe[F],Qe):x[F];b?(M.copy(T.normals[0]).multiplyScalar(xe.x),E.copy(T.binormals[0]).multiplyScalar(xe.y),I.copy(_[0]).add(M).add(E),Ce(I.x,I.y,I.z)):Ce(xe.x,xe.y,0)}for(let F=1;F<=h;F++)for(let xe=0;xe<V;xe++){const be=d?H(x[xe],Pe[xe],Qe):x[xe];b?(M.copy(T.normals[F]).multiplyScalar(be.x),E.copy(T.binormals[F]).multiplyScalar(be.y),I.copy(_[F]).add(M).add(E),Ce(I.x,I.y,I.z)):Ce(be.x,be.y,u/h*F)}for(let F=g-1;F>=0;F--){const xe=F/g,be=p*Math.cos(xe*Math.PI/2),Ne=m*Math.sin(xe*Math.PI/2)+A;for(let ge=0,ut=N.length;ge<ut;ge++){const ke=H(N[ge],ce[ge],Ne);Ce(ke.x,ke.y,u+be)}for(let ge=0,ut=D.length;ge<ut;ge++){const ke=D[ge];we=ue[ge];for(let Ve=0,z=ke.length;Ve<z;Ve++){const B=H(ke[Ve],we[Ve],Ne);b?Ce(B.x,B.y+_[h-1].y,_[h-1].x+be):Ce(B.x,B.y,u+be)}}}ie(),oe();function ie(){const F=n.length/3;if(d){let xe=0,be=V*xe;for(let Ne=0;Ne<X;Ne++){const ge=O[Ne];Xe(ge[2]+be,ge[1]+be,ge[0]+be)}xe=h+g*2,be=V*xe;for(let Ne=0;Ne<X;Ne++){const ge=O[Ne];Xe(ge[0]+be,ge[1]+be,ge[2]+be)}}else{for(let xe=0;xe<X;xe++){const be=O[xe];Xe(be[2],be[1],be[0])}for(let xe=0;xe<X;xe++){const be=O[xe];Xe(be[0]+V*h,be[1]+V*h,be[2]+V*h)}}i.addGroup(F,n.length/3-F,0)}function oe(){const F=n.length/3;let xe=0;me(N,xe),xe+=N.length;for(let be=0,Ne=D.length;be<Ne;be++){const ge=D[be];me(ge,xe),xe+=ge.length}i.addGroup(F,n.length/3-F,1)}function me(F,xe){let be=F.length;for(;--be>=0;){const Ne=be;let ge=be-1;ge<0&&(ge=F.length-1);for(let ut=0,ke=h+g*2;ut<ke;ut++){const Ve=V*ut,z=V*(ut+1),B=xe+Ne+Ve,ne=xe+ge+Ve,de=xe+ge+z,ye=xe+Ne+z;dt(B,ne,de,ye)}}}function Ce(F,xe,be){l.push(F),l.push(xe),l.push(be)}function Xe(F,xe,be){Ke(F),Ke(xe),Ke(be);const Ne=n.length/3,ge=v.generateTopUV(i,n,Ne-3,Ne-2,Ne-1);gt(ge[0]),gt(ge[1]),gt(ge[2])}function dt(F,xe,be,Ne){Ke(F),Ke(xe),Ke(Ne),Ke(xe),Ke(be),Ke(Ne);const ge=n.length/3,ut=v.generateSideWallUV(i,n,ge-6,ge-3,ge-2,ge-1);gt(ut[0]),gt(ut[1]),gt(ut[3]),gt(ut[1]),gt(ut[2]),gt(ut[3])}function Ke(F){n.push(l[F*3+0]),n.push(l[F*3+1]),n.push(l[F*3+2])}function gt(F){s.push(F.x),s.push(F.y)}}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON(),t=this.parameters.shapes,i=this.parameters.options;return kO(t,i,e)}static fromJSON(e,t){const i=[];for(let s=0,a=e.shapes.length;s<a;s++){const o=t[e.shapes[s]];i.push(o)}const n=e.options.extrudePath;return n!==void 0&&(e.options.extrudePath=new Rp[n.type]().fromJSON(n)),new Hp(i,e.options)}}const NO={generateTopUV:function(r,e,t,i,n){const s=e[t*3],a=e[t*3+1],o=e[i*3],l=e[i*3+1],c=e[n*3],h=e[n*3+1];return[new K(s,a),new K(o,l),new K(c,h)]},generateSideWallUV:function(r,e,t,i,n,s){const a=e[t*3],o=e[t*3+1],l=e[t*3+2],c=e[i*3],h=e[i*3+1],u=e[i*3+2],d=e[n*3],p=e[n*3+1],m=e[n*3+2],A=e[s*3],g=e[s*3+1],y=e[s*3+2];return Math.abs(o-h)<Math.abs(a-c)?[new K(a,1-l),new K(c,1-u),new K(d,1-m),new K(A,1-y)]:[new K(o,1-l),new K(h,1-u),new K(p,1-m),new K(g,1-y)]}};function kO(r,e,t){if(t.shapes=[],Array.isArray(r))for(let i=0,n=r.length;i<n;i++){const s=r[i];t.shapes.push(s.uuid)}else t.shapes.push(r.uuid);return t.options=Object.assign({},e),e.extrudePath!==void 0&&(t.options.extrudePath=e.extrudePath.toJSON()),t}class Qp extends qa{constructor(e=1,t=0){const i=(1+Math.sqrt(5))/2,n=[-1,i,0,1,i,0,-1,-i,0,1,-i,0,0,-1,i,0,1,i,0,-1,-i,0,1,-i,i,0,-1,i,0,1,-i,0,-1,-i,0,1],s=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(n,s,e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Qp(e.radius,e.detail)}}class da extends qa{constructor(e=1,t=0){const i=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],n=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2];super(i,n,e,t),this.type="OctahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new da(e.radius,e.detail)}}class jp extends Je{constructor(e=.5,t=1,i=32,n=1,s=0,a=Math.PI*2){super(),this.type="RingGeometry",this.parameters={innerRadius:e,outerRadius:t,thetaSegments:i,phiSegments:n,thetaStart:s,thetaLength:a},i=Math.max(3,i),n=Math.max(1,n);const o=[],l=[],c=[],h=[];let u=e;const d=(t-e)/n,p=new S,m=new K;for(let A=0;A<=n;A++){for(let g=0;g<=i;g++){const y=s+g/i*a;p.x=u*Math.cos(y),p.y=u*Math.sin(y),l.push(p.x,p.y,p.z),c.push(0,0,1),m.x=(p.x/t+1)/2,m.y=(p.y/t+1)/2,h.push(m.x,m.y)}u+=d}for(let A=0;A<n;A++){const g=A*(i+1);for(let y=0;y<i;y++){const v=y+g,_=v,b=v+i+1,T=v+i+2,E=v+1;o.push(_,b,E),o.push(b,T,E)}}this.setIndex(o),this.setAttribute("position",new Ee(l,3)),this.setAttribute("normal",new Ee(c,3)),this.setAttribute("uv",new Ee(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new jp(e.innerRadius,e.outerRadius,e.thetaSegments,e.phiSegments,e.thetaStart,e.thetaLength)}}class Ou extends Je{constructor(e=new rr([new K(0,.5),new K(-.5,-.5),new K(.5,-.5)]),t=12){super(),this.type="ShapeGeometry",this.parameters={shapes:e,curveSegments:t};const i=[],n=[],s=[],a=[];let o=0,l=0;if(Array.isArray(e)===!1)c(e);else for(let h=0;h<e.length;h++)c(e[h]),this.addGroup(o,l,h),o+=l,l=0;this.setIndex(i),this.setAttribute("position",new Ee(n,3)),this.setAttribute("normal",new Ee(s,3)),this.setAttribute("uv",new Ee(a,2));function c(h){const u=n.length/3,d=h.extractPoints(t);let p=d.shape;const m=d.holes;ar.isClockWise(p)===!1&&(p=p.reverse());for(let g=0,y=m.length;g<y;g++){const v=m[g];ar.isClockWise(v)===!0&&(m[g]=v.reverse())}const A=ar.triangulateShape(p,m);for(let g=0,y=m.length;g<y;g++){const v=m[g];p=p.concat(v)}for(let g=0,y=p.length;g<y;g++){const v=p[g];n.push(v.x,v.y,0),s.push(0,0,1),a.push(v.x,v.y)}for(let g=0,y=A.length;g<y;g++){const v=A[g],_=v[0]+u,b=v[1]+u,T=v[2]+u;i.push(_,b,T),l+=3}}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON(),t=this.parameters.shapes;return GO(t,e)}static fromJSON(e,t){const i=[];for(let n=0,s=e.shapes.length;n<s;n++){const a=t[e.shapes[n]];i.push(a)}return new Ou(i,e.curveSegments)}}function GO(r,e){if(e.shapes=[],Array.isArray(r))for(let t=0,i=r.length;t<i;t++){const n=r[t];e.shapes.push(n.uuid)}else e.shapes.push(r.uuid);return e}class Is extends Je{constructor(e=1,t=32,i=16,n=0,s=Math.PI*2,a=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:i,phiStart:n,phiLength:s,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),i=Math.max(2,Math.floor(i));const l=Math.min(a+o,Math.PI);let c=0;const h=[],u=new S,d=new S,p=[],m=[],A=[],g=[];for(let y=0;y<=i;y++){const v=[],_=y/i;let b=0;y===0&&a===0?b=.5/t:y===i&&l===Math.PI&&(b=-.5/t);for(let T=0;T<=t;T++){const E=T/t;u.x=-e*Math.cos(n+E*s)*Math.sin(a+_*o),u.y=e*Math.cos(a+_*o),u.z=e*Math.sin(n+E*s)*Math.sin(a+_*o),m.push(u.x,u.y,u.z),d.copy(u).normalize(),A.push(d.x,d.y,d.z),g.push(E+b,1-_),v.push(c++)}h.push(v)}for(let y=0;y<i;y++)for(let v=0;v<t;v++){const _=h[y][v+1],b=h[y][v],T=h[y+1][v],E=h[y+1][v+1];(y!==0||a>0)&&p.push(_,b,E),(y!==i-1||l<Math.PI)&&p.push(b,T,E)}this.setIndex(p),this.setAttribute("position",new Ee(m,3)),this.setAttribute("normal",new Ee(A,3)),this.setAttribute("uv",new Ee(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Is(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class Wp extends qa{constructor(e=1,t=0){const i=[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],n=[2,1,0,0,3,2,1,3,0,2,3,1];super(i,n,e,t),this.type="TetrahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Wp(e.radius,e.detail)}}class Xa extends Je{constructor(e=1,t=.4,i=12,n=48,s=Math.PI*2){super(),this.type="TorusGeometry",this.parameters={radius:e,tube:t,radialSegments:i,tubularSegments:n,arc:s},i=Math.floor(i),n=Math.floor(n);const a=[],o=[],l=[],c=[],h=new S,u=new S,d=new S;for(let p=0;p<=i;p++)for(let m=0;m<=n;m++){const A=m/n*s,g=p/i*Math.PI*2;u.x=(e+t*Math.cos(g))*Math.cos(A),u.y=(e+t*Math.cos(g))*Math.sin(A),u.z=t*Math.sin(g),o.push(u.x,u.y,u.z),h.x=e*Math.cos(A),h.y=e*Math.sin(A),d.subVectors(u,h).normalize(),l.push(d.x,d.y,d.z),c.push(m/n),c.push(p/i)}for(let p=1;p<=i;p++)for(let m=1;m<=n;m++){const A=(n+1)*p+m-1,g=(n+1)*(p-1)+m-1,y=(n+1)*(p-1)+m,v=(n+1)*p+m;a.push(A,g,v),a.push(g,y,v)}this.setIndex(a),this.setAttribute("position",new Ee(o,3)),this.setAttribute("normal",new Ee(l,3)),this.setAttribute("uv",new Ee(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Xa(e.radius,e.tube,e.radialSegments,e.tubularSegments,e.arc)}}class qp extends Je{constructor(e=1,t=.4,i=64,n=8,s=2,a=3){super(),this.type="TorusKnotGeometry",this.parameters={radius:e,tube:t,tubularSegments:i,radialSegments:n,p:s,q:a},i=Math.floor(i),n=Math.floor(n);const o=[],l=[],c=[],h=[],u=new S,d=new S,p=new S,m=new S,A=new S,g=new S,y=new S;for(let _=0;_<=i;++_){const b=_/i*s*Math.PI*2;v(b,s,a,e,p),v(b+.01,s,a,e,m),g.subVectors(m,p),y.addVectors(m,p),A.crossVectors(g,y),y.crossVectors(A,g),A.normalize(),y.normalize();for(let T=0;T<=n;++T){const E=T/n*Math.PI*2,M=-t*Math.cos(E),I=t*Math.sin(E);u.x=p.x+(M*y.x+I*A.x),u.y=p.y+(M*y.y+I*A.y),u.z=p.z+(M*y.z+I*A.z),l.push(u.x,u.y,u.z),d.subVectors(u,p).normalize(),c.push(d.x,d.y,d.z),h.push(_/i),h.push(T/n)}}for(let _=1;_<=i;_++)for(let b=1;b<=n;b++){const T=(n+1)*(_-1)+(b-1),E=(n+1)*_+(b-1),M=(n+1)*_+b,I=(n+1)*(_-1)+b;o.push(T,E,I),o.push(E,M,I)}this.setIndex(o),this.setAttribute("position",new Ee(l,3)),this.setAttribute("normal",new Ee(c,3)),this.setAttribute("uv",new Ee(h,2));function v(_,b,T,E,M){const I=Math.cos(_),C=Math.sin(_),x=T/b*_,D=Math.cos(x);M.x=E*(2+D)*.5*I,M.y=E*(2+D)*C*.5,M.z=E*Math.sin(x)*.5}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new qp(e.radius,e.tube,e.tubularSegments,e.radialSegments,e.p,e.q)}}class Uu extends Je{constructor(e=new Tu(new S(-1,-1,0),new S(-1,1,0),new S(1,1,0)),t=64,i=1,n=8,s=!1){super(),this.type="TubeGeometry",this.parameters={path:e,tubularSegments:t,radius:i,radialSegments:n,closed:s};const a=e.computeFrenetFrames(t,s);this.tangents=a.tangents,this.normals=a.normals,this.binormals=a.binormals;const o=new S,l=new S,c=new K;let h=new S;const u=[],d=[],p=[],m=[];A(),this.setIndex(m),this.setAttribute("position",new Ee(u,3)),this.setAttribute("normal",new Ee(d,3)),this.setAttribute("uv",new Ee(p,2));function A(){for(let _=0;_<t;_++)g(_);g(s===!1?t:0),v(),y()}function g(_){h=e.getPointAt(_/t,h);const b=a.normals[_],T=a.binormals[_];for(let E=0;E<=n;E++){const M=E/n*Math.PI*2,I=Math.sin(M),C=-Math.cos(M);l.x=C*b.x+I*T.x,l.y=C*b.y+I*T.y,l.z=C*b.z+I*T.z,l.normalize(),d.push(l.x,l.y,l.z),o.x=h.x+i*l.x,o.y=h.y+i*l.y,o.z=h.z+i*l.z,u.push(o.x,o.y,o.z)}}function y(){for(let _=1;_<=t;_++)for(let b=1;b<=n;b++){const T=(n+1)*(_-1)+(b-1),E=(n+1)*_+(b-1),M=(n+1)*_+b,I=(n+1)*(_-1)+b;m.push(T,E,I),m.push(E,M,I)}}function v(){for(let _=0;_<=t;_++)for(let b=0;b<=n;b++)c.x=_/t,c.y=b/n,p.push(c.x,c.y)}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON();return e.path=this.parameters.path.toJSON(),e}static fromJSON(e){return new Uu(new Rp[e.path.type]().fromJSON(e.path),e.tubularSegments,e.radius,e.radialSegments,e.closed)}}class Xp extends Je{constructor(e=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:e},e!==null){const t=[],i=new Set,n=new S,s=new S;if(e.index!==null){const a=e.attributes.position,o=e.index;let l=e.groups;l.length===0&&(l=[{start:0,count:o.count,materialIndex:0}]);for(let c=0,h=l.length;c<h;++c){const u=l[c],d=u.start,p=u.count;for(let m=d,A=d+p;m<A;m+=3)for(let g=0;g<3;g++){const y=o.getX(m+g),v=o.getX(m+(g+1)%3);n.fromBufferAttribute(a,y),s.fromBufferAttribute(a,v),wx(n,s,i)===!0&&(t.push(n.x,n.y,n.z),t.push(s.x,s.y,s.z))}}}else{const a=e.attributes.position;for(let o=0,l=a.count/3;o<l;o++)for(let c=0;c<3;c++){const h=3*o+c,u=3*o+(c+1)%3;n.fromBufferAttribute(a,h),s.fromBufferAttribute(a,u),wx(n,s,i)===!0&&(t.push(n.x,n.y,n.z),t.push(s.x,s.y,s.z))}}this.setAttribute("position",new Ee(t,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}function wx(r,e,t){const i=`${r.x},${r.y},${r.z}-${e.x},${e.y},${e.z}`,n=`${e.x},${e.y},${e.z}-${r.x},${r.y},${r.z}`;return t.has(i)===!0||t.has(n)===!0?!1:(t.add(i),t.add(n),!0)}var Cx=Object.freeze({__proto__:null,BoxGeometry:gi,CapsuleGeometry:Bp,CircleGeometry:Lp,ConeGeometry:Op,CylinderGeometry:sn,DodecahedronGeometry:Up,EdgesGeometry:mx,ExtrudeGeometry:Hp,IcosahedronGeometry:Qp,LatheGeometry:Du,OctahedronGeometry:da,PlaneGeometry:ca,PolyhedronGeometry:qa,RingGeometry:jp,ShapeGeometry:Ou,SphereGeometry:Is,TetrahedronGeometry:Wp,TorusGeometry:Xa,TorusKnotGeometry:qp,TubeGeometry:Uu,WireframeGeometry:Xp});class xx extends tn{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new ee(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}class Sx extends nn{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Ya extends tn{constructor(e){super(),this.isMeshStandardMaterial=!0,this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new ee(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 ee(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Us,this.normalScale=new K(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 Pt,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Jo extends Ya{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 K(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Gi(2.5*(this.ior-1)/(this.ior+1),0,2.5)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new ee(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 ee(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new ee(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class Zo extends tn{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ee(16777215),this.specular=new ee(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ee(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Us,this.normalScale=new K(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Pt,this.combine=$l,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Ex extends tn{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new ee(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ee(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Us,this.normalScale=new K(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class a_ extends tn{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Us,this.normalScale=new K(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class o_ extends tn{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ee(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ee(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Us,this.normalScale=new K(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Pt,this.combine=$l,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Mx extends tn{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new ee(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Us,this.normalScale=new K(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Tx extends Mi{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 el(r,e,t){return!r||!t&&r.constructor===e?r:typeof e.BYTES_PER_ELEMENT=="number"?new e(r):Array.prototype.slice.call(r)}function Ix(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function Px(r){function e(n,s){return r[n]-r[s]}const t=r.length,i=new Array(t);for(let n=0;n!==t;++n)i[n]=n;return i.sort(e),i}function l_(r,e,t){const i=r.length,n=new r.constructor(i);for(let s=0,a=0;a!==i;++s){const o=t[s]*e;for(let l=0;l!==e;++l)n[a++]=r[o+l]}return n}function c_(r,e,t,i){let n=1,s=r[0];for(;s!==void 0&&s[i]===void 0;)s=r[n++];if(s===void 0)return;let a=s[i];if(a!==void 0)if(Array.isArray(a))do a=s[i],a!==void 0&&(e.push(s.time),t.push.apply(t,a)),s=r[n++];while(s!==void 0);else if(a.toArray!==void 0)do a=s[i],a!==void 0&&(e.push(s.time),a.toArray(t,t.length)),s=r[n++];while(s!==void 0);else do a=s[i],a!==void 0&&(e.push(s.time),t.push(a)),s=r[n++];while(s!==void 0)}function zO(r,e,t,i,n=30){const s=r.clone();s.name=e;const a=[];for(let l=0;l<s.tracks.length;++l){const c=s.tracks[l],h=c.getValueSize(),u=[],d=[];for(let p=0;p<c.times.length;++p){const m=c.times[p]*n;if(!(m<t||m>=i)){u.push(c.times[p]);for(let A=0;A<h;++A)d.push(c.values[p*h+A])}}u.length!==0&&(c.times=el(u,c.times.constructor),c.values=el(d,c.values.constructor),a.push(c))}s.tracks=a;let o=1/0;for(let l=0;l<s.tracks.length;++l)o>s.tracks[l].times[0]&&(o=s.tracks[l].times[0]);for(let l=0;l<s.tracks.length;++l)s.tracks[l].shift(-1*o);return s.resetDuration(),s}function VO(r,e=0,t=r,i=30){i<=0&&(i=30);const n=t.tracks.length,s=e/i;for(let a=0;a<n;++a){const o=t.tracks[a],l=o.ValueTypeName;if(l==="bool"||l==="string")continue;const c=r.tracks.find(function(y){return y.name===o.name&&y.ValueTypeName===l});if(c===void 0)continue;let h=0;const u=o.getValueSize();o.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(h=u/3);let d=0;const p=c.getValueSize();c.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(d=p/3);const m=o.times.length-1;let A;if(s<=o.times[0]){const y=h,v=u-h;A=o.values.slice(y,v)}else if(s>=o.times[m]){const y=m*u+h,v=y+u-h;A=o.values.slice(y,v)}else{const y=o.createInterpolant(),v=h,_=u-h;y.evaluate(s),A=y.resultBuffer.slice(v,_)}l==="quaternion"&&new $e().fromArray(A).normalize().conjugate().toArray(A);const g=c.times.length;for(let y=0;y<g;++y){const v=y*p+d;if(l==="quaternion")$e.multiplyQuaternionsFlat(c.values,v,A,0,c.values,v);else{const _=p-d*2;for(let b=0;b<_;++b)c.values[v+b]-=A[b]}}}return r.blendMode=Ow,r}const HO={convertArray:el,isTypedArray:Ix,getKeyframeOrder:Px,sortedArray:l_,flattenJSON:c_,subclip:zO,makeClipAdditive:VO};class kc{constructor(e,t,i,n){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=n!==void 0?n:new t.constructor(i),this.sampleValues=t,this.valueSize=i,this.settings=null,this.DefaultSettings_={}}evaluate(e){const t=this.parameterPositions;let i=this._cachedIndex,n=t[i],s=t[i-1];e:{t:{let a;i:{n:if(!(e<n)){for(let o=i+2;;){if(n===void 0){if(e<s)break n;return i=t.length,this._cachedIndex=i,this.copySampleValue_(i-1)}if(i===o)break;if(s=n,n=t[++i],e<n)break t}a=t.length;break i}if(!(e>=s)){const o=t[1];e<o&&(i=2,s=o);for(let l=i-2;;){if(s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===l)break;if(n=s,s=t[--i-1],e>=s)break t}a=i,i=0;break i}break e}for(;i<a;){const o=i+a>>>1;e<t[o]?a=o:i=o+1}if(n=t[i],s=t[i-1],s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===void 0)return i=t.length,this._cachedIndex=i,this.copySampleValue_(i-1)}this._cachedIndex=i,this.intervalChanged_(i,s,n)}return this.interpolate_(i,s,e,n)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){const t=this.resultBuffer,i=this.sampleValues,n=this.valueSize,s=e*n;for(let a=0;a!==n;++a)t[a]=i[s+a];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}}class Dx extends kc{constructor(e,t,i,n){super(e,t,i,n),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:ic,endingEnd:ic}}intervalChanged_(e,t,i){const n=this.parameterPositions;let s=e-2,a=e+1,o=n[s],l=n[a];if(o===void 0)switch(this.getSettings_().endingStart){case nc:s=e,o=2*t-i;break;case Tf:s=n.length-2,o=t+n[s]-n[s+1];break;default:s=e,o=i}if(l===void 0)switch(this.getSettings_().endingEnd){case nc:a=e,l=2*i-t;break;case Tf:a=1,l=i+n[1]-n[0];break;default:a=e-1,l=t}const c=(i-t)*.5,h=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(l-i),this._offsetPrev=s*h,this._offsetNext=a*h}interpolate_(e,t,i,n){const s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,h=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,p=this._weightNext,m=(i-t)/(n-t),A=m*m,g=A*m,y=-d*g+2*d*A-d*m,v=(1+d)*g+(-1.5-2*d)*A+(-.5+d)*m+1,_=(-1-p)*g+(1.5+p)*A+.5*m,b=p*g-p*A;for(let T=0;T!==o;++T)s[T]=y*a[h+T]+v*a[c+T]+_*a[l+T]+b*a[u+T];return s}}class h_ extends kc{constructor(e,t,i,n){super(e,t,i,n)}interpolate_(e,t,i,n){const s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=e*o,c=l-o,h=(i-t)/(n-t),u=1-h;for(let d=0;d!==o;++d)s[d]=a[c+d]*u+a[l+d]*h;return s}}class Rx extends kc{constructor(e,t,i,n){super(e,t,i,n)}interpolate_(e){return this.copySampleValue_(e-1)}}class or{constructor(e,t,i,n){if(e===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=el(t,this.TimeBufferType),this.values=el(i,this.ValueBufferType),this.setInterpolation(n||this.DefaultInterpolation)}static toJSON(e){const t=e.constructor;let i;if(t.toJSON!==this.toJSON)i=t.toJSON(e);else{i={name:e.name,times:el(e.times,Array),values:el(e.values,Array)};const n=e.getInterpolation();n!==e.DefaultInterpolation&&(i.interpolation=n)}return i.type=e.ValueTypeName,i}InterpolantFactoryMethodDiscrete(e){return new Rx(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new h_(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Dx(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case ec:t=this.InterpolantFactoryMethodDiscrete;break;case tc:t=this.InterpolantFactoryMethodLinear;break;case ry:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){const i="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 new Error(i);return console.warn("THREE.KeyframeTrack:",i),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return ec;case this.InterpolantFactoryMethodLinear:return tc;case this.InterpolantFactoryMethodSmooth:return ry}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){const t=this.times;for(let i=0,n=t.length;i!==n;++i)t[i]+=e}return this}scale(e){if(e!==1){const t=this.times;for(let i=0,n=t.length;i!==n;++i)t[i]*=e}return this}trim(e,t){const i=this.times,n=i.length;let s=0,a=n-1;for(;s!==n&&i[s]<e;)++s;for(;a!==-1&&i[a]>t;)--a;if(++a,s!==0||a!==n){s>=a&&(a=Math.max(a,1),s=a-1);const o=this.getValueSize();this.times=i.slice(s,a),this.values=this.values.slice(s*o,a*o)}return this}validate(){let e=!0;const t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);const i=this.times,n=this.values,s=i.length;s===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==s;o++){const l=i[o];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(a!==null&&a>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,o,l,a),e=!1;break}a=l}if(n!==void 0&&Ix(n))for(let o=0,l=n.length;o!==l;++o){const c=n[o];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),n=this.getInterpolation()===ry,s=e.length-1;let a=1;for(let o=1;o<s;++o){let l=!1;const c=e[o],h=e[o+1];if(c!==h&&(o!==1||c!==e[0]))if(n)l=!0;else{const u=o*i,d=u-i,p=u+i;for(let m=0;m!==i;++m){const A=t[u+m];if(A!==t[d+m]||A!==t[p+m]){l=!0;break}}}if(l){if(o!==a){e[a]=e[o];const u=o*i,d=a*i;for(let p=0;p!==i;++p)t[d+p]=t[u+p]}++a}}if(s>0){e[a]=e[s];for(let o=s*i,l=a*i,c=0;c!==i;++c)t[l+c]=t[o+c];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=this.constructor,n=new i(this.name,e,t);return n.createInterpolant=this.createInterpolant,n}}or.prototype.TimeBufferType=Float32Array,or.prototype.ValueBufferType=Float32Array,or.prototype.DefaultInterpolation=tc;class tl extends or{constructor(e,t,i){super(e,t,i)}}tl.prototype.ValueTypeName="bool",tl.prototype.ValueBufferType=Array,tl.prototype.DefaultInterpolation=ec,tl.prototype.InterpolantFactoryMethodLinear=void 0,tl.prototype.InterpolantFactoryMethodSmooth=void 0;class u_ extends or{}u_.prototype.ValueTypeName="color";class $a extends or{}$a.prototype.ValueTypeName="number";class Bx extends kc{constructor(e,t,i,n){super(e,t,i,n)}interpolate_(e,t,i,n){const s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(i-t)/(n-t);let c=e*o;for(let h=c+o;c!==h;c+=4)$e.slerpFlat(s,0,a,c-o,a,c,l);return s}}class fa extends or{InterpolantFactoryMethodLinear(e){return new Bx(this.times,this.values,this.getValueSize(),e)}}fa.prototype.ValueTypeName="quaternion",fa.prototype.InterpolantFactoryMethodSmooth=void 0;class il extends or{constructor(e,t,i){super(e,t,i)}}il.prototype.ValueTypeName="string",il.prototype.ValueBufferType=Array,il.prototype.DefaultInterpolation=ec,il.prototype.InterpolantFactoryMethodLinear=void 0,il.prototype.InterpolantFactoryMethodSmooth=void 0;class Ka extends or{}Ka.prototype.ValueTypeName="vector";class Ja{constructor(e="",t=-1,i=[],n=ay){this.name=e,this.tracks=i,this.duration=t,this.blendMode=n,this.uuid=Cs(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,n=1/(e.fps||1);for(let a=0,o=i.length;a!==o;++a)t.push(jO(i[a]).scale(n));const s=new this(e.name,e.duration,t,e.blendMode);return s.uuid=e.uuid,s.userData=JSON.parse(e.userData||"{}"),s}static toJSON(e){const t=[],i=e.tracks,n={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let s=0,a=i.length;s!==a;++s)t.push(or.toJSON(i[s]));return n}static CreateFromMorphTargetSequence(e,t,i,n){const s=t.length,a=[];for(let o=0;o<s;o++){let l=[],c=[];l.push((o+s-1)%s,o,(o+1)%s),c.push(0,1,0);const h=Px(l);l=l_(l,1,h),c=l_(c,1,h),!n&&l[0]===0&&(l.push(s),c.push(c[0])),a.push(new $a(".morphTargetInfluences["+t[o].name+"]",l,c).scale(1/i))}return new this(e,-1,a)}static findByName(e,t){let i=e;if(!Array.isArray(e)){const n=e;i=n.geometry&&n.geometry.animations||n.animations}for(let n=0;n<i.length;n++)if(i[n].name===t)return i[n];return null}static CreateClipsFromMorphTargetSequences(e,t,i){const n={},s=/^([\w-]*?)([\d]+)$/;for(let o=0,l=e.length;o<l;o++){const c=e[o],h=c.name.match(s);if(h&&h.length>1){const u=h[1];let d=n[u];d||(n[u]=d=[]),d.push(c)}}const a=[];for(const o in n)a.push(this.CreateFromMorphTargetSequence(o,n[o],t,i));return a}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(u,d,p,m,A){if(p.length!==0){const g=[],y=[];c_(p,g,y,m),g.length!==0&&A.push(new u(d,g,y))}},n=[],s=e.name||"default",a=e.fps||30,o=e.blendMode;let l=e.length||-1;const c=e.hierarchy||[];for(let u=0;u<c.length;u++){const d=c[u].keys;if(!(!d||d.length===0))if(d[0].morphTargets){const p={};let m;for(m=0;m<d.length;m++)if(d[m].morphTargets)for(let A=0;A<d[m].morphTargets.length;A++)p[d[m].morphTargets[A]]=-1;for(const A in p){const g=[],y=[];for(let v=0;v!==d[m].morphTargets.length;++v){const _=d[m];g.push(_.time),y.push(_.morphTarget===A?1:0)}n.push(new $a(".morphTargetInfluence["+A+"]",g,y))}l=p.length*a}else{const p=".bones["+t[u].name+"]";i(Ka,p+".position",d,"pos",n),i(fa,p+".quaternion",d,"rot",n),i(Ka,p+".scale",d,"scl",n)}}return n.length===0?null:new this(s,l,n,o)}resetDuration(){const e=this.tracks;let t=0;for(let i=0,n=e.length;i!==n;++i){const s=this.tracks[i];t=Math.max(t,s.times[s.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e=e&&this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){const e=[];for(let i=0;i<this.tracks.length;i++)e.push(this.tracks[i].clone());const t=new this.constructor(this.name,this.duration,e,this.blendMode);return t.userData=JSON.parse(JSON.stringify(this.userData)),t}toJSON(){return this.constructor.toJSON(this)}}function QO(r){switch(r.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return $a;case"vector":case"vector2":case"vector3":case"vector4":return Ka;case"color":return u_;case"quaternion":return fa;case"bool":case"boolean":return tl;case"string":return il}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+r)}function jO(r){if(r.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const e=QO(r.type);if(r.times===void 0){const t=[],i=[];c_(r.keys,t,i,"value"),r.times=t,r.values=i}return e.parse!==void 0?e.parse(r):new e(r.name,r.times,r.values,r.interpolation)}const Ai={enabled:!1,files:{},add:function(r,e){this.enabled!==!1&&(this.files[r]=e)},get:function(r,e){return this.enabled===!1?e?Promise.resolve():void 0:e?Promise.resolve(this.files[r]):this.files[r]},remove:function(r){delete this.files[r]},clear:function(){this.files={}}};class Yp{constructor(e,t,i){const n=this;let s=!1,a=0,o=0,l;const c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i,this.itemStart=function(h){o++,s===!1&&n.onStart!==void 0&&n.onStart(h,a,o),s=!0},this.itemEnd=function(h){a++,n.onProgress!==void 0&&n.onProgress(h,a,o),a===o&&(s=!1,n.onLoad!==void 0&&n.onLoad())},this.itemError=function(h){n.onError!==void 0&&n.onError(h)},this.resolveURL=function(h){return l?l(h):h},this.setURLModifier=function(h){return l=h,this},this.addHandler=function(h,u){return c.push(h,u),this},this.removeHandler=function(h){const u=c.indexOf(h);return u!==-1&&c.splice(u,2),this},this.getHandler=function(h){for(let u=0,d=c.length;u<d;u+=2){const p=c[u],m=c[u+1];if(p.global&&(p.lastIndex=0),p.test(h))return m}return null}}}const d_=new Yp;class oi{constructor(e){this.manager=e!==void 0?e:d_,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const i=this;return new Promise(function(n,s){i.load(e,n,t,s)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}oi.DEFAULT_MATERIAL_NAME="__DEFAULT";const pa={};class WO extends Error{constructor(e,t){super(e),this.response=t}}class ti extends oi{constructor(e){super(e),this.responseType="text",this.useCache=!0}load(e,t,i,n){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e),(this.useCache?Ai.get(e,this.responseType,this.mimeType):Promise.resolve(void 0)).then(s=>{if(s!==void 0)return this.manager.itemStart(e),setTimeout(()=>{t&&t(s),this.manager.itemEnd(e)},0),s;if(pa[e]!==void 0){pa[e].push({onLoad:t,onProgress:i,onError:n});return}pa[e]=[],pa[e].push({onLoad:t,onProgress:i,onError:n});const a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),o=this.mimeType,l=this.responseType;fetch(a).then(c=>{if(c.status===200||c.status===0){if(c.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||c.body===void 0||c.body.getReader===void 0)return c;const h=pa[e],u=c.body.getReader(),d=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),p=d?parseInt(d):0,m=p!==0;let A=0;const g=new ReadableStream({start(y){v();function v(){u.read().then(({done:_,value:b})=>{if(_)y.close();else{A+=b.byteLength;const T=new ProgressEvent("progress",{lengthComputable:m,loaded:A,total:p});for(let E=0,M=h.length;E<M;E++){const I=h[E];I.onProgress&&I.onProgress(T)}y.enqueue(b),v()}},_=>{y.error(_)})}}});return new Response(g)}else throw new WO(`fetch for "${c.url}" responded with ${c.status}: ${c.statusText}`,c)}).then(c=>{switch(l){case"arraybuffer":return c.arrayBuffer();case"blob":return c.blob();case"document":return c.text().then(h=>new DOMParser().parseFromString(h,o));case"json":return c.json();default:if(o===void 0)return c.text();{const u=/charset="?([^;"\s]*)"?/i.exec(o),d=u&&u[1]?u[1].toLowerCase():void 0,p=new TextDecoder(d);return c.arrayBuffer().then(m=>p.decode(m))}}}).then(c=>{this.useCache&&Ai.add(e,c,this.responseType);const h=pa[e];delete pa[e];for(let u=0,d=h.length;u<d;u++){const p=h[u];p.onLoad&&p.onLoad(c)}}).catch(c=>{const h=pa[e];if(h===void 0)throw this.manager.itemError(e),c;delete pa[e];for(let u=0,d=h.length;u<d;u++){const p=h[u];p.onError&&p.onError(c)}this.manager.itemError(e)}).finally(()=>{this.useCache&&this.manager.itemEnd(e)}),this.useCache&&this.manager.itemStart(e)})}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class qO extends oi{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new ti(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(JSON.parse(o)))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}parse(e){const t=[];for(let i=0;i<e.length;i++){const n=Ja.parse(e[i]);t.push(n)}return t}}class Lx extends oi{constructor(e){super(e)}load(e,t,i,n){const s=this,a=[],o=new ua,l=new ti(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(s.withCredentials);let c=0;function h(u){l.load(e[u],function(d){const p=s.parse(d,!0);a[u]={width:p.width,height:p.height,format:p.format,mipmaps:p.mipmaps},c+=1,c===6&&(p.mipmapCount===1&&(o.minFilter=at),o.image=a,o.format=p.format,o.needsUpdate=!0,t&&t(o))},i,n)}if(Array.isArray(e))for(let u=0,d=e.length;u<d;++u)h(u);else l.load(e,function(u){const d=s.parse(u,!0);if(d.isCubemap){const p=d.mipmaps.length/d.mipmapCount;for(let m=0;m<p;m++){a[m]={mipmaps:[]};for(let A=0;A<d.mipmapCount;A++)a[m].mipmaps.push(d.mipmaps[m*d.mipmapCount+A]),a[m].format=d.format,a[m].width=d.width,a[m].height=d.height}o.image=a}else o.image.width=d.width,o.image.height=d.height,o.mipmaps=d.mipmaps;d.mipmapCount===1&&(o.minFilter=at),o.format=d.format,o.needsUpdate=!0,t&&t(o)},i,n);return o}}class Gc extends oi{constructor(e){super(e)}load(e,t,i,n){const s=e;this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const a=this,o=Ai.get(e);if(o!==void 0)return a.manager.itemStart(e),setTimeout(function(){t&&t(o),a.manager.itemEnd(e)},0),o;const l=au("img");function c(){u(),Ai.add(e,this),t&&t(this),a.manager.itemEnd(e)}function h(d){u(),n&&n(d),a.manager.itemError(e),a.manager.itemEnd(e)}function u(){l.removeEventListener("load",c,!1),l.removeEventListener("error",h,!1)}return l.addEventListener("load",c,!1),l.addEventListener("error",h,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(l.crossOrigin=this.crossOrigin),a.manager.itemStart(e),Ai.get(e,"blob").then(d=>{if(d!==void 0&&!d.type.startsWith("text/plain")){d.type||(e.endsWith(".svg")||e.startsWith("data:image/svg"))&&(d=new Blob([d],{type:"image/svg+xml"})),l.src=URL.createObjectURL(d);return}const p=new ti(this.manager);p.useCache=!1,p.setPath(this.path),p.setCrossOrigin(this.crossOrigin),p.setResponseType("blob"),p.load(s,function(m){m.type||(e.endsWith(".svg")||e.startsWith("data:image/svg"))&&(m=new Blob([m],{type:"image/svg+xml"})),Ai.add(e,m,"blob"),l.src=URL.createObjectURL(m)},i,m=>{u(),n&&n(m)})}),l}}class XO extends oi{constructor(e){super(e)}load(e,t,i,n){const s=new wc;s.colorSpace=Ct;const a=new Gc(this.manager);a.setCrossOrigin(this.crossOrigin),a.setPath(this.path);let o=0;function l(c){a.load(e[c],function(h){s.images[c]=h,o++,o===6&&(s.needsUpdate=!0,t&&t(s))},void 0,n)}for(let c=0;c<e.length;++c)l(c);return s}}class f_ extends oi{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new Vn,o=new ti(this.manager);return o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setPath(this.path),o.setWithCredentials(s.withCredentials),o.load(e,function(l){let c;try{c=s.parse(l)}catch(h){if(n!==void 0)n(h);else{console.error(h);return}}c.image!==void 0?a.image=c.image:c.data!==void 0&&(a.image.width=c.width,a.image.height=c.height,a.image.data=c.data,a.image.complete=!0),a.wrapS=c.wrapS!==void 0?c.wrapS:di,a.wrapT=c.wrapT!==void 0?c.wrapT:di,a.magFilter=c.magFilter!==void 0?c.magFilter:at,a.minFilter=c.minFilter!==void 0?c.minFilter:at,a.anisotropy=c.anisotropy!==void 0?c.anisotropy:1,c.colorSpace!==void 0&&(a.colorSpace=c.colorSpace),c.flipY!==void 0&&(a.flipY=c.flipY),c.format!==void 0&&(a.format=c.format),c.type!==void 0&&(a.type=c.type),c.mipmaps!==void 0&&(a.mipmaps=c.mipmaps,a.minFilter=Dn),c.mipmapCount===1&&(a.minFilter=at),c.generateMipmaps!==void 0&&(a.generateMipmaps=c.generateMipmaps),a.needsUpdate=!0,t&&t(a,c)},i,n),a}}class Za extends oi{constructor(e){super(e)}load(e,t,i,n){const s=new kt,a=new Gc(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(o){s.image=o,s.needsUpdate=!0,e.startsWith("blob:")||(s.userData.rootPath=a.path+e),t!==void 0&&t(s)},i,function(o){s.image instanceof ImageData&&(s.needsUpdate=!0),n!==void 0&&n(o)}),s}}class eo extends ft{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new ee(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}}class $p extends eo{constructor(e,t,i){super(e,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(ft.DEFAULT_UP),this.updateMatrix(),this.groundColor=new ee(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}const p_=new fe,Ox=new S,Ux=new S;class m_{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new K(512,512),this.map=null,this.mapPass=null,this.matrix=new fe,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new pu,this._frameExtents=new K(1,1),this._viewportCount=1,this._viewports=[new et(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,i=this.matrix;Ox.setFromMatrixPosition(e.matrixWorld),t.position.copy(Ox),Ux.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Ux),t.updateMatrixWorld(),p_.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(p_),i.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),i.multiply(p_)}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.normalBias=e.normalBias,this.radius=e.radius,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class YO extends m_{constructor(){super(new zi(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){const t=this.camera,i=rc*2*e.angle*this.focus,n=this.mapSize.width/this.mapSize.height,s=e.distance||t.far;(i!==t.fov||n!==t.aspect||s!==t.far)&&(t.fov=i,t.aspect=n,t.far=s,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class zc extends eo{constructor(e,t,i=0,n=Math.PI/3,s=0,a=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(ft.DEFAULT_UP),this.updateMatrix(),this.target=new ft,this.distance=i,this.angle=n,this.penumbra=s,this.decay=a,this.map=null,this.shadow=new YO}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}const Fx=new fe,Fu=new S,g_=new S;class $O extends m_{constructor(){super(new zi(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new K(4,2),this._viewportCount=6,this._viewports=[new et(2,1,1,1),new et(0,1,1,1),new et(3,1,1,1),new et(1,1,1,1),new et(3,0,1,1),new et(1,0,1,1)],this._cubeDirections=[new S(1,0,0),new S(-1,0,0),new S(0,0,1),new S(0,0,-1),new S(0,1,0),new S(0,-1,0)],this._cubeUps=[new S(0,1,0),new S(0,1,0),new S(0,1,0),new S(0,1,0),new S(0,0,1),new S(0,0,-1)]}updateMatrices(e,t=0){const i=this.camera,n=this.matrix,s=e.distance||i.far;s!==i.far&&(i.far=s,i.updateProjectionMatrix()),Fu.setFromMatrixPosition(e.matrixWorld),i.position.copy(Fu),g_.copy(i.position),g_.add(this._cubeDirections[t]),i.up.copy(this._cubeUps[t]),i.lookAt(g_),i.updateMatrixWorld(),n.makeTranslation(-Fu.x,-Fu.y,-Fu.z),Fx.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Fx)}}class nl extends eo{constructor(e,t,i=0,n=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=i,this.decay=n,this.shadow=new $O}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}}class KO extends m_{constructor(){super(new Mr(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class sl extends eo{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(ft.DEFAULT_UP),this.updateMatrix(),this.target=new ft,this.shadow=new KO}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class Kp extends eo{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Jp extends eo{constructor(e,t,i=10,n=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=i,this.height=n}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class Nx{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new S)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const i=e.x,n=e.y,s=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.282095),t.addScaledVector(a[1],.488603*n),t.addScaledVector(a[2],.488603*s),t.addScaledVector(a[3],.488603*i),t.addScaledVector(a[4],1.092548*(i*n)),t.addScaledVector(a[5],1.092548*(n*s)),t.addScaledVector(a[6],.315392*(3*s*s-1)),t.addScaledVector(a[7],1.092548*(i*s)),t.addScaledVector(a[8],.546274*(i*i-n*n)),t}getIrradianceAt(e,t){const i=e.x,n=e.y,s=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.886227),t.addScaledVector(a[1],2*.511664*n),t.addScaledVector(a[2],2*.511664*s),t.addScaledVector(a[3],2*.511664*i),t.addScaledVector(a[4],2*.429043*i*n),t.addScaledVector(a[5],2*.429043*n*s),t.addScaledVector(a[6],.743125*s*s-.247708),t.addScaledVector(a[7],2*.429043*i*s),t.addScaledVector(a[8],.429043*(i*i-n*n)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let i=0;i<9;i++)this.coefficients[i].addScaledVector(e.coefficients[i],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let i=0;i<9;i++)this.coefficients[i].lerp(e.coefficients[i],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){const i=this.coefficients;for(let n=0;n<9;n++)i[n].fromArray(e,t+n*3);return this}toArray(e=[],t=0){const i=this.coefficients;for(let n=0;n<9;n++)i[n].toArray(e,t+n*3);return e}static getBasisAt(e,t){const i=e.x,n=e.y,s=e.z;t[0]=.282095,t[1]=.488603*n,t[2]=.488603*s,t[3]=.488603*i,t[4]=1.092548*i*n,t[5]=1.092548*n*s,t[6]=.315392*(3*s*s-1),t[7]=1.092548*i*s,t[8]=.546274*(i*i-n*n)}}class kx extends eo{constructor(e=new Nx,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}fromJSON(e){return this.intensity=e.intensity,this.sh.fromArray(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}class Nu extends oi{constructor(e){super(e),this.textures={}}load(e,t,i,n){const s=this,a=new ti(s.manager);a.setPath(s.path),a.setRequestHeader(s.requestHeader),a.setWithCredentials(s.withCredentials),a.load(e,function(o){try{t(s.parse(JSON.parse(o)))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}parse(e){const t=this.textures;function i(a){return t[a]===void 0&&console.warn("THREE.MaterialLoader: Undefined texture",a),t[a]}const n=e.metadata&&e.metadata.version<=4.5?Bt:void 0,s=Nu.createMaterialFromType(e.type);if(e.uuid!==void 0&&(s.uuid=e.uuid),e.name!==void 0&&(s.name=e.name),e.color!==void 0&&s.color!==void 0&&s.color.setHex(e.color,n),e.roughness!==void 0&&(s.roughness=e.roughness),e.metalness!==void 0&&(s.metalness=e.metalness),e.sheen!==void 0&&(s.sheen=e.sheen),e.sheenColor!==void 0&&(s.sheenColor=new ee().setHex(e.sheenColor,n)),e.sheenRoughness!==void 0&&(s.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&s.emissive!==void 0&&s.emissive.setHex(e.emissive,n),e.specular!==void 0&&s.specular!==void 0&&s.specular.setHex(e.specular,n),e.specularIntensity!==void 0&&(s.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&s.specularColor!==void 0&&s.specularColor.setHex(e.specularColor,n),e.shininess!==void 0&&(s.shininess=e.shininess),e.clearcoat!==void 0&&(s.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(s.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(s.dispersion=e.dispersion),e.iridescence!==void 0&&(s.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(s.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(s.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(s.transmission=e.transmission),e.thickness!==void 0&&(s.thickness=e.thickness),e.attenuationDistance!==void 0&&(s.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&s.attenuationColor!==void 0&&s.attenuationColor.setHex(e.attenuationColor,n),e.anisotropy!==void 0&&(s.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(s.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(s.fog=e.fog),e.flatShading!==void 0&&(s.flatShading=e.flatShading),e.blending!==void 0&&(s.blending=e.blending),e.combine!==void 0&&(s.combine=e.combine),e.side!==void 0&&(s.side=e.side),e.shadowSide!==void 0&&(s.shadowSide=e.shadowSide),e.opacity!==void 0&&(s.opacity=e.opacity),e.transparent!==void 0&&(s.transparent=e.transparent),e.alphaTest!==void 0&&(s.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(s.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(s.depthFunc=e.depthFunc),e.depthTest!==void 0&&(s.depthTest=e.depthTest),e.depthWrite!==void 0&&(s.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(s.colorWrite=e.colorWrite),e.blendSrc!==void 0&&(s.blendSrc=e.blendSrc),e.blendDst!==void 0&&(s.blendDst=e.blendDst),e.blendEquation!==void 0&&(s.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(s.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(s.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(s.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&s.blendColor!==void 0&&s.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(s.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(s.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(s.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(s.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(s.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(s.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(s.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(s.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(s.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(s.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(s.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(s.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(s.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(s.rotation=e.rotation),e.linewidth!==void 0&&(s.linewidth=e.linewidth),e.dashSize!==void 0&&(s.dashSize=e.dashSize),e.gapSize!==void 0&&(s.gapSize=e.gapSize),e.scale!==void 0&&(s.scale=e.scale),e.polygonOffset!==void 0&&(s.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(s.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(s.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(s.dithering=e.dithering),e.alphaToCoverage!==void 0&&(s.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(s.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(s.forceSinglePass=e.forceSinglePass),e.visible!==void 0&&(s.visible=e.visible),e.toneMapped!==void 0&&(s.toneMapped=e.toneMapped),e.userData!==void 0&&(s.userData=e.userData),e.vertexColors!==void 0&&(typeof e.vertexColors=="number"?s.vertexColors=e.vertexColors>0:s.vertexColors=e.vertexColors),e.uniforms!==void 0)for(const a in e.uniforms){const o=e.uniforms[a];switch(s.uniforms[a]={},o.type){case"t":s.uniforms[a].value=i(o.value);break;case"c":s.uniforms[a].value=new ee().setHex(o.value,n);break;case"v2":s.uniforms[a].value=new K().fromArray(o.value);break;case"v3":s.uniforms[a].value=new S().fromArray(o.value);break;case"v4":s.uniforms[a].value=new et().fromArray(o.value);break;case"m3":s.uniforms[a].value=new At().fromArray(o.value);break;case"m4":s.uniforms[a].value=new fe().fromArray(o.value);break;default:s.uniforms[a].value=o.value}}if(e.defines!==void 0&&(s.defines=e.defines),e.vertexShader!==void 0&&(s.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(s.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(s.glslVersion=e.glslVersion),e.extensions!==void 0)for(const a in e.extensions)s.extensions[a]=e.extensions[a];if(e.lights!==void 0&&(s.lights=e.lights),e.clipping!==void 0&&(s.clipping=e.clipping),e.size!==void 0&&(s.size=e.size),e.sizeAttenuation!==void 0&&(s.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(s.map=i(e.map)),e.matcap!==void 0&&(s.matcap=i(e.matcap)),e.alphaMap!==void 0&&(s.alphaMap=i(e.alphaMap)),e.bumpMap!==void 0&&(s.bumpMap=i(e.bumpMap)),e.bumpScale!==void 0&&(s.bumpScale=e.bumpScale),e.normalMap!==void 0&&(s.normalMap=i(e.normalMap)),e.normalMapType!==void 0&&(s.normalMapType=e.normalMapType),e.normalScale!==void 0){let a=e.normalScale;Array.isArray(a)===!1&&(a=[a,a]),s.normalScale=new K().fromArray(a)}return e.displacementMap!==void 0&&(s.displacementMap=i(e.displacementMap)),e.displacementScale!==void 0&&(s.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(s.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(s.roughnessMap=i(e.roughnessMap)),e.metalnessMap!==void 0&&(s.metalnessMap=i(e.metalnessMap)),e.emissiveMap!==void 0&&(s.emissiveMap=i(e.emissiveMap)),e.emissiveIntensity!==void 0&&(s.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(s.specularMap=i(e.specularMap)),e.specularIntensityMap!==void 0&&(s.specularIntensityMap=i(e.specularIntensityMap)),e.specularColorMap!==void 0&&(s.specularColorMap=i(e.specularColorMap)),e.envMap!==void 0&&(s.envMap=i(e.envMap)),e.envMapRotation!==void 0&&s.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(s.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(s.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(s.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(s.lightMap=i(e.lightMap)),e.lightMapIntensity!==void 0&&(s.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(s.aoMap=i(e.aoMap)),e.aoMapIntensity!==void 0&&(s.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(s.gradientMap=i(e.gradientMap)),e.clearcoatMap!==void 0&&(s.clearcoatMap=i(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(s.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(s.clearcoatNormalMap=i(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(s.clearcoatNormalScale=new K().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(s.iridescenceMap=i(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(s.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(s.transmissionMap=i(e.transmissionMap)),e.thicknessMap!==void 0&&(s.thicknessMap=i(e.thicknessMap)),e.anisotropyMap!==void 0&&(s.anisotropyMap=i(e.anisotropyMap)),e.sheenColorMap!==void 0&&(s.sheenColorMap=i(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(s.sheenRoughnessMap=i(e.sheenRoughnessMap)),s}setTextures(e){return this.textures=e,this}static createMaterialFromType(e){const t={ShadowMaterial:xx,SpriteMaterial:gu,RawShaderMaterial:Sx,ShaderMaterial:nn,PointsMaterial:Tr,MeshPhysicalMaterial:Jo,MeshStandardMaterial:Ya,MeshPhongMaterial:Zo,MeshToonMaterial:Ex,MeshNormalMaterial:a_,MeshLambertMaterial:o_,MeshDepthMaterial:Ec,MeshDistanceMaterial:zy,MeshBasicMaterial:is,MeshMatcapMaterial:Mx,LineDashedMaterial:Tx,LineBasicMaterial:Mi,Material:tn};return new t[e]}}class Ps{static decodeText(e){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),typeof TextDecoder<"u")return new TextDecoder().decode(e);let t="";for(let i=0,n=e.length;i<n;i++)t+=String.fromCharCode(e[i]);try{return decodeURIComponent(escape(t))}catch{return t}}static extractUrlBase(e){const t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){if(typeof e!="string"||e==="")return"";if(e[0]==="/")if(/^https?:\/\//i.test(t))t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1");else return e;return/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e}}class A_ extends Je{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){const e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}}class y_ extends oi{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new ti(s.manager);a.setPath(s.path),a.setRequestHeader(s.requestHeader),a.setWithCredentials(s.withCredentials),a.load(e,function(o){try{t(s.parse(JSON.parse(o)))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}parse(e){const t={},i={};function n(p,m){if(t[m]!==void 0)return t[m];const g=p.interleavedBuffers[m],y=s(p,g.buffer),v=ac(g.type,y),_=new Mc(v,g.stride);return _.uuid=g.uuid,t[m]=_,_}function s(p,m){if(i[m]!==void 0)return i[m];const g=p.arrayBuffers[m],y=new Uint32Array(g).buffer;return i[m]=y,y}const a=e.isInstancedBufferGeometry?new A_:new Je,o=e.data.index;if(o!==void 0){const p=ac(o.type,o.array);a.setIndex(new Ze(p,1))}const l=e.data.attributes;for(const p in l){const m=l[p];let A;if(m.isInterleavedBufferAttribute){const g=n(e.data,m.data);A=new Rn(g,m.itemSize,m.offset,m.normalized)}else{const g=ac(m.type,m.array),y=m.isInstancedBufferAttribute?ha:Ze;A=new y(g,m.itemSize,m.normalized)}m.name!==void 0&&(A.name=m.name),m.usage!==void 0&&A.setUsage(m.usage),a.setAttribute(p,A)}const c=e.data.morphAttributes;if(c)for(const p in c){const m=c[p],A=[];for(let g=0,y=m.length;g<y;g++){const v=m[g];let _;if(v.isInterleavedBufferAttribute){const b=n(e.data,v.data);_=new Rn(b,v.itemSize,v.offset,v.normalized)}else{const b=ac(v.type,v.array);_=new Ze(b,v.itemSize,v.normalized)}v.name!==void 0&&(_.name=v.name),A.push(_)}a.morphAttributes[p]=A}e.data.morphTargetsRelative&&(a.morphTargetsRelative=!0);const u=e.data.groups||e.data.drawcalls||e.data.offsets;if(u!==void 0)for(let p=0,m=u.length;p!==m;++p){const A=u[p];a.addGroup(A.start,A.count,A.materialIndex)}const d=e.data.boundingSphere;if(d!==void 0){const p=new S;d.center!==void 0&&p.fromArray(d.center),a.boundingSphere=new un(p,d.radius)}return e.name&&(a.name=e.name),e.userData&&(a.userData=e.userData),a}}class Zp extends oi{constructor(e){super(e)}load(e,t,i,n){const s=this,a=this.path===""?Ps.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||a;const o=new ti(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(l){let c=null;try{c=JSON.parse(l)}catch(u){n!==void 0&&n(u),console.error("THREE:ObjectLoader: Can't parse "+e+".",u.message);return}const h=c.metadata;if(h===void 0||h.type===void 0||h.type.toLowerCase()==="geometry"){n!==void 0&&n(new Error("THREE.ObjectLoader: Can't load "+e)),console.error("THREE.ObjectLoader: Can't load "+e);return}s.parse(c,t)},i,n)}async loadAsync(e,t){const i=this,n=this.path===""?Ps.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||n;const s=new ti(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials);const a=await s.loadAsync(e,t),o=JSON.parse(a),l=o.metadata;if(l===void 0||l.type===void 0||l.type.toLowerCase()==="geometry")throw new Error("THREE.ObjectLoader: Can't load "+e);return await i.parseAsync(o)}parse(e,t){const i=this.parseAnimations(e.animations),n=this.parseShapes(e.shapes),s=this.parseGeometries(e.geometries,n),a=this.parseImages(e.images,function(){t!==void 0&&t(c)}),o=this.parseTextures(e.textures,a),l=this.parseMaterials(e.materials,o),c=this.parseObject(e.object,s,l,o,i),h=this.parseSkeletons(e.skeletons,c);if(this.bindSkeletons(c,h),this.bindLightTargets(c),t!==void 0){let u=!1;for(const d in a)if(a[d].data instanceof HTMLImageElement){u=!0;break}u===!1&&t(c)}return c}async parseAsync(e){const t=this.parseAnimations(e.animations),i=this.parseShapes(e.shapes),n=this.parseGeometries(e.geometries,i),s=await this.parseImagesAsync(e.images),a=this.parseTextures(e.textures,s),o=this.parseMaterials(e.materials,a),l=this.parseObject(e.object,n,o,a,t),c=this.parseSkeletons(e.skeletons,l);return this.bindSkeletons(l,c),this.bindLightTargets(l),l}parseShapes(e){const t={};if(e!==void 0)for(let i=0,n=e.length;i<n;i++){const s=new rr().fromJSON(e[i]);t[s.uuid]=s}return t}parseSkeletons(e,t){const i={},n={};if(t.traverse(function(s){s.isBone&&(n[s.uuid]=s)}),e!==void 0)for(let s=0,a=e.length;s<a;s++){const o=new Bc().fromJSON(e[s],n);i[o.uuid]=o}return i}parseGeometries(e,t){const i={};if(e!==void 0){const n=new y_;for(let s=0,a=e.length;s<a;s++){let o;const l=e[s];switch(l.type){case"BufferGeometry":case"InstancedBufferGeometry":o=n.parse(l);break;default:l.type in Cx?o=Cx[l.type].fromJSON(l,t):console.warn(`THREE.ObjectLoader: Unsupported geometry type "${l.type}"`)}o.uuid=l.uuid,l.name!==void 0&&(o.name=l.name),l.userData!==void 0&&(o.userData=l.userData),i[l.uuid]=o}}return i}parseMaterials(e,t){const i={},n={};if(e!==void 0){const s=new Nu;s.setTextures(t);for(let a=0,o=e.length;a<o;a++){const l=e[a];i[l.uuid]===void 0&&(i[l.uuid]=s.parse(l)),n[l.uuid]=i[l.uuid]}}return n}parseAnimations(e){const t={};if(e!==void 0)for(let i=0;i<e.length;i++){const n=e[i],s=Ja.parse(n);t[s.uuid]=s}return t}parseImages(e,t){const i=this,n={};let s;function a(l){return i.manager.itemStart(l),s.load(l,function(){i.manager.itemEnd(l)},void 0,function(){i.manager.itemError(l),i.manager.itemEnd(l)})}function o(l){if(typeof l=="string"){const c=l,h=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(c)?c:i.resourcePath+c;return a(h)}else return l.data?{data:ac(l.type,l.data),width:l.width,height:l.height,complete:!0}:null}if(e!==void 0&&e.length>0){const l=new Yp(t);s=new Gc(l),s.setCrossOrigin(this.crossOrigin);for(let c=0,h=e.length;c<h;c++){const u=e[c],d=u.url;if(Array.isArray(d)){const p=[];for(let m=0,A=d.length;m<A;m++){const g=d[m],y=o(g);y!==null&&(y instanceof HTMLImageElement?p.push(y):p.push(new Vn(y.data,y.width,y.height)))}n[u.uuid]=new ia(p)}else{const p=o(u.url);n[u.uuid]=new ia(p)}}}return n}async parseImagesAsync(e){const t=this,i={};let n;async function s(a){if(typeof a=="string"){const o=a,l=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(o)?o:t.resourcePath+o;return await n.loadAsync(l)}else return a.data?{data:ac(a.type,a.data),width:a.width,height:a.height,complete:!0}:null}if(e!==void 0&&e.length>0){n=new Gc(this.manager),n.setCrossOrigin(this.crossOrigin);for(let a=0,o=e.length;a<o;a++){const l=e[a],c=l.url;if(Array.isArray(c)){const h=[];for(let u=0,d=c.length;u<d;u++){const p=c[u],m=await s(p);m!==null&&(m instanceof HTMLImageElement?h.push(m):h.push(new Vn(m.data,m.width,m.height)))}i[l.uuid]=new ia(h)}else{const h=await s(l.url);i[l.uuid]=new ia(h)}}}return i}parseTextures(e,t){function i(s,a){return typeof s=="number"?s:(console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",s),a[s])}const n={};if(e!==void 0)for(let s=0,a=e.length;s<a;s++){const o=e[s];o.image===void 0&&console.warn('THREE.ObjectLoader: No "image" specified for',o.uuid),t[o.image]===void 0&&console.warn("THREE.ObjectLoader: Undefined image",o.image);const l=t[o.image],c=l?l.data:void 0;let h;Array.isArray(c)?(h=new wc,c.length===6&&(h.needsUpdate=!0)):(c&&c.data?h=new Vn:h=new kt,c&&c.complete&&(h.needsUpdate=!0)),h.source=l,h.uuid=o.uuid,o.name!==void 0&&(h.name=o.name),o.mapping!==void 0&&(h.mapping=i(o.mapping,JO)),o.channel!==void 0&&(h.channel=o.channel),o.offset!==void 0&&h.offset.fromArray(o.offset),o.repeat!==void 0&&h.repeat.fromArray(o.repeat),o.center!==void 0&&h.center.fromArray(o.center),o.rotation!==void 0&&(h.rotation=o.rotation),o.wrap!==void 0&&(h.wrapS=i(o.wrap[0],Gx),h.wrapT=i(o.wrap[1],Gx)),o.format!==void 0&&(h.format=o.format),o.internalFormat!==void 0&&(h.internalFormat=o.internalFormat),o.type!==void 0&&(h.type=o.type),o.colorSpace!==void 0?h.colorSpace=o.colorSpace:o.encoding!==void 0&&(h.encoding=o.encoding),o.minFilter!==void 0&&(h.minFilter=i(o.minFilter,zx)),o.magFilter!==void 0&&(h.magFilter=i(o.magFilter,zx)),o.anisotropy!==void 0&&(h.anisotropy=o.anisotropy),o.flipY!==void 0&&(h.flipY=o.flipY),o.generateMipmaps!==void 0&&(h.generateMipmaps=o.generateMipmaps),o.premultiplyAlpha!==void 0&&(h.premultiplyAlpha=o.premultiplyAlpha),o.unpackAlignment!==void 0&&(h.unpackAlignment=o.unpackAlignment),o.compareFunction!==void 0&&(h.compareFunction=o.compareFunction),o.userData!==void 0&&(h.userData=o.userData),n[o.uuid]=h}return n}parseObject(e,t,i,n,s){let a;const o=e.metadata&&e.metadata.version<=4.5?Bt:void 0;function l(p){return t[p]===void 0&&console.warn("THREE.ObjectLoader: Undefined geometry",p),t[p]}function c(p){if(p!==void 0){if(Array.isArray(p)){const m=[];for(let A=0,g=p.length;A<g;A++){const y=p[A];i[y]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",y),m.push(i[y])}return m}return i[p]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",p),i[p]}}function h(p){return n[p]===void 0&&console.warn("THREE.ObjectLoader: Undefined texture",p),n[p]}let u,d;switch(e.type){case"Scene":a=new Qo,e.background!==void 0&&(Number.isInteger(e.background)?a.background=new ee().setHex(e.background,o):a.background=h(e.background)),e.environment!==void 0&&(a.environment=h(e.environment)),e.fog!==void 0&&(e.fog.type==="Fog"?a.fog=new dp(e.fog.color,e.fog.near,e.fog.far):e.fog.type==="FogExp2"&&(a.fog=new up(e.fog.color,e.fog.density)),e.fog.name!==""&&(a.fog.name=e.fog.name)),e.backgroundBlurriness!==void 0&&(a.backgroundBlurriness=e.backgroundBlurriness),e.backgroundIntensity!==void 0&&(a.backgroundIntensity=e.backgroundIntensity),e.backgroundRotation!==void 0&&a.backgroundRotation.fromArray(e.backgroundRotation),e.environmentIntensity!==void 0&&(a.environmentIntensity=e.environmentIntensity),e.environmentRotation!==void 0&&a.environmentRotation.fromArray(e.environmentRotation);break;case"PerspectiveCamera":a=new zi(e.fov,e.aspect,e.near,e.far),e.focus!==void 0&&(a.focus=e.focus),e.zoom!==void 0&&(a.zoom=e.zoom),e.filmGauge!==void 0&&(a.filmGauge=e.filmGauge),e.filmOffset!==void 0&&(a.filmOffset=e.filmOffset),e.view!==void 0&&(a.view=Object.assign({},e.view));break;case"OrthographicCamera":a=new Mr(e.left,e.right,e.top,e.bottom,e.near,e.far),e.zoom!==void 0&&(a.zoom=e.zoom),e.view!==void 0&&(a.view=Object.assign({},e.view));break;case"AmbientLight":a=new Kp(e.color,e.intensity);break;case"DirectionalLight":a=new sl(e.color,e.intensity),a.target=e.target||"";break;case"PointLight":a=new nl(e.color,e.intensity,e.distance,e.decay);break;case"RectAreaLight":a=new Jp(e.color,e.intensity,e.width,e.height);break;case"SpotLight":a=new zc(e.color,e.intensity,e.distance,e.angle,e.penumbra,e.decay),a.target=e.target||"";break;case"HemisphereLight":a=new $p(e.color,e.groundColor,e.intensity);break;case"LightProbe":a=new kx().fromJSON(e);break;case"SkinnedMesh":u=l(e.geometry),d=c(e.material),a=new _p(u,d),e.bindMode!==void 0&&(a.bindMode=e.bindMode),e.bindMatrix!==void 0&&a.bindMatrix.fromArray(e.bindMatrix),e.skeleton!==void 0&&(a.skeleton=e.skeleton);break;case"Mesh":u=l(e.geometry),d=c(e.material),a=new _e(u,d);break;case"InstancedMesh":u=l(e.geometry),d=c(e.material);const p=e.count,m=e.instanceMatrix,A=e.instanceColor;a=new Oc(u,d,p),a.instanceMatrix=new ha(new Float32Array(m.array),16),A!==void 0&&(a.instanceColor=new ha(new Float32Array(A.array),A.itemSize));break;case"BatchedMesh":u=l(e.geometry),d=c(e.material),a=new rx(e.maxInstanceCount,e.maxVertexCount,e.maxIndexCount,d),a.geometry=u,a.perObjectFrustumCulled=e.perObjectFrustumCulled,a.sortObjects=e.sortObjects,a._drawRanges=e.drawRanges,a._reservedRanges=e.reservedRanges,a._visibility=e.visibility,a._active=e.active,a._bounds=e.bounds.map(g=>{const y=new en;y.min.fromArray(g.boxMin),y.max.fromArray(g.boxMax);const v=new un;return v.radius=g.sphereRadius,v.center.fromArray(g.sphereCenter),{boxInitialized:g.boxInitialized,box:y,sphereInitialized:g.sphereInitialized,sphere:v}}),a._maxInstanceCount=e.maxInstanceCount,a._maxVertexCount=e.maxVertexCount,a._maxIndexCount=e.maxIndexCount,a._geometryInitialized=e.geometryInitialized,a._geometryCount=e.geometryCount,a._matricesTexture=h(e.matricesTexture.uuid),e.colorsTexture!==void 0&&(a._colorsTexture=h(e.colorsTexture.uuid));break;case"LOD":a=new XC;break;case"Line":a=new fn(l(e.geometry),c(e.material));break;case"LineLoop":a=new $y(l(e.geometry),c(e.material));break;case"LineSegments":a=new Ms(l(e.geometry),c(e.material));break;case"PointCloud":case"Points":a=new Wo(l(e.geometry),c(e.material));break;case"Sprite":a=new mp(c(e.material));break;case"Group":a=new Vi;break;case"Bone":a=new Rc;break;default:a=new ft}if(a.uuid=e.uuid,e.name!==void 0&&(a.name=e.name),e.matrix!==void 0?(a.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(a.matrixAutoUpdate=e.matrixAutoUpdate),a.matrixAutoUpdate&&a.matrix.decompose(a.position,a.quaternion,a.scale)):(e.position!==void 0&&a.position.fromArray(e.position),e.rotation!==void 0&&a.rotation.fromArray(e.rotation),e.quaternion!==void 0&&a.quaternion.fromArray(e.quaternion),e.scale!==void 0&&a.scale.fromArray(e.scale)),e.up!==void 0&&a.up.fromArray(e.up),e.castShadow!==void 0&&(a.castShadow=e.castShadow),e.receiveShadow!==void 0&&(a.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(a.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(a.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(a.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(a.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&a.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(a.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(a.visible=e.visible),e.frustumCulled!==void 0&&(a.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(a.renderOrder=e.renderOrder),e.userData!==void 0&&(a.userData=e.userData),e.layers!==void 0&&(a.layers.mask=e.layers),e.children!==void 0){const p=e.children;for(let m=0;m<p.length;m++)a.add(this.parseObject(p[m],t,i,n,s))}if(e.animations!==void 0){const p=e.animations;for(let m=0;m<p.length;m++){const A=p[m];a.animations.push(s[A])}}if(e.type==="LOD"){e.autoUpdate!==void 0&&(a.autoUpdate=e.autoUpdate);const p=e.levels;for(let m=0;m<p.length;m++){const A=p[m],g=a.getObjectByProperty("uuid",A.object);g!==void 0&&a.addLevel(g,A.distance,A.hysteresis)}}return a}bindSkeletons(e,t){Object.keys(t).length!==0&&e.traverse(function(i){if(i.isSkinnedMesh===!0&&i.skeleton!==void 0){const n=t[i.skeleton];n===void 0?console.warn("THREE.ObjectLoader: No skeleton found with UUID:",i.skeleton):i.bind(n,i.bindMatrix)}})}bindLightTargets(e){e.traverse(function(t){if(t.isDirectionalLight||t.isSpotLight){const i=t.target,n=e.getObjectByProperty("uuid",i);n!==void 0?t.target=n:t.target=new ft}})}}const JO={UVMapping:Kh,CubeReflectionMapping:Yr,CubeRefractionMapping:To,EquirectangularReflectionMapping:$r,EquirectangularRefractionMapping:mf,CubeUVReflectionMapping:Kl},Gx={RepeatWrapping:Pn,ClampToEdgeWrapping:di,MirroredRepeatWrapping:Kr},zx={NearestFilter:mi,NearestMipmapNearestFilter:Jh,NearestMipmapLinearFilter:Na,LinearFilter:at,LinearMipmapNearestFilter:Io,LinearMipmapLinearFilter:Dn};class Vx extends oi{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}setOptions(e){return this.options=e,this}load(e,t,i,n){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const s=this,a=Ai.get(e);if(a!==void 0){if(s.manager.itemStart(e),a.then){a.then(c=>{t&&t(c),s.manager.itemEnd(e)}).catch(c=>{n&&n(c)});return}return setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0),a}const o={};o.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",o.headers=this.requestHeader;const l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return Ai.add(e,c,"blob"),createImageBitmap(c,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(c){return Ai.add(e,c),t&&t(c),s.manager.itemEnd(e),c}).catch(function(c){n&&n(c),Ai.remove(e),s.manager.itemError(e),s.manager.itemEnd(e)});Ai.add(e,l),s.manager.itemStart(e)}}let em;class __{static getContext(){return em===void 0&&(em=new(window.AudioContext||window.webkitAudioContext)),em}static setContext(e){em=e}}class ZO extends oi{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new ti(this.manager);a.setResponseType("arraybuffer"),a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(l){try{const c=l.slice(0);__.getContext().decodeAudioData(c,function(u){t(u)}).catch(o)}catch(c){o(c)}},i,n);function o(l){n?n(l):console.error(l),s.manager.itemError(e)}}}const Hx=new fe,Qx=new fe,rl=new fe;class eU{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new zi,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new zi,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){const t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,rl.copy(e.projectionMatrix);const n=t.eyeSep/2,s=n*t.near/t.focus,a=t.near*Math.tan(Bo*t.fov*.5)/t.zoom;let o,l;Qx.elements[12]=-n,Hx.elements[12]=n,o=-a*t.aspect+s,l=a*t.aspect+s,rl.elements[0]=2*t.near/(l-o),rl.elements[8]=(l+o)/(l-o),this.cameraL.projectionMatrix.copy(rl),o=-a*t.aspect-s,l=a*t.aspect-s,rl.elements[0]=2*t.near/(l-o),rl.elements[8]=(l+o)/(l-o),this.cameraR.projectionMatrix.copy(rl)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(Qx),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(Hx)}}class ku{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=jx(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=jx();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function jx(){return(typeof performance>"u"?Date:performance).now()}const al=new S,Wx=new $e,tU=new S,ol=new S;class iU extends ft{constructor(){super(),this.type="AudioListener",this.context=__.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new ku}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);const t=this.context.listener,i=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(al,Wx,tU),ol.set(0,0,-1).applyQuaternion(Wx),t.positionX){const n=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(al.x,n),t.positionY.linearRampToValueAtTime(al.y,n),t.positionZ.linearRampToValueAtTime(al.z,n),t.forwardX.linearRampToValueAtTime(ol.x,n),t.forwardY.linearRampToValueAtTime(ol.y,n),t.forwardZ.linearRampToValueAtTime(ol.z,n),t.upX.linearRampToValueAtTime(i.x,n),t.upY.linearRampToValueAtTime(i.y,n),t.upZ.linearRampToValueAtTime(i.z,n)}else t.setPosition(al.x,al.y,al.z),t.setOrientation(ol.x,ol.y,ol.z,i.x,i.y,i.z)}}class qx extends ft{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;const t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].connect(this.filters[e]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this._connected=!0,this}disconnect(){if(this._connected!==!1){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].disconnect(this.filters[e]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this._connected=!1,this}}getFilters(){return this.filters}setFilters(e){return e||(e=[]),this._connected===!0?(this.disconnect(),this.filters=e.slice(),this.connect()):this.filters=e.slice(),this}setDetune(e){return this.detune=e,this.isPlaying===!0&&this.source.detune!==void 0&&this.source.detune.setTargetAtTime(this.detune,this.context.currentTime,.01),this}getDetune(){return this.detune}getFilter(){return this.getFilters()[0]}setFilter(e){return this.setFilters(e?[e]:[])}setPlaybackRate(e){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.playbackRate=e,this.isPlaying===!0&&this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,.01),this}getPlaybackRate(){return this.playbackRate}onEnded(){this.isPlaying=!1}getLoop(){return this.hasPlaybackControl===!1?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop}setLoop(e){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.loop=e,this.isPlaying===!0&&(this.source.loop=this.loop),this}setLoopStart(e){return this.loopStart=e,this}setLoopEnd(e){return this.loopEnd=e,this}getVolume(){return this.gain.gain.value}setVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}}const ll=new S,Xx=new $e,nU=new S,cl=new S;class sU extends qx{constructor(e){super(e),this.panner=this.context.createPanner(),this.panner.panningModel="HRTF",this.panner.connect(this.gain)}connect(){super.connect(),this.panner.connect(this.gain)}disconnect(){super.disconnect(),this.panner.disconnect(this.gain)}getOutput(){return this.panner}getRefDistance(){return this.panner.refDistance}setRefDistance(e){return this.panner.refDistance=e,this}getRolloffFactor(){return this.panner.rolloffFactor}setRolloffFactor(e){return this.panner.rolloffFactor=e,this}getDistanceModel(){return this.panner.distanceModel}setDistanceModel(e){return this.panner.distanceModel=e,this}getMaxDistance(){return this.panner.maxDistance}setMaxDistance(e){return this.panner.maxDistance=e,this}setDirectionalCone(e,t,i){return this.panner.coneInnerAngle=e,this.panner.coneOuterAngle=t,this.panner.coneOuterGain=i,this}updateMatrixWorld(e){if(super.updateMatrixWorld(e),this.hasPlaybackControl===!0&&this.isPlaying===!1)return;this.matrixWorld.decompose(ll,Xx,nU),cl.set(0,0,1).applyQuaternion(Xx);const t=this.panner;if(t.positionX){const i=this.context.currentTime+this.listener.timeDelta;t.positionX.linearRampToValueAtTime(ll.x,i),t.positionY.linearRampToValueAtTime(ll.y,i),t.positionZ.linearRampToValueAtTime(ll.z,i),t.orientationX.linearRampToValueAtTime(cl.x,i),t.orientationY.linearRampToValueAtTime(cl.y,i),t.orientationZ.linearRampToValueAtTime(cl.z,i)}else t.setPosition(ll.x,ll.y,ll.z),t.setOrientation(cl.x,cl.y,cl.z)}}class rU{constructor(e,t=2048){this.analyser=e.context.createAnalyser(),this.analyser.fftSize=t,this.data=new Uint8Array(this.analyser.frequencyBinCount),e.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let e=0;const t=this.getFrequencyData();for(let i=0;i<t.length;i++)e+=t[i];return e/t.length}}class Yx{constructor(e,t,i){this.binding=e,this.valueSize=i;let n,s,a;switch(t){case"quaternion":n=this._slerp,s=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(i*6),this._workIndex=5;break;case"string":case"bool":n=this._select,s=this._select,a=this._setAdditiveIdentityOther,this.buffer=new Array(i*5);break;default:n=this._lerp,s=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(i*5)}this._mixBufferRegion=n,this._mixBufferRegionAdditive=s,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){const i=this.buffer,n=this.valueSize,s=e*n+n;let a=this.cumulativeWeight;if(a===0){for(let o=0;o!==n;++o)i[s+o]=i[o];a=t}else{a+=t;const o=t/a;this._mixBufferRegion(i,s,0,o,n)}this.cumulativeWeight=a}accumulateAdditive(e){const t=this.buffer,i=this.valueSize,n=i*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,n,0,e,i),this.cumulativeWeightAdditive+=e}apply(e){const t=this.valueSize,i=this.buffer,n=e*t+t,s=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,s<1){const l=t*this._origIndex;this._mixBufferRegion(i,n,l,1-s,t)}a>0&&this._mixBufferRegionAdditive(i,n,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,n);break}}saveOriginalState(){const e=this.binding,t=this.buffer,i=this.valueSize,n=i*this._origIndex;e.getValue(t,n);for(let s=i,a=n;s!==a;++s)t[s]=t[n+s%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){const e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i<t;i++)this.buffer[i]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){const e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let i=0;i<this.valueSize;i++)this.buffer[t+i]=this.buffer[e+i]}_select(e,t,i,n,s){if(n>=.5)for(let a=0;a!==s;++a)e[t+a]=e[i+a]}_slerp(e,t,i,n){$e.slerpFlat(e,t,e,t,e,i,n)}_slerpAdditive(e,t,i,n,s){const a=this._workIndex*s;$e.multiplyQuaternionsFlat(e,a,e,t,e,i),$e.slerpFlat(e,t,e,t,e,a,n)}_lerp(e,t,i,n,s){const a=1-n;for(let o=0;o!==s;++o){const l=t+o;e[l]=e[l]*a+e[i+o]*n}}_lerpAdditive(e,t,i,n,s){for(let a=0;a!==s;++a){const o=t+a;e[o]=e[o]+e[i+a]*n}}}const v_="\\[\\]\\.:\\/",aU=new RegExp("["+v_+"]","g"),b_="[^"+v_+"]",oU="[^"+v_.replace("\\.","")+"]",lU=/((?:WC+[\/:])*)/.source.replace("WC",b_),cU=/(WCOD+)?/.source.replace("WCOD",oU),hU=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",b_),uU=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",b_),dU=new RegExp("^"+lU+cU+hU+uU+"$"),fU=["material","materials","bones","map"];class pU{constructor(e,t,i){const n=i||Et.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,n)}getValue(e,t){this.bind();const i=this._targetGroup.nCachedObjects_,n=this._bindings[i];n!==void 0&&n.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let n=this._targetGroup.nCachedObjects_,s=i.length;n!==s;++n)i[n].setValue(e,t)}bind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){const e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}}class Et{constructor(e,t,i){this.path=t,this.parsedPath=i||Et.parseTrackName(t),this.node=Et.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new Et.Composite(e,t,i):new Et(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(aU,"")}static parseTrackName(e){const t=dU.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);const i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},n=i.nodeName&&i.nodeName.lastIndexOf(".");if(n!==void 0&&n!==-1){const s=i.nodeName.substring(n+1);fU.indexOf(s)!==-1&&(i.nodeName=i.nodeName.substring(0,n),i.objectName=s)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){const i=function(s){for(let a=0;a<s.length;a++){const o=s[a];if(o.name===t||o.uuid===t)return o;const l=i(o.children);if(l)return l}return null},n=i(e.children);if(n)return n}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)e[t++]=i[n]}_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){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=e[t++]}_setValue_array_setNeedsUpdate(e,t){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=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 e=this.node;const t=this.parsedPath,i=t.objectName,n=t.propertyName;let s=t.propertyIndex;if(e||(e=Et.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e){console.warn("THREE.PropertyBinding: No target node found for track: "+this.path+".");return}if(i){let c=t.objectIndex;switch(i){case"materials":if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}e=e.material.materials;break;case"bones":if(!e.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}e=e.skeleton.bones;for(let h=0;h<e.length;h++)if(e[h].name===c){c=h;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}e=e.material.map;break;default:if(e[i]===void 0){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[i]}if(c!==void 0){if(e[c]===void 0){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);return}e=e[c]}}const a=e[n];if(a===void 0){const c=t.nodeName;console.error("THREE.PropertyBinding: Trying to update property for track: "+c+"."+n+" but it wasn't found.",e);return}let o=this.Versioning.None;this.targetObject=e,e.needsUpdate!==void 0?o=this.Versioning.NeedsUpdate:e.matrixWorldNeedsUpdate!==void 0&&(o=this.Versioning.MatrixWorldNeedsUpdate);let l=this.BindingType.Direct;if(s!==void 0){if(n==="morphTargetInfluences"){if(!e.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}e.morphTargetDictionary[s]!==void 0&&(s=e.morphTargetDictionary[s])}l=this.BindingType.ArrayElement,this.resolvedProperty=a,this.propertyIndex=s}else a.fromArray!==void 0&&a.toArray!==void 0?(l=this.BindingType.HasFromToArray,this.resolvedProperty=a):Array.isArray(a)?(l=this.BindingType.EntireArray,this.resolvedProperty=a):this.propertyName=n;this.getValue=this.GetterByBindingType[l],this.setValue=this.SetterByBindingTypeAndVersioning[l][o]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}Et.Composite=pU,Et.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Et.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Et.prototype.GetterByBindingType=[Et.prototype._getValue_direct,Et.prototype._getValue_array,Et.prototype._getValue_arrayElement,Et.prototype._getValue_toArray],Et.prototype.SetterByBindingTypeAndVersioning=[[Et.prototype._setValue_direct,Et.prototype._setValue_direct_setNeedsUpdate,Et.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Et.prototype._setValue_array,Et.prototype._setValue_array_setNeedsUpdate,Et.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Et.prototype._setValue_arrayElement,Et.prototype._setValue_arrayElement_setNeedsUpdate,Et.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Et.prototype._setValue_fromArray,Et.prototype._setValue_fromArray_setNeedsUpdate,Et.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class mU{constructor(){this.isAnimationObjectGroup=!0,this.uuid=Cs(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;const e={};this._indicesByUUID=e;for(let i=0,n=arguments.length;i!==n;++i)e[arguments[i].uuid]=i;this._paths=[],this._parsedPaths=[],this._bindings=[],this._bindingsIndicesByPath={};const t=this;this.stats={objects:{get total(){return t._objects.length},get inUse(){return this.total-t.nCachedObjects_}},get bindingsPerObject(){return t._bindings.length}}}add(){const e=this._objects,t=this._indicesByUUID,i=this._paths,n=this._parsedPaths,s=this._bindings,a=s.length;let o,l=e.length,c=this.nCachedObjects_;for(let h=0,u=arguments.length;h!==u;++h){const d=arguments[h],p=d.uuid;let m=t[p];if(m===void 0){m=l++,t[p]=m,e.push(d);for(let A=0,g=a;A!==g;++A)s[A].push(new Et(d,i[A],n[A]))}else if(m<c){o=e[m];const A=--c,g=e[A];t[g.uuid]=m,e[m]=g,t[p]=A,e[A]=d;for(let y=0,v=a;y!==v;++y){const _=s[y],b=_[A];let T=_[m];_[m]=b,T===void 0&&(T=new Et(d,i[y],n[y])),_[A]=T}}else e[m]!==o&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=c}remove(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,n=i.length;let s=this.nCachedObjects_;for(let a=0,o=arguments.length;a!==o;++a){const l=arguments[a],c=l.uuid,h=t[c];if(h!==void 0&&h>=s){const u=s++,d=e[u];t[d.uuid]=h,e[h]=d,t[c]=u,e[u]=l;for(let p=0,m=n;p!==m;++p){const A=i[p],g=A[u],y=A[h];A[h]=g,A[u]=y}}}this.nCachedObjects_=s}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,n=i.length;let s=this.nCachedObjects_,a=e.length;for(let o=0,l=arguments.length;o!==l;++o){const c=arguments[o],h=c.uuid,u=t[h];if(u!==void 0)if(delete t[h],u<s){const d=--s,p=e[d],m=--a,A=e[m];t[p.uuid]=u,e[u]=p,t[A.uuid]=d,e[d]=A,e.pop();for(let g=0,y=n;g!==y;++g){const v=i[g],_=v[d],b=v[m];v[u]=_,v[d]=b,v.pop()}}else{const d=--a,p=e[d];d>0&&(t[p.uuid]=u),e[u]=p,e.pop();for(let m=0,A=n;m!==A;++m){const g=i[m];g[u]=g[d],g.pop()}}}this.nCachedObjects_=s}subscribe_(e,t){const i=this._bindingsIndicesByPath;let n=i[e];const s=this._bindings;if(n!==void 0)return s[n];const a=this._paths,o=this._parsedPaths,l=this._objects,c=l.length,h=this.nCachedObjects_,u=new Array(c);n=s.length,i[e]=n,a.push(e),o.push(t),s.push(u);for(let d=h,p=l.length;d!==p;++d){const m=l[d];u[d]=new Et(m,e,t)}return u}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(i!==void 0){const n=this._paths,s=this._parsedPaths,a=this._bindings,o=a.length-1,l=a[o],c=e[o];t[c]=i,a[i]=l,a.pop(),s[i]=s[o],s.pop(),n[i]=n[o],n.pop()}}}class $x{constructor(e,t,i=null,n=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=n;const s=t.tracks,a=s.length,o=new Array(a),l={endingStart:ic,endingEnd:ic};for(let c=0;c!==a;++c){const h=s[c].createInterpolant(null);o[c]=h,h.settings=l}this._interpolantSettings=l,this._interpolants=o,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=sy,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,i){if(e.fadeOut(t),this.fadeIn(t),i){const n=this._clip.duration,s=e._clip.duration,a=s/n,o=n/s;e.warp(1,a,t),this.warp(o,1,t)}return this}crossFadeTo(e,t,i){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,i){const n=this._mixer,s=n.time,a=this.timeScale;let o=this._timeScaleInterpolant;o===null&&(o=n._lendControlInterpolant(),this._timeScaleInterpolant=o);const l=o.parameterPositions,c=o.sampleValues;return l[0]=s,l[1]=s+i,c[0]=e/a,c[1]=t/a,this}stopWarping(){const e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,i,n){if(!this.enabled){this._updateWeight(e);return}const s=this._startTime;if(s!==null){const l=(e-s)*i;l<0||i===0?t=0:(this._startTime=null,t=i*l)}t*=this._updateTimeScale(e);const a=this._updateTime(t),o=this._updateWeight(e);if(o>0){const l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case Ow:for(let h=0,u=l.length;h!==u;++h)l[h].evaluate(a),c[h].accumulateAdditive(o);break;case ay:default:for(let h=0,u=l.length;h!==u;++h)l[h].evaluate(a),c[h].accumulate(n,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(i!==null){const n=i.evaluate(e)[0];t*=n,e>i.parameterPositions[1]&&(this.stopFading(),n===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const n=i.evaluate(e)[0];t*=n,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){const t=this._clip.duration,i=this.loop;let n=this.time+e,s=this._loopCount;const a=i===KP;if(e===0)return s===-1?n:a&&(s&1)===1?t-n:n;if(i===ny){s===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(n>=t)n=t;else if(n<0)n=0;else{this.time=n;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(s===-1&&(e>=0?(s=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),n>=t||n<0){const o=Math.floor(n/t);n-=t*o,s+=Math.abs(o);const l=this.repetitions-s;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,n=e>0?t:0,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){const c=e<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=s,this.time=n,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this.time=n;if(a&&(s&1)===1)return t-n}return n}_setEndings(e,t,i){const n=this._interpolantSettings;i?(n.endingStart=nc,n.endingEnd=nc):(e?n.endingStart=this.zeroSlopeAtStart?nc:ic:n.endingStart=Tf,t?n.endingEnd=this.zeroSlopeAtEnd?nc:ic:n.endingEnd=Tf)}_scheduleFading(e,t,i){const n=this._mixer,s=n.time;let a=this._weightInterpolant;a===null&&(a=n._lendControlInterpolant(),this._weightInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=s,l[0]=t,o[1]=s+e,l[1]=i,this}}const gU=new Float32Array(1);class Kx extends xi{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){const i=e._localRoot||this._root,n=e._clip.tracks,s=n.length,a=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName;let h=c[l];h===void 0&&(h={},c[l]=h);for(let u=0;u!==s;++u){const d=n[u],p=d.name;let m=h[p];if(m!==void 0)++m.referenceCount,a[u]=m;else{if(m=a[u],m!==void 0){m._cacheIndex===null&&(++m.referenceCount,this._addInactiveBinding(m,l,p));continue}const A=t&&t._propertyBindings[u].binding.parsedPath;m=new Yx(Et.create(i,p,A),d.ValueTypeName,d.getValueSize()),++m.referenceCount,this._addInactiveBinding(m,l,p),a[u]=m}o[u].resultBuffer=m.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){const i=(e._localRoot||this._root).uuid,n=e._clip.uuid,s=this._actionsByClip[n];this._bindAction(e,s&&s.knownActions[0]),this._addInactiveAction(e,n,i)}const t=e._propertyBindings;for(let i=0,n=t.length;i!==n;++i){const s=t[i];s.useCount++===0&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let i=0,n=t.length;i!==n;++i){const s=t[i];--s.useCount===0&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){const t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,i){const n=this._actions,s=this._actionsByClip;let a=s[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,s[t]=a;else{const o=a.knownActions;e._byClipCacheIndex=o.length,o.push(e)}e._cacheIndex=n.length,n.push(e),a.actionByRoot[i]=e}_removeInactiveAction(e){const t=this._actions,i=t[t.length-1],n=e._cacheIndex;i._cacheIndex=n,t[n]=i,t.pop(),e._cacheIndex=null;const s=e._clip.uuid,a=this._actionsByClip,o=a[s],l=o.knownActions,c=l[l.length-1],h=e._byClipCacheIndex;c._byClipCacheIndex=h,l[h]=c,l.pop(),e._byClipCacheIndex=null;const u=o.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],l.length===0&&delete a[s],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){const t=e._propertyBindings;for(let i=0,n=t.length;i!==n;++i){const s=t[i];--s.referenceCount===0&&this._removeInactiveBinding(s)}}_lendAction(e){const t=this._actions,i=e._cacheIndex,n=this._nActiveActions++,s=t[n];e._cacheIndex=n,t[n]=e,s._cacheIndex=i,t[i]=s}_takeBackAction(e){const t=this._actions,i=e._cacheIndex,n=--this._nActiveActions,s=t[n];e._cacheIndex=n,t[n]=e,s._cacheIndex=i,t[i]=s}_addInactiveBinding(e,t,i){const n=this._bindingsByRootAndName,s=this._bindings;let a=n[t];a===void 0&&(a={},n[t]=a),a[i]=e,e._cacheIndex=s.length,s.push(e)}_removeInactiveBinding(e){const t=this._bindings,i=e.binding,n=i.rootNode.uuid,s=i.path,a=this._bindingsByRootAndName,o=a[n],l=t[t.length-1],c=e._cacheIndex;l._cacheIndex=c,t[c]=l,t.pop(),delete o[s],Object.keys(o).length===0&&delete a[n]}_lendBinding(e){const t=this._bindings,i=e._cacheIndex,n=this._nActiveBindings++,s=t[n];e._cacheIndex=n,t[n]=e,s._cacheIndex=i,t[i]=s}_takeBackBinding(e){const t=this._bindings,i=e._cacheIndex,n=--this._nActiveBindings,s=t[n];e._cacheIndex=n,t[n]=e,s._cacheIndex=i,t[i]=s}_lendControlInterpolant(){const e=this._controlInterpolants,t=this._nActiveControlInterpolants++;let i=e[t];return i===void 0&&(i=new h_(new Float32Array(2),new Float32Array(2),1,gU),i.__cacheIndex=t,e[t]=i),i}_takeBackControlInterpolant(e){const t=this._controlInterpolants,i=e.__cacheIndex,n=--this._nActiveControlInterpolants,s=t[n];e.__cacheIndex=n,t[n]=e,s.__cacheIndex=i,t[i]=s}clipAction(e,t,i){const n=t||this._root,s=n.uuid;let a=typeof e=="string"?Ja.findByName(n,e):e;const o=a!==null?a.uuid:e,l=this._actionsByClip[o];let c=null;if(i===void 0&&(a!==null?i=a.blendMode:i=ay),l!==void 0){const u=l.actionByRoot[s];if(u!==void 0&&u.blendMode===i)return u;c=l.knownActions[0],a===null&&(a=c._clip)}if(a===null)return null;const h=new $x(this,a,t,i);return this._bindAction(h,c),this._addInactiveAction(h,o,s),h}existingAction(e,t){const i=t||this._root,n=i.uuid,s=typeof e=="string"?Ja.findByName(i,e):e,a=s?s.uuid:e,o=this._actionsByClip[a];return o!==void 0&&o.actionByRoot[n]||null}stopAllAction(){const e=this._actions,t=this._nActiveActions;for(let i=t-1;i>=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,n=this.time+=e,s=Math.sign(e),a=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(n,e,s,a);const o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(a);return this}setTime(e){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){const t=this._actions,i=e.uuid,n=this._actionsByClip,s=n[i];if(s!==void 0){const a=s.knownActions;for(let o=0,l=a.length;o!==l;++o){const c=a[o];this._deactivateAction(c);const h=c._cacheIndex,u=t[t.length-1];c._cacheIndex=null,c._byClipCacheIndex=null,u._cacheIndex=h,t[h]=u,t.pop(),this._removeInactiveBindingsForAction(c)}delete n[i]}}uncacheRoot(e){const t=e.uuid,i=this._actionsByClip;for(const a in i){const o=i[a].actionByRoot,l=o[t];l!==void 0&&(this._deactivateAction(l),this._removeInactiveAction(l))}const n=this._bindingsByRootAndName,s=n[t];if(s!==void 0)for(const a in s){const o=s[a];o.restoreOriginalState(),this._removeInactiveBinding(o)}}uncacheAction(e,t){const i=this.existingAction(e,t);i!==null&&(this._deactivateAction(i),this._removeInactiveAction(i))}}class tm{constructor(e){this.value=e}clone(){return new tm(this.value.clone===void 0?this.value:this.value.clone())}}let AU=0;class yU extends xi{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:AU++}),this.name="",this.usage=Bf,this.uniforms=[]}add(e){return this.uniforms.push(e),this}remove(e){const t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}setName(e){return this.name=e,this}setUsage(e){return this.usage=e,this}dispose(){return this.dispatchEvent({type:"dispose"}),this}copy(e){this.name=e.name,this.usage=e.usage;const t=e.uniforms;this.uniforms.length=0;for(let i=0,n=t.length;i<n;i++){const s=Array.isArray(t[i])?t[i]:[t[i]];for(let a=0;a<s.length;a++)this.uniforms.push(s[a].clone())}return this}clone(){return new this.constructor().copy(this)}}class Gu extends Mc{constructor(e,t,i=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}class _U{constructor(e,t,i,n,s){this.isGLBufferAttribute=!0,this.name="",this.buffer=e,this.type=t,this.itemSize=i,this.elementSize=n,this.count=s,this.version=0}set needsUpdate(e){e===!0&&this.version++}setBuffer(e){return this.buffer=e,this}setType(e,t){return this.type=e,this.elementSize=t,this}setItemSize(e){return this.itemSize=e,this}setCount(e){return this.count=e,this}}const Jx=new fe;class zu{constructor(e,t,i=0,n=1/0){this.ray=new Va(e,t),this.near=i,this.far=n,this.camera=null,this.layers=new Qf,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):console.error("THREE.Raycaster: Unsupported camera type: "+t.type)}setFromXRController(e){return Jx.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(Jx),this}intersectObject(e,t=!0,i=[]){return w_(e,this,i,t),i.sort(Zx),i}intersectObjects(e,t=!0,i=[]){for(let n=0,s=e.length;n<s;n++)w_(e[n],this,i,t);return i.sort(Zx),i}}function Zx(r,e){return r.distance-e.distance}function w_(r,e,t,i){let n=!0;if(r.layers.test(e.layers)&&r.raycast(e,t)===!1&&(n=!1),n===!0&&i===!0){const s=r.children;for(let a=0,o=s.length;a<o;a++)w_(s[a],e,t,!0)}}class Ir{constructor(e=1,t=0,i=0){return this.radius=e,this.phi=t,this.theta=i,this}set(e,t,i){return this.radius=e,this.phi=t,this.theta=i,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=Math.max(1e-6,Math.min(Math.PI-1e-6,this.phi)),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,i){return this.radius=Math.sqrt(e*e+t*t+i*i),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,i),this.phi=Math.acos(Gi(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}class vU{constructor(e=1,t=0,i=0){return this.radius=e,this.theta=t,this.y=i,this}set(e,t,i){return this.radius=e,this.theta=t,this.y=i,this}copy(e){return this.radius=e.radius,this.theta=e.theta,this.y=e.y,this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,i){return this.radius=Math.sqrt(e*e+i*i),this.theta=Math.atan2(e,i),this.y=t,this}clone(){return new this.constructor().copy(this)}}class im{constructor(e,t,i,n){im.prototype.isMatrix2=!0,this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,i,n)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let i=0;i<4;i++)this.elements[i]=e[i+t];return this}set(e,t,i,n){const s=this.elements;return s[0]=e,s[2]=t,s[1]=i,s[3]=n,this}}const eS=new K;class C_{constructor(e=new K(1/0,1/0),t=new K(-1/0,-1/0)){this.isBox2=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromPoints(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const i=eS.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),this}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=1/0,this.max.x=this.max.y=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y}getCenter(e){return this.isEmpty()?e.set(0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(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}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}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}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))}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}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,eS).distanceTo(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}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)}}const tS=new S,nm=new S;class x_{constructor(e=new S,t=new S){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){tS.subVectors(e,this.start),nm.subVectors(this.end,this.start);const i=nm.dot(nm);let s=nm.dot(tS)/i;return t&&(s=Gi(s,0,1)),s}closestPointToPoint(e,t,i){const n=this.closestPointToPointParameter(e,t);return this.delta(i).multiplyScalar(n).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}const iS=new S;class bU extends ft{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new Je,n=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let a=0,o=1,l=32;a<l;a++,o++){const c=a/l*Math.PI*2,h=o/l*Math.PI*2;n.push(Math.cos(c),Math.sin(c),1,Math.cos(h),Math.sin(h),1)}i.setAttribute("position",new Ee(n,3));const s=new Mi({fog:!1,toneMapped:!1});this.cone=new Ms(i,s),this.add(this.cone),this.update()}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),this.parent?(this.parent.updateWorldMatrix(!0),this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)):this.matrix.copy(this.light.matrixWorld),this.matrixWorld.copy(this.light.matrixWorld);const e=this.light.distance?this.light.distance:1e3,t=e*Math.tan(this.light.angle);this.cone.scale.set(t,t,e),iS.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(iS),this.color!==void 0?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}}const to=new S,sm=new fe,S_=new fe;class wU extends Ms{constructor(e){const t=nS(e),i=new Je,n=[],s=[],a=new ee(0,0,1),o=new ee(0,1,0);for(let c=0;c<t.length;c++){const h=t[c];h.parent&&h.parent.isBone&&(n.push(0,0,0),n.push(0,0,0),s.push(a.r,a.g,a.b),s.push(o.r,o.g,o.b))}i.setAttribute("position",new Ee(n,3)),i.setAttribute("color",new Ee(s,3));const l=new Mi({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});super(i,l),this.isSkeletonHelper=!0,this.type="SkeletonHelper",this.root=e,this.bones=t,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1}updateMatrixWorld(e){const t=this.bones,i=this.geometry,n=i.getAttribute("position");S_.copy(this.root.matrixWorld).invert();for(let s=0,a=0;s<t.length;s++){const o=t[s];o.parent&&o.parent.isBone&&(sm.multiplyMatrices(S_,o.matrixWorld),to.setFromMatrixPosition(sm),n.setXYZ(a,to.x,to.y,to.z),sm.multiplyMatrices(S_,o.parent.matrixWorld),to.setFromMatrixPosition(sm),n.setXYZ(a+1,to.x,to.y,to.z),a+=2)}i.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose()}}function nS(r){const e=[];r.isBone===!0&&e.push(r);for(let t=0;t<r.children.length;t++)e.push.apply(e,nS(r.children[t]));return e}class CU extends _e{constructor(e,t,i){const n=new Is(t,4,2),s=new is({wireframe:!0,fog:!1,toneMapped:!1});super(n,s),this.light=e,this.color=i,this.type="PointLightHelper",this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1,this.update()}dispose(){this.geometry.dispose(),this.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.color!==void 0?this.material.color.set(this.color):this.material.color.copy(this.light.color)}}const xU=new S,sS=new ee,rS=new ee;class SU extends ft{constructor(e,t,i){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=i,this.type="HemisphereLightHelper";const n=new da(t);n.rotateY(Math.PI*.5),this.material=new is({wireframe:!0,fog:!1,toneMapped:!1}),this.color===void 0&&(this.material.vertexColors=!0);const s=n.getAttribute("position"),a=new Float32Array(s.count*3);n.setAttribute("color",new Ze(a,3)),this.add(new _e(n,this.material)),this.update()}dispose(){this.children[0].geometry.dispose(),this.children[0].material.dispose()}update(){const e=this.children[0];if(this.color!==void 0)this.material.color.set(this.color);else{const t=e.geometry.getAttribute("color");sS.copy(this.light.color),rS.copy(this.light.groundColor);for(let i=0,n=t.count;i<n;i++){const s=i<n/2?sS:rS;t.setXYZ(i,s.r,s.g,s.b)}t.needsUpdate=!0}this.light.updateWorldMatrix(!0,!1),e.lookAt(xU.setFromMatrixPosition(this.light.matrixWorld).negate())}}class EU extends Ms{constructor(e=10,t=10,i=4473924,n=8947848){i=new ee(i),n=new ee(n);const s=t/2,a=e/t,o=e/2,l=[],c=[];for(let d=0,p=0,m=-o;d<=t;d++,m+=a){l.push(-o,0,m,o,0,m),l.push(m,0,-o,m,0,o);const A=d===s?i:n;A.toArray(c,p),p+=3,A.toArray(c,p),p+=3,A.toArray(c,p),p+=3,A.toArray(c,p),p+=3}const h=new Je;h.setAttribute("position",new Ee(l,3)),h.setAttribute("color",new Ee(c,3));const u=new Mi({vertexColors:!0,toneMapped:!1});super(h,u),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}class MU extends Ms{constructor(e=10,t=16,i=8,n=64,s=4473924,a=8947848){s=new ee(s),a=new ee(a);const o=[],l=[];if(t>1)for(let u=0;u<t;u++){const d=u/t*(Math.PI*2),p=Math.sin(d)*e,m=Math.cos(d)*e;o.push(0,0,0),o.push(p,0,m);const A=u&1?s:a;l.push(A.r,A.g,A.b),l.push(A.r,A.g,A.b)}for(let u=0;u<i;u++){const d=u&1?s:a,p=e-e/i*u;for(let m=0;m<n;m++){let A=m/n*(Math.PI*2),g=Math.sin(A)*p,y=Math.cos(A)*p;o.push(g,0,y),l.push(d.r,d.g,d.b),A=(m+1)/n*(Math.PI*2),g=Math.sin(A)*p,y=Math.cos(A)*p,o.push(g,0,y),l.push(d.r,d.g,d.b)}}const c=new Je;c.setAttribute("position",new Ee(o,3)),c.setAttribute("color",new Ee(l,3));const h=new Mi({vertexColors:!0,toneMapped:!1});super(c,h),this.type="PolarGridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}}const aS=new S,rm=new S,oS=new S;class TU extends ft{constructor(e,t,i){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=i,this.type="DirectionalLightHelper",t===void 0&&(t=1);let n=new Je;n.setAttribute("position",new Ee([-t,t,0,t,t,0,t,-t,0,-t,-t,0,-t,t,0],3));const s=new Mi({fog:!1,toneMapped:!1});this.lightPlane=new fn(n,s),this.add(this.lightPlane),n=new Je,n.setAttribute("position",new Ee([0,0,0,0,0,1],3)),this.targetLine=new fn(n,s),this.add(this.targetLine),this.update()}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),aS.setFromMatrixPosition(this.light.matrixWorld),rm.setFromMatrixPosition(this.light.target.matrixWorld),oS.subVectors(rm,aS),this.lightPlane.lookAt(rm),this.color!==void 0?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color)),this.targetLine.lookAt(rm),this.targetLine.scale.z=oS.length()}}const am=new S,Hi=new fu;class IU extends Ms{constructor(e){const t=new Je,i=new Mi({color:16777215,vertexColors:!0,toneMapped:!1}),n=[],s=[],a={};o("n1","n2"),o("n2","n4"),o("n4","n3"),o("n3","n1"),o("f1","f2"),o("f2","f4"),o("f4","f3"),o("f3","f1"),o("n1","f1"),o("n2","f2"),o("n3","f3"),o("n4","f4"),o("p","n1"),o("p","n2"),o("p","n3"),o("p","n4"),o("u1","u2"),o("u2","u3"),o("u3","u1"),o("c","t"),o("p","c"),o("cn1","cn2"),o("cn3","cn4"),o("cf1","cf2"),o("cf3","cf4");function o(m,A){l(m),l(A)}function l(m){n.push(0,0,0),s.push(0,0,0),a[m]===void 0&&(a[m]=[]),a[m].push(n.length/3-1)}t.setAttribute("position",new Ee(n,3)),t.setAttribute("color",new Ee(s,3)),super(t,i),this.type="CameraHelper",this.camera=e,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=a,this.update();const c=new ee(16755200),h=new ee(16711680),u=new ee(43775),d=new ee(16777215),p=new ee(3355443);this.setColors(c,h,u,d,p)}setColors(e,t,i,n,s){const o=this.geometry.getAttribute("color");o.setXYZ(0,e.r,e.g,e.b),o.setXYZ(1,e.r,e.g,e.b),o.setXYZ(2,e.r,e.g,e.b),o.setXYZ(3,e.r,e.g,e.b),o.setXYZ(4,e.r,e.g,e.b),o.setXYZ(5,e.r,e.g,e.b),o.setXYZ(6,e.r,e.g,e.b),o.setXYZ(7,e.r,e.g,e.b),o.setXYZ(8,e.r,e.g,e.b),o.setXYZ(9,e.r,e.g,e.b),o.setXYZ(10,e.r,e.g,e.b),o.setXYZ(11,e.r,e.g,e.b),o.setXYZ(12,e.r,e.g,e.b),o.setXYZ(13,e.r,e.g,e.b),o.setXYZ(14,e.r,e.g,e.b),o.setXYZ(15,e.r,e.g,e.b),o.setXYZ(16,e.r,e.g,e.b),o.setXYZ(17,e.r,e.g,e.b),o.setXYZ(18,e.r,e.g,e.b),o.setXYZ(19,e.r,e.g,e.b),o.setXYZ(20,e.r,e.g,e.b),o.setXYZ(21,e.r,e.g,e.b),o.setXYZ(22,e.r,e.g,e.b),o.setXYZ(23,e.r,e.g,e.b),o.setXYZ(24,t.r,t.g,t.b),o.setXYZ(25,t.r,t.g,t.b),o.setXYZ(26,t.r,t.g,t.b),o.setXYZ(27,t.r,t.g,t.b),o.setXYZ(28,t.r,t.g,t.b),o.setXYZ(29,t.r,t.g,t.b),o.setXYZ(30,t.r,t.g,t.b),o.setXYZ(31,t.r,t.g,t.b),o.setXYZ(32,i.r,i.g,i.b),o.setXYZ(33,i.r,i.g,i.b),o.setXYZ(34,i.r,i.g,i.b),o.setXYZ(35,i.r,i.g,i.b),o.setXYZ(36,i.r,i.g,i.b),o.setXYZ(37,i.r,i.g,i.b),o.setXYZ(38,n.r,n.g,n.b),o.setXYZ(39,n.r,n.g,n.b),o.setXYZ(40,s.r,s.g,s.b),o.setXYZ(41,s.r,s.g,s.b),o.setXYZ(42,s.r,s.g,s.b),o.setXYZ(43,s.r,s.g,s.b),o.setXYZ(44,s.r,s.g,s.b),o.setXYZ(45,s.r,s.g,s.b),o.setXYZ(46,s.r,s.g,s.b),o.setXYZ(47,s.r,s.g,s.b),o.setXYZ(48,s.r,s.g,s.b),o.setXYZ(49,s.r,s.g,s.b),o.needsUpdate=!0}update(){const e=this.geometry,t=this.pointMap,i=1,n=1;Hi.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),rn("c",t,e,Hi,0,0,-1),rn("t",t,e,Hi,0,0,1),rn("n1",t,e,Hi,-i,-n,-1),rn("n2",t,e,Hi,i,-n,-1),rn("n3",t,e,Hi,-i,n,-1),rn("n4",t,e,Hi,i,n,-1),rn("f1",t,e,Hi,-i,-n,1),rn("f2",t,e,Hi,i,-n,1),rn("f3",t,e,Hi,-i,n,1),rn("f4",t,e,Hi,i,n,1),rn("u1",t,e,Hi,i*.7,n*1.1,-1),rn("u2",t,e,Hi,-i*.7,n*1.1,-1),rn("u3",t,e,Hi,0,n*2,-1),rn("cf1",t,e,Hi,-i,0,1),rn("cf2",t,e,Hi,i,0,1),rn("cf3",t,e,Hi,0,-n,1),rn("cf4",t,e,Hi,0,n,1),rn("cn1",t,e,Hi,-i,0,-1),rn("cn2",t,e,Hi,i,0,-1),rn("cn3",t,e,Hi,0,-n,-1),rn("cn4",t,e,Hi,0,n,-1),e.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}}function rn(r,e,t,i,n,s,a){am.set(n,s,a).unproject(i);const o=e[r];if(o!==void 0){const l=t.getAttribute("position");for(let c=0,h=o.length;c<h;c++)l.setXYZ(o[c],am.x,am.y,am.z)}}const om=new en;class PU extends Ms{constructor(e,t=16776960){const i=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),n=new Float32Array(24),s=new Je;s.setIndex(new Ze(i,1)),s.setAttribute("position",new Ze(n,3)),super(s,new Mi({color:t,toneMapped:!1})),this.object=e,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(e){if(e!==void 0&&console.warn("THREE.BoxHelper: .update() has no longer arguments."),this.object!==void 0&&om.setFromObject(this.object),om.isEmpty())return;const t=om.min,i=om.max,n=this.geometry.attributes.position,s=n.array;s[0]=i.x,s[1]=i.y,s[2]=i.z,s[3]=t.x,s[4]=i.y,s[5]=i.z,s[6]=t.x,s[7]=t.y,s[8]=i.z,s[9]=i.x,s[10]=t.y,s[11]=i.z,s[12]=i.x,s[13]=i.y,s[14]=t.z,s[15]=t.x,s[16]=i.y,s[17]=t.z,s[18]=t.x,s[19]=t.y,s[20]=t.z,s[21]=i.x,s[22]=t.y,s[23]=t.z,n.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(e){return this.object=e,this.update(),this}copy(e,t){return super.copy(e,t),this.object=e.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class DU extends Ms{constructor(e,t=16776960){const i=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),n=[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],s=new Je;s.setIndex(new Ze(i,1)),s.setAttribute("position",new Ee(n,3)),super(s,new Mi({color:t,toneMapped:!1})),this.box=e,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(e){const t=this.box;t.isEmpty()||(t.getCenter(this.position),t.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(e))}dispose(){this.geometry.dispose(),this.material.dispose()}}class RU extends fn{constructor(e,t=1,i=16776960){const n=i,s=[1,-1,0,-1,1,0,-1,-1,0,1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],a=new Je;a.setAttribute("position",new Ee(s,3)),a.computeBoundingSphere(),super(a,new Mi({color:n,toneMapped:!1})),this.type="PlaneHelper",this.plane=e,this.size=t;const o=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],l=new Je;l.setAttribute("position",new Ee(o,3)),l.computeBoundingSphere(),this.add(new _e(l,new is({color:n,opacity:.2,transparent:!0,depthWrite:!1,toneMapped:!1})))}updateMatrixWorld(e){this.position.set(0,0,0),this.scale.set(.5*this.size,.5*this.size,1),this.lookAt(this.plane.normal),this.translateZ(-this.plane.constant),super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()}}const lS=new S;let lm,E_;class BU extends ft{constructor(e=new S(0,0,1),t=new S(0,0,0),i=1,n=16776960,s=i*.2,a=s*.2){super(),this.type="ArrowHelper",lm===void 0&&(lm=new Je,lm.setAttribute("position",new Ee([0,0,0,0,1,0],3)),E_=new sn(0,.5,1,5,1),E_.translate(0,-.5,0)),this.position.copy(t),this.line=new fn(lm,new Mi({color:n,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new _e(E_,new is({color:n,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(e),this.setLength(i,s,a)}setDirection(e){if(e.y>.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{lS.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(lS,t)}}setLength(e,t=e*.2,i=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(i,t,i),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class LU extends Ms{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],n=new Je;n.setAttribute("position",new Ee(t,3)),n.setAttribute("color",new Ee(i,3));const s=new Mi({vertexColors:!0,toneMapped:!1});super(n,s),this.type="AxesHelper"}setColors(e,t,i){const n=new ee,s=this.geometry.attributes.color.array;return n.set(e),n.toArray(s,0),n.toArray(s,3),n.set(t),n.toArray(s,6),n.toArray(s,9),n.set(i),n.toArray(s,12),n.toArray(s,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class OU{constructor(){this.type="ShapePath",this.color=new ee,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Fc,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,i,n){return this.currentPath.quadraticCurveTo(e,t,i,n),this}bezierCurveTo(e,t,i,n,s,a){return this.currentPath.bezierCurveTo(e,t,i,n,s,a),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(y){const v=[];for(let _=0,b=y.length;_<b;_++){const T=y[_],E=new rr;E.curves=T.curves,v.push(E)}return v}function i(y,v){const _=v.length;let b=!1;for(let T=_-1,E=0;E<_;T=E++){let M=v[T],I=v[E],C=I.x-M.x,x=I.y-M.y;if(Math.abs(x)>Number.EPSILON){if(x<0&&(M=v[E],C=-C,I=v[T],x=-x),y.y<M.y||y.y>I.y)continue;if(y.y===M.y){if(y.x===M.x)return!0}else{const D=x*(y.x-M.x)-C*(y.y-M.y);if(D===0)return!0;if(D<0)continue;b=!b}}else{if(y.y!==M.y)continue;if(I.x<=y.x&&y.x<=M.x||M.x<=y.x&&y.x<=I.x)return!0}}return b}const n=ar.isClockWise,s=this.subPaths;if(s.length===0)return[];let a,o,l;const c=[];if(s.length===1)return o=s[0],l=new rr,l.curves=o.curves,c.push(l),c;let h=!n(s[0].getPoints());h=e?!h:h;const u=[],d=[];let p=[],m=0,A;d[m]=void 0,p[m]=[];for(let y=0,v=s.length;y<v;y++)o=s[y],A=o.getPoints(),a=n(A),a=e?!a:a,a?(!h&&d[m]&&m++,d[m]={s:new rr,p:A},d[m].s.curves=o.curves,h&&m++,p[m]=[]):p[m].push({h:o,p:A[0]});if(!d[0])return t(s);if(d.length>1){let y=!1,v=0;for(let _=0,b=d.length;_<b;_++)u[_]=[];for(let _=0,b=d.length;_<b;_++){const T=p[_];for(let E=0;E<T.length;E++){const M=T[E];let I=!0;for(let C=0;C<d.length;C++)i(M.p,d[C].p)&&(_!==C&&v++,I?(I=!1,u[C].push(M)):y=!0);I&&u[_].push(M)}}v>0&&y===!1&&(p=u)}let g;for(let y=0,v=d.length;y<v;y++){l=d[y].s,c.push(l),g=p[y];for(let _=0,b=g.length;_<b;_++)l.holes.push(g[_].h)}return c}}class UU extends xi{constructor(e,t){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(){}disconnect(){}dispose(){}update(){}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"168"}})),typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="168");let cm=class{constructor(){this._eventListeners={},this.dispatchEvent=this.dispatchEvent.bind(this),this.addEventListener=this.addEventListener.bind(this),this.removeEventListener=this.removeEventListener.bind(this),this.hasEventListener=this.hasEventListener.bind(this)}addEventListener(e,t){const i=this._eventListeners;i[e]===void 0&&(i[e]=[]),i[e].includes(t)||i[e].push(t)}hasEventListener(e,t){const i=this._eventListeners;return i[e]!==void 0&&i[e].includes(t)}removeEventListener(e,t){const i=this._eventListeners[e];if(i!==void 0){const n=i.indexOf(t);n!==-1&&i.splice(n,1)}}dispatchEvent(e){const t=this._eventListeners[e.type];if(t!==void 0){e.target=this;const i=t.slice(0);for(let n=0,s=i.length;n<s;n++)i[n].call(this,e)}}};async function Qn(r){return new Promise(e=>setTimeout(e,Math.max(0,r)))}function Cn(){return(typeof performance>"u"?Date:performance).now()}class cS extends cm{constructor(){super(...arguments),this._onPointerDown=e=>{if(e.button!==0||!this._element)return;this._pointerUp=void 0;const t=e.clientX/this._element.clientWidth*2-1,i=-(e.clientY/this._element.clientHeight)*2+1,n=Cn();this._pointerDown={x:t,y:i,time:n},this._pointer=this._pointerDown,this.dispatchEvent({type:"dragStart",pointer:this._pointerDown})},this._onPointerMove=e=>{if(!this._pointerDown||!this._pointer||!this._element)return;const t=e.clientX/this._element.clientWidth*2-1,i=-(e.clientY/this._element.clientHeight)*2+1,n=Cn();this.dispatchEvent({type:"drag",pointer:this._pointer,drag:{x:t-this._pointerDown.x,y:i-this._pointerDown.y,time:n-this._pointerDown.time},delta:{x:t-this._pointer.x,y:i-this._pointer.y,time:n-this._pointer.time}}),this._pointer={x:t,y:i,time:Cn()},e.buttons%2===0&&this._onPointerUp(e)},this._onPointerUp=e=>{if(e.button!==0||!this._pointerDown||!this._element)return;const t=e.clientX/this._element.clientWidth*2-1,i=-(e.clientY/this._element.clientHeight)*2+1,n=Cn();this._pointerUp={x:t,y:i,time:n},this.dispatchEvent({type:"dragEnd",pointer:this._pointerUp,drag:{x:this._pointerUp.x-this._pointerDown.x,y:this._pointerUp.y-this._pointerDown.y,time:this._pointerUp.time-this._pointerDown.time}}),this._pointerDown=void 0,this._pointer=void 0}}get element(){return this._element}set element(e){this._element!==e&&(this._element&&this._removeElement(),this._element=e,this._element&&this._addElement())}_removeElement(){var e,t,i,n,s;(e=this._element)==null||e.removeEventListener("pointerdown",this._onPointerDown),(t=this._element)==null||t.removeEventListener("pointermove",this._onPointerMove),(i=this._element)==null||i.removeEventListener("pointerup",this._onPointerUp),(n=this._element)==null||n.removeEventListener("pointercancel",this._onPointerUp),(s=this._element)==null||s.removeEventListener("pointerout",this._onPointerUp)}_addElement(){var e,t,i,n,s;(e=this._element)==null||e.addEventListener("pointerdown",this._onPointerDown),(t=this._element)==null||t.addEventListener("pointermove",this._onPointerMove),(i=this._element)==null||i.addEventListener("pointerup",this._onPointerUp),(n=this._element)==null||n.addEventListener("pointercancel",this._onPointerUp),(s=this._element)==null||s.addEventListener("pointerout",this._onPointerUp)}dispose(){this.element=void 0}}class M_{constructor(e){this.options={limit:500,debug:!1,bindHotKeys:!1},this.enabled=!0,this.presets={},this._keyDown=t=>{if(!this.enabled)return;const i=t.ctrlKey||t.metaKey;t.code==="KeyZ"&&i&&!t.shiftKey?this.undo():(t.code==="KeyZ"&&i&&t.shiftKey||t.code==="KeyY"&&t.ctrlKey)&&this.redo()},Object.assign(this.options,e),this.limit=e.limit,this.options=e,this.reset(),e.bindHotKeys&&this.bindHotKeys(),this.log(`Initialized with stack limit of ${this.limit} commands`)}bindHotKeys(){return this.log("Bound 'undo' and 'redo' actions to 'Ctrl/Cmd+Z', 'Ctrl+Y' & 'Ctrl/Cmd+Shift+Z' hot keys"),(this.options.hotKeyRoot??document).addEventListener("keydown",this._keyDown),this}dispose(){return(this.options.hotKeyRoot??document).removeEventListener("keydown",this._keyDown),this.reset()}record(e){return this.enabled?(this._record(e),this):this}replaceLast(e){const t=this.peek();if(t)return this.log("replace",t,"with",e),this.stack[this.sp]=e,this}execute(e){if(!this.enabled)return;let t=this._rc(e),i=t.redo;return this.record.apply(this,t),this.log("Executing function..."),i.apply(e),this}_rc(e){if(e.type){const t=this.presets[e.type];if(typeof t=="function")return t(e);throw console.error(e,t,this.presets),new Error("Preset command not found")}else return e}_record(e){this.enabled&&(this.log("Recording command",e),this._rebase(),this.stack.push(e),this.sp++,this._keepLimit())}_rebase(){this.canRedo()&&(this.stack.length=this.sp+1)}_keepLimit(){if(this.stack.length<=this.limit)return;let e=this.stack.length-this.limit;this.log("Stack size reached its limit: ${this.limit} commands. Cutting off most old commands..."),e===1?this.stack.shift():this.stack.splice(0,e),this.sp-=e}undo(){if(!this.canUndo())return this;let e=this.stack[this.sp];return this.log("undo"),this.sp--,this._rc(e).undo(),this}canUndo(){return this.sp>=0&&this.enabled}peek(){return this.canUndo()?this.stack[this.sp]:null}redo(){if(!this.canRedo())return this;let e=this.stack[this.sp+1];return this.log("redo"),this.sp++,this._rc(e).redo(),this}canRedo(){return this.sp<this.stack.length-1&&this.enabled}peekForward(){return this.canRedo()?this.stack[this.sp+1]:null}setLimit(e){let t=this.stack.length-this.sp-1;if(e<1||typeof e!="number")throw new TypeError(`JSUndoManager.setLimit(): unexpected argument limit=${e}. Should be a positive number`);return e<t?console.warn(`JSUndoManager.setLimit(): cannot set stack limit (${e}) less than the number of 'redoable' commands (${t})`):(this.limit=Math.floor(e),this._keepLimit()),this}reset(){return this.log("reset"),this.stack=[],this.sp=-1,this}isEmpty(){return!this.stack.length}isFull(){return this.stack.length===this.limit}getSize(){return this.stack.length}log(e,...t){this.options.debug&&console.log(`Command Manager: ${e}`,...t)}}const hm=class lw{constructor(e=lw.DECAY_MILLISECONDS){this.velocity=0,this.naturalFrequency=0,this.setDecayTime(e)}setDecayTime(e){this.naturalFrequency=1/Math.max(lw.MIN_DECAY_MILLISECONDS,e)}update(e,t,i,n){const s=2e-4*this.naturalFrequency;if(e==null||n===0||e===t&&this.velocity===0)return t;if(i<0)return e;const a=e-t,o=this.velocity+this.naturalFrequency*a,l=a+i*o,c=Math.exp(-this.naturalFrequency*i),h=(o-this.naturalFrequency*l)*c,u=-this.naturalFrequency*(h+o*c);return Math.abs(h)<s*Math.abs(n)&&u*a>=0?(this.velocity=0,t):(this.velocity=h,t+l*c)}};hm.SETTLING_TIME=1e4,hm.MIN_DECAY_MILLISECONDS=.001,hm.DECAY_MILLISECONDS=50;let FU=hm;function hS(){const r=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");return r.style.display="block",r}function Pr({innerHTML:r="",id:e,classList:t,addToBody:i=!0,elementTag:n="div"}){const s=document.createElement(n);return e&&(s.id=e),s.innerHTML=r,t&&s.classList.add(...t),i&&document.body.appendChild(s),s}async function uS(r){return new Promise((e,t)=>{const i=new Image;i.onload=()=>e(i),i.onerror=t,i.crossOrigin="anonymous",i.decoding="sync",i.src=r})}function hl(r,e=document.head){const t=document.createElement("style");return t.type="text/css",t.innerText=r,e?.appendChild(t),t}async function NU(r,e=document.head){return new Promise((t,i)=>{const n=document.createElement("script");n.setAttribute("src",r),n.addEventListener("load",()=>t(n)),n.addEventListener("error",i),e.appendChild(n)})}async function kU(r,e){var t;r.innerHTML=e;const i=r.getElementsByTagName("script");for(let n=0;n<i.length;n++){const s=i[n],a=dS(s);let o=!1;await new Promise(l=>{a.onload=l,a.onerror=()=>{o=!0,l(void 0)}}),!o&&((t=s.parentNode)==null||t.replaceChild(a,s))}}function dS(r,e){e=e??document.createElement("script"),e.type=r.type||"text/javascript",e.text=r.text;for(let t=0;t<r.attributes.length;t++){const i=r.attributes[t];e.setAttribute(i.name,i.value)}return e}function um(r){if(!window)return console.warn("window is required"),"";let e="";const t=new Uint8Array(r),i=t.byteLength;for(let n=0;n<i;n++)e+=String.fromCharCode(t[n]);return window.btoa(e)}function T_(r){if(!window)return console.warn("window is required"),new Uint8Array(0);const e=window.atob(r),t=e.length,i=new Uint8Array(t);for(let n=0;n<t;n++)i[n]=e.charCodeAt(n);return i.buffer}const fS={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function pS(r,e){return new fS[r](e)}function mS(r){return r.replace(/\w\S*/g,function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()})}function GU(r){return r.replace(/([-_][a-z])/ig,e=>e.toUpperCase().replace("-","").replace("_",""))}function Vu(r){if(!r||r===""||r.match(/__MACOSX\/.*\._/))return"";r=r.replace(/\?.*$/,"");const e=r.split(/[\\/]/).pop()??"",t=e.lastIndexOf(".");return e===""||t<1?"":e.slice(t+1)}function zU(r){return r.substring(r.lastIndexOf("/")+1)}function Hu(r){return RegExp.escape?RegExp.escape(r):r.replace(/[.*+?^${}()|[\]/\\=!:]/g,"\\$&")}function jn(r,e,t){return r.replace(new RegExp(Hu(e),"g"),t)}function VU(r,e,t,{replaceAll:i=!1,prepend:n=!1,append:s=!1,notFoundCallback:a=()=>{}}={}){if(a&&!r.includes(e))return a(),r;let o=t;return n?o=t+e:s&&(o=e+t),i?r.replaceAll(e,o):r.replace(e,o)}function HU(r){return r.sort(),r[0].split("").map((e,t)=>r[r.length-1][t]===e?e:"\0").join("").split("\0").at(0)||""}function ks(r){return r.replace(/[&<>"']/g,function(e){switch(e){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return e}})}const ma=(r,...e)=>String.raw({raw:r},...e),gS=(r,...e)=>String.raw({raw:r},...e),QU=(r,...e)=>String.raw({raw:r},...e),I_=(r,...e)=>{let t=String.raw({raw:r},...e);return t=jn(t,"%","%25"),t=jn(t,"> <","><"),t=jn(t,"; }",";}"),t=jn(t,"<","%3c"),t=jn(t,">","%3e"),t=jn(t,'"',"'"),t=jn(t,"#","%23"),t=jn(t,"{","%7b"),t=jn(t,"}","%7d"),t=jn(t,"|","%7c"),t=jn(t,"^","%5e"),t=jn(t,"`","%60"),t=jn(t,"@","%40"),t=jn(t,"&","&amp;"),t=jn(t,`
`,"%0A"),"data:image/svg+xml;charset=UTF-8,"+t};function jU(r=document.head){return hl(gS`
      ::-webkit-scrollbar
      {
        width: 8px;  /* for vertical scrollbars */
        height: 8px; /* for horizontal scrollbars */
      }
      ::-webkit-scrollbar-track
      {
        background: rgba(64, 64, 64, 0.4);
        border-radius: 6px;
      }
      ::-webkit-scrollbar-thumb
      {
        background: rgba(128, 128, 128, 0.2);
        border-radius: 6px;
      }
      ::-webkit-scrollbar-corner {background: rgba(0,0,0,0.5);}
    `,r)}function Qu(r,e){const t=window.URL.createObjectURL(r),i=document.createElement("a");i.style.display="none",i.href=t,i.download=e,document.body.appendChild(i),i.click(),setTimeout(()=>{document.body.removeChild(i),window.URL.revokeObjectURL(t)},1e3)}async function dm(r){return new Promise((e,t)=>{const i=new FileReader;i.onload=n=>e(i.result),i.onerror=n=>t(i.error),i.onabort=n=>t(new Error("Read aborted")),i.readAsDataURL(r)})}function AS(r,e){return Qu(r,e??r.name)}async function yS(r=!1,e=!1,t){const i=document.createElement("input");i.type="file",i.multiple=r,i.accept=t||"*",i.webkitdirectory=e,i.style.display="none",document.body.appendChild(i),i.click();const n=await new Promise(s=>{i.onchange=a=>{s(Array.from(i.files||[]))}});return document.body.removeChild(i),n}function WU(){let r=!1;return(function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(r=!0)})(navigator.userAgent||navigator.vendor||window.opera),r}function qU(r){return r<.04045?r*.0773993808:Math.pow(r*.9478672986+.0521327014,2.4)}function _S(r){return r<.0031308?r*12.92:1.055*Math.pow(r,.41666)-.055}function XU(r,e=1,t=1){const i=document.createElement("canvas");i.width=e,i.height=t;const n=i.getContext("2d");n.fillStyle="#"+r,n.fillRect(0,0,e,t);const s=i.toDataURL();return i.remove(),s}function vS(r,e){let t;do t=Object.getOwnPropertyDescriptor(r,e);while(!t&&(r=Object.getPrototypeOf(r)));return t}function bS(r,e,t=!0,i=!1){const n=vS(r,e);return!!(n!=null&&n.set)||t&&n?.writable!==!1&&n?.get===void 0||i&&!n}function an(r,e,t,i=!0,n=!1){return r&&bS(r,e,i,n)?(r[e]=t,!0):!1}function tt(r,...e){return typeof r=="function"&&(r=r(...e)),r}function wS(r,e,t){for(const i of t){const n=r[i];n!==void 0&&an(e,i,n,!0)}return e}function CS(r,e){for(const t of e)if(!r.includes(t))return!1;return!0}function xS(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}function YU(r,e){return function(...t){return r(),e&&e.call(this,...t)}}function SS(r,e){return function(...t){return r(...t),e&&e.call(this,...t)}}function ju(r,e,t=!1){for(typeof r=="string"&&(r=r.split("."));r.length>0;){if(!e)return e;const i=r.splice(0,1)[0];if(!(i.length<1))if(Array.isArray(e))e=e[parseInt(i)];else if(typeof e=="object"&&i in e)e=e[i];else{if(t)throw new Error("invalid access, check "+i+" in "+e);return}}return e}function $U(r,e){return Object.keys(r).find(t=>r[t]===e)}function Wn(r,e){return Object.hasOwn?Object.hasOwn(r,e):r.hasOwnProperty(e)}function ES(r,e,t=!0){const i=t?r:{},n=Object.keys(r);for(const s of n)i[s]=e(r[s],s);return i}function P_(r,e){return Object.fromEntries(Object.entries(r).map(t=>e(t)))}const D_={priority:1/0,type:"Object",serialize:(r,e)=>P_(r,([t,i])=>[t,Lt.Serialize(i,e,!1)]),deserialize:(r,e,t)=>Object.assign(e||{},P_(r,([i,n])=>[i,Lt.Deserialize(n,e?.[i],t,!1)])),isType:r=>(r.constructor||Object)===Object},ul=class ws{static GetSerializer(e){return ws.Serializers.find(t=>t.isType(e))}static RegisterSerializer(...e){for(const t of e){const i=t.priority??1e10,n=xS(ws.Serializers,s=>s.priority!==void 0&&s.priority<i);n>=0?ws.Serializers.splice(n+1,0,t):ws.Serializers.push(t)}}static UnregisterSerializer(...e){for(const t of e){const i=ws.Serializers.indexOf(t);i>=0&&ws.Serializers.splice(i,1)}}static Serialize(e,t,i=!1){if(typeof e=="function")return;if(!i){const a=ws.GetSerializer(e);if(a)return a.serialize(e,t);if(typeof e.toJSON=="function"){const o=e.toJSON(t,!0);return e.serializableClassId&&o&&(o.serializableClassId=e.serializableClassId),o}}let n=e.constructor??Object;const s={};for(;n&&n!==Object;){const a=ws.TypeMap.get(n)??[];for(const[o,l]of a)s[o]=ws.Serialize(e[l],t,!1);n=Object.getPrototypeOf(n)}return e.serializableClassId&&(s.serializableClassId=e.serializableClassId),s}static Deserialize(e,t,i,n=!1){if(e===void 0||t===e)return t;if(e&&typeof e=="object"&&(e.constructor||Object)===Object&&e.resource&&typeof e.resource=="string"&&e.uuid){const a=i?.[e.resource];if(!a)return console.warn(`Serialization: Resource ${e.resource} not found`),t;const o=e.uuid,l=a[o];if(!l)return console.warn(`Serialization: Resource ${e.resource} with uuid ${o} not found`),t;if(e=l,typeof e=="object"&&(e.__useCount=e.__useCount?e.__useCount+1:1),t===e)return t;if(e&&typeof e=="object")if((e.constructor||Object)!==Object)if(t){if(t.uuid&&t.uuid===o){if(typeof t.copy=="function"&&t.copyOnDeserialize===!0)return t.copy(e),t;console.warn("Serialization: replacing object",t,"with deserialized resource",e)}else if(!t.uuid&&typeof t.copy=="function"&&t.copyOnDeserialize===!0)return t.copy(e),t;return e}else return e;else console.error("Serialization: during Deserialize, meta should only have class instances, not js objects",e,t,i)}if(e&&typeof e=="object"&&(e.constructor||Object)!==Object&&!Array.isArray(e)&&!e.serializableClassId){if(e instanceof Blob)return e;console.warn("Serialization: Data might already be deserialized. It will be cloned, or copied to source",e,"source",t,e.constructor,e.constructor!==Object)}if(e&&typeof e=="object"){const a=o=>{const l=ws.SerializableClasses.get(o);l&&(l.DataInConstructor?t=new l(e):t=new l)};e.serializableClassId&&(!t||t.serializableClassId!==e.serializableClassId)&&a(e.serializableClassId),e.type&&(!t||t.type!==e.type)&&a(e.type),!Array.isArray(t)&&Array.isArray(e)?t=[]:typeof t!="object"&&(e.constructor||Object)===Object&&(t={})}if(typeof t=="function")return console.error("Serialization: Cannot deserialize into a function",t,e),t;if(!n){const a=ws.GetSerializer(e);if(a&&a!==D_)return a.deserialize(e,t,i)}if(!e||t===void 0||t===null||typeof t!="object")return e;if(!n&&typeof t?.fromJSON=="function")return t.fromJSON(e,i,!0),t;let s=t.constructor??Object;if(s===Object)return D_.deserialize(e,t,i);for(;s&&s!==Object;){const a=ws.TypeMap.get(s)??[];for(const[o,l]of a){const c=t[l],h=ws.Deserialize(e[o],c,i,!1);h!==c&&an(t,l,h,!0)}s=Object.getPrototypeOf(s)}return t}};ul.TypeMap=new WeakMap,ul.SerializableClasses=new Map,ul.Serializers=[{priority:0,type:"Array",isType:r=>Array.isArray(r),serialize:(r,e)=>r.map(t=>ul.Serialize(t,e,!1)),deserialize:(r,e,t)=>{const i=r.length;Array.isArray(e)||(e=[]);for(let n=0;n<i;n++){const s=r[n],a=e.length>n?ul.Deserialize(s,e[n],t,!1):ul.Deserialize(s,void 0,t,!1);e.length<=n?e.push(a):e[n]=a}return e}},{priority:0,isType:r=>!r||typeof r!="object",serialize:r=>{if(r&&typeof r=="number"){if(r===1/0)return"Infinity";if(r===-1/0)return"-Infinity";if(isNaN(r))return"NaN"}return r},deserialize:(r,e)=>{if(typeof e=="number"){if(r==="Infinity")return 1/0;if(r==="-Infinity")return-1/0;if(r==="NaN")return NaN;if(typeof r=="number"||!r)return r}return r}},D_];let Lt=ul;const MS=class CA{static callFunction(e,t,i=[]){if(!t)return e(...i);if(e.name&&t[e.name]===e)return e.call(t,...i);CA.methodMap.has(t)||CA.methodMap.set(t,new WeakMap);const n=CA.methodMap.get(t);if(!n.has(e)){let s=t;for(;s;){const a=Object.values(Object.getOwnPropertyDescriptors(s));for(let o of a)if(o.value===e)return n.set(e,!0),e.call(t,...i);s=Object.getPrototypeOf(s)}n.set(e,!1)}return n.get(e)?e.call(t,...i):e(...i)}};MS.methodMap=new WeakMap;let Wu=MS;function he(r,e="param"){if(!r)throw new Error("onChange: fnKey is undefined, make sure the function exists or provide a string");return(t,i,n)=>{const s={get(){return this[`_oc_${i}`]},set(a){var o;const l=this[`_oc_${i}`];if(l===a)return;this[`_oc_${i}`]=a;const c=e==="param"?[i,a,l,this]:e==="object"?[{key:i,value:a,oldValue:l,target:this}]:[];typeof r=="string"?(o=this[r])==null||o.call(this,...c):typeof r=="function"&&Wu.callFunction(r,this,c)}};if(n)return Wn(n,"value")&&delete n.value,Wn(n,"writable")&&delete n.writable,Wn(n,"initializer")&&delete n.initializer,Object.assign(n,s);Object.defineProperty(t,i,s)}}function Zt(r,e="void"){if(!r)throw new Error("onChange: fnKey is undefined, make sure the function exists or provide a string");return he(r,e)}function rt(r,e="object"){if(!r)throw new Error("onChange: fnKey is undefined, make sure the function exists or provide a string");return he(r,e)}function io(r){return he((e,t,i,n)=>{if(!n.dispatchEvent)throw new Error("onChangeDispatchEvent: target does not have dispatchEvent");n.dispatchEvent({type:r||`${e}-changed`,detail:{key:e,value:t,oldValue:i}})},"param")}function G(r){return(e,t)=>{const i=e.constructor;if(i===Object)throw new Error("All properties in an object are serialized by default");Lt.TypeMap.has(i)||Lt.TypeMap.set(i,[]),Lt.TypeMap.get(i).push([r||t,t])}}function Vc(r){return e=>(e.prototype.serializableClassId=r,Lt.SerializableClasses.set(r,e),e)}async function TS(r,e,t,i=12){const n=typeof e=="string"?new TextEncoder().encode(e):e,s=await crypto.subtle.digest("SHA-256",n),a=crypto.getRandomValues(new Uint8Array(i)),o=Array.from(a).map(y=>String.fromCharCode(y)).join(""),l={name:"AES-GCM",iv:a},c=await crypto.subtle.importKey("raw",s,l,!1,["encrypt"]),h=typeof r=="string"?new TextEncoder().encode(r):r,u=await crypto.subtle.encrypt(l,c,h),d=new Uint8Array(u),p=Array.from(d),m=p.map(y=>String.fromCharCode(y)).join(""),A=t?typeof t=="string"?t:new TextDecoder().decode(t):"",g=t?typeof t=="string"?new TextEncoder().encode(t):Array.from(t):[];return typeof r=="string"?A+o+m:new Uint8Array([...g,...a,...p])}async function IS(r,e,t=12){const i=typeof e=="string"?new TextEncoder().encode(e):e,n=await crypto.subtle.digest("SHA-256",i),s=r.slice(0,t),a={name:"AES-GCM",iv:typeof s=="string"?new Uint8Array(Array.from(s).map(h=>h.charCodeAt(0))):s},o=await crypto.subtle.importKey("raw",n,a,!1,["decrypt"]),l=r.slice(t),c=typeof l=="string"?new Uint8Array(Array.from(l).map(h=>h.charCodeAt(0))):l;try{const h=await crypto.subtle.decrypt(a,o,c);return typeof r=="string"?new TextDecoder().decode(h):new Uint8Array(h)}catch{throw new Error("Decrypt failed")}}async function KU(){return"showOpenFilePicker"in window?window.showOpenFilePicker().then(r=>r[0]):window.chooseFileSystemEntries()}function JU(){if("showSaveFilePicker"in window){const e={types:[{description:"Text file",accept:{"text/plain":[".txt"]}}]};return window.showSaveFilePicker(e)}const r={type:"save-file",accepts:[{description:"Text file",extensions:["txt"],mimeTypes:["text/plain"]}]};return window.chooseFileSystemEntries(r)}function ZU(r){return r.text?r.text():eF(r)}function eF(r){return new Promise(e=>{const t=new FileReader;t.addEventListener("loadend",i=>{const n=(i.srcElement||i.target).result;e(n)}),t.readAsText(r)})}async function tF(r,e){if(r.createWriter){const i=await r.createWriter();await i.write(0,e),await i.close();return}const t=await r.createWritable();await t.write(e),await t.close()}async function iF(r,e){const t={};return e&&(t.writable=!0,t.mode="readwrite"),await r.queryPermission(t)==="granted"||await r.requestPermission(t)==="granted"}function R_(r,e=8192,t=!1){var i;const n=r.width||r.videoWidth,s=r.height||r.videoHeight;if(!n||!s)throw new Error("Invalid bitmap");const a=document.createElement("canvas");a.width=Math.min(e,n),a.height=Math.floor(1+a.width*s/n);const o=r instanceof ImageBitmap,l=o&&t&&Math.abs(a.width-n)<.5?a.getContext("bitmaprenderer"):void 0;return l?l.transferFromImageBitmap(r):(i=a.getContext("2d"))==null||i.drawImage(r,0,0,a.width,a.height),o&&t&&r.close(),a}function PS(r,e=8192,t=!1,i="image/png"){if(!(r.width||r.videoWidth)||!(r.height||r.videoHeight))return"";const n=R_(r,e,!1),s=n.toDataURL(i);return n.remove(),t&&r instanceof ImageBitmap&&r.close(),s}async function nF(r,e=8192,t=!1,i="image/png"){if(!(r.width||r.videoWidth)||!(r.height||r.videoHeight))return Promise.reject("Invalid bitmap");const n=R_(r,e,!1);return new Promise((s,a)=>{n.toBlob(o=>{o?s(o):a("Could not get blob"),n.remove(),t&&r instanceof ImageBitmap&&r.close()},i)})}async function DS(r){return new Promise((e,t)=>{const i=new Image;i.addEventListener("load",()=>{const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const s=n.getContext("2d");if(!s){t(new Error("Could not get 2d context"));return}s.drawImage(i,0,0,n.width,n.height);const a=s.getImageData(0,0,n.width,n.height);e(a),n.remove(),i.remove()},!1),i.addEventListener("error",n=>{i.remove(),t(n)},!1),i.src=r})}function RS(r,{backgroundColor:e="",scale:t=1,width:i=512,height:n=512}){const s=document.createElement("canvas"),a=s.getContext("2d"),o=t,l=i,c=n;return s.width=l*o,s.height=c*o,s.style.width=`${l}`,s.style.height=`${c}`,e?.length>0&&(a.fillStyle=e,a.fillRect(0,0,s.width,s.height)),a.drawImage(r,0,0,s.width,s.height),s}function sF(r){const e=document.createElement("canvas");return e.width=r.width,e.height=r.height,e.getContext("2d").putImageData(r,0,0),e}function rF(){const r=document.createElement("canvas");return r.getContext&&r.getContext("2d")?r.toDataURL("image/webp").startsWith("data:image/webp"):!1}function B_(r){const e=document.createElement("canvas");e.width=r.width||r.videoWidth||1,e.height=r.height||r.videoHeight||1;const t=e.getContext("2d");if(!t)throw new Error("Unable to get 2d context");return t.translate(0,r.height||r.videoHeight||1),t.scale(1,-1),t.drawImage(r,0,0),e}function aF(r){return new Promise((e,t)=>{const i=new Image,n=URL.createObjectURL(r);i.onload=()=>{URL.revokeObjectURL(n),e(i)},i.onerror=s=>{URL.revokeObjectURL(n),t(s)},i.src=n})}const oF=r=>`data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='16' height='16' fill='%23${r}'/%3E%3C/svg%3E%0A`,BS=r=>`data:image/svg+xml,%3Csvg width='16' height='16' viewBox='0 0 16 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Ccircle cx='8' cy='8' r='7' fill='%23${r}'/%3E%3C/svg%3E%0A`,lF=r=>`data:image/svg+xml,%3Csvg viewBox='0 0 80 14' xmlns='http://www.w3.org/2000/svg'%3E%3Ctext style='font: 8px "Roboto Mono", "Source Code Pro", Menlo, Courier, monospace; fill: white;' x='9' y='9'%3E${r}%3C/text%3E%3C/svg%3E%0A`,L_=async(r,e)=>{const t=await uS(r);return RS(t,e)},LS=async(r,e)=>await L_(r,e).then(t=>t.toDataURL("image/png")),cF=async r=>dm(await(await fetch(r)).blob());async function OS(r,e=cF){const t=r.match(/(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)/g);if(t)for(const i of t){const n=await e(i);r=r.replace(i,n)}return r}function O_(r,e,{width:t,height:i},n=!0){const s=`
<svg viewBox="0 0 ${t} ${i}" xmlns="http://www.w3.org/2000/svg">
    <style>
    ${e}
    </style>
    <foreignObject x="0" y="0" width="100%" height="100%">
        <div xmlns="http://www.w3.org/1999/xhtml" style="height: 100%; width: 100%; position: absolute: top:0; left:0">
            ${r}
        </div>
    </foreignObject>
</svg>
    `;return n?I_(s):s}async function hF(r,e,t){const i=O_(r,e,t);return await L_(i,t)}async function uF(r,e,t){const i=O_(r,e,t);return await LS(i,t)}function US(r,e){return Math.abs(r)>Math.abs(e)?r:e}function U_(r,e,t){const i=t?1:0,n=~(1<<e);return r&n|i<<e}function dF(r,e){const t=~(1<<e);return r&t}function F_(){const r=(i,n)=>i.toString(16).padStart(n,"0"),e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=new DataView(e.buffer);return`${r(t.getUint32(0),8)}-${r(t.getUint16(4),4)}-${r(t.getUint16(6),4)}-${r(t.getUint16(8),4)}-${r(t.getUint32(10),8)}${r(t.getUint16(14),4)}`}function qu(r,e=null){var t;return(t=window?.location)!=null&&t.href?new URL(window.location.href).searchParams.get(r)??e:e}function fF(r,e,t=!1){var i;if(!((i=window?.location)!=null&&i.href))return;const n=new URLSearchParams(window.location.search);e==null?n.has(r)&&n.delete(r):n.set(r,e),t?window.location.search=n.toString():window.history.replaceState({},"","?"+n.toString())}function pF(r,e="/"){return r.join(e)}function mF(r,e){const t=(e?`var Module = { locateFile: function(s) { return "${e}"; } }; 
`:"")+`importScripts( "${r}" );`;return URL.createObjectURL(new Blob([t],{type:"text/javascript"}))}const FS={alert:async r=>window.alert(r),prompt:async(r,e,t)=>window.prompt(r,e),confirm:async r=>window.confirm(r),confirmSync:r=>window.confirm(r)},gF='.dialog-container{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:1000;border-radius:10px;padding:20px;max-width:calc(100% - 32px);width:calc(100% - 32px);color:#0a0a0a;background-color:#fff;border:1px solid oklch(.922 0 0);box-shadow:#0000 0 0,#0000 0 0,#0000 0 0,#0000 0 0,#0000001a 0 10px 15px -3px,#0000001a 0 4px 6px -4px;display:flex;gap:1rem;flex-direction:column;box-sizing:border-box;font-family:Inter,-apple-system,"system-ui",Segoe UI,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";transition:max-width .5s,width .5s,height .5s}.dialog-content{display:flex;flex-direction:column;gap:.5rem;text-align:center}.dialog-title{font-size:1.125rem;font-weight:600;line-height:1.5;color:#0a0a0a}.dialog-message{color:#737373;font-size:.875rem;line-height:1.42}.dialog-footer{display:flex;gap:10px;flex-direction:column-reverse}@media (width >= 40rem){.dialog-content{text-align:left}.dialog-container{max-width:512px;width:512px}.dialog-footer{flex-direction:row;justify-content:flex-end}}.dialog-button,.dialog-input{height:2.25rem;box-sizing:border-box}.dialog-input{width:100%;padding:.25rem .75rem;font-size:1rem;border:1px solid oklch(.922 0 0);border-radius:.5rem;background:transparent;color:#0a0a0a;outline:none;transition:outline-width .2s}.dialog-button{padding:.5rem 1rem;box-shadow:#0000 0 0,#0000 0 0,#0000 0 0,#0000000d 0 1px 2px;border-radius:.5rem;border:1px solid oklch(.922 0 0);cursor:pointer;font-size:.875rem;background-color:#fff;color:#0a0a0a;transition:background-color .2s ease,color .2s ease,outline-width .2s ease}.dialog-button:focus,.dialog-input:focus{outline:3px solid #6d7a8c66}.dialog-button:hover{background-color:#f8f8f8}.dialog-ok{background-color:#0a0a0a;color:#fff}.dialog-ok:hover{background-color:#222}.dialog-link{max-width:100%;display:inline-block;vertical-align:bottom;text-decoration:underline;color:var(#2563eb);overflow:hidden}.dialog-link-text{display:inline-block;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:bottom}';let fm=null;function AF(r){const e=/((https?:\/\/|www\.)[^\s<]+)/g;return r.replace(e,t=>{let i=t;return i.startsWith("http")||(i="https://"+i),`<a href="${i}" target="_blank" rel="noopener noreferrer" class="dialog-link"><span class="dialog-link-text">${ks(t)}</span></a>`})}function yF(r){const e=ks(r);return AF(e).replace(/\n/g,"<br>")}function N_(r){return`
${r.title?`<div class="dialog-title">${ks(r.title)}</div>`:""}
<div class="dialog-message">${yF(r.message)}</div>
`}const _F=r=>`
<div class="dialog-content">
${N_(r)}
</div>
<div class="dialog-footer">
    ${r.ok&&`<button class="dialog-button dialog-ok">${ks(r.ok)}</button>`||""}
</div>
`,vF=r=>`
<div class="dialog-content">
${N_(r)}
</div>
<div class="dialog-footer">
    ${r.cancel&&`<button class="dialog-button dialog-cancel">${ks(r.cancel)}</button>`||""}
    ${r.ok&&`<button class="dialog-button dialog-ok">${ks(r.ok)}</button>`||""}
</div>
`,bF=r=>`
<div class="dialog-content">
    ${N_(r)}
    <input class="dialog-input" type="text" value="${r.defaultValue??""}" style="margin-top:0.5rem;"/>
</div>
<div class="dialog-footer">
    ${r.cancel&&`<button class="dialog-button dialog-cancel">${ks(r.cancel)}</button>`||""}
    ${r.ok&&`<button class="dialog-button dialog-ok">${ks(r.ok)}</button>`||""}
</div>
`;function wF(){fm||(fm=document.createElement("style"),fm.textContent=gF,document.head.appendChild(fm))}function k_(r,{message:e,...t}){wF();const i=document.createElement("div"),n=e?.split(":")[0];return n&&e&&(e=e.replace(n+":","").trim()),i.innerHTML=r({...t,message:e,title:n}),i.classList.add("dialog-container"),document.body.appendChild(i),i}const CF={alert:async r=>{const e=k_(_F,{message:r||"Alert",ok:"Okay"});return new Promise(t=>{const i=e.querySelector(".dialog-ok"),n=a=>{(a.key==="Enter"||a.key==="Escape")&&(a.preventDefault(),i?.click())},s=()=>{window.removeEventListener("keydown",n),document.body.removeChild(e)};window.addEventListener("keydown",n),i?.addEventListener("click",()=>{s(),t()}),i?.focus()})},prompt:async(r,e,t=!0)=>{const i=k_(bF,{message:r||"Enter some text",ok:"OK",cancel:t?"Cancel":void 0,defaultValue:e});return new Promise(n=>{const s=i.querySelector(".dialog-ok"),a=i.querySelector(".dialog-cancel"),o=i.querySelector(".dialog-input");o.addEventListener("keydown",h=>{h.key==="Enter"&&(h.preventDefault(),s?.click())});const l=h=>{h.key==="Escape"&&a&&(h.preventDefault(),a?.click())},c=()=>{window.removeEventListener("keydown",l),document.body.removeChild(i)};window.addEventListener("keydown",l),s?.addEventListener("click",()=>{const h=o.value;c(),n(h)}),a?.addEventListener("click",()=>{c(),n(null)}),o?.focus(),o?.select()})},confirm:async r=>{const e=k_(vF,{message:r||"Are you sure?",ok:"Yes",cancel:"No"});return new Promise(t=>{const i=e.querySelector(".dialog-ok"),n=e.querySelector(".dialog-cancel"),s=o=>{o.key==="Escape"&&n&&(o.preventDefault(),n.click())},a=()=>{window.removeEventListener("keydown",s),document.body.removeChild(e)};window.addEventListener("keydown",s),i?.addEventListener("click",()=>{a(),t(!0)}),n?.addEventListener("click",()=>{a(),t(!1)}),n?.focus()})},confirmSync:r=>window.confirm(r)};function ga(r){return r===null||typeof r!="object"?r:Array.isArray(r)?r.map(ga):!r._ui_isPrimitive&&typeof r.clone=="function"&&r._ui_primitiveClone!==!1?r.clone():r}function Xu(r,e){return r===null||typeof r!="object"||e===null||typeof e!="object"?r===e:Array.isArray(r)?Array.isArray(e)&&r.length===e.length&&r.every((t,i)=>Xu(t,e[i])):!r._ui_isPrimitive&&typeof r.equals=="function"&&r._ui_primitiveEquals!==!1?!!r.equals(e):r===e}function Yu(r,e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))if(r&&Array.isArray(r)){if(r.length<e.length){for(let t=0;t<r.length;t++)r[t]=Yu(r[t],e[t]);for(let t=r.length;t<e.length;t++)r.push(ga(e[t]))}else{for(let t=0;t<e.length;t++)r[t]=Yu(r[t],e[t]);r.length=e.length}return r}else return ga(e);else return!e._ui_isPrimitive&&typeof e.copy=="function"&&e._ui_primitiveCopy!==!1?r&&typeof r=="object"&&!Array.isArray(r)&&!r._ui_isPrimitive&&typeof r.copy=="function"&&r._ui_primitiveCopy!==!1?(r.copy(e),r):ga(e):e}function $u(r,e,t,i=2e3){if(!r||!r.enabled)return;const n=e;if(n.type!==t)return r.record(e);const s=r.peek();let a=!!s&&s.type===t&&s.uid===n.uid;if(a){const o=s;!o.final&&n.time-o.time<i?(n.lastVal=o.lastVal,n.val=ga(n.val),r.replaceLast(n)):a=!1}a||Xu(n.lastVal,n.val)||(n.val=ga(n.val),r.record(n))}function G_(r,e,t,i,n,s,a=!0,o=2e3,l=!1,c){const[h,u]=e,d=i.lastValue??h?.[u];let p=!1;const m=i.last??!0,A=Xu(d,t),g=ga(d);A?p=!m:h?Yu(d,t)!==d?p=!an(h,u,t,!0,!0):p=!1:p=!0;const y=!p&&(m||!A);return a&&y&&r&&$u(r,{type:s,lastVal:g,val:t,final:m,props:i,time:Date.now(),uid:n,binding:l?e:void 0,onUndoRedo:c},s,o),{last:m,value:t,lastValue:g,undoable:y}}function z_(r,e){let t=r,i;for(;!i&&t;)t=Object.getPrototypeOf(t),t&&(i=Object.getOwnPropertyDescriptor(t,e));return{proto:t,protoDesc:i}}function Hc(r){return r.startsWith("http://")||r.startsWith("https://")||r.startsWith("data:")||r.startsWith("asset://")||r.startsWith("/")||r.startsWith("//")}const V_={simpleCameraHelpers:`#ifndef SIMPLE_CAMERA_HELPERS
#define SIMPLE_CAMERA_HELPERS
#ifndef USE_TRANSMISSION
uniform mat4 projectionMatrix;
#endif
vec3 viewToScreen(const in vec3 pos){vec4 projected=projectionMatrix*vec4(pos,1.0);return vec3(0.5+0.5*projected.xy/projected.w,projected.w);}vec3 screenToView(const in vec2 uv,const in float viewZ){vec2 uv_=2.*uv-1.;float xe=-(uv_.x+projectionMatrix[2][0])*viewZ/projectionMatrix[0][0];float ye=-(uv_.y+projectionMatrix[2][1])*viewZ/projectionMatrix[1][1];return vec3(xe,ye,viewZ);}
#endif
`,cameraHelpers:`#ifndef BASIC_CAMERA_HELPERS
#define BASIC_CAMERA_HELPERS
uniform mat4 projection;uniform vec2 cameraNearFar;uniform vec3 cameraPositionWorld;
#ifndef THREE_PACKING_INCLUDED
#define THREE_PACKING_INCLUDED
#include <packing>
#endif
float linstep(float edge0,float edge1,float value){return clamp((value-edge0)/(edge1-edge0),0.0,1.0);}float depthToViewZ(const in float depth){return(depth>0.999)?-cameraNearFar.y*1000.0 :-mix(cameraNearFar.x,cameraNearFar.y,depth);}float viewZToDepth(const in float viewZ){return linstep(-cameraNearFar.x,-cameraNearFar.y,viewZ);}vec4 viewToScreen3(const in vec3 pos){vec4 projected=projection*vec4(pos,1.0);projected.z=pos.z;projected.w=1./projected.w;projected.xyz*=projected.w;projected.xy=0.5+0.5*projected.xy;return projected;}vec3 screenToView3(const in vec2 uv,const in float viewZ){vec2 uv_=2.*uv-1.;float xe=-(uv_.x+projection[2][0])*viewZ/projection[0][0];float ye=-(uv_.y+projection[2][1])*viewZ/projection[1][1];return vec3(xe,ye,viewZ);}float viewZFromNDCZ(const in float depth){
#if PERSPECTIVE_CAMERA == 1
return perspectiveDepthToViewZ(depth,cameraNearFar.x,cameraNearFar.y);
#else
return orthographicDepthToViewZ(depth,cameraNearFar.x,cameraNearFar.y);
#endif
}
#endif
`,randomHelpers:`#ifndef BASIC_RANDOM_HELPERS
#define BASIC_RANDOM_HELPERS
float random(float n){return fract(sin(n)*43758.5453123);}float random2(vec2 n,float x){n+=x;return fract(sin(dot(n.xy,vec2(12.9898,78.233)))*43758.5453);}float random3(vec3 v){v=fract(v*443.8975);v+=dot(v,v.yzx+19.19);return fract((v.x+v.y)*v.z);}float interleavedGradientNoise(const in vec2 fragCoord,const in float seed){vec3 magic=vec3(0.06711056,0.00583715,52.9829189);return fract(magic.z*fract(dot(fragCoord.xy+seed*vec2(2.083,4.867),magic.xy)));}vec3 hash3(vec2 p){vec3 q=vec3(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3)),dot(p,vec2(419.2,371.9)));return fract(sin(q)*43758.5453);}
#endif
`,defaultVertex:"varying vec2 vUv;void main(){vUv=uv;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}",defaultFragment:"varying vec2 vUv;void main(){gl_FragColor=vec4(vUv,0.0,1.0);}",voronoiNoise:`#ifndef VORONOI_HELPER
#define VORONOI_HELPER
float voronoi_distance(vec2 a,vec2 b,float metric){return distance(a,b);}float voronoi_f1_2d(in vec2 coord,in float randomness,in float flakeClamp,in float flakeRadius,inout vec3 outColor){vec2 cellPosition=floor(coord);vec2 localPosition=coord-cellPosition;float minDistance=8.0;vec2 targetOffset,targetPosition;for(int j=-1;j<=1;j++){for(int i=-1;i<=1;i++){vec2 cellOffset=vec2(i,j);vec2 pointPosition=cellOffset+hash3(cellPosition+cellOffset).xy*randomness;float distanceToPoint=voronoi_distance(pointPosition,localPosition,1.);if(distanceToPoint<minDistance){targetOffset=cellOffset;minDistance=distanceToPoint;targetPosition=pointPosition;}}}float outDistance=minDistance;float dist=step(flakeRadius,outDistance);outColor=hash3(cellPosition+hash3(cellPosition+targetOffset).xy*randomness+targetOffset);vec3 outColor1=minDistance<flakeRadius ? outColor : vec3(0.5,0.5,1.);outDistance=mix(dist,minDistance,flakeClamp);outColor=mix(outColor1,outColor,flakeClamp);return outDistance;}
#endif
`},NS=class{};NS.Map=new WeakMap;let Ku=NS;function ii(r,e,t,i,n=!0){i=i!==void 0?i:r[e],t=t??e+"";const s=i?.uiConfig;let a;if(s)a=s;else{const o=xF(i);o==="folder"?a=pm(t,i,{},"folder",n,e+""):o&&(a={type:o,label:t,property:[r,e],propertyKey:e+""})}return a&&!a.label&&(a.label=t),a}function bi(r){if(!r)return[];let e=r.constructor||Object;e===Array&&(e=Object);const t=[],i=[];for(;e&&e!==Object;)i.push(e),e=Object.getPrototypeOf(e);if(!i.length||Array.isArray(r)){const n=typeof r=="object"?Object.keys(r):Array.isArray(r)?r.map((s,a)=>a):[];for(const s of n){const a=r[s];if(a==null)continue;const o=ii(r,s,s+"",a,!0);o&&t.push(o)}}return i.reverse().forEach(n=>{Ku.Map.get(n)?.forEach(({params:s,propKey:a,uiType:o})=>{let l;if(o||(l=()=>ii(r,a)),l||(l={property:[r,a],type:o||"input"}),s){const c=typeof s.params=="function"?s.params(r):s.params||{},h={...s};if(delete h.params,typeof l=="function"){const u=l;l=()=>{const d=u();return d&&Object.assign(d,{...h,...c})}}else Object.assign(l,{...h,...c})}t.push(l)})}),t}function pm(r,e,t={},i="folder",n=!1,s){return{type:i,label:r,children:n?[()=>bi(e)]:bi(e),uuid:F_(),propertyKey:s,...t}}function xF(r){return r==null?null:Array.isArray(r)?"folder":typeof r=="boolean"?"checkbox":typeof r=="number"?"number":typeof r=="string"?"input":typeof r=="function"?"button":typeof r.x=="number"?"vec":typeof r.r=="number"?"color":r.isTexture?"image":typeof r=="object"?"folder":null}function SF(r){return(e,t)=>{const i=e.constructor;if(i===Object)throw new Error("Not possible to use uiConfig decorator on an object, use class instead");Ku.Map.has(i)||Ku.Map.set(i,[]),r(e,t,Ku.Map.get(i))}}function Bi(r,e){return SF((t,i,n)=>{const s=n.findIndex(a=>a.propKey===i);if(s&&s<0)n.push({params:e||{},propKey:i,uiType:r});else throw new Error(`Property ${i} already has a uiConfig decorator`)})}function H_(r,e,t="panel"){return i=>class extends i{constructor(){super(...arguments),this.uiConfig=pm(r,this,e||{},t)}}}function dl(r,e){return Bi("monitor",{label:r,params:e})}function Fe(r,e,t,i){return Bi("slider",{label:r,bounds:e,stepSize:t,params:i})}function yi(r,e,t,i){return Bi("vec",{label:r,bounds:e,stepSize:t,params:i})}function Li(r,e,t){return Array.isArray(e)&&typeof e[0]=="string"&&(e=e.map(i=>({label:i,value:i}))),Bi("dropdown",{label:r,children:e,params:t})}function ct(r,e){return Bi("button",{label:r,params:e})}function He(r,e){return Bi("input",{label:r,params:e})}function Ot(r,e){return Bi("number",{label:r,params:e})}function xn(r,e){return Bi("color",{label:r,params:e})}function Dr(r,e){return Bi("image",{label:r,params:e})}function se(r,e){return Bi("checkbox",{label:r,params:e})}function Aa(r,e){return H_(r,e,"panel")}function vt(r,e){return H_(r,e,"folder")}const Ju={setValue:"UiConfigMethods_set",action:"UiConfigMethods_action"},kS=class hs{constructor(e){this._renderer=e,this.undoEditingWaitTime=2e3,this.undoPresets={[Ju.setValue]:t=>{const i=()=>{t.onUndoRedo&&t.onUndoRedo(t),t.uid.uiRefresh?.(!1)};return{undo:()=>{this.setValue(t.uid,t.lastVal,t.props,void 0,!1).then(i)},redo:()=>{this.setValue(t.uid,t.val,t.props,void 0,!1).then(i)}}},[Ju.action]:t=>{const i=()=>{t.onUndoRedo&&t.onUndoRedo(t),t.uid.uiRefresh?.(!1)};return{undo:async()=>{await t.undo.call(t.target,...t.args),i()},redo:async()=>{await t.redo.call(t.target,...t.args),i()}}}}}recordUndo(e){$u(this._renderer.undoManager,e,Ju.setValue,this.undoEditingWaitTime)}async performAction(e,t,i,n,s){return hs.PerformAction(e,t,i,n,s,this._renderer.undoManager,this.undoEditingWaitTime)}getValue(e,t,i=!0){return hs.GetValue(e,t,i)}async setValue(e,t,i,n,s=!0){return hs.SetValue(e,t,i,n,s,this._renderer,this._renderer.undoManager,this.undoEditingWaitTime)}async dispatchOnChange(e,t){return this.runAtEvent(e,()=>hs.DispatchOnChangeSync(e,t))}async clickButton(e,t){return this.runAtEvent(e,async()=>{const i=hs.GetBinding(e,!1),n=i[0],s=i[1],a=tt(e.sendArgs,e)===!1?[]:t?.args??[],o=[];if(n){const l=n[s]??n.value;typeof l=="function"?o.push([l,n]):l&&console.warn("Invalid action type for button",l)}typeof e.onClick=="function"&&o.push([e.onClick,e]);for(const[l,c]of o)await this.performAction(c,l,a,e);await this.dispatchOnChange(e,{})})}async runAtEvent(e,t){return hs.RunAtEvent(e,t,this._renderer)}static async RunAtEvent(e,t,i){const n=tt(e.dispatchMode,e)??this.DefaultDispatchMode;return n==="immediate"||!i?t():new Promise(s=>{const a=async()=>{i.removeEventListener(n,a),s(await t())};i.addEventListener(n,a)})}static GetBinding(e,t=!0){let i=tt(e.property,e);const n=tt(e.path,e);if(i===void 0&&Object.hasOwn(e,"value")&&(i=[e,"value"]),i===void 0&&t&&(i=tt(e.parentProperty,e)),!i||typeof i[0]!="object"||!i[1])return[void 0,""];if(typeof i[1]=="string"&&n&&n.length&&(i=[i[0],i[1]+"."+n]),typeof i[1]=="string"&&i[1].includes(".")){const s=i[1].split(".");let a=i[0];const o=s.pop()||"";for(const l of s)if(a=Array.isArray(a)?a[parseInt(l)]:a[l],!a)return console.warn("Cannot determine property, invalid property path",e,i),[void 0,""];i=[a,o]}return Array.isArray(i[0])&&typeof i[1]=="string"&&(i[1]=parseInt(i[1])),i}static GetRawValue(e){const[t,i]=this.GetBinding(e);return t?t[i]:void 0}static GetValue(e,t,i=!0){const[n,s]=this.GetBinding(e);if(!n)return;const a=n[s];return t!==void 0&&a!==void 0?Xu(t,a)&&!i?void 0:Yu(t,a):ga(a)}static DispatchOnChangeSync(e,t,...i){const n=[{type:"change",last:t.last??!0,config:t.config??e,configPath:[e,...t.configPath||[]],target:e,value:t.value,lastValue:t.lastValue},...i];typeof e.onChange=="function"?e.onChange(...n):Array.isArray(e.onChange)?e.onChange.flat().forEach(s=>typeof s=="function"&&s?.(...n)):e.onChange&&console.error("Invalid onChange type, must be a function or array of functions",e.onChange),e.parentOnChange?.(...n)}static RecordUndo(e,t,i){$u(t,e,Ju.setValue,i)}static async PerformAction(e,t,i,n,s,a,o){const l=()=>e===void 0?t(...i):t.call(e,...i);let c=await l();const h=typeof c=="function"?c:c?.undo?.bind(c),u=typeof c!="function"?c?.action?.bind(c):null,d=typeof c=="function"?l:c?.redo?.bind(c)??u;typeof u=="function"&&(c=await u()),typeof h=="function"&&this.RecordUndo({type:"UiConfigMethods_action",uid:n,target:e,undo:h,redo:d,args:i,onUndoRedo:s},a,o)}static async SetValue(e,t,i,n,s=!0,a,o,l){return this.RunAtEvent(e,()=>{const c=this.GetBinding(e),h=G_(o,c,t,i,e,Ju.setValue,s,l,!1,void 0);return!h.undoable&&!n?!1:(this.DispatchOnChangeSync(e,{...i,...h}),!0)},a)}static GetLabel(e){return(tt(e.label,e)??this.GetBinding(e)?.[1])+""}static GetChildren(e){return(tt(e.children,e)??[]).map(t=>tt(t,e)).flat(2).filter(t=>t)}static InitUiConfig(e){e&&(e.type||(console.warn("No type for config",e),e.type="input"),e.uuid||(e.uuid=F_()),e.property===void 0&&(e.binding?e.property=e.binding:e.value===void 0?(e.getValue||e.setValue)&&(Object.defineProperty(e,"value",{get:()=>e.getValue&&e.getValue(),set:t=>e.setValue&&e.setValue(t)}),e.property=[e,"value"]):(e.getValue||e.setValue)&&console.warn("getValue/setValue is ignored since value is provided",e),e.property))}static GetBounds(e,t=!1){const i=tt(e.bounds),n=(i?.length??0)>=2?i[1]:t?1/0:1,s=(i?.length??0)>=1?i[0]:t?-1/0:0,a=tt(e.stepSize)||(t?.01:Math.pow(10,Math.floor(Math.log10((n-s)/100))));return{min:s,max:n,step:a}}static GetBaseProps(e){const t=tt(e.hidden)??!1,i=tt(e.disabled)??!1,n=tt(e.readOnly)??!1;return{hidden:t,disabled:i,readOnly:n}}getBinding(e,t=!0){return hs.GetBinding(e,t)}getRawValue(e){return hs.GetRawValue(e)}getLabel(e){return hs.GetLabel(e)}getChildren(e){return hs.GetChildren(e)}initUiConfig(e){return hs.InitUiConfig(e)}getBounds(e,t=!1){return hs.GetBounds(e,t)}getBaseProps(e){return hs.GetBaseProps(e)}dispatchOnChangeSync(e,t,...i){hs.DispatchOnChangeSync(e,t,...i)}};kS.DefaultDispatchMode="immediate";let GS=kS;class zS extends cm{constructor(e=!0,t,i){super(),this._rafId=null,this.raf=()=>{this._autoFrameEvents&&(this.dispatchEvent({type:"preFrame"}),this.dispatchEvent({type:"preRender"}),this.dispatchEvent({type:"postRender"}),this.dispatchEvent({type:"postFrame"}),this._rafId=requestAnimationFrame(this.raf))},this._refreshQueue={preRender:[],postRender:[],preFrame:[],postFrame:[]},this._lastModeTime={preRender:0,postRender:0,preFrame:0,postFrame:0},this.methods=t||new GS(this),this.undoManager=i===!1?void 0:i||new M_({bindHotKeys:!0,limit:1e3,debug:qu("debugUndo")!==null}),this._autoFrameEvents=e,e&&(this.addEventListener("preFrame",()=>this.refreshQueue("preFrame")),this.addEventListener("postFrame",()=>this.refreshQueue("postFrame")),this.addEventListener("preRender",()=>this.refreshQueue("preRender")),this.addEventListener("postRender",()=>this.refreshQueue("postRender")))}get undoManager(){return this._undoManager}set undoManager(e){this._undoManager=e,this._undoManager&&Object.assign(this._undoManager.presets,this.methods.undoPresets)}start(){this._rafId===null&&(this._rafId=requestAnimationFrame(this.raf))}stop(){this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}refreshQueue(e){const t=this._refreshQueue[e],i=[],n=Cn(),s=n-this._lastModeTime[e];t.forEach(a=>{a[1]>.001?(a[1]-=s,i.push(a)):this._refreshUiConfigObject(a[0])}),this._refreshQueue[e]=i,this._lastModeTime[e]=n}_addToRefreshQueue(e,t,i){const n=t.uuid,s=this._refreshQueue[e],a=s.find(o=>o[2]===n);a?a[1]=Math.max(a[1],i):s.push([t,i,n]),this._refreshQueue[e]=s}disposeUiConfig(e,t=!0){e&&(e.uiRef&&(t&&e.uiRef.dispose?.(),e.uiRef=void 0),e.uiRefType=void 0,e.uiRefresh=void 0)}addToRefreshQueue(e,t,i,n){const s=i?this._flattenUiConfig(t):[t];for(const a of s)e==="immediate"?Qn(n).then(()=>this._refreshUiConfigObject(a)):this._addToRefreshQueue(e,a,n)}_flattenUiConfig(e,t){return t=t??[],!e||!e.uiRef||(t.push(e),typeof e.children=="function")||e.children?.forEach(i=>{typeof i!="function"&&i&&(Array.isArray(i)?i.forEach(n=>t=this._flattenUiConfig(n,t)):t=this._flattenUiConfig(i,t))}),t}}class EF extends zS{constructor(e=document.body,t=!0,i,n){super(t,i,n),this.config={type:"panel",label:"Configuration",children:[]},this._uiContainer=this._createUiContainer(),e.appendChild(this._uiContainer),this.start()}unmount(){this.disposeUiConfig(this.config),this._uiContainer.remove(),this.stop()}appendChild(e,t){e&&(Object.assign(e,t),this.config.children.push(e),this.refreshRoot())}removeChild(e){const t=this.config.children.indexOf(e);t!==-1&&(this.config.children.splice(t,1),this.disposeUiConfig(e),this.refreshRoot())}refreshRoot(e=!0,t="postFrame",i=0){this.config.uiRefresh?.(e,t,i)}_createUiContainer(){return Pr({id:"uiConfigContainer",addToBody:!1})}}var MF=Object.defineProperty,TF=Object.getOwnPropertyDescriptor,Rr=(r,e,t,i)=>{for(var n=i>1?void 0:i?TF(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&MF(e,t,n),n};f.ViewerTimeline=class extends xi{constructor(){super(...arguments),this._time=0,this.delta=0,this.endTime=2,this.resetOnEnd=!0,this.stopOnEnd=!1,this.running=!1,this._clock=new ku(!1),this._start=!1,this._stop=!1,this._reset=!1,this._step=!1}get time(){return this._time}set time(e){this._time!==e&&this.setTime(e,!0)}shouldRun(){return this.running||this._step}start(){this._start=!0,this._stop&&(this._stop=!1),this._step&&(this._step=!1)}stop(){this._stop=!0,this._start&&(this._start=!1),this._step&&(this._step=!1)}reset(){this._reset=!0,this._step&&(this._step=!1)}update(e){if(this._refreshParams(),!this.running){this.delta=this._clock.getDelta(),this._time=this._clock.elapsedTime;return}const t=e.getPlugin("ProgressivePlugin")?.postFrameConvergedRecordingDelta();t&&t>0?(this.delta=t/1e3,this._clock.oldTime+=t,this._clock.elapsedTime+=this.delta,this._time=this._clock.elapsedTime,this.dispatchEvent({type:"update"})):t!==void 0&&t===0?(this.delta=0,this._time=this._clock.elapsedTime):(t===void 0||t<0)&&(this.delta=this._clock.getDelta(),this._time=this._clock.elapsedTime,this.dispatchEvent({type:"update"})),this._refreshParams()}_refreshParams(){const e=this.endTime>0&&this.time>=this.endTime&&this.running,t=this.resetOnEnd&&e,i=this.stopOnEnd&&e;(this._stop||i)&&(this._clock.stop(),this._start=!1,this._stop=!1,this.running=this._clock.running,this.dispatchEvent({type:"stop"})),this._start&&(this._clock.start(),this._clock.elapsedTime=this.time,this._start=!1,this.running=this._clock.running,this.dispatchEvent({type:"start"})),(this._reset||t)&&(this._clock.elapsedTime=0,this.time=0,this.delta=0,this._reset=!1,this.dispatchEvent({type:"reset"})),this.running=this._clock.running}update2(e){this._step=!1}setTime(e,t=!0){e<0&&(e=0),this._clock.elapsedTime=e,this._time=e,this.delta=0,this._reset=!1,this._start||(this._step=t),this.dispatchEvent({type:"update"})}},Rr([He("Time",{readOnly:!0})],f.ViewerTimeline.prototype,"time",1),Rr([He("Delta",{readOnly:!0})],f.ViewerTimeline.prototype,"delta",2),Rr([He("Max Time"),G(),io("endTimeChanged")],f.ViewerTimeline.prototype,"endTime",2),Rr([se("Reset on End"),G(),io("resetOnEndChanged")],f.ViewerTimeline.prototype,"resetOnEnd",2),Rr([se("Stop on End"),G(),io("stopOnEndChanged")],f.ViewerTimeline.prototype,"stopOnEnd",2),Rr([He("Running",{readOnly:!0})],f.ViewerTimeline.prototype,"running",2),Rr([ct("Start")],f.ViewerTimeline.prototype,"start",1),Rr([ct("Stop")],f.ViewerTimeline.prototype,"stop",1),Rr([ct("Reset")],f.ViewerTimeline.prototype,"reset",1),f.ViewerTimeline=Rr([Vc("ViewerTimeline"),vt("Timeline")],f.ViewerTimeline);function IF(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var mm={exports:{}},PF=mm.exports,VS;function DF(){return VS||(VS=1,(function(r,e){(function(t,i){r.exports=i()})(PF,function(){var t=function(){function i(p){return a.appendChild(p.dom),p}function n(p){for(var m=0;m<a.children.length;m++)a.children[m].style.display=m===p?"block":"none";s=p}var s=0,a=document.createElement("div");a.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",a.addEventListener("click",function(p){p.preventDefault(),n(++s%a.children.length)},!1);var o=(performance||Date).now(),l=o,c=0,h=i(new t.Panel("FPS","#0ff","#002")),u=i(new t.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var d=i(new t.Panel("MB","#f08","#201"));return n(0),{REVISION:16,dom:a,addPanel:i,showPanel:n,begin:function(){o=(performance||Date).now()},end:function(){c++;var p=(performance||Date).now();if(u.update(p-o,200),p>l+1e3&&(h.update(1e3*c/(p-l),100),l=p,c=0,d)){var m=performance.memory;d.update(m.usedJSHeapSize/1048576,m.jsHeapSizeLimit/1048576)}return p},update:function(){o=this.end()},domElement:a,setMode:n}};return t.Panel=function(i,n,s){var a=1/0,o=0,l=Math.round,c=l(window.devicePixelRatio||1),h=80*c,u=48*c,d=3*c,p=2*c,m=3*c,A=15*c,g=74*c,y=30*c,v=document.createElement("canvas");v.width=h,v.height=u,v.style.cssText="width:80px;height:48px";var _=v.getContext("2d");return _.font="bold "+9*c+"px Helvetica,Arial,sans-serif",_.textBaseline="top",_.fillStyle=s,_.fillRect(0,0,h,u),_.fillStyle=n,_.fillText(i,d,p),_.fillRect(m,A,g,y),_.fillStyle=s,_.globalAlpha=.9,_.fillRect(m,A,g,y),{dom:v,update:function(b,T){a=Math.min(a,b),o=Math.max(o,b),_.fillStyle=s,_.globalAlpha=1,_.fillRect(0,0,h,A),_.fillStyle=n,_.fillText(l(b)+" "+i+" ("+l(a)+"-"+l(o)+")",d,p),_.drawImage(v,m+c,A,g-c,y,m,A,g-c,y),_.fillRect(m+g-c,A,c,y),_.fillStyle=s,_.globalAlpha=.9,_.fillRect(m+g-c,A,c,l((1-b/T)*y))}}},t})})(mm)),mm.exports}var RF=DF();const BF=IF(RF);class HS{constructor(e){this._stats=new BF,this._container=e,this._stats.dom.id="stats-js",this._stats.dom.style.position="absolute",this._stats.dom.style.left="unset",this._stats.dom.style.right="0"}show(){this._container.appendChild(this._stats.dom),this._stats.showPanel(0)}hide(){this._container.removeChild(this._stats.dom)}begin(){this._stats.begin()}end(){this._stats.end()}}const LF=".CustomContextMenu{position:absolute;background:#333e;min-width:8rem;color:#fff;font-size:.8rem;overflow:hidden;border-radius:8px;box-shadow:2px 2px 10px #6666;z-index:100000}.CustomContextMenu div{cursor:pointer;padding:6px 10px;transition:background-color .25s ease-in-out}.CustomContextMenu div:hover{background:#1a1a1c}#customContextMenu{background:#333e;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);border:.5px solid rgba(20,20,20,.3);width:auto;height:auto;position:absolute;display:flex;flex-direction:column;z-index:9999;padding:.4rem .25rem;border-radius:.375rem;min-width:8rem;pointer-events:auto;box-shadow:0 2px 10px #0c0c0c33}.customContextMenuItems{color:#fff;font-size:.8rem;font-family:monospace;background-color:transparent;cursor:pointer;padding:4px 8px;border-radius:.25rem;line-height:1rem;font-weight:500;transition:background-color .25s ease-in-out}.customContextMenuItems:hover{color:#fff;background-color:#017aff}",aA=class aA{static _initialize(){this._inited=!0,document.addEventListener("pointerdown",e=>{this.Element&&!this.Element.contains(e.target)&&e.button===0&&this.Remove()})}static Create(e,t,i,n=!0,s=!0){this._inited||this._initialize(),this.Element&&this.Remove();const a=document.createElement("div");a.id="customContextMenu",a.style.top=i+"px",a.style.left=t+"px",a.innerHTML="<style>"+LF+"</style>";for(const[o,l]of Object.entries(e)){const c=document.createElement("div");c.classList.add("customContextMenuItems"),c.textContent=o,a.appendChild(c),c.onclick=async()=>{await l(),s&&this.Remove()}}return this.Element=a,n&&document.body.appendChild(a),a}static Remove(){this.Element?.remove(),this.Element=void 0}};aA.Element=void 0,aA._inited=!1;let Zu=aA;const oA=class oA{get inputEl(){return this._inputEl}get el(){return this._el}constructor(e,t,i){this._el=e,this._inputEl=t,this._listeners={drop:[],dropstart:[],droperror:[]},this._onDragover=this._onDragover.bind(this),this._onDrop=this._onDrop.bind(this),this._onSelect=this._onSelect.bind(this),e?.addEventListener("dragover",this._onDragover,!1),e?.addEventListener("drop",this._onDrop,!1),t?.addEventListener("change",this._onSelect),i&&Object.entries(i).forEach(([n,s])=>s&&this.on(n,s))}on(e,t){return this._listeners[e].push(t),this}_emit(e,t){return this._listeners[e].forEach(i=>i(t)),this}destroy(){const e=this._el,t=this._inputEl;e?.removeEventListener("dragover",this._onDragover),e?.removeEventListener("drop",this._onDrop),t?.removeEventListener("change",this._onSelect)}_onDrop(e){e.stopPropagation(),e.preventDefault(),this._emit("dropstart");const t=Array.from(e.dataTransfer?.files||[]),i=Array.from(e.dataTransfer?.items||[]);if(t.length===0&&i.length===0){this._fail("Required drag-and-drop APIs are not supported in this browser.");return}if(oA.USE_DATA_TRANSFER_ITEMS&&i.length>0){const n=i.map(s=>s.webkitGetAsEntry());this._loadNextEntry(new Map,n,e);return}this._emit("drop",{nativeEvent:e,files:new Map(t.map(n=>(n.filePath=n.name,[n.filePath,n])))})}_onDragover(e){e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy")}_onSelect(e){if(!this._inputEl){console.warn("Invalid Dropzone event ",e);return}this._emit("dropstart");const t=[].slice.call(this._inputEl.files??new FileList),i=new Map;t.forEach(n=>{n.filePath=n.webkitRelativePath||n.name,i.set(n.filePath,n)}),this._emit("drop",{files:i,nativeEvent:e})}_loadNextEntry(e,t,i){const n=t.pop();if(!n){this._emit("drop",{files:e,nativeEvent:i});return}if(n.isFile)n.file(s=>{s.filePath=n.fullPath,e.set(n.fullPath,s),this._loadNextEntry(e,t,i)},s=>console.error("Could not load file: %s",n.fullPath,s,"Try setting Dropzone.USE_DATA_TRANSFER_ITEMS to false."));else if(n.isDirectory){const s=n.createReader(),a=o=>{o.length?(t=t.concat(o),s.readEntries(a)):this._loadNextEntry(e,t,i)};s.readEntries(a)}else console.warn("Unknown asset type: "+n.fullPath),this._loadNextEntry(e,t,i)}_fail(e){this._emit("droperror",{message:e})}};oA.USE_DATA_TRANSFER_ITEMS=!0;let gm=oA;const QS={type:"change"},Q_={type:"start"},jS={type:"end"},Am=new Va,WS=new Es,OF=Math.cos(70*Ft.DEG2RAD),Sn=new S,ym=new Ir,qS=new S,ms=2*Math.PI,fi={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},j_=1e-6;class W_ extends UU{constructor(e,t=null){super(e,t),this.state=fi.NONE,this.enabled=!0,this.target=new S,this.cursor=new S,this.minDistance=1e-5,this.maxDistance=1/0,this.autoPushTarget=!0,this.autoPullTarget=!0,this.clampMax=new S(1/0,1/0,1/0),this.clampMin=new S(-1/0,-1/0,-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.maxZoomSpeed=1,this.maxZoomSpeed=1,this.dollyZoom=!1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.throttleUpdate=0,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Hl.ROTATE,MIDDLE:Hl.DOLLY,RIGHT:Hl.PAN},this.touches={ONE:Ql.ROTATE,TWO:Ql.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new S,this._lastQuaternion=new $e,this._lastTargetPosition=new S,this._quat=new $e().setFromUnitVectors(e.up,new S(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Ir,this._sphericalDelta=new Ir(0),this._scale=1,this._panOffset=new S,this._rotateStart=new K,this._rotateEnd=new K,this._rotateDelta=new K,this._panStart=new K,this._panEnd=new K,this._panDelta=new K,this._dollyStart=new K,this._dollyEnd=new K,this._dollyDelta=new K,this._dollyDirection=new S,this._mouse=new K,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=FF.bind(this),this._onPointerDown=UF.bind(this),this._onPointerUp=NF.bind(this),this._onContextMenu=jF.bind(this),this._onMouseWheel=zF.bind(this),this._onKeyDown=VF.bind(this),this._onTouchStart=HF.bind(this),this._onTouchMove=QF.bind(this),this._onMouseDown=kF.bind(this),this._onMouseMove=GF.bind(this),this._interceptControlDown=WF.bind(this),this._interceptControlUp=qF.bind(this),this._lastUpdateTime=0,this.domElement!==null&&this.connect(),this.update()}connect(){this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){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(QS),this.update(),this.state=fi.NONE}update(e=null){if(this.throttleUpdate&&this.throttleUpdate>=1&&Date.now()-this._lastUpdateTime<1e3/this.throttleUpdate)return;const t=this.object.position;Sn.copy(t).sub(this.target),Sn.applyQuaternion(this._quat),this._spherical.setFromVector3(Sn),ym.copy(this._spherical),qS.copy(this.target),this.autoRotate&&this.state===fi.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 i=this.minAzimuthAngle,n=this.maxAzimuthAngle;isFinite(i)&&isFinite(n)&&(i<-Math.PI?i+=ms:i>Math.PI&&(i-=ms),n<-Math.PI?n+=ms:n>Math.PI&&(n-=ms),i<=n?this._spherical.theta=Math.max(i,Math.min(n,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+n)/2?Math.max(i,this._spherical.theta):Math.min(n,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=0,a=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const l=this._spherical.radius;Math.abs(this._sphericalDelta.radius)>0&&(this.dollyZoom&&(this.object.zoom=Math.max(Math.max(this.minZoom,.1),Math.min(Math.min(this.maxZoom,20),this.object.zoom*(1+this._sphericalDelta.radius*(this.enableDamping?this.dampingFactor:1)))),this.object.updateProjectionMatrix(),(this.object.zoom>=Math.min(this.maxZoom,20)||this.object.zoom<=Math.max(this.minZoom,.1))&&(this._sphericalDelta.radius=0)),this._spherical.radius*=1+this._sphericalDelta.radius*(this.enableDamping?this.dampingFactor:1)),Math.abs(this._scale-1)>1e-5&&(this.dollyZoom&&(this.object.zoom=Math.max(Math.max(this.minZoom,.1),Math.min(Math.min(this.maxZoom,20),this.object.zoom*this._scale)),this.object.updateProjectionMatrix(),(this.object.zoom>=Math.min(this.maxZoom,20)||this.object.zoom<=Math.max(this.minZoom,.1))&&(this._scale=1)),this._spherical.radius*=this._scale),this.autoPushTarget&&this._spherical.radius<this.minDistance&&(s=this.minDistance-this._spherical.radius),this.autoPullTarget&&this._spherical.radius>this.maxDistance&&(s=this.maxDistance-this._spherical.radius),this._spherical.radius=this._clampDistance(this._spherical.radius),a=l!=this._spherical.radius}(s!==0||!this.target.equals(qS)||this._spherical.radius!==ym.radius||this._spherical.phi!==ym.phi||this._spherical.theta!==ym.theta)&&(Sn.setFromSpherical(this._spherical),Sn.applyQuaternion(this._quatInverse),t.copy(this.target).add(Sn),this.target.add(Sn.normalize().multiplyScalar(-s))),t.clamp(this.clampMin,this.clampMax),this.target.clamp(this.clampMin,this.clampMax),this.object.lookAt(this.target);let o=!1;if(this.enableDamping===!0&&Math.abs(this._sphericalDelta.theta)+Math.abs(this._sphericalDelta.phi)+Math.abs(this._sphericalDelta.radius)+this._panOffset.length()>.001?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._sphericalDelta.radius*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor),o=!0):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let l=null;if(this.object.isPerspectiveCamera){const c=this._spherical.radius;l=this._spherical.radius*this._scale,l=this._clampDistance(l);const h=c-l;this.object.position.addScaledVector(this._dollyDirection,h),this.object.updateMatrixWorld(),a=!!h}else if(this.object.isOrthographicCamera){const c=new S(this._mouse.x,this._mouse.y,0);c.unproject(this.object);const h=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),a=h!==this.object.zoom;const u=new S(this._mouse.x,this._mouse.y,0);u.unproject(this.object),this.object.position.sub(u).add(c),this.object.updateMatrixWorld(),l=this._spherical.radius}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;l!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(l).add(this.object.position):(Am.origin.copy(this.object.position),Am.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Am.direction))<OF?this.object.lookAt(this.target):(WS.setFromNormalAndCoplanarPoint(this.object.up,this.target),Am.intersectPlane(WS,this.target))))}else if(this.object.isOrthographicCamera){const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),l!==this.object.zoom&&(this.object.updateProjectionMatrix(),a=!0)}return this._scale=1,this._performCursorZoom=!1,a||o||this._lastPosition.distanceToSquared(this.object.position)>j_||8*(1-this._lastQuaternion.dot(this.object.quaternion))>j_||this._lastTargetPosition.distanceToSquared(this.target)>j_?(this.dispatchEvent(QS),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}stopDamping(){this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)}_getAutoRotationAngle(e){return e!==null?ms/60*this.autoRotateSpeed*e:ms/60/60*this.autoRotateSpeed}_getZoomScale(e){return this.enableDamping&&!this.zoomToCursor&&!this.object.isOrthographicCamera?1:Math.pow(.95,this.zoomSpeed)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Sn.setFromMatrixColumn(t,0),Sn.multiplyScalar(-e),this._panOffset.add(Sn)}_panUp(e,t){this.screenSpacePanning===!0?Sn.setFromMatrixColumn(t,1):(Sn.setFromMatrixColumn(t,0),Sn.crossVectors(this.object.up,Sn)),Sn.multiplyScalar(e),this._panOffset.add(Sn)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const n=this.object.position;Sn.copy(n).sub(this.target);let s=Sn.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/i.clientHeight,this.object.matrix),this._panUp(2*t*s/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e,t=0){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?(this._scale/=e,this._sphericalDelta.radius=Math.max(-this.maxZoomSpeed,Math.min(this.maxZoomSpeed,this._sphericalDelta.radius-t))):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e,t=0){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?(this._scale*=e,this._sphericalDelta.radius=Math.max(-this.maxZoomSpeed,Math.min(this.maxZoomSpeed,this._sphericalDelta.radius+t))):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}zoomIn(e){this._dollyOut(1,e*this.zoomSpeed)}zoomOut(e){this._dollyIn(1,e*this.zoomSpeed)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const i=this.domElement.getBoundingClientRect(),n=e-i.left,s=t-i.top,a=i.width,o=i.height;this._mouse.x=n/a*2-1,this._mouse.y=-(s/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.clientY),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(ms*this._rotateDelta.x/t.clientHeight),this._rotateUp(ms*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);let t=0;switch(e.deltaMode){case 2:t+=e.deltaY*1;break;case 1:t+=e.deltaY*.4;break;default:t+=e.deltaY*.01;break}e.deltaY<0?this.zoomToCursor||this.object.isOrthographicCamera?this._dollyIn(this._getZoomScale(e.deltaY)):this._dollyIn(1,t*this.zoomSpeed):e.deltaY>0&&(this.zoomToCursor||this.object.isOrthographicCamera?this._dollyOut(this._getZoomScale(e.deltaY)):this._dollyOut(1,-t*this.zoomSpeed)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateUp(ms*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateUp(-ms*this.rotateSpeed/this.domElement.clientHeight):this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(ms*this.rotateSpeed/this.domElement.clientHeight):this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this._rotateLeft(-ms*this.rotateSpeed/this.domElement.clientHeight):this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._rotateStart.set(i,n)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panStart.set(i,n)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,n=e.pageY-t.y,s=Math.sqrt(i*i+n*n);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const i=this._getSecondPointerPosition(e),n=.5*(e.pageX+i.x),s=.5*(e.pageY+i.y);this._rotateEnd.set(n,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(ms*this._rotateDelta.x/t.clientHeight),this._rotateUp(ms*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._panEnd.set(i,n)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,n=e.pageY-t.y,s=Math.sqrt(i*i+n*n);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed*6)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const 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 K,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,i={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:i.deltaY*=16;break;case 2:i.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(i.deltaY*=10),i}rotateUp(e){this._rotateUp(e)}rotateLeft(e){this._rotateLeft(e)}}function UF(r){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(r.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(r)&&(this._addPointer(r),r.pointerType==="touch"?this._onTouchStart(r):this._onMouseDown(r)))}function FF(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchMove(r):r.buttons?this._onMouseMove(r):this._onPointerUp(r))}function NF(r){switch(this._removePointer(r),this._pointers.length){case 0:this.domElement.releasePointerCapture(r.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(jS),this.state=fi.NONE;break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function kF(r){let e;switch(r.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Hl.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(r),this.state=fi.DOLLY;break;case Hl.ROTATE:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=fi.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=fi.ROTATE}break;case Hl.PAN:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=fi.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=fi.PAN}break;default:this.state=fi.NONE}this.state!==fi.NONE&&this.dispatchEvent(Q_)}function GF(r){switch(this.state){case fi.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(r);break;case fi.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(r);break;case fi.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(r);break}}function zF(r){this.enabled===!1||this.enableZoom===!1||this.state!==fi.NONE||(r.preventDefault(),this.dispatchEvent(Q_),this._handleMouseWheel(this._customWheelEvent(r)),this.dispatchEvent(jS))}function VF(r){this.enabled===!1||this.enablePan===!1||this._handleKeyDown(r)}function HF(r){switch(this._trackPointer(r),this._pointers.length){case 1:switch(this.touches.ONE){case Ql.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(r),this.state=fi.TOUCH_ROTATE;break;case Ql.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(r),this.state=fi.TOUCH_PAN;break;default:this.state=fi.NONE}break;case 2:switch(this.touches.TWO){case Ql.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(r),this.state=fi.TOUCH_DOLLY_PAN;break;case Ql.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(r),this.state=fi.TOUCH_DOLLY_ROTATE;break;default:this.state=fi.NONE}break;default:this.state=fi.NONE}this.state!==fi.NONE&&this.dispatchEvent(Q_)}function QF(r){switch(this._trackPointer(r),this.state){case fi.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(r),this.update();break;case fi.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(r),this.update();break;case fi.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(r),this.update();break;case fi.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(r),this.update();break;default:this.state=fi.NONE}}function jF(r){this.enabled!==!1&&r.preventDefault()}function WF(r){r.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function qF(r){r.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}var XF=Object.defineProperty,YF=Object.getOwnPropertyDescriptor,li=(r,e,t,i)=>{for(var n=i>1?void 0:i?YF(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&XF(e,t,n),n};f.OrbitControls3=class extends W_{constructor(){super(...arguments),this.type="OrbitControls",this.enabled=!0,this.dollyZoom=!1,this.zoomToCursor=!1,this.enableDamping=!0,this.dampingFactor=.08,this.autoRotate=!1,this.autoRotateSpeed=2,this.enableZoom=!0,this.zoomSpeed=.15,this.maxZoomSpeed=.2,this.enableRotate=!0,this.rotateSpeed=2,this.enablePan=!0,this.panSpeed=1,this.autoPushTarget=!1,this.autoPullTarget=!1,this.minDistance=.35,this.maxDistance=1e6,this.minZoom=.01,this.maxZoom=1e6,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1e6,this.maxAzimuthAngle=1e6,this.clampMin=new S(-1e6,-1e6,-1e6),this.clampMax=new S(1e6,1e6,1e6),this.screenSpacePanning=!0,this.keyPanSpeed=7,this.throttleUpdate=60}},li([G()],f.OrbitControls3.prototype,"type",2),li([se()],f.OrbitControls3.prototype,"enabled",2),li([se(),G()],f.OrbitControls3.prototype,"dollyZoom",2),li([se(),G()],f.OrbitControls3.prototype,"zoomToCursor",2),li([se(),G()],f.OrbitControls3.prototype,"enableDamping",2),li([He(),G()],f.OrbitControls3.prototype,"dampingFactor",2),li([se(),G()],f.OrbitControls3.prototype,"autoRotate",2),li([He(),G()],f.OrbitControls3.prototype,"autoRotateSpeed",2),li([se(),G()],f.OrbitControls3.prototype,"enableZoom",2),li([He(),G()],f.OrbitControls3.prototype,"zoomSpeed",2),li([He(),G()],f.OrbitControls3.prototype,"maxZoomSpeed",2),li([se(),G()],f.OrbitControls3.prototype,"enableRotate",2),li([He(),G()],f.OrbitControls3.prototype,"rotateSpeed",2),li([se(),G()],f.OrbitControls3.prototype,"enablePan",2),li([He(),G()],f.OrbitControls3.prototype,"panSpeed",2),li([He(),G()],f.OrbitControls3.prototype,"autoPushTarget",2),li([He(),G()],f.OrbitControls3.prototype,"autoPullTarget",2),li([He(),G()],f.OrbitControls3.prototype,"minDistance",2),li([He(),G()],f.OrbitControls3.prototype,"maxDistance",2),li([He(),G()],f.OrbitControls3.prototype,"minZoom",2),li([He(),G()],f.OrbitControls3.prototype,"maxZoom",2),li([He(),G()],f.OrbitControls3.prototype,"minPolarAngle",2),li([He(),G()],f.OrbitControls3.prototype,"maxPolarAngle",2),li([He(),G()],f.OrbitControls3.prototype,"minAzimuthAngle",2),li([He(),G()],f.OrbitControls3.prototype,"maxAzimuthAngle",2),li([yi(),G()],f.OrbitControls3.prototype,"clampMin",2),li([yi(),G()],f.OrbitControls3.prototype,"clampMax",2),li([G()],f.OrbitControls3.prototype,"screenSpacePanning",2),li([G()],f.OrbitControls3.prototype,"keyPanSpeed",2),f.OrbitControls3=li([Aa("Orbit Controls")],f.OrbitControls3);const no=new zu;no.params.Line2={threshold:.01};const qn=new S,so=new S,Ti=new $e,XS={X:new S(1,0,0),Y:new S(0,1,0),Z:new S(0,0,1)},q_={type:"change"},YS={type:"mouseDown",mode:null},$S={type:"mouseUp",mode:null},KS={type:"objectChange"};class lr extends ft{constructor(e,t){super(),t===void 0&&(console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.'),t=document),this.isTransformControls=!0,this.visible=!1,this.domElement=t,this.domElement.style.touchAction="none";const i=new tE;this._gizmo=i,this.add(i);const n=new iE;this._plane=n,this.add(n);const s=this;function a(v,_){let b=_;Object.defineProperty(s,v,{get:function(){return b!==void 0?b:_},set:function(T){b!==T&&!(s.lockProps&&s.lockProps.includes(v))&&(b=T,n[v]=T,i[v]=T,s.dispatchEvent({type:v+"-changed",value:T}),s.dispatchEvent(q_))}}),s[v]=_,n[v]=_,i[v]=_}a("camera",e),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0);const o=new S,l=new S,c=new $e,h=new $e,u=new S,d=new $e,p=new S,m=new S,A=new S,g=0,y=new S;a("worldPosition",o),a("worldPositionStart",l),a("worldQuaternion",c),a("worldQuaternionStart",h),a("cameraPosition",u),a("cameraQuaternion",d),a("pointStart",p),a("pointEnd",m),a("rotationAxis",A),a("rotationAngle",g),a("eye",y),this._offset=new S,this._startNorm=new S,this._endNorm=new S,this._cameraScale=new S,this._parentPosition=new S,this._parentQuaternion=new $e,this._parentQuaternionInv=new $e,this._parentScale=new S,this._worldScaleStart=new S,this._worldQuaternionInv=new $e,this._worldScale=new S,this._positionStart=new S,this._quaternionStart=new $e,this._scaleStart=new S,this._getPointer=$F.bind(this),this._onPointerDown=JF.bind(this),this._onPointerHover=KF.bind(this),this._onPointerMove=ZF.bind(this),this._onPointerUp=e3.bind(this),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp)}updateMatrixWorld(){this.object!==void 0&&(this.object.updateMatrixWorld(),this.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):this.object.parent.matrixWorld.decompose(this._parentPosition,this._parentQuaternion,this._parentScale),this.object.matrixWorld.decompose(this.worldPosition,this.worldQuaternion,this._worldScale),this._parentQuaternionInv.copy(this._parentQuaternion).invert(),this._worldQuaternionInv.copy(this.worldQuaternion).invert()),this.camera.updateMatrixWorld(),this.camera.matrixWorld.decompose(this.cameraPosition,this.cameraQuaternion,this._cameraScale),this.camera.isOrthographicCamera?this.camera.getWorldDirection(this.eye).negate():this.eye.copy(this.cameraPosition).sub(this.worldPosition).normalize(),super.updateMatrixWorld(this)}pointerHover(e){if(this.object===void 0||this.dragging===!0)return;e!==null&&no.setFromCamera(e,this.camera);const t=X_(this._gizmo.picker[this.mode],no);t?this.axis=t.object.name:this.axis=null}pointerDown(e){if(!(this.object===void 0||this.dragging===!0||e!=null&&e.button!==0)&&this.axis!==null){e!==null&&no.setFromCamera(e,this.camera);const t=X_(this._plane,no,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,YS.mode=this.mode,this.dispatchEvent(YS)}}pointerMove(e){const t=this.axis,i=this.mode,n=this.object,s=n&&n.userData&&n.userData.isMultiSelectDummy;let a=s?"world":this.space;if(i==="scale"&&!s?a="local":(t==="E"||t==="XYZE"||t==="XYZ")&&(a="world"),n===void 0||t===null||this.dragging===!1||e!==null&&e.button!==-1)return;e!==null&&no.setFromCamera(e,this.camera);const o=X_(this._plane,no,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),i==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),a==="local"&&t!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),t.indexOf("X")===-1&&(this._offset.x=0),t.indexOf("Y")===-1&&(this._offset.y=0),t.indexOf("Z")===-1&&(this._offset.z=0),a==="local"&&t!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),n.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(a==="local"&&(n.position.applyQuaternion(Ti.copy(this._quaternionStart).invert()),t.search("X")!==-1&&(n.position.x=Math.round(n.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(n.position.y=Math.round(n.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(n.position.z=Math.round(n.position.z/this.translationSnap)*this.translationSnap),n.position.applyQuaternion(this._quaternionStart)),a==="world"&&(n.parent&&n.position.add(qn.setFromMatrixPosition(n.parent.matrixWorld)),t.search("X")!==-1&&(n.position.x=Math.round(n.position.x/this.translationSnap)*this.translationSnap),t.search("Y")!==-1&&(n.position.y=Math.round(n.position.y/this.translationSnap)*this.translationSnap),t.search("Z")!==-1&&(n.position.z=Math.round(n.position.z/this.translationSnap)*this.translationSnap),n.parent&&n.position.sub(qn.setFromMatrixPosition(n.parent.matrixWorld))));else if(i==="scale"){if(t.search("XYZ")!==-1){let l=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(l*=-1),so.set(l,l,l)}else qn.copy(this.pointStart),so.copy(this.pointEnd),qn.applyQuaternion(this._worldQuaternionInv),so.applyQuaternion(this._worldQuaternionInv),so.divide(qn),t.search("X")===-1&&(so.x=1),t.search("Y")===-1&&(so.y=1),t.search("Z")===-1&&(so.z=1);n.scale.copy(this._scaleStart).multiply(so),this.scaleSnap&&(t.search("X")!==-1&&(n.scale.x=Math.round(n.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Y")!==-1&&(n.scale.y=Math.round(n.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),t.search("Z")!==-1&&(n.scale.z=Math.round(n.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(i==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);const l=20/this.worldPosition.distanceTo(qn.setFromMatrixPosition(this.camera.matrixWorld));let c=!1;t==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(qn.copy(this.rotationAxis).cross(this.eye))*l):(t==="X"||t==="Y"||t==="Z")&&(this.rotationAxis.copy(XS[t]),qn.copy(XS[t]),a==="local"&&qn.applyQuaternion(this.worldQuaternion),qn.cross(this.eye),qn.length()===0?c=!0:this.rotationAngle=this._offset.dot(qn.normalize())*l),(t==="E"||c)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),a==="local"&&t!=="E"&&t!=="XYZE"?(n.quaternion.copy(this._quaternionStart),n.quaternion.multiply(Ti.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),n.quaternion.copy(Ti.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),n.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(q_),this.dispatchEvent(KS)}}pointerUp(e){e!==null&&e.button!==0||(this.dragging&&this.axis!==null&&($S.mode=this.mode,this.dispatchEvent($S)),this.dragging=!1,this.axis=null)}dispose(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}attach(e){return this.object=e,this.visible=!0,this}detach(){return this.object=void 0,this.visible=!1,this.dragging=!1,this.axis=null,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(q_),this.dispatchEvent(KS),this.pointStart.copy(this.pointEnd))}getRaycaster(){return no}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}}lr.ObjectConstructors={MeshBasicMaterial:is,LineBasicMaterial:Mi};function $F(r){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:r.button,buttons:r.buttons};{const e=this.domElement.getBoundingClientRect();return{x:(r.clientX-e.left)/e.width*2-1,y:-(r.clientY-e.top)/e.height*2+1,button:r.button,buttons:r.buttons}}}function KF(r){if(this.enabled)switch(r.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(r));break}}function JF(r){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(r.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(r)),this.pointerDown(this._getPointer(r)))}function ZF(r){this.enabled&&this.pointerMove(this._getPointer(r))}function e3(r){this.enabled&&(this.domElement.releasePointerCapture(r.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(r)))}function X_(r,e,t){const i=e.intersectObject(r,!0);for(let n=0;n<i.length;n++)if(i[n].object.visible||t)return i[n];return!1}const _m=new Pt,_i=new S(0,1,0),JS=new S(0,0,0),ZS=new fe,vm=new $e,bm=new $e,Br=new S,eE=new fe,ed=new S(1,0,0),fl=new S(0,1,0),td=new S(0,0,1),wm=new S,id=new S,nd=new S;class tE extends ft{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new lr.ObjectConstructors.MeshBasicMaterial({allowOverride:!1,depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new lr.ObjectConstructors.LineBasicMaterial({allowOverride:!1,depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=e.clone();i.opacity=.15;const n=t.clone();n.opacity=1;const s=e.clone();s.color.setHex(15663205),s.opacity=.95;const a=e.clone();a.color.setHex(2014720),a.opacity=.95;const o=e.clone();o.color.setHex(37885),o.opacity=.95;const l=e.clone();l.color.setHex(16618689),l.__color=s.color.getHex();const c=e.clone();c.color.setHex(12516474),c.__color=a.color.getHex();const h=e.clone();h.color.setHex(11397372),h.__color=o.color.getHex();const u=e.clone();u.color.setHex(15663205),u.opacity=.75;const d=e.clone();d.color.setHex(2014720),d.opacity=.75;const p=e.clone();p.color.setHex(37885),p.opacity=.75;const m=e.clone();m.color.setHex(12893629),m.opacity=.75;const A=e.clone();A.color.setHex(16777051),A.opacity=.25;const g=e.clone();g.color.setHex(7895160),g.opacity=.75;const y=new sn(0,.04,.1,12);y.translate(0,.05,0);const v=new gi(.08,.08,.08);v.translate(0,.04,0);const _=new Je;_.setAttribute("position",new Ee([0,0,0,1,0,0],3));const b=new sn(.0075,.0075,.5,3);b.translate(0,.25,0);function T(W,ce){const ue=new Xa(W,.0075,3,64,ce*Math.PI*2);return ue.rotateY(Math.PI/2),ue.rotateX(Math.PI/2),ue}function E(W,ce){const ue=new Xa(W,.1,4,24,ce*Math.PI*2);return ue.rotateY(Math.PI/2),ue.rotateX(Math.PI/2),ue}function M(){const W=new Je;return W.setAttribute("position",new Ee([0,0,0,1,1,1],3)),W}const I={X:[[new _e(y,l),[.5,0,0],[0,0,-Math.PI/2]],[new _e(b,s),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new _e(y,c),[0,.5,0]],[new _e(b,a)]],Z:[[new _e(y,h),[0,0,.5],[Math.PI/2,0,0]],[new _e(b,o),null,[Math.PI/2,0,0]]],XYZ:[[new _e(new da(.1,2),m.clone()),[0,0,0]]],XY:[[new _e(new gi(.2,.2,.01),p.clone()),[.2,.2,0]]],YZ:[[new _e(new gi(.2,.2,.01),u.clone()),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new _e(new gi(.2,.2,.01),d.clone()),[.2,0,.2],[-Math.PI/2,0,0]]]},C={X:[[new _e(new sn(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]]],Y:[[new _e(new sn(.2,0,.6,4),i),[0,.3,0]]],Z:[[new _e(new sn(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]]],XYZ:[[new _e(new da(.2,0),i)]],XY:[[new _e(new gi(.25,.25,.01),i),[.2,.2,0]]],YZ:[[new _e(new gi(.25,.25,.01),i),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new _e(new gi(.25,.25,.01),i),[.2,0,.2],[-Math.PI/2,0,0]]]},x={START:[[new _e(new da(.01,2),n),null,null,null,"helper"]],END:[[new _e(new da(.01,2),n),null,null,null,"helper"]],DELTA:[[new fn(M(),n),null,null,null,"helper"]],X:[[new fn(_,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new fn(_,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new fn(_,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},D={XYZE:[[new _e(new Is(.1,10,8),m)],[new _e(T(.5,1),g),null,[0,Math.PI/2,0]]],X:[[new _e(T(.5,.5),s)],[new _e(b,s),[0,0,0],[0,0,-Math.PI/2]],[new _e(y.clone().translate(.5,0,0),l),[0,0,0],[-Math.PI/2,-Math.PI/2,-Math.PI/2]]],Y:[[new _e(T(.5,.5),a),null,[0,0,-Math.PI/2]],[new _e(b,a)],[new _e(y.clone().rotateZ(-Math.PI/2).translate(0,.5,0),c),[0,0,0],[Math.PI/2,0,0]]],Z:[[new _e(T(.5,.5),o),null,[0,Math.PI/2,0]],[new _e(b,o),null,[Math.PI/2,0,0]],[new _e(y.clone().rotateZ(-Math.PI).translate(0,0,.5),h),[0,0,0],[0,Math.PI/2,0]]]},U={AXIS:[[new fn(_,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},O={XYZE:[[new _e(new Is(.25,10,8),i)]],X:[[new _e(E(.5,.5),i)]],Y:[[new _e(E(.5,.5),i),[0,0,0],[0,0,-Math.PI/2]]],Z:[[new _e(E(.5,.5),i),[0,0,0],[0,Math.PI/2,0]]]},N={X:[[new _e(v,l),[.5,0,0],[0,0,-Math.PI/2]],[new _e(b,s),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new _e(v,c),[0,.5,0]],[new _e(b,a)]],Z:[[new _e(v,h),[0,0,.5],[Math.PI/2,0,0]],[new _e(b,o),[0,0,0],[Math.PI/2,0,0]]],XY:[[new _e(new gi(.15,.15,.01),p),[.15,.15,0]]],YZ:[[new _e(new gi(.15,.15,.01),u),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new _e(new gi(.15,.15,.01),d),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new _e(new gi(.1,.1,.1),m.clone())]]},H={X:[[new _e(new sn(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new _e(new sn(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new _e(new sn(.2,0,.6,4),i),[0,.3,0]],[new _e(new sn(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new _e(new sn(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new _e(new sn(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new _e(new gi(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new _e(new gi(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new _e(new gi(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new _e(new gi(.2,.2,.2),i),[0,0,0]]]},V={X:[[new fn(_,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new fn(_,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new fn(_,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function X(W){const ce=new ft;for(const ue in W)for(let we=W[ue].length;we--;){const Pe=W[ue][we][0].clone(),Qe=W[ue][we][1],ie=W[ue][we][2],oe=W[ue][we][3],me=W[ue][we][4];Pe.name=ue,Pe.tag=me,Qe&&Pe.position.set(Qe[0],Qe[1],Qe[2]),ie&&Pe.rotation.set(ie[0],ie[1],ie[2]),oe&&Pe.scale.set(oe[0],oe[1],oe[2]),Pe.updateMatrix();const Ce=Pe.geometry.clone();Ce.applyMatrix4(Pe.matrix),Pe.geometry=Ce,Pe.renderOrder=1/0,Pe.position.set(0,0,0),Pe.rotation.set(0,0,0),Pe.scale.set(1,1,1),ce.add(Pe)}return ce}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=X(I)),this.add(this.gizmo.rotate=X(D)),this.add(this.gizmo.scale=X(N)),this.add(this.picker.translate=X(C)),this.add(this.picker.rotate=X(O)),this.add(this.picker.scale=X(H)),this.add(this.helper.translate=X(x)),this.add(this.helper.rotate=X(U)),this.add(this.helper.scale=X(V)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const t=this.object&&this.object.userData&&this.object.userData.isMultiSelectDummy,n=(this.mode==="scale"&&!t?"local":t?"world":this.space)==="local"?this.worldQuaternion:bm;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let a=0;a<s.length;a++){const o=s[a];o.visible=!0,o.rotation.set(0,0,0),o.position.copy(this.worldPosition);let l;if(this.camera.isOrthographicCamera?l=(this.camera.top-this.camera.bottom)/this.camera.zoom:l=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),o.scale.set(1,1,1).multiplyScalar(l*this.size/4),o.tag==="helper"){o.visible=!1,o.name==="AXIS"?(o.visible=!!this.axis,this.axis==="X"&&(Ti.setFromEuler(_m.set(0,0,0)),o.quaternion.copy(n).multiply(Ti),Math.abs(_i.copy(ed).applyQuaternion(n).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Y"&&(Ti.setFromEuler(_m.set(0,0,Math.PI/2)),o.quaternion.copy(n).multiply(Ti),Math.abs(_i.copy(fl).applyQuaternion(n).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Z"&&(Ti.setFromEuler(_m.set(0,Math.PI/2,0)),o.quaternion.copy(n).multiply(Ti),Math.abs(_i.copy(td).applyQuaternion(n).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="XYZE"&&(Ti.setFromEuler(_m.set(0,Math.PI/2,0)),_i.copy(this.rotationAxis),o.quaternion.setFromRotationMatrix(ZS.lookAt(JS,_i,fl)),o.quaternion.multiply(Ti),o.visible=this.dragging),this.axis==="E"&&(o.visible=!1)):o.name==="START"?(o.position.copy(this.worldPositionStart),o.visible=this.dragging):o.name==="END"?(o.position.copy(this.worldPosition),o.visible=this.dragging):o.name==="DELTA"?(o.position.copy(this.worldPositionStart),o.quaternion.copy(this.worldQuaternionStart),qn.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),qn.applyQuaternion(this.worldQuaternionStart.clone().invert()),o.scale.copy(qn),o.visible=this.dragging):(o.quaternion.copy(n),this.dragging?o.position.copy(this.worldPositionStart):o.position.copy(this.worldPosition),this.axis&&(o.visible=this.axis.search(o.name)!==-1));continue}o.quaternion.copy(n),this.mode==="translate"||this.mode==="scale"?(o.name==="X"&&Math.abs(_i.copy(ed).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Y"&&Math.abs(_i.copy(fl).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Z"&&Math.abs(_i.copy(td).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XY"&&Math.abs(_i.copy(td).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="YZ"&&Math.abs(_i.copy(ed).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XZ"&&Math.abs(_i.copy(fl).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1)):this.mode==="rotate"&&(vm.copy(n),_i.copy(this.eye).applyQuaternion(Ti.copy(n).invert()),o.name.search("E")!==-1&&o.quaternion.setFromRotationMatrix(ZS.lookAt(this.eye,JS,fl)),o.name==="X"&&(Ti.setFromAxisAngle(ed,Math.atan2(-_i.y,_i.z)),Ti.multiplyQuaternions(vm,Ti),o.quaternion.copy(Ti)),o.name==="Y"&&(Ti.setFromAxisAngle(fl,Math.atan2(_i.x,_i.z)),Ti.multiplyQuaternions(vm,Ti),o.quaternion.copy(Ti)),o.name==="Z"&&(Ti.setFromAxisAngle(td,Math.atan2(_i.y,_i.x)),Ti.multiplyQuaternions(vm,Ti),o.quaternion.copy(Ti))),o.visible=o.visible&&(o.name.indexOf("X")===-1||this.showX),o.visible=o.visible&&(o.name.indexOf("Y")===-1||this.showY),o.visible=o.visible&&(o.name.indexOf("Z")===-1||this.showZ),o.visible=o.visible&&(o.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),o.material._color=o.material._color||o.material.color.clone(),o.material._opacity=o.material._opacity||o.material.opacity,o.material.color.copy(o.material._color),o.material.opacity=o.material._opacity,this.enabled&&this.axis&&(o.name===this.axis||this.axis.split("").some(function(c){return o.name===c}))&&(o.material.__color&&o.material.color.setHex(o.material.__color),o.material.opacity=1)}super.updateMatrixWorld(e)}}class iE extends _e{constructor(){super(new ca(1e5,1e5,2,2),new lr.ObjectConstructors.MeshBasicMaterial({visible:!1,wireframe:!0,side:Zi,transparent:!0,opacity:.1,toneMapped:!1,allowOverride:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){const t=this.object&&this.object.userData&&this.object.userData.isMultiSelectDummy;let i=t?"world":this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&!t&&(i="local"),wm.copy(ed).applyQuaternion(i==="local"?this.worldQuaternion:bm),id.copy(fl).applyQuaternion(i==="local"?this.worldQuaternion:bm),nd.copy(td).applyQuaternion(i==="local"?this.worldQuaternion:bm),_i.copy(id),this.mode){case"translate":case"scale":switch(this.axis){case"X":_i.copy(this.eye).cross(wm),Br.copy(wm).cross(_i);break;case"Y":_i.copy(this.eye).cross(id),Br.copy(id).cross(_i);break;case"Z":_i.copy(this.eye).cross(nd),Br.copy(nd).cross(_i);break;case"XY":Br.copy(nd);break;case"YZ":Br.copy(wm);break;case"XZ":_i.copy(nd),Br.copy(id);break;case"XYZ":case"E":Br.set(0,0,0);break}break;default:Br.set(0,0,0)}Br.length()===0?this.quaternion.copy(this.cameraQuaternion):(eE.lookAt(qn.set(0,0,0),Br,_i),this.quaternion.setFromRotationMatrix(eE)),super.updateMatrixWorld(e)}}function nE(r,e){if(r.metaKey||r.ctrlKey||r.target?.tagName==="TEXTAREA"||r.target?.tagName==="INPUT")return!1;switch(r.code){case"KeyQ":return e.toggleSpace(),!0;case"Equal":case"NumpadAdd":return e.adjustSize(.1),!0;case"Minus":case"NumpadSubtract":return e.adjustSize(-.1),!0;case"KeyX":return e.toggleAxis(0),!0;case"KeyY":return e.toggleAxis(1),!0;case"KeyZ":return e.toggleAxis(2),!0;case"Space":return e.toggleEnabled(),!0;default:return!1}}const Cm=new S,sE=new S;function rE(r,e,t,i){const n=e.dot(e),s=e.dot(r)-e.dot(t),a=e.dot(i);return a===0?-s/n:(Cm.copy(i).multiplyScalar(n/a).sub(e),sE.copy(i).multiplyScalar(s/a).add(t).sub(r),-Cm.dot(sE)/Cm.dot(Cm))}function t3(r,e,t){const i=Math.abs(r.x)>=Math.abs(r.y)&&Math.abs(r.x)>=Math.abs(r.z)?0:Math.abs(r.y)>=Math.abs(r.x)&&Math.abs(r.y)>=Math.abs(r.z)?1:2,n=[0,1,2].sort((m,A)=>Math.abs(e.getComponent(A))-Math.abs(e.getComponent(m))),s=i===n[0]?n[1]:n[0],a=r.getComponent(i),o=r.getComponent(s),l=e.getComponent(i),c=e.getComponent(s),h=t.getComponent(i),d=(t.getComponent(s)-h*(o/a))/(c-l*(o/a));return[(h-d*l)/a,d]}const aE=new fe,oE=new fe,Y_=new fe,lE=new fe,cE=new fe,$_=new fe,hE=new fe,i3=new fe,xm=new fe,Sm=new fe,K_=new fe,J_=new K,Z_=new S,ev=new S,uE=new S,ro=new Va,ao=new S,sd=new S(0,1,0),rd=new S(1,0,0),ad=new S(0,1,0),od=new S(0,0,1),lA=class lA extends Vi{constructor(e,t){super(),this.enabled=!0,this.autoTransform=!0,this.gizmoScale=1.25,this.activeAxes=[!0,!0,!0],this.disableAxes=!1,this.disableSliders=!1,this.disableRotations=!1,this.disableScaling=!1,this.axisColors=[15663205,2014720,37885],this.hoveredColor=16777024,this.handleOpacity=.95,this.space="world",this.translationSnap=.5,this.rotationSnap=15,this.scaleSnap=.1,this.depthTest=!1,this.fixed=!0,this.uniformScaleEnabled=!0,this.annotations=!0,this._handles=[],this._raycaster=new zu,this._activeHandle=null,this._dragging=!1,this._hoveredHandle=null,this._translation=[0,0,0],this._uniformScaling=!1,this._annotationEl=null,this.camera=e,this.domElement=t,this._gizmoGroup=new Vi,this.add(this._gizmoGroup),this._buildHandles(),this._onPointerDown=this._handlePointerDown.bind(this),this._onPointerMove=this._handlePointerMove.bind(this),this._onPointerUp=this._handlePointerUp.bind(this),t.addEventListener("pointerdown",this._onPointerDown),t.addEventListener("pointermove",this._onPointerMove),t.addEventListener("pointerup",this._onPointerUp),this._onKeyDown=this._handleKeyDown.bind(this),window.addEventListener("keydown",this._onKeyDown)}_handleKeyDown(e){if(!this.enabled||!this.object)return;nE(e,{toggleSpace:()=>{this.space=this.space==="local"?"world":"local"},adjustSize:i=>{this.gizmoScale=Math.max(this.gizmoScale+i,.1)},toggleAxis:i=>{this.activeAxes[i]=!this.activeAxes[i],this.updateHandleVisibility()},toggleEnabled:()=>{this.enabled=!this.enabled}})&&this.dispatchEvent({type:"change"})}_ensureAnnotationEl(){if(!this._annotationEl){const e=document.createElement("div");e.style.cssText="position:absolute;pointer-events:none;display:none;background:#151520;color:white;padding:6px 8px;border-radius:7px;white-space:nowrap;z-index:1000;",this.domElement.parentElement?.appendChild(e),this._annotationEl=e}return this._annotationEl}_showAnnotation(e,t){if(!this.annotations)return;const i=this._ensureAnnotationEl();i.textContent=e,i.style.display="block";const n=t.clone().project(this.camera),s=this.domElement.getBoundingClientRect(),a=(n.x*.5+.5)*s.width,o=(-n.y*.5+.5)*s.height;i.style.left=s.left+a+12+"px",i.style.top=s.top+o-12+"px"}_hideAnnotation(){this._annotationEl&&(this._annotationEl.style.display="none")}_updateAnnotation(e){if(!this.annotations||!this.object)return;const t=["X","Y","Z"];let i="";if(e.type==="arrow")i=`${t[e.axis]}: ${this._translation[e.axis].toFixed(2)}`;else if(e.type==="slider"){const n=(e.axis+1)%3,s=(e.axis+2)%3;i=`${t[n]}: ${this._translation[n].toFixed(2)}, ${t[s]}: ${this._translation[s].toFixed(2)}`}else if(e.type==="rotator"){const n=(e.extraState.angle*180/Math.PI).toFixed(0);i=`${t[e.axis]}: ${n}°`}else e.type==="scaler"&&(i=`${this._uniformScaling?"Uniform":t[e.axis]}: ${e.extraState.scaleCur.toFixed(2)}`);this._showAnnotation(i,this.position)}_buildHandles(){this._handles=[],this._gizmoGroup.clear();const e=lA.ObjectConstructors,t=1,i=this.depthTest,n=(c,h=this.handleOpacity)=>new e.MeshBasicMaterial({allowOverride:!1,depthTest:i,depthWrite:i,fog:!1,toneMapped:!1,transparent:!0,color:c,opacity:h}),s=()=>new e.MeshBasicMaterial({allowOverride:!1,depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0,opacity:.15,visible:!1}),a=[rd,ad,od];for(let c=0;c<3;c++){const h=n(this.axisColors[c]),u=s(),d=new sn(.0075*t,.0075*t,.5*t,3);d.translate(0,.25*t,0);const p=new _e(d,h);p.renderOrder=500,p.raycast=()=>{};const m=new sn(0,.04*t,.1*t,12);m.translate(0,.05*t,0);const A=new _e(m,h);A.position.set(0,.5*t,0),A.renderOrder=500,A.raycast=()=>{};const g=new sn(.2*t,0,.6*t,4);g.translate(0,.3*t,0);const y=new _e(g,u);y.visible=!1;const v=new $e().setFromUnitVectors(sd,a[c]),_=new Vi;_.quaternion.copy(v),_.add(p,A,y),this._gizmoGroup.add(_);const b={type:"arrow",axis:c,gizmoMeshes:[p,A],pickerMeshes:[y],materials:[h],clickInfo:null,extraState:null};y.userData._pivotHandle=b,this._handles.push(b)}const o=[[2,rd,ad],[1,od,rd],[0,ad,od]];for(const[c,h,u]of o){const d=n(this.axisColors[c],.75),p=s(),m=.2*t,A=new gi(m,m,.01*t),g=new _e(A,d);g.renderOrder=500,g.raycast=()=>{};const y=new gi(m*1.25,m*1.25,.01*t),v=new _e(y,p);v.visible=!1;const _=h.clone().normalize(),b=u.clone().normalize(),T=_.clone().cross(b),E=_.clone().multiplyScalar(m).add(b.clone().multiplyScalar(m)),M=new Vi,I=new fe().makeBasis(_,b,T);M.applyMatrix4(I),M.position.copy(E),M.add(g,v),this._gizmoGroup.add(M);const C={type:"slider",axis:c,gizmoMeshes:[g],pickerMeshes:[v],materials:[d],clickInfo:null,extraState:null};v.userData._pivotHandle=C,this._handles.push(C)}const l=[[2,rd,ad],[1,od,rd],[0,ad,od]];for(const[c,h,u]of l){const d=n(this.axisColors[c]),p=s(),m=.5*t,A=new Xa(m,.0075*t,3,16,Math.PI/2),g=new _e(A,d);g.renderOrder=500,g.raycast=()=>{};const y=new Xa(m,.1*t,4,12,Math.PI/2),v=new _e(y,p);v.visible=!1;const _=h.clone().normalize(),b=u.clone().normalize(),T=_.clone().cross(b),E=new Vi,M=new fe().makeBasis(_,b,T);E.applyMatrix4(M),E.add(g,v),this._gizmoGroup.add(E);const I={type:"rotator",axis:c,gizmoMeshes:[g],pickerMeshes:[v],materials:[d],clickInfo:null,extraState:{angle0:0,angle:0}};v.userData._pivotHandle=I,this._handles.push(I)}for(let c=0;c<3;c++){const h=n(this.axisColors[c]),u=.04*t,d=new Is(u,12,12),p=new _e(d,h);p.renderOrder=500;const m=new $e().setFromUnitVectors(sd,a[c]),A=new Vi;A.quaternion.copy(m),p.position.set(0,.6*t+u,0),A.add(p),this._gizmoGroup.add(A);const g={type:"scaler",axis:c,gizmoMeshes:[p],pickerMeshes:[p],materials:[h],clickInfo:null,extraState:{scale0:1,scaleCur:1}};p.userData._pivotHandle=g,this._handles.push(g)}this.updateHandleVisibility(),this._gizmoGroup.traverse(c=>{c.castShadow=!1,c.receiveShadow=!1,c.userData.__keepShadowDef=!0})}updateHandleVisibility(){if(this._handles)for(const e of this._handles){let t=!0;if(e.type==="arrow")t=!this.disableAxes&&this.activeAxes[e.axis];else if(e.type==="scaler")t=!this.disableScaling&&this.activeAxes[e.axis];else if(e.type==="slider"){const i=[[1,2],[0,2],[0,1]],[n,s]=i[e.axis];t=!this.disableSliders&&this.activeAxes[n]&&this.activeAxes[s]}else if(e.type==="rotator"){const i=[[1,2],[0,2],[0,1]],[n,s]=i[e.axis];t=!this.disableRotations&&this.activeAxes[n]&&this.activeAxes[s]}for(const i of e.gizmoMeshes)i.visible=t;for(const i of e.pickerMeshes)i.parent&&(i.parent.visible=t)}}attach(e){return this.object=e,this.visible=!0,this._translation=[0,0,0],this.updateHandleVisibility(),this.updateMatrixWorld(!0),this.dispatchEvent({type:"change"}),this}detach(){return this._dragging&&this._endDrag(),this.object=void 0,this.visible=!1,this._activeHandle=null,this._hideAnnotation(),this.dispatchEvent({type:"change"}),this}updateGizmoScale(){if(!this.object||!this.visible)return;this.object.updateWorldMatrix(!0,!1);const e=new S().setFromMatrixPosition(this.object.matrixWorld);if(this.position.copy(e),this.space==="local"&&!this.object.userData?.isMultiSelectDummy?this.object.matrixWorld.decompose(Z_,this.quaternion,ev):this.quaternion.identity(),this.fixed){Z_.copy(e),ev.setFromMatrixPosition(this.camera.matrixWorld);let t;if(this.camera.isOrthographicCamera){const i=this.camera;t=(i.top-i.bottom)/i.zoom}else{const i=this.camera;t=Z_.distanceTo(ev)*Math.min(1.9*Math.tan(Math.PI*i.fov/360)/i.zoom,7)}this._gizmoGroup.scale.setScalar(t*this.gizmoScale/4)}else this._gizmoGroup.scale.setScalar(this.gizmoScale);for(const t of this._handles)if(t.type==="scaler"){const i=this._uniformScaling?1.8:1;for(const n of t.gizmoMeshes)n.scale.setScalar(i)}}rebuild(){this._buildHandles()}dispose(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),window.removeEventListener("keydown",this._onKeyDown),this._annotationEl&&(this._annotationEl.remove(),this._annotationEl=null)}_getNDC(e){const t=this.domElement.getBoundingClientRect();return J_.x=(e.clientX-t.left)/t.width*2-1,J_.y=-((e.clientY-t.top)/t.height)*2+1,J_}_getAllPickers(){const e=[];for(const t of this._handles)for(const i of t.pickerMeshes)e.push(i);return e}_findHandle(e){let t=e;for(;t;){if(t.userData._pivotHandle)return t.userData._pivotHandle;t=t.parent}return null}_handlePointerDown(e){if(!this.enabled||!this.object||!this.visible)return;this._raycaster.setFromCamera(this._getNDC(e),this.camera);const t=this._raycaster.intersectObjects(this._getAllPickers(),!0);if(t.length===0)return;const i=this._findHandle(t[0].object);i&&(e.stopPropagation(),this._activeHandle=i,this._dragging=!0,aE.copy(this.object.matrix),oE.copy(this.object.matrixWorld),this._onDragStart(i,t[0].point,e),this.domElement.setPointerCapture(e.pointerId),this.dispatchEvent({type:"mouseDown",mode:this._getMode(i)}),this.dispatchEvent({type:"dragging-changed",value:!0}))}_handlePointerMove(e){if(!(!this.enabled||!this.object||!this.visible))if(this._raycaster.setFromCamera(this._getNDC(e),this.camera),this._dragging&&this._activeHandle){const t=this._onDragMove(this._activeHandle,this._raycaster.ray,e);t&&(this._applyTransform(t),this._updateAnnotation(this._activeHandle))}else{const t=this._raycaster.intersectObjects(this._getAllPickers(),!0),i=t.length>0?this._findHandle(t[0].object):null;if(i!==this._hoveredHandle){if(this._hoveredHandle)for(const n of this._hoveredHandle.materials)n.color.set(this.axisColors[this._hoveredHandle.axis]);if(i)for(const n of i.materials)n.color.set(this.hoveredColor);this._hoveredHandle=i,this.dispatchEvent({type:"change"})}}}_handlePointerUp(e){!this._dragging||!this._activeHandle||(e.stopPropagation(),this.domElement.releasePointerCapture(e.pointerId),this._endDrag())}_endDrag(){if(!this._activeHandle)return;this._onDragEnd(this._activeHandle),this._hideAnnotation();const e=this._getMode(this._activeHandle);this._activeHandle=null,this._dragging=!1,this.dispatchEvent({type:"mouseUp",mode:e}),this.dispatchEvent({type:"dragging-changed",value:!1})}_onDragStart(e,t,i){const n=e.gizmoMeshes[0].parent;if(n.updateWorldMatrix(!0,!0),e.type==="arrow"){const s=new fe().extractRotation(n.matrixWorld),a=sd.clone().applyMatrix4(s).normalize();e.clickInfo={clickPoint:t.clone(),dir:a},e.extraState=this._translation[e.axis]}else if(e.type==="slider"){const s=new S().setFromMatrixColumn(n.matrixWorld,0).normalize(),a=new S().setFromMatrixColumn(n.matrixWorld,1).normalize(),o=new S().setFromMatrixColumn(n.matrixWorld,2).normalize(),l=new S().setFromMatrixPosition(n.matrixWorld),c=new Es().setFromNormalAndCoplanarPoint(o,l);e.clickInfo={clickPoint:t.clone(),e1:s,e2:a,plane:c},e.extraState={x0:this._translation[(e.axis+1)%3],y0:this._translation[(e.axis+2)%3]}}else if(e.type==="rotator"){const s=new S().setFromMatrixPosition(n.matrixWorld),a=new S().setFromMatrixColumn(n.matrixWorld,2).normalize(),o=new S().setFromMatrixPosition(this.camera.matrixWorld).sub(s).normalize(),l=a.clone().cross(o);l.length()===0&&l.copy(o).cross(sd),l.normalize();const c=20/s.distanceTo(new S().setFromMatrixPosition(this.camera.matrixWorld));e.clickInfo={clickPoint:t.clone(),origin:s,normal:a,tangent:l,rotSpeed:c},e.extraState={angle:0}}else if(e.type==="scaler"){const s=new fe().extractRotation(n.matrixWorld),a=sd.clone().applyMatrix4(s).normalize(),o=n.matrixWorld.clone(),l=o.clone().invert();e.clickInfo={clickPoint:t.clone(),dir:a,mPLG:o,mPLGInv:l}}}_onDragMove(e,t,i){if(!e.clickInfo)return null;if(e.type==="arrow"){const{clickPoint:n,dir:s}=e.clickInfo,a=e.extraState,o=this.translationLimits?.[e.axis];let l=rE(n,s,t.origin,t.direction);if(i.shiftKey&&this.translationSnap!==null){const c=this.translationSnap;l=Math.round(l/c)*c}return o&&(o[0]!==void 0&&(l=Math.max(l,o[0]-a)),o[1]!==void 0&&(l=Math.min(l,o[1]-a))),this._translation[e.axis]=a+l,xm.makeTranslation(s.x*l,s.y*l,s.z*l),xm}else if(e.type==="slider"){const{clickPoint:n,e1:s,e2:a,plane:o}=e.clickInfo,{x0:l,y0:c}=e.extraState;ro.copy(t),ro.intersectPlane(o,ao),ro.direction.negate(),ro.intersectPlane(o,ao),ao.sub(n);let[h,u]=t3(s,a,ao);if(i.shiftKey&&this.translationSnap!==null){const m=this.translationSnap;h=Math.round(h/m)*m,u=Math.round(u/m)*m}const d=this.translationLimits?.[(e.axis+1)%3],p=this.translationLimits?.[(e.axis+2)%3];return d&&(d[0]!==void 0&&(h=Math.max(h,d[0]-l)),d[1]!==void 0&&(h=Math.min(h,d[1]-l))),p&&(p[0]!==void 0&&(u=Math.max(u,p[0]-c)),p[1]!==void 0&&(u=Math.min(u,p[1]-c))),this._translation[(e.axis+1)%3]=l+h,this._translation[(e.axis+2)%3]=c+u,xm.makeTranslation(h*s.x+u*a.x,h*s.y+u*a.y,h*s.z+u*a.z),xm}else if(e.type==="rotator"){const{clickPoint:n,origin:s,normal:a,tangent:o,rotSpeed:l}=e.clickInfo,c=this.rotationLimits?.[e.axis],h=new Es().setFromNormalAndCoplanarPoint(a,s);ro.copy(t),ro.intersectPlane(h,ao)||(ro.direction.negate(),ro.intersectPlane(h,ao)),ao.sub(n);let u=ao.dot(o)*l;if(i.shiftKey&&this.rotationSnap!==null){const d=this.rotationSnap*Math.PI/180;u=Math.round(u/d)*d}return c&&(u=Ft.clamp(u,c[0],c[1])),e.extraState.angle=u,Sm.makeRotationAxis(a,u),uE.copy(s).applyMatrix4(Sm).sub(s).negate(),Sm.setPosition(uE),Sm}else if(e.type==="scaler"){const{clickPoint:n,dir:s,mPLG:a,mPLGInv:o}=e.clickInfo,l=this.scaleLimits?.[e.axis],c=rE(n,s,t.origin,t.direction);let h=Math.pow(2,c*.2);i.shiftKey&&this.scaleSnap!==null&&(h=Math.round(h/this.scaleSnap)*this.scaleSnap,h===0&&(h=this.scaleSnap));const u=this.uniformScaleEnabled&&i.altKey;this._uniformScaling=u;const d=l?l[0]:1e-5;return h=Math.max(h,d/e.extraState.scale0),l&&l[1]!==void 0&&(h=Math.min(h,l[1]/e.extraState.scale0)),e.extraState.scaleCur=e.extraState.scale0*h,u?K_.makeScale(h,h,h):K_.makeScale(1,h,1).premultiply(a).multiply(o),K_}return null}_onDragEnd(e){e.type==="rotator"&&(e.extraState.angle0=e.extraState.angle),e.type==="scaler"&&(e.extraState.scale0=e.extraState.scaleCur),this._uniformScaling=!1,e.clickInfo=null}_applyTransform(e){this.object&&(this.object.parent?Y_.copy(this.object.parent.matrixWorld):Y_.identity(),lE.copy(Y_).invert(),cE.copy(oE).premultiply(e),$_.copy(cE).premultiply(lE),hE.copy(aE).invert(),i3.copy($_).multiply(hE),this.autoTransform&&(this.object.matrix.copy($_),this.object.matrix.decompose(this.object.position,this.object.quaternion,this.object.scale)),this.dispatchEvent({type:"objectChange"}),this.dispatchEvent({type:"change"}))}_getMode(e){return e.type==="arrow"||e.type==="slider"?"translate":e.type==="rotator"?"rotate":e.type==="scaler"?"scale":"unknown"}};lA.ObjectConstructors={MeshBasicMaterial:is,LineBasicMaterial:Mi};let Qc=lA;var n3=Object.defineProperty,s3=Object.getOwnPropertyDescriptor,Xn=(r,e,t,i)=>{for(var n=i>1?void 0:i?s3(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&n3(e,t,n),n};const dE=new S,tv=new Ir,iv=new S,r3={type:"change"};f.FirstPersonControls2=class extends xi{constructor(e,t){super(),this.enabled=!0,this.enableKeys=!0,this.movementSpeed=1,this.lookSpeed=.005,this.lookVertical=!0,this.autoForward=!1,this.activeLook=!0,this.heightSpeed=!1,this.heightCoef=1,this.heightMin=0,this.heightMax=1,this.constrainVertical=!1,this.verticalMin=0,this.verticalMax=Math.PI,this.mouseDragOn=!1,this.autoSpeedFactor=0,this.pointerX=0,this.pointerY=0,this.moveForward=!1,this.moveBackward=!1,this.moveLeft=!1,this.moveRight=!1,this.moveUp=!1,this.moveDown=!1,this.viewHalfX=0,this.viewHalfY=0,this.lat=0,this.lon=0,this.targetPosition=new S,this._lastTime=-1,this.object=e,this.domElement=t,this.onPointerMove=this.onPointerMove.bind(this),this.onPointerDown=this.onPointerDown.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onKeyUp=this.onKeyUp.bind(this),this.onContextMenu=this.onContextMenu.bind(this),this.domElement.addEventListener("contextmenu",this.onContextMenu),this.domElement.addEventListener("pointermove",this.onPointerMove),this.domElement.addEventListener("pointerdown",this.onPointerDown),this.domElement.addEventListener("pointerup",this.onPointerUp),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp),this.handleResize(),this.setOrientation()}setOrientation(){const e=this.object.quaternion;dE.set(0,0,-1).applyQuaternion(e),tv.setFromVector3(dE),this.lat=90-Ft.radToDeg(tv.phi),this.lon=Ft.radToDeg(tv.theta)}handleResize(){this.domElement===document?(this.viewHalfX=window.innerWidth/2,this.viewHalfY=window.innerHeight/2):(this.viewHalfX=this.domElement.offsetWidth/2,this.viewHalfY=this.domElement.offsetHeight/2)}onPointerDown(e){if(this.domElement!==document&&this.domElement.focus(),this.activeLook)switch(e.button){case 0:this.moveForward=!0;break;case 2:this.moveBackward=!0;break}this.mouseDragOn=!0}onPointerUp(e){if(this.activeLook)switch(e.button){case 0:this.moveForward=!1;break;case 2:this.moveBackward=!1;break}this.mouseDragOn=!1}onPointerMove(e){this.domElement===document?(this.pointerX=e.pageX-this.viewHalfX,this.pointerY=e.pageY-this.viewHalfY):(this.pointerX=e.pageX-this.domElement.offsetLeft-this.viewHalfX,this.pointerY=e.pageY-this.domElement.offsetTop-this.viewHalfY)}onKeyDown(e){if(this.enableKeys)switch(e.code){case"ArrowUp":case"KeyW":this.moveForward=!0;break;case"ArrowLeft":case"KeyA":this.moveLeft=!0;break;case"ArrowDown":case"KeyS":this.moveBackward=!0;break;case"ArrowRight":case"KeyD":this.moveRight=!0;break;case"KeyR":this.moveUp=!0;break;case"KeyF":this.moveDown=!0;break}}onKeyUp(e){if(this.enableKeys)switch(e.code){case"ArrowUp":case"KeyW":this.moveForward=!1;break;case"ArrowLeft":case"KeyA":this.moveLeft=!1;break;case"ArrowDown":case"KeyS":this.moveBackward=!1;break;case"ArrowRight":case"KeyD":this.moveRight=!1;break;case"KeyR":this.moveUp=!1;break;case"KeyF":this.moveDown=!1;break}}lookAt(e,t,i){return e.isVector3?iv.copy(e):t===void 0||i===void 0?console.error("FirstPersonControls2.lookAt: y and z parameters are required"):iv.set(e,t,i),this.object.lookAt(iv),this.setOrientation(),this}update(){const e=Cn(),t=(this._lastTime<0?16:Math.min(e-this._lastTime,1e3))/1e3;if(this._lastTime=e,!this.enabled)return;if(this.heightSpeed){const h=Ft.clamp(this.object.position.y,this.heightMin,this.heightMax)-this.heightMin;this.autoSpeedFactor=t*(h*this.heightCoef)}else this.autoSpeedFactor=0;const i=t*this.movementSpeed;(this.moveForward||this.autoForward&&!this.moveBackward)&&this.object.translateZ(-(i+this.autoSpeedFactor)),this.moveBackward&&this.object.translateZ(i),this.moveLeft&&this.object.translateX(-i),this.moveRight&&this.object.translateX(i),this.moveUp&&this.object.translateY(i),this.moveDown&&this.object.translateY(-i);let n=t*this.lookSpeed;this.activeLook||(n=0);let s=1;this.constrainVertical&&(s=Math.PI/(this.verticalMax-this.verticalMin)),this.lon-=this.pointerX*n,this.lookVertical&&(this.lat-=this.pointerY*n*s),this.lat=Math.max(-85,Math.min(85,this.lat));let a=Ft.degToRad(90-this.lat);const o=Ft.degToRad(this.lon);this.constrainVertical&&(a=Ft.mapLinear(a,0,Math.PI,this.verticalMin,this.verticalMax));const l=this.object.position;this.targetPosition.setFromSphericalCoords(1,a,o).add(l),this.object.lookAt(this.targetPosition),this.dispatchEvent(r3)}dispose(){this.domElement.removeEventListener("contextmenu",this.onContextMenu),this.domElement.removeEventListener("pointerdown",this.onPointerDown),this.domElement.removeEventListener("pointermove",this.onPointerMove),this.domElement.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}onContextMenu(e){this.enableKeys&&e.preventDefault()}},Xn([G(),se()],f.FirstPersonControls2.prototype,"enabled",2),Xn([G(),se()],f.FirstPersonControls2.prototype,"enableKeys",2),Xn([G(),He()],f.FirstPersonControls2.prototype,"movementSpeed",2),Xn([G(),He()],f.FirstPersonControls2.prototype,"lookSpeed",2),Xn([G(),se()],f.FirstPersonControls2.prototype,"lookVertical",2),Xn([G(),se()],f.FirstPersonControls2.prototype,"autoForward",2),Xn([G(),se()],f.FirstPersonControls2.prototype,"activeLook",2),Xn([G(),se()],f.FirstPersonControls2.prototype,"heightSpeed",2),Xn([G(),He()],f.FirstPersonControls2.prototype,"heightCoef",2),Xn([G(),He()],f.FirstPersonControls2.prototype,"heightMin",2),Xn([G(),He()],f.FirstPersonControls2.prototype,"heightMax",2),Xn([G(),se()],f.FirstPersonControls2.prototype,"constrainVertical",2),Xn([G(),He()],f.FirstPersonControls2.prototype,"verticalMin",2),Xn([G(),He()],f.FirstPersonControls2.prototype,"verticalMax",2),Xn([G(),se()],f.FirstPersonControls2.prototype,"mouseDragOn",2),f.FirstPersonControls2=Xn([Aa("First Person Controls")],f.FirstPersonControls2);var a3=Object.defineProperty,o3=Object.getOwnPropertyDescriptor,jc=(r,e,t,i)=>{for(var n=i>1?void 0:i?o3(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&a3(e,t,n),n};const Wc=new Pt(0,0,0,"YXZ"),qc=new S,l3={type:"change"},c3={type:"lock"},h3={type:"unlock"},fE=Math.PI/2;f.PointerLockControls2=class extends xi{constructor(e,t){super(),this.isLocked=!1,this.enabled=!0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.pointerSpeed=1,this.autoLockOnClick=!0,this._movementX=0,this._movementY=0,this._forwardDirection=new S(0,0,-1),this.domElement=t,this.object=e,this.onElementClick=this.onElementClick.bind(this),this.onMouseMove=this.onMouseMove.bind(this),this.onPointerlockChange=this.onPointerlockChange.bind(this),this.onPointerlockError=this.onPointerlockError.bind(this),this.connect()}onElementClick(e){this.isLocked||this.autoLockOnClick&&(e.preventDefault(),this.lock())}onMouseMove(e){this.isLocked&&(this._movementX+=e.movementX||e.mozMovementX||e.webkitMovementX||0,this._movementY+=e.movementY||e.mozMovementY||e.webkitMovementY||0)}onPointerlockChange(){this.domElement.ownerDocument.pointerLockElement===this.domElement?(this.dispatchEvent(c3),this.isLocked=!0):(this.dispatchEvent(h3),this.isLocked=!1)}onPointerlockError(){console.error("THREE.PointerLockControls: Unable to use Pointer Lock API")}connect(){this.domElement.ownerDocument.addEventListener("mousemove",this.onMouseMove),this.domElement.ownerDocument.addEventListener("pointerlockchange",this.onPointerlockChange),this.domElement.ownerDocument.addEventListener("pointerlockerror",this.onPointerlockError),this.domElement.addEventListener("click",this.onElementClick)}disconnect(){this.domElement.ownerDocument.removeEventListener("mousemove",this.onMouseMove),this.domElement.ownerDocument.removeEventListener("pointerlockchange",this.onPointerlockChange),this.domElement.ownerDocument.removeEventListener("pointerlockerror",this.onPointerlockError),this.domElement.removeEventListener("click",this.onElementClick)}dispose(){this.disconnect()}getDirection(e){return e.copy(this._forwardDirection).applyQuaternion(this.object.quaternion)}moveForward(e){qc.setFromMatrixColumn(this.object.matrix,0),qc.crossVectors(this.object.up,qc),this.object.position.addScaledVector(qc,e)}moveRight(e){qc.setFromMatrixColumn(this.object.matrix,0),this.object.position.addScaledVector(qc,e)}lock(){this.domElement.requestPointerLock()}unlock(){this.domElement.ownerDocument.exitPointerLock()}update(){Math.abs(this._movementX)<1e-4&&Math.abs(this._movementY)<1e-4||(Wc.setFromQuaternion(this.object.quaternion),Wc.y-=this._movementX*.002*this.pointerSpeed,Wc.x-=this._movementY*.002*this.pointerSpeed,this._movementX=0,this._movementY=0,Wc.x=Math.max(fE-this.maxPolarAngle,Math.min(fE-this.minPolarAngle,Wc.x)),this.object.quaternion.setFromEuler(Wc),this.dispatchEvent(l3))}},jc([se(),G()],f.PointerLockControls2.prototype,"enabled",2),jc([He(),G()],f.PointerLockControls2.prototype,"minPolarAngle",2),jc([He(),G()],f.PointerLockControls2.prototype,"maxPolarAngle",2),jc([He(),G()],f.PointerLockControls2.prototype,"pointerSpeed",2),jc([se(),G()],f.PointerLockControls2.prototype,"autoLockOnClick",2),f.PointerLockControls2=jc([Aa("Pointer Lock Controls")],f.PointerLockControls2);var u3=Object.defineProperty,d3=Object.getOwnPropertyDescriptor,ld=(r,e,t,i)=>{for(var n=i>1?void 0:i?d3(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&u3(e,t,n),n};const f3=new S(0,0,1),pE=new Pt,p3=new $e,m3=new $e(-Math.sqrt(.5),0,0,Math.sqrt(.5)),Xc=new $e,g3={type:"change"},A3=1e-6;f.DeviceOrientationControls2=class extends xi{constructor(e){super(),this.enabled=!1,this.lastOrder="XYZ",this.dampingFactor=.05,this.lastQuaternion=new $e,this.onDeviceOrientationChangeEvent=t=>{this.deviceOrientation=t},this.onScreenOrientationChangeEvent=()=>{this.screenOrientation=screen.orientation},this._initQuaternion=new $e,this._initQuaternionInvert=new $e,this._initQuaternionDest=new $e,this._lastTime=-1,window.isSecureContext===!1&&console.error("DeviceOrientationControls2: DeviceOrientationEvent is only available in secure contexts (https)"),this.object=e,this.lastOrder=this.object.rotation.order,this.object.rotation.reorder("YXZ"),this.connect()}resetView(){this._initQuaternionDest.__init=!1}connect(){this.enabled||(this.onScreenOrientationChangeEvent(),window.DeviceOrientationEvent!==void 0&&typeof window.DeviceOrientationEvent.requestPermission=="function"?window.DeviceOrientationEvent.requestPermission().then(e=>{e=="granted"&&(window.addEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.addEventListener("deviceorientation",this.onDeviceOrientationChangeEvent))}).catch(e=>{console.error("DeviceOrientationControls2: Unable to use DeviceOrientation API:",e)}):(window.addEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.addEventListener("deviceorientation",this.onDeviceOrientationChangeEvent)),this.enabled=!0,this._initQuaternion.copy(this.object.quaternion),this._initQuaternionInvert.copy(this.object.quaternion).invert())}disconnect(){this.enabled&&(window.removeEventListener("orientationchange",this.onScreenOrientationChangeEvent),window.removeEventListener("deviceorientation",this.onDeviceOrientationChangeEvent),this._initQuaternion.identity(),this._initQuaternionInvert.identity(),this._initQuaternionDest=new $e,this.object.rotation.reorder(this.lastOrder),this.lastOrder="XYZ",this.enabled=!1)}update(){if(!this.enabled)return;const e=this.deviceOrientation;if(e){const t=e.alpha!==null?Ft.degToRad(e.alpha):0,i=e.beta!==null?Ft.degToRad(e.beta):0,n=e.gamma!==null?Ft.degToRad(e.gamma):0,s=this.screenOrientation?Ft.degToRad(this.screenOrientation.angle):0;this.setObjectQuaternion(t,i,n,s),8*(1-this.lastQuaternion.dot(this.object.quaternion))>A3&&(this.lastQuaternion.copy(this.object.quaternion),this.dispatchEvent(g3))}}dispose(){this.disconnect()}setObjectQuaternion(e,t,i,n){const s=Cn()/1e3;pE.set(t,e,-i,"YXZ"),Xc.setFromEuler(pE),Xc.multiply(m3),Xc.multiply(p3.setFromAxisAngle(f3,-n)),this._initQuaternionDest.__init||(this._initQuaternionDest.copy(Xc).invert(),this._initQuaternionDest.__init=!0),Xc.premultiply(this._initQuaternionDest);const a=1/60;this.object.quaternion.multiply(this._initQuaternionInvert),this.object.quaternion.slerp(Xc,this.dampingFactor/(Math.min(1,s-this._lastTime)/a)),this.object.quaternion.multiply(this._initQuaternion),this._lastTime=s}},ld([G(),Fe("Damping",[0,1],.01)],f.DeviceOrientationControls2.prototype,"dampingFactor",2),ld([ct("Reset View")],f.DeviceOrientationControls2.prototype,"resetView",1),ld([ct()],f.DeviceOrientationControls2.prototype,"connect",1),ld([ct()],f.DeviceOrientationControls2.prototype,"disconnect",1),f.DeviceOrientationControls2=ld([Aa("Device Orientation Controls")],f.DeviceOrientationControls2);const ya=new S,pl=new S,Em=new S,nv=new S,Mm=new S,Yc=new S;let sv=1;const y3=new S(0,1,0);class _3 extends W_{constructor(e,t){super(e,t),this.throttleUpdate=60,this.targetOffset=new S(0,0,0);const i=this.update;this.update=()=>this._update(i)}_update(e){this.target.add(this.targetOffset),ya.copy(this.object.position).sub(this.target),sv=ya.length(),Yc.copy(this.target);const t=e();return Yc.sub(this.target),ya.copy(this.object.position).sub(this.target),sv/=ya.length(),this.target.add(Yc),this.object.position.copy(this.target).add(ya),ya.normalize(),pl.crossVectors(y3,ya).normalize(),Em.crossVectors(ya,pl).normalize(),nv.crossVectors(pl,Em).normalize().negate(),pl.length()>.1&&this.object.up.crossVectors(ya.clone().normalize(),pl),this.enablePan&&(Mm.set(0,0,0).addScaledVector(pl,Yc.x).addScaledVector(Em,Yc.y).addScaledVector(nv,Yc.z),this.targetOffset.add(Mm),this.targetOffset.multiplyScalar(1/sv)),Mm.set(0,0,0).addScaledVector(pl,-this.targetOffset.x).addScaledVector(Em,-this.targetOffset.y).addScaledVector(nv,-this.targetOffset.z),this.object.lookAt(Mm.add(this.target)),this.object.updateMatrixWorld(),this.object.isCamera&&this.object.updateProjectionMatrix(),this.target.sub(this.targetOffset),t}}const Ls=class Ls extends en{constructor(){super(...arguments),this._vector=new S}expandByObject(e,t=!1,i=!1,n){if(e.userData?.bboxVisible===!1)return this;if(!e.visible&&i)return this;if(n&&n(e))return this;e.updateWorldMatrix(!1,!1);const s=e.geometry;if(s!==void 0){const o=s.getAttribute("position");if(t===!0&&o!==void 0&&Object.getPrototypeOf(s).computeBoundingBox===Je.prototype.computeBoundingBox)for(let l=0,c=o.count;l<c;l++)e.isMesh===!0?e.getVertexPosition(l,this._vector):this._vector.fromBufferAttribute(o,l),this._vector.applyMatrix4(e.matrixWorld),this.expandByPoint(this._vector);else e.boundingBox!==void 0?((t||e.boundingBox===null)&&typeof e.computeBoundingBox=="function"&&e.computeBoundingBox(),e.boundingBox!==null?(Ls._box.copy(e.boundingBox),Ls._box.applyMatrix4(e.matrixWorld),this.union(Ls._box)):console.warn("Box3B - Unable to compute bounds for",e)):(s.boundingBox===null&&s.computeBoundingBox(),s.boundingBox?(Ls._box.copy(s.boundingBox),Ls._box.applyMatrix4(e.matrixWorld),this.union(Ls._box)):console.warn("Box3B - Unable to compute bounds for",e,s))}else e.boundingBox!==void 0&&((t||e.boundingBox===null)&&typeof e.computeBoundingBox=="function"&&e.computeBoundingBox(),e.boundingBox!==null?(Ls._box.copy(e.boundingBox),Ls._box.applyMatrix4(e.matrixWorld),this.union(Ls._box)):console.warn("Box3B - Unable to compute bounds for",e));const a=e.children;for(let o=0,l=a.length;o<l;o++)this.expandByObject(a[o],t,i);return this}expandByObjects(e,t=!1,i=!1){for(let n=0,s=e.length;n<s;n++)this.expandByObject(e[n],t,i);return this}getPoints(){return[new S(this.min.x,this.min.y,this.min.z),new S(this.min.x,this.min.y,this.max.z),new S(this.min.x,this.max.y,this.min.z),new S(this.min.x,this.max.y,this.max.z),new S(this.max.x,this.min.y,this.min.z),new S(this.max.x,this.min.y,this.max.z),new S(this.max.x,this.max.y,this.min.z),new S(this.max.x,this.max.y,this.max.z)]}getScreenSpaceBounds(e){const t=this.getPoints(),i=new C_;for(const n of t){const s=n.project(e);i.min.min(s),i.max.max(s)}return i}};Ls._box=new Ls;let En=Ls;function rv(r,e){let t,i;if(Array.isArray(r))for(const s of r){const a=rv(s,e);t===void 0||i===void 0?(t=a.min.clone(),i=a.max.clone()):(t.min(a.min),i.max(a.max))}const n=r;if(n.geometry!==void 0){const s=n.geometry.vertices;if(s===void 0&&n.geometry.attributes!==void 0&&"position"in n.geometry.attributes){const a=new S,o=n.geometry.attributes.position;for(let l=0;l<o.count*o.itemSize;l+=o.itemSize){a.set(o.array[l],o.array[l+1],o.array[3]);const h=a.applyMatrix4(r.matrixWorld).project(e),u=new K(h.x,h.y);t===void 0||i===void 0?(t=u.clone(),i=u.clone()):(t.min(u),i.max(u))}}else for(const a of s){const l=a.clone().applyMatrix4(r.matrixWorld).project(e),c=new K(l.x,l.y);t===void 0||i===void 0?(t=c.clone(),i=c.clone()):(t.min(c),i.max(c))}}if(r.children!==void 0)for(const s of r.children){const a=rv(s,e);t===void 0||i===void 0?(t=a.min.clone(),i=a.max.clone()):(t.min(a.min),i.max(a.max))}return new C_(t,i)}function mE(r){return r==null?!0:r instanceof ArrayBuffer||ArrayBuffer.isView(r)?r.byteLength===0:typeof Blob<"u"&&r instanceof Blob?r.size===0:typeof r=="string"?r.length===0:!1}async function v3(r,e,t){switch(e){case"arraybuffer":return r.arrayBuffer();case"blob":return r.blob();case"document":{const i=await r.text();return i?new DOMParser().parseFromString(i,t??"text/html"):void 0}case"json":{const i=await r.text();return i?JSON.parse(i):void 0}default:if(t===void 0)return r.text();{const n=/charset="?([^;"\s]*)"?/i.exec(t),s=n&&n[1]?n[1].toLowerCase():void 0;return new TextDecoder(s).decode(await r.arrayBuffer())}}}function gE(r){if(Ai._orig){if(Ai._storage===r)return;Object.assign(Ai,Ai._orig),delete Ai._orig,delete Ai._storage}if(!r)return;const e=r,t={...Ai};Ai._orig=t,Ai._storage=r,Ai.get=(i,n,s)=>n?i.startsWith("data:")||i.startsWith("blob:")||i.startsWith("chrome-extension")?Promise.resolve(void 0):e.match(i).then(async a=>{if(!a)return;let o;try{o=await v3(a,n,s)}catch{o=void 0}if(mE(o)){console.warn("[threepipe cache] removing invalid cache entry for",i),await e.delete(i).catch(()=>{});return}return o}).catch(a=>{console.warn("[threepipe cache] lookup failed for",i,a)}):t.get(i),Ai.add=async(i,n,s)=>{if(!s)return t.add(i,n);if(!(i.startsWith("data:")||i.startsWith("blob:")||i.startsWith("chrome-extension")||i.startsWith("asset://"))){if(mE(n)){console.warn("[threepipe cache] skipping empty payload for",i);return}try{const a=s==="json"?JSON.stringify(n):s==="document"?new XMLSerializer().serializeToString(n):n;await e.match(i)&&await e.delete(i),await e.put(i,new Response(a,{status:200}))}catch(a){console.warn("[threepipe cache] add failed for",i,a)}}},Ai.remove=(i,n)=>{if(!n)return t.remove(i);e.delete(i).catch(s=>{console.warn("[threepipe cache] remove failed for",i,s)})}}function b3(r){const e=new Vn(new Uint8Array([Math.floor(r.r*255),Math.floor(r.g*255),Math.floor(r.b*255),255]),1,1,qt,Qt);return e.needsUpdate=!0,e.colorSpace=Bt,e}function w3(r){const e=new Vn(new Uint8Array([Math.floor(r.x*255),Math.floor(r.y*255),Math.floor(r.z*255),Math.floor(r.w*255)]),1,1,qt,Qt);return e.needsUpdate=!0,e.colorSpace=Bt,e}function AE(r,e=3,t){let i,n,s,a,o;const l=r.byteLength/(e*2)|0;t=t||new Uint8ClampedArray(l*4);for(let c=0;c<l;c++){i=zn.fromHalfFloat(r[c*e])*65504,n=zn.fromHalfFloat(r[c*e+1])*65504,s=zn.fromHalfFloat(r[c*e+2])*65504,a=Math.max(Math.max(i,n),s);const h=Math.ceil(Math.log2(a));o=Math.pow(2,h-8),t[c*4]=i/o|0,t[c*4+1]=n/o|0,t[c*4+2]=s/o|0,t[c*4+3]=h+128}return t}function _a({uniforms:r,propKey:e,thisTarget:t=!1,onChange:i}={}){const n=!!r,s=!!e,a=t;return(o,l,c)=>{const h=d=>{const p=a?d:n?r:d.uniforms||d._uniforms||d.extraUniforms;let m=s?e:l;a&&(m="_"+m);let A=p[m];return A||(A={value:null},p[m]=A),A},u={get(){return h(this).value},set(d){const p=h(this);p.value!==d&&(p.value=d,an(this,"uniformsNeedUpdate",!0,!0),i&&Wu.callFunction(i,this,[l,d]))}};if(c)return Wn(c,"value")&&delete c.value,Wn(c,"writable")&&delete c.writable,Wn(c,"initializer")&&delete c.initializer,Object.assign(c,u);Object.defineProperty(o,l,u)}}function Tm(r,e,t=!1,i,n,s){const a=!!e,o=!!r;return(l,c,h)=>{const u=p=>({t:a?e:p.defines||p._defines||p.extraDefines,p:o?r:c}),d={get(){const{t:p,p:m}=u(t?this:this.material);let A=p[m];return s&&(A=s(A)),A},set(p){const{t:m,p:A}=u(t?this:this.material);n&&(p=n(p)),an(m,A,p,!0),p===void 0&&delete m[A],i&&typeof i=="function"?Wu.callFunction(i,this,[A,p]):an(t?this:this.material,"needsUpdate",!0,!0)}};if(h)return Wn(h,"value")&&delete h.value,Wn(h,"writable")&&delete h.writable,Wn(h,"initializer")&&delete h.initializer,Object.assign(h,d);Object.defineProperty(l,c,d)}}function Im(r,e,t=!1,i,n=!1){return Tm(r,e,t,i,s=>s?"1":n?void 0:"0",s=>!!(s&&s!=="0"))}function jt({obj:r,key:e,processVal:t,invProcessVal:i,onChange:n,onChangeParams:s=!0,allowUndefined:a=!1}){const o=!!e;return(l,c,h)=>{const u=p=>{let m=tt(r)||p;typeof m=="string"&&(m=p[m]);let A=o&&tt(e)||c,g;if(Array.isArray(A)){for(;A.length>1&&m&&typeof m=="object";)m=m[A[0]],A=A.slice(1);g=A.length?A[0]:c}else g=A;return{t:m,p:g}},d={get(){const{t:p,p:m}=u(this);if(!p||typeof p!="object")return;let A=p[m];return i&&(A=i(A)),A},set(p){const{t:m,p:A}=u(this);if(!m||typeof m!="object")return;t&&(p=t(p)),an(m,A,p,!0)&&p===void 0&&!a&&delete m[A];let y=n;y&&(typeof y=="string"||typeof y=="symbol")&&(y=this[y]),y&&typeof y=="function"&&Wu.callFunction(y,this,s?[A,p]:[])}};if(h)return Wn(h,"value")&&delete h.value,Wn(h,"writable")&&delete h.writable,Wn(h,"initializer")&&delete h.initializer,Object.assign(h,d);Object.defineProperty(l,c,d)}}function yE(r,e){let t;switch(e){case ai:case Bt:t="";break;case Ct:t="";break;case Fs:t="RGBM16ToLinear";break;default:console.warn("THREE.WebGLProgram: Unsupported color space:",e),t="";break}return`#define ${r}( value ) ${t} ( value )`}function av(r,e){return yE(r+"TexelToLinear",e??Bt)+`
`}function C3(r,e,t=!0){if(!e||!e.isReady)throw new Error("BufferGeometryUtils: Initialized MikkTSpace library required.");if(!r.hasAttribute("position")||!r.hasAttribute("normal")||!r.hasAttribute("uv"))throw new Error('BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.');function i(a){if(a.normalized||a.isInterleavedBufferAttribute){const o=new Float32Array(a.count*a.itemSize);for(let l=0,c=0;l<a.count;l++)o[c++]=a.getX(l),o[c++]=a.getY(l),a.itemSize>2&&(o[c++]=a.getZ(l));return o}return a.array instanceof Float32Array?a.array:new Float32Array(a.array)}const n=r.index?r.toNonIndexed():r,s=e.generateTangents(i(n.attributes.position),i(n.attributes.normal),i(n.attributes.uv));if(t)for(let a=3;a<s.length;a+=4)s[a]*=-1;return n.setAttribute("tangent",new Ze(s,4)),r!==n&&r.copy(n),r}function _E(r,e=!1){const t=r[0].index!==null,i=new Set(Object.keys(r[0].attributes)),n=new Set(Object.keys(r[0].morphAttributes)),s={},a={},o=r[0].morphTargetsRelative,l=new Je;let c=0;for(let h=0;h<r.length;++h){const u=r[h];let d=0;if(t!==(u.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const p in u.attributes){if(!i.has(p))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+'. All geometries must have compatible attributes; make sure "'+p+'" attribute exists among all geometries, or in none of them.'),null;s[p]===void 0&&(s[p]=[]),s[p].push(u.attributes[p]),d++}if(d!==i.size)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". Make sure all geometries have the same number of attributes."),null;if(o!==u.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const p in u.morphAttributes){if(!n.has(p))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+".  .morphAttributes must be consistent throughout all geometries."),null;a[p]===void 0&&(a[p]=[]),a[p].push(u.morphAttributes[p])}if(e){let p;if(t)p=u.index.count;else if(u.attributes.position!==void 0)p=u.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". The geometry must have either an index or a position attribute"),null;l.addGroup(c,p,h),c+=p}}if(t){let h=0;const u=[];for(let d=0;d<r.length;++d){const p=r[d].index;for(let m=0;m<p.count;++m)u.push(p.getX(m)+h);h+=r[d].attributes.position.count}l.setIndex(u)}for(const h in s){const u=Pm(s[h]);if(!u)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+h+" attribute."),null;l.setAttribute(h,u)}for(const h in a){const u=a[h][0].length;if(u===0)break;l.morphAttributes=l.morphAttributes||{},l.morphAttributes[h]=[];for(let d=0;d<u;++d){const p=[];for(let A=0;A<a[h].length;++A)p.push(a[h][A][d]);const m=Pm(p);if(!m)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+h+" morphAttribute."),null;l.morphAttributes[h].push(m)}}return l}function Pm(r){let e,t,i,n=-1,s=0;for(let c=0;c<r.length;++c){const h=r[c];if(e===void 0&&(e=h.array.constructor),e!==h.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(t===void 0&&(t=h.itemSize),t!==h.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(i===void 0&&(i=h.normalized),i!==h.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(n===-1&&(n=h.gpuType),n!==h.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;s+=h.count*t}const a=new e(s),o=new Ze(a,t,i);let l=0;for(let c=0;c<r.length;++c){const h=r[c];if(h.isInterleavedBufferAttribute){const u=l/t;for(let d=0,p=h.count;d<p;d++)for(let m=0;m<t;m++){const A=h.getComponent(d,m);o.setComponent(d+u,m,A)}}else a.set(h.array,l);l+=h.count*t}return n!==void 0&&(o.gpuType=n),o}function x3(r){return r.isInstancedInterleavedBufferAttribute||r.isInterleavedBufferAttribute?Dm(r):r.isInstancedBufferAttribute?new ha().copy(r):new Ze().copy(r)}function S3(r){let e,t=0,i=0;for(let c=0,h=r.length;c<h;++c){const u=r[c];if(e===void 0&&(e=u.array.constructor),e!==u.array.constructor)return console.error("AttributeBuffers of different types cannot be interleaved"),null;t+=u.array.length,i+=u.itemSize}const n=new Mc(new e(t),i);let s=0;const a=[],o=["getX","getY","getZ","getW"],l=["setX","setY","setZ","setW"];for(let c=0,h=r.length;c<h;c++){const u=r[c],d=u.itemSize,p=u.count,m=new Rn(n,d,s,u.normalized);a.push(m),s+=d;for(let A=0;A<p;A++)for(let g=0;g<d;g++)m[l[g]](A,u[o[g]](A))}return a}function Dm(r){const e=r.data.array.constructor,t=r.count,i=r.itemSize,n=r.normalized,s=new e(t*i);let a;r.isInstancedInterleavedBufferAttribute?a=new ha(s,i,n,r.meshPerAttribute):a=new Ze(s,i,n);for(let o=0;o<t;o++)a.setX(o,r.getX(o)),i>=2&&a.setY(o,r.getY(o)),i>=3&&a.setZ(o,r.getZ(o)),i>=4&&a.setW(o,r.getW(o));return a}function E3(r){const e=r.attributes,t=r.morphTargets,i=new Map;for(const n in e){const s=e[n];s.isInterleavedBufferAttribute&&(i.has(s)||i.set(s,Dm(s)),e[n]=i.get(s))}for(const n in t){const s=t[n];s.isInterleavedBufferAttribute&&(i.has(s)||i.set(s,Dm(s)),t[n]=i.get(s))}}function M3(r){let e=0;for(const i in r.attributes){const n=r.getAttribute(i);e+=n.count*n.itemSize*n.array.BYTES_PER_ELEMENT}const t=r.getIndex();return e+=t?t.count*t.itemSize*t.array.BYTES_PER_ELEMENT:0,e}function vE(r,e=1e-4){const t=e>0;e=Math.max(e,Number.EPSILON);const i={},n=r.getIndex(),s=r.getAttribute("position"),a=n?n.count:s.count;let o=0;const l=Object.keys(r.attributes),c={},h={},u=[],d=["getX","getY","getZ","getW"],p=["setX","setY","setZ","setW"];for(let _=0,b=l.length;_<b;_++){const T=l[_],E=r.attributes[T];c[T]=new E.constructor(new E.array.constructor(E.count*E.itemSize),E.itemSize,E.normalized);const M=r.morphAttributes[T];M&&(h[T]||(h[T]=[]),M.forEach((I,C)=>{const x=new I.array.constructor(I.count*I.itemSize);h[T][C]=new I.constructor(x,I.itemSize,I.normalized)}))}const m=e*.5,A=Math.log10(1/e),g=Math.pow(10,A),y=m*g;for(let _=0;_<a;_++){const b=n?n.getX(_):_;let T="";for(let E=0,M=l.length;E<M&&t;E++){const I=l[E],C=r.getAttribute(I),x=C.itemSize;for(let D=0;D<x;D++)T+=`${~~(C[d[D]](b)*g+y)},`}if(t&&T in i)u.push(i[T]);else{for(let E=0,M=l.length;E<M;E++){const I=l[E],C=r.getAttribute(I),x=r.morphAttributes[I],D=C.itemSize,U=c[I],O=h[I];for(let N=0;N<D;N++){const H=d[N],V=p[N];if(U[V](o,C[H](b)),x)for(let X=0,W=x.length;X<W;X++)O[X][V](o,x[X][H](b))}}t&&(i[T]=o),u.push(o),o++}}const v=r.clone();for(const _ in r.attributes){const b=c[_];if(v.setAttribute(_,new b.constructor(b.array.slice(0,o*b.itemSize),b.itemSize,b.normalized)),_ in h)for(let T=0;T<h[_].length;T++){const E=h[_][T];v.morphAttributes[_][T]=new E.constructor(E.array.slice(0,o*E.itemSize),E.itemSize,E.normalized)}}return v.setIndex(u),v}function ov(r,e){if(e===JP)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),r;if(e===oy||e===Uw){let t=r.getIndex();if(t===null){const a=[],o=r.getAttribute("position");if(o!==void 0){for(let l=0;l<o.count;l++)a.push(l);r.setIndex(a),t=r.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),r}const i=t.count-2,n=[];if(e===oy)for(let a=1;a<=i;a++)n.push(t.getX(0)),n.push(t.getX(a)),n.push(t.getX(a+1));else for(let a=0;a<i;a++)a%2===0?(n.push(t.getX(a)),n.push(t.getX(a+1)),n.push(t.getX(a+2))):(n.push(t.getX(a+2)),n.push(t.getX(a+1)),n.push(t.getX(a)));n.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const s=r.clone();return s.setIndex(n),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),r}function T3(r){const e=new S,t=new S,i=new S,n=new S,s=new S,a=new S,o=new S,l=new S,c=new S;function h(ce,ue,we,Pe,Qe,ie,oe,me){e.fromBufferAttribute(ue,Qe),t.fromBufferAttribute(ue,ie),i.fromBufferAttribute(ue,oe);const Ce=ce.morphTargetInfluences;if(we&&Ce){o.set(0,0,0),l.set(0,0,0),c.set(0,0,0);for(let Xe=0,dt=we.length;Xe<dt;Xe++){const Ke=Ce[Xe],gt=we[Xe];Ke!==0&&(n.fromBufferAttribute(gt,Qe),s.fromBufferAttribute(gt,ie),a.fromBufferAttribute(gt,oe),Pe?(o.addScaledVector(n,Ke),l.addScaledVector(s,Ke),c.addScaledVector(a,Ke)):(o.addScaledVector(n.sub(e),Ke),l.addScaledVector(s.sub(t),Ke),c.addScaledVector(a.sub(i),Ke)))}e.add(o),t.add(l),i.add(c)}ce.isSkinnedMesh&&(ce.applyBoneTransform(Qe,e),ce.applyBoneTransform(ie,t),ce.applyBoneTransform(oe,i)),me[Qe*3+0]=e.x,me[Qe*3+1]=e.y,me[Qe*3+2]=e.z,me[ie*3+0]=t.x,me[ie*3+1]=t.y,me[ie*3+2]=t.z,me[oe*3+0]=i.x,me[oe*3+1]=i.y,me[oe*3+2]=i.z}const u=r.geometry,d=r.material;let p,m,A;const g=u.index,y=u.attributes.position,v=u.morphAttributes.position,_=u.morphTargetsRelative,b=u.attributes.normal,T=u.morphAttributes.position,E=u.groups,M=u.drawRange;let I,C,x,D,U,O,N;const H=new Float32Array(y.count*y.itemSize),V=new Float32Array(b.count*b.itemSize);if(g!==null)if(Array.isArray(d))for(I=0,x=E.length;I<x;I++)for(U=E[I],O=Math.max(U.start,M.start),N=Math.min(U.start+U.count,M.start+M.count),C=O,D=N;C<D;C+=3)p=g.getX(C),m=g.getX(C+1),A=g.getX(C+2),h(r,y,v,_,p,m,A,H),h(r,b,T,_,p,m,A,V);else for(O=Math.max(0,M.start),N=Math.min(g.count,M.start+M.count),I=O,x=N;I<x;I+=3)p=g.getX(I),m=g.getX(I+1),A=g.getX(I+2),h(r,y,v,_,p,m,A,H),h(r,b,T,_,p,m,A,V);else if(Array.isArray(d))for(I=0,x=E.length;I<x;I++)for(U=E[I],O=Math.max(U.start,M.start),N=Math.min(U.start+U.count,M.start+M.count),C=O,D=N;C<D;C+=3)p=C,m=C+1,A=C+2,h(r,y,v,_,p,m,A,H),h(r,b,T,_,p,m,A,V);else for(O=Math.max(0,M.start),N=Math.min(y.count,M.start+M.count),I=O,x=N;I<x;I+=3)p=I,m=I+1,A=I+2,h(r,y,v,_,p,m,A,H),h(r,b,T,_,p,m,A,V);const X=new Ee(H,3),W=new Ee(V,3);return{positionAttribute:y,normalAttribute:b,morphedPositionAttribute:X,morphedNormalAttribute:W}}function I3(r){if(r.groups.length===0)return console.warn("THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge."),r;let e=r.groups;if(e=e.sort((a,o)=>a.materialIndex!==o.materialIndex?a.materialIndex-o.materialIndex:a.start-o.start),r.getIndex()===null){const a=r.getAttribute("position"),o=[];for(let l=0;l<a.count;l+=3)o.push(l,l+1,l+2);r.setIndex(o)}const t=r.getIndex(),i=[];for(let a=0;a<e.length;a++){const o=e[a],l=o.start,c=l+o.count;for(let h=l;h<c;h++)i.push(t.getX(h))}r.dispose(),r.setIndex(i);let n=0;for(let a=0;a<e.length;a++){const o=e[a];o.start=n,n+=o.count}let s=e[0];r.groups=[s];for(let a=1;a<e.length;a++){const o=e[a];s.materialIndex===o.materialIndex?s.count+=o.count:(s=o,r.groups.push(s))}return r}function P3(r,e=Math.PI/3){const t=Math.cos(e),i=(1+1e-10)*100,n=[new S,new S,new S],s=new S,a=new S,o=new S,l=new S;function c(A){const g=~~(A.x*i),y=~~(A.y*i),v=~~(A.z*i);return`${g},${y},${v}`}const h=r.index?r.toNonIndexed():r,u=h.attributes.position,d={};for(let A=0,g=u.count/3;A<g;A++){const y=3*A,v=n[0].fromBufferAttribute(u,y+0),_=n[1].fromBufferAttribute(u,y+1),b=n[2].fromBufferAttribute(u,y+2);s.subVectors(b,_),a.subVectors(v,_);const T=new S().crossVectors(s,a).normalize();for(let E=0;E<3;E++){const M=n[E],I=c(M);I in d||(d[I]=[]),d[I].push(T)}}const p=new Float32Array(u.count*3),m=new Ze(p,3,!1);for(let A=0,g=u.count/3;A<g;A++){const y=3*A,v=n[0].fromBufferAttribute(u,y+0),_=n[1].fromBufferAttribute(u,y+1),b=n[2].fromBufferAttribute(u,y+2);s.subVectors(b,_),a.subVectors(v,_),o.crossVectors(s,a).normalize();for(let T=0;T<3;T++){const E=n[T],M=c(E),I=d[M];l.set(0,0,0);for(let C=0,x=I.length;C<x;C++){const D=I[C];o.dot(D)>t&&l.add(D)}l.normalize(),m.setXYZ(y+T,l.x,l.y,l.z)}}return h.setAttribute("normal",m),h}function D3(r,e=!1){return console.warn("THREE.BufferGeometryUtils: mergeBufferGeometries() has been renamed to mergeGeometries()."),_E(r,e)}function R3(r){return console.warn("THREE.BufferGeometryUtils: mergeBufferAttributes() has been renamed to mergeAttributes()."),Pm(r)}function lv(r,e=-1){return vE(r,e)}function Oi(){return Ft.generateUUID()}function cv(...r){if(r.length>1)return r.some(i=>cv(i));const e=r[0];if(e.isTexture)return Array.from(e.appliedObjects||[]).some(i=>cv(i))??!1;const t=e.isObject3D?[e]:e.appliedMeshes;for(const i of t){let n=!1;if(i.traverseAncestors(s=>s.isScene&&(n=!0)),n)return!0}return!1}function bE(r,e,t=new $e){return e.premultiply(r.getWorldQuaternion(t).invert())}function B3(r,e,t=new $e){return e.premultiply(r.getWorldQuaternion(t))}function cd(r,e,t,i=!1){const n=i?ju(r,e,!1):r in e?e[r]:void 0;n&&n.isTexture&&t.set(r,n)}function hv(r){if(!r)return Qt;const e=r.extensions.has("EXT_color_buffer_half_float")||r.capabilities.isWebGL2&&r.extensions.has("EXT_color_buffer_float"),t=r.capabilities.isWebGL2||r.extensions.has("OES_texture_float")||r.extensions.has("WEBGL_color_buffer_float");return e?Yt:t?Ut:Qt}function uv(r,e,t){const i=t?.data??new Uint8ClampedArray(r.height*r.width*4),n=r.data instanceof Float32Array,s=r.data instanceof Uint16Array;for(let a=0;a<i.length;a++)n?i[a]=r.data[a]*255:s?i[a]=zn.fromHalfFloat(r.data[a])*255:i[a]=r.data[a],e===Bt&&(i[a]=_S(i[a]/255)*255);return t??new ImageData(i,r.width,r.height)}function Rm(r,e,t=!1){let i;return r.isDataTexture?i=uv(r.image,r.colorSpace):i=r.image,wE(i,e,t)}function wE(r,e,t=!1){let i,n;window.VideoFrame||(window.VideoFrame=HTMLVideoElement),r instanceof window.VideoFrame?(i=r.displayWidth,n=r.displayHeight):(i=r.width||r.videoWidth||r.naturalWidth||1,n=r.height||r.videoHeight||r.naturalHeight||1),window.VideoFrame===HTMLVideoElement&&delete window.VideoFrame;const s=document.createElement("canvas");s.width=Math.min(e,i),s.height=Math.floor(1+s.width*n/i);const a=s.getContext("2d");if(!a)return console.error("textureToDataUrl: could not get canvas context"),s;t===!0&&(a.translate(0,s.height),a.scale(1,-1));let o=!1;if(r.data!==void 0){const l=r;if(i!==s.width||n!==s.height){const c=document.createElement("canvas");c.width=i,c.height=n;const h=c.getContext("2d");h?(h.putImageData(l,0,0),a.drawImage(c,0,0,s.width,s.height)):(console.error("textureToDataUrl: could not get temp canvas context"),a.putImageData(l,0,0))}else a.putImageData(l,0,0),t&&(o=!0)}else a.drawImage(r,0,0,s.width,s.height);return o?B_(s):s}function L3(r,e,t,i,n){return Rm(r,e,t).toDataURL(i,n)}async function O3(r,e,t,i,n){const s=Rm(r,e,t);return new Promise((a,o)=>{s.toBlob(l=>{l?a(l):o(new Error("Failed to create blob"))},i,n)})}const U3={None:gn,Normal:Sr,Additive:df,Subtractive:ff,Multiply:pf,Custom:er},F3={UV:Kh,Cube:Yr,CubeUV:Kl,Equirectangular:$r},N3={None:"",SRGB:Ct,LinearSRGB:Bt,RGBM16:Fs,DisplayP3:nu},k3={UnsignedByte:Qt,Byte:LA,Short:OA,UnsignedShort:Jl,Int:gf,UnsignedInt:tr,Float:Ut,HalfFloat:Yt,UnsignedShort4444:Af,UnsignedShort5551:yf,UnsignedInt248:Po},G3={Basic:If,RGBA:sc,RGB:ZP,RG:eD};function hd(r){return{map:r,inv:Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),uiConfig:Object.entries(r).map(([e,t])=>({label:e,value:t}))}}const dv={Blending:hd(U3),AnyMapping:hd(F3),ColorSpace:hd(N3),TextureDataType:hd(k3),DepthPackingStrategies:hd(G3)},Bm=new ImageData(new Uint8ClampedArray([255,255,255,255]),1,1),Lm=new kt(Bm);var z3=Object.defineProperty,fv=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&z3(e,t,n),n};const Om=(Oa=class extends xi{constructor(e,t,i,n){super(),this.hoverEnabled=!1,this.multiSelectEnabled=!0,this.selectionMode="object",this.pickingMode="auto",this.extraObjects=[],this._mouseDownPos=new K,this._onSelectedRemoved=s=>{const a=s.target;if(this._selected.includes(a)){const o=this._selected.filter(l=>l!==a);this.setSelected(o.length?o.length===1?o[0]:o:null,!1)}},this._onPointerMove=s=>{if(s.isPrimary!==!1&&(this.updateMouseFromEvent(s),this.hoverEnabled)){const{obj:a,intersects:o}=this._hitObject();this.setHoverObject(a,!0,o||void 0)}},this._onPointerLeave=s=>{s.isPrimary!==!1&&(this.domElement.style.cursor=this.cursorStyles.default,(this.hoverEnabled||this.hoverObject)&&this.setHoverObject(null))},this._onPointerEnter=s=>{},this._onPointerCancel=s=>{},this._onPointerDown=s=>{s.isPrimary!==!1&&(this.domElement.style.cursor=this.cursorStyles.down,this._mouseDownTime=this.time,this._mouseDownPos.copy(this.mouse))},this._onPointerUp=s=>{if(s.isPrimary===!1)return;this.domElement.style.cursor=this.cursorStyles.default,this._mouseUpTime=this.time;const a=this.mouseDownDeltaTime,o=this._mouseDownPos.distanceTo(this.mouse);a<Oa.PointerClickMaxTime&&o<Oa.PointerClickMaxDistance&&this._onPointerClick(s)},this._onPointerClick=s=>{if(s.isPrimary===!1)return;this.updateMouseFromEvent(s);const{obj:a,intersects:o}=this._hitObject();if(!o?.consumed)if(this.multiSelectEnabled&&(s.shiftKey||s.ctrlKey||s.metaKey)&&a&&this.selectionMode==="object"){const l=[...this._selected],c=l.indexOf(a);c>=0?l.splice(c,1):l.unshift(a),this.setSelected(l.length?l.length===1?l[0]:l:null,!0)}else this.setSelected(a,!0,o||void 0)},this._root=e,this._camera=i,this.domElement=t,this._time=this.time,this._mouseDownTime=0,this._mouseUpTime=1,this.selectionCondition=n??(s=>s.userData.userSelectable!==!1&&s.userData.bboxVisible!==!1&&s.material!=null&&s.material.type!=="ShadowMaterial"),this.raycaster=new zu,this.raycaster.params.Line2={threshold:.01},this.mouse=new K,this._selected=[],this._hovering=[],this.cursorStyles={default:"grab",down:"grabbing"},this.domElement.style.touchAction="none",this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerleave",this._onPointerLeave),this.domElement.addEventListener("pointerout",this._onPointerLeave),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("pointerenter",this._onPointerEnter),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerUp)}dispose(){this.setSelected(null),this.setHoverObject(null),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerleave",this._onPointerLeave),this.domElement.removeEventListener("pointerout",this._onPointerLeave),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("pointerenter",this._onPointerEnter),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp)}get camera(){return this._camera}set camera(e){this._camera=e}get selectedObject(){return this._selected.length>0?this._selected[0]:null}get selectedObjects(){return[...this._selected]}setSelected(e,t=!0,i){e&&(e?.isObject3D&&this.selectionMode!=="object"?this.selectionMode="object":e?.isMaterial&&this.selectionMode!=="material"?this.selectionMode="material":e?.isTexture&&this.selectionMode!=="texture"?this.selectionMode="texture":e?.isBufferGeometry&&this.selectionMode!=="geometry"&&(this.selectionMode="geometry"));const n=this._selectedIntersects;if(Array.isArray(e)){if(this._selected.length===e.length&&this._selected.every((o,l)=>o===e[l]))return}else if(!this._selected.length&&!e||this._selected.length===1&&this._selected[0]===e&&n?.selectedObject===i?.selectedObject&&n?.selectedWidget===i?.selectedWidget&&n?.selectedHandle===i?.selectedHandle)return;const s=[...this._selected];this._selected=e?Array.isArray(e)?[...e]:[e]:[],this._selectedIntersects=i||void 0;for(const o of s)o&&o.removeEventListener&&o.removeEventListener("__unregister",this._onSelectedRemoved);for(const o of this._selected)o&&o.addEventListener&&o.addEventListener("__unregister",this._onSelectedRemoved);const a=this.selectedObject;this.dispatchEvent({type:"selectedObjectChanged",object:a?.isObject3D?a:null,objects:[...this._selected],material:a?.isMaterial?a:null,value:a,lastValue:s.length?s[0]:null,lastValues:[...s],intersects:i}),t&&this.undoManager?.record({undo:()=>this.setSelected(s.length?s.length===1?s[0]:s:null,!1,n),redo:()=>this.setSelected(e,!1,i)})}get hoverObject(){return this._hovering.length>0?this._hovering[0]:null}setHoverObject(e,t=!0,i){if(!this._hovering.length&&!e||this._hovering.length===1&&this._hovering[0]===e&&this._hoveringIntersects?.selectedObject===i?.selectedObject&&this._hoveringIntersects?.selectedWidget===i?.selectedWidget&&this._hoveringIntersects?.selectedHandle===i?.selectedHandle)return;this._hovering=e?Array.isArray(e)?[...e]:[e]:[],this._hoveringIntersects=i||void 0;const n=this.hoverObject;this.dispatchEvent({type:"hoverObjectChanged",object:n?.isObject3D?n:null,material:n?.isMaterial?n:null,value:n,intersects:i})}get time(){return this._time=Cn(),this._time}get isMouseDown(){return this.mouseDownDeltaTime<0}get mouseDownDeltaTime(){return this._mouseUpTime-this._mouseDownTime}updateMouseFromEvent(e){const t=this.domElement.getBoundingClientRect();this.mouse.x=(e.clientX-t.x)/t.width*2-1,this.mouse.y=-((e.clientY-t.y)/t.height)*2+1}_hitObject(){const e=this.checkIntersection();e?this.dispatchEvent({type:"hitObject",time:this.time,intersects:e}):this.dispatchEvent({type:"hitObject",time:this.time,intersects:{selectedObject:null,intersect:null,intersects:[],mouse:this.mouse.clone()}});let t=e?.selectedObject||null;if(t)switch(this.pickingMode==="auto"?this.selectionMode:this.pickingMode){case"material":t.material&&(t=Array.isArray(t.material)?t.material[0]:t.material);break;case"texture":if(t.material){const n=Array.isArray(t.material)?t.material[0]:t.material;t=n.map||n.normalMap||n.roughnessMap||n.metalnessMap||n.aoMap||null}else t=null;break;case"geometry":t=t.geometry||null;break}return{obj:t,intersects:e}}checkIntersection(){const e=this._camera;if(!e)return null;this.raycaster.setFromCamera(this.mouse,e);let t=this.raycaster.intersectObjects([this._root,...this.extraObjects],!0);const i=[];t=t.filter(l=>i.includes(l.object.id)?!1:(i.push(l.object.id),!0));let s=null,a;const o=[];for(const l of t){for(s=l.object,a=l;s!=null&&(!s.visible||!this.selectionCondition(s));)s=s.parent;s!=null&&(l.object=s,o.push(l))}if(t=o,t.length>0){if(s=t[0].object,a=t[0],this._firstHit&&s.id!==this._firstHit.id)s=a.object;else for(let l=0;l<t.length;l++)if(this.selectedObject&&this.selectedObject.id===t[l].object.id){const c=l+1;if(c<t.length)a=t[c],s=a.object;else return null}this._firstHit=t[0].object}return s&&a&&s?{selectedObject:s,intersect:a,intersects:t,mouse:this.mouse.clone()}:null}isHovering(){return this.hoverObject!=null}isSelected(){return this.selectedObject!=null}},Oa.PointerClickMaxTime=200,Oa.PointerClickMaxDistance=.1,Oa);fv([io("multiSelectChanged")],Om.prototype,"multiSelectEnabled"),fv([io("selectionModeChanged")],Om.prototype,"selectionMode"),fv([io("pickingModeChanged")],Om.prototype,"pickingMode");let CE=Om;function pv(r){if(!r.isMaterial&&!r.isBufferGeometry)return;const e=Array.from(r.appliedMeshes).filter(s=>!s.isInstancedMesh&&!!s.parent&&s.children.length===0&&!Array.isArray(s.material));if(e.length<2)return;const t=s=>s.parent.uuid+"_"+s.geometry?.uuid+"_"+s.material?.uuid,i=new Map;for(const s of e){const a=t(s);i.has(a)||i.set(a,[]),i.get(a).push(s),s.updateMatrix()}const n=i.keys();for(const s of n){const a=i.get(s),o=a[0];if(!o||a.length<2)continue;const l=new Oc(o.geometry,o.material,a.length),c=o.userData;o.userData={},l.copy(o),Hm(l.userData,c);const h=o.parent;l.position.set(0,0,0),l.rotation.set(0,0,0),l.scale.set(1,1,1),l.updateMatrix();const u=new Float32Array(l.count*3),d=new Float32Array(l.count*4),p=new Float32Array(l.count*3);for(let m=0;m<a.length;m++){const A=a[m],g=A.matrix;g.determinant()<0&&(g.elements[0]*=-1,g.elements[1]*=-1,g.elements[2]*=-1),l.setMatrixAt(m,g),A.position.toArray(u,m*3),A.quaternion.toArray(d,m*4),A.scale.toArray(p,m*3),A.removeFromParent(),A.material=void 0,A.geometry=void 0}l.sourceTrs={TRANSLATION:new Ze(u,3),ROTATION:new Ze(d,4),SCALE:new Ze(p,3)},l.instanceMatrix.needsUpdate=!0,h.add(l),h.setDirty()}}const xE={name:"HorizontalBlurShader",uniforms:{tDiffuse:{value:null},h:{value:1/512}},vertexShader:`

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,fragmentShader:`

		uniform sampler2D tDiffuse;
		uniform float h;

		varying vec2 vUv;

		void main() {

			vec4 sum = vec4( 0.0 );

			sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051;
			sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
			sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051;

			gl_FragColor = sum;

		}`},SE={name:"VerticalBlurShader",uniforms:{tDiffuse:{value:null},v:{value:1/512}},vertexShader:`

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,fragmentShader:`

		uniform sampler2D tDiffuse;
		uniform float v;

		varying vec2 vUv;

		void main() {

			vec4 sum = vec4( 0.0 );

			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051;

			gl_FragColor = sum;

		}`};class EE{constructor(e){this._viewer=e,this.horizontalBlurMaterial=new nn(xE),this.verticalBlurMaterial=new nn(SE),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial.depthTest=!1}blur(e,t,i,n=1){this.horizontalBlurMaterial.uniforms.h.value=n,this.verticalBlurMaterial.uniforms.v.value=n,this._viewer.renderManager.blit(i,{material:this.horizontalBlurMaterial,clear:!0,source:e}),this._viewer.renderManager.blit(t,{material:this.verticalBlurMaterial,clear:!0,source:i.texture})}dispose(){this.horizontalBlurMaterial.dispose(),this.verticalBlurMaterial.dispose()}}function mv(r,e,t,i=7,n=new S(0,0,1.5),s=new zi(45,1,.1,1e3)){const a=e.visible;e.visible=!0;const o=new En().expandByObject(e,!0,!0),l=o.getCenter(new S),c=o.getSize(new S);s.position.copy(l).add(n.clone().multiplyScalar(Math.max(c.x,c.y,c.z))),s.lookAt(l),e&&e.traverseVisible(p=>{p.layers.enable(i)}),i>0?s.layers.set(i):s.layers.enableAll(),r.setRenderTarget(null);const h=r.getClearColor(new ee),u=r.getClearAlpha();r.setClearColor(0,0);let d;try{r.clear(),typeof r.renderWithModes=="function"?r.renderWithModes({backgroundRender:!1},()=>{r.render(t??e,s)}):r.render(t??e,s),d=r.domElement.toDataURL("image/png"),r.clear()}finally{r.setClearColor(h,u)}return e.visible=a,e.traverseVisible(p=>{p.layers.disable(i)}),s.layers.enableAll(),d}class ME{constructor(){this._lights=[],this.shapes={sphere:new _e(new Is(1)),cube:new _e(new gi(1,1,1)),cylinder:new _e(new sn(.5,.5,1))};const e=new Qo;this._channel=7;const t=new $p(16777215,4473924,1);t.position.set(0,10,0),t.layers.set(this._channel),e.add(t),this._lights.push(t),this._scene=e}dispose(){[...this._lights].forEach(e=>e.dispose()),Object.values(this.shapes).forEach(e=>{e.geometry&&e.geometry.dispose()})}generate(e,t,i,n="sphere"){const s=this.shapes[n]||new _e(new Is(1));s.material=e,s.geometry.attributes.tangent||s.geometry.computeTangents(),this._scene.add(s),this._scene.environment=i??null;const a=e.envMapIntensity;typeof a=="number"&&(e.envMapIntensity=Math.max(a,2));const o=mv(t,s,this._scene,this._channel,new S(0,0,1.5));return typeof a=="number"&&(e.envMapIntensity=a),this._scene.remove(s),s.material=void 0,o}}const TE=new en,Um=new S;class Gs extends A_{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type="LineSegmentsGeometry";const e=[-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],t=[-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],i=[0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5];this.setIndex(i),this.setAttribute("position",new Ee(e,3)),this.setAttribute("uv",new Ee(t,2))}applyMatrix4(e){const t=this.attributes.instanceStart,i=this.attributes.instanceEnd;return t!==void 0&&(t.applyMatrix4(e),i.applyMatrix4(e),t.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));const i=new Gu(t,6,1);return this.setAttribute("instanceStart",new Rn(i,3,0)),this.setAttribute("instanceEnd",new Rn(i,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));const i=new Gu(t,6,1);return this.setAttribute("instanceColorStart",new Rn(i,3,0)),this.setAttribute("instanceColorEnd",new Rn(i,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new Xp(e.geometry)),this}fromLineSegments(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new en);const e=this.attributes.instanceStart,t=this.attributes.instanceEnd;e!==void 0&&t!==void 0&&(this.boundingBox.setFromBufferAttribute(e),TE.setFromBufferAttribute(t),this.boundingBox.union(TE))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un),this.boundingBox===null&&this.computeBoundingBox();const e=this.attributes.instanceStart,t=this.attributes.instanceEnd;if(e!==void 0&&t!==void 0){const i=this.boundingSphere.center;this.boundingBox.getCenter(i);let n=0;for(let s=0,a=e.count;s<a;s++)Um.fromBufferAttribute(e,s),n=Math.max(n,i.distanceToSquared(Um)),Um.fromBufferAttribute(t,s),n=Math.max(n,i.distanceToSquared(Um));this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&console.error("THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.",this)}}toJSON(){}applyMatrix(e){return console.warn("THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4()."),this.applyMatrix4(e)}}De.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new K(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},Di.line={uniforms:ko.merge([De.common,De.fog,De.line]),vertexShader:`
		#include <common>
		#include <color_pars_vertex>
		#include <fog_pars_vertex>
		#include <logdepthbuf_pars_vertex>
		#include <clipping_planes_pars_vertex>

		uniform float linewidth;
		uniform vec2 resolution;

		attribute vec3 instanceStart;
		attribute vec3 instanceEnd;

		attribute vec3 instanceColorStart;
		attribute vec3 instanceColorEnd;

		#ifdef WORLD_UNITS

			varying vec4 worldPos;
			varying vec3 worldStart;
			varying vec3 worldEnd;

			#ifdef USE_DASH

				varying vec2 vUv;

			#endif

		#else

			varying vec2 vUv;

		#endif

		#ifdef USE_DASH

			uniform float dashScale;
			attribute float instanceDistanceStart;
			attribute float instanceDistanceEnd;
			varying float vLineDistance;

		#endif

		void trimSegment( const in vec4 start, inout vec4 end ) {

			// trim end segment so it terminates between the camera plane and the near plane

			// conservative estimate of the near plane
			float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
			float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
			float nearEstimate = - 0.5 * b / a;

			float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );

			end.xyz = mix( start.xyz, end.xyz, alpha );

		}

		void main() {

			#ifdef USE_COLOR

				vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;

			#endif

			#ifdef USE_DASH

				vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
				vUv = uv;

			#endif

			float aspect = resolution.x / resolution.y;

			// camera space
			vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
			vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );

			#ifdef WORLD_UNITS

				worldStart = start.xyz;
				worldEnd = end.xyz;

			#else

				vUv = uv;

			#endif

			// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
			// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
			// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
			// perhaps there is a more elegant solution -- WestLangley

			bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column

			if ( perspective ) {

				if ( start.z < 0.0 && end.z >= 0.0 ) {

					trimSegment( start, end );

				} else if ( end.z < 0.0 && start.z >= 0.0 ) {

					trimSegment( end, start );

				}

			}

			// clip space
			vec4 clipStart = projectionMatrix * start;
			vec4 clipEnd = projectionMatrix * end;

			// ndc space
			vec3 ndcStart = clipStart.xyz / clipStart.w;
			vec3 ndcEnd = clipEnd.xyz / clipEnd.w;

			// direction
			vec2 dir = ndcEnd.xy - ndcStart.xy;

			// account for clip-space aspect ratio
			dir.x *= aspect;
			dir = normalize( dir );

			#ifdef WORLD_UNITS

				vec3 worldDir = normalize( end.xyz - start.xyz );
				vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) );
				vec3 worldUp = normalize( cross( worldDir, tmpFwd ) );
				vec3 worldFwd = cross( worldDir, worldUp );
				worldPos = position.y < 0.5 ? start: end;

				// height offset
				float hw = linewidth * 0.5;
				worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp;

				// don't extend the line if we're rendering dashes because we
				// won't be rendering the endcaps
				#ifndef USE_DASH

					// cap extension
					worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir;

					// add width to the box
					worldPos.xyz += worldFwd * hw;

					// endcaps
					if ( position.y > 1.0 || position.y < 0.0 ) {

						worldPos.xyz -= worldFwd * 2.0 * hw;

					}

				#endif

				// project the worldpos
				vec4 clip = projectionMatrix * worldPos;

				// shift the depth of the projected points so the line
				// segments overlap neatly
				vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
				clip.z = clipPose.z * clip.w;

			#else

				vec2 offset = vec2( dir.y, - dir.x );
				// undo aspect ratio adjustment
				dir.x /= aspect;
				offset.x /= aspect;

				// sign flip
				if ( position.x < 0.0 ) offset *= - 1.0;

				// endcaps
				if ( position.y < 0.0 ) {

					offset += - dir;

				} else if ( position.y > 1.0 ) {

					offset += dir;

				}

				// adjust for linewidth
				offset *= linewidth;

				// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
				offset /= resolution.y;

				// select end
				vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;

				// back to clip space
				offset *= clip.w;

				clip.xy += offset;

			#endif

			gl_Position = clip;

			vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation

			#include <logdepthbuf_vertex>
			#include <clipping_planes_vertex>
			#include <fog_vertex>

		}
		`,fragmentShader:`
		uniform vec3 diffuse;
		uniform float opacity;
		uniform float linewidth;

		#ifdef USE_DASH

			uniform float dashOffset;
			uniform float dashSize;
			uniform float gapSize;

		#endif

		varying float vLineDistance;

		#ifdef WORLD_UNITS

			varying vec4 worldPos;
			varying vec3 worldStart;
			varying vec3 worldEnd;

			#ifdef USE_DASH

				varying vec2 vUv;

			#endif

		#else

			varying vec2 vUv;

		#endif

		#include <common>
		#include <color_pars_fragment>
		#include <fog_pars_fragment>
		#include <logdepthbuf_pars_fragment>
		#include <clipping_planes_pars_fragment>

		vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {

			float mua;
			float mub;

			vec3 p13 = p1 - p3;
			vec3 p43 = p4 - p3;

			vec3 p21 = p2 - p1;

			float d1343 = dot( p13, p43 );
			float d4321 = dot( p43, p21 );
			float d1321 = dot( p13, p21 );
			float d4343 = dot( p43, p43 );
			float d2121 = dot( p21, p21 );

			float denom = d2121 * d4343 - d4321 * d4321;

			float numer = d1343 * d4321 - d1321 * d4343;

			mua = numer / denom;
			mua = clamp( mua, 0.0, 1.0 );
			mub = ( d1343 + d4321 * ( mua ) ) / d4343;
			mub = clamp( mub, 0.0, 1.0 );

			return vec2( mua, mub );

		}

		void main() {

			#include <clipping_planes_fragment>

			#ifdef USE_DASH

				if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps

				if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX

			#endif

			float alpha = opacity;

			#ifdef WORLD_UNITS

				// Find the closest points on the view ray and the line segment
				vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
				vec3 lineDir = worldEnd - worldStart;
				vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );

				vec3 p1 = worldStart + lineDir * params.x;
				vec3 p2 = rayEnd * params.y;
				vec3 delta = p1 - p2;
				float len = length( delta );
				float norm = len / linewidth;

				#ifndef USE_DASH

					#ifdef USE_ALPHA_TO_COVERAGE

						float dnorm = fwidth( norm );
						alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );

					#else

						if ( norm > 0.5 ) {

							discard;

						}

					#endif

				#endif

			#else

				#ifdef USE_ALPHA_TO_COVERAGE

					// artifacts appear on some hardware if a derivative is taken within a conditional
					float a = vUv.x;
					float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
					float len2 = a * a + b * b;
					float dlen = fwidth( len2 );

					if ( abs( vUv.y ) > 1.0 ) {

						alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );

					}

				#else

					if ( abs( vUv.y ) > 1.0 ) {

						float a = vUv.x;
						float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
						float len2 = a * a + b * b;

						if ( len2 > 1.0 ) discard;

					}

				#endif

			#endif

			vec4 diffuseColor = vec4( diffuse, alpha );

			#include <logdepthbuf_fragment>
			#include <color_fragment>

			gl_FragColor = vec4( diffuseColor.rgb, alpha );

			#include <tonemapping_fragment>
			#include <colorspace_fragment>
			#include <fog_fragment>
			#include <premultiplied_alpha_fragment>

		}
		`};class $c extends nn{constructor(e){super({type:"LineMaterial",uniforms:ko.clone(Di.line.uniforms),vertexShader:Di.line.vertexShader,fragmentShader:Di.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?this.defines.USE_ALPHA_TO_COVERAGE="":delete this.defines.USE_ALPHA_TO_COVERAGE)}}const gv=new et,IE=new S,PE=new S,Bn=new et,Ln=new et,Lr=new et,Av=new S,yv=new fe,On=new x_,DE=new S,Fm=new en,Nm=new un,Or=new et;let Ur,ml;function RE(r,e,t){return Or.set(0,0,-e,1).applyMatrix4(r.projectionMatrix),Or.multiplyScalar(1/Or.w),Or.x=ml/t.width,Or.y=ml/t.height,Or.applyMatrix4(r.projectionMatrixInverse),Or.multiplyScalar(1/Or.w),Math.abs(Math.max(Or.x,Or.y))}function V3(r,e){const t=r.matrixWorld,i=r.geometry,n=i.attributes.instanceStart,s=i.attributes.instanceEnd,a=Math.min(i.instanceCount,n.count);for(let o=0,l=a;o<l;o++){On.start.fromBufferAttribute(n,o),On.end.fromBufferAttribute(s,o),On.applyMatrix4(t);const c=new S,h=new S;Ur.distanceSqToSegment(On.start,On.end,h,c),h.distanceTo(c)<ml*.5&&e.push({point:h,pointOnLine:c,distance:Ur.origin.distanceTo(h),object:r,face:null,faceIndex:o,uv:null,uv1:null})}}function H3(r,e,t){const i=e.projectionMatrix,s=r.material.resolution,a=r.matrixWorld,o=r.geometry,l=o.attributes.instanceStart,c=o.attributes.instanceEnd,h=Math.min(o.instanceCount,l.count),u=-e.near;Ur.at(1,Lr),Lr.w=1,Lr.applyMatrix4(e.matrixWorldInverse),Lr.applyMatrix4(i),Lr.multiplyScalar(1/Lr.w),Lr.x*=s.x/2,Lr.y*=s.y/2,Lr.z=0,Av.copy(Lr),yv.multiplyMatrices(e.matrixWorldInverse,a);for(let d=0,p=h;d<p;d++){if(Bn.fromBufferAttribute(l,d),Ln.fromBufferAttribute(c,d),Bn.w=1,Ln.w=1,Bn.applyMatrix4(yv),Ln.applyMatrix4(yv),Bn.z>u&&Ln.z>u)continue;if(Bn.z>u){const _=Bn.z-Ln.z,b=(Bn.z-u)/_;Bn.lerp(Ln,b)}else if(Ln.z>u){const _=Ln.z-Bn.z,b=(Ln.z-u)/_;Ln.lerp(Bn,b)}Bn.applyMatrix4(i),Ln.applyMatrix4(i),Bn.multiplyScalar(1/Bn.w),Ln.multiplyScalar(1/Ln.w),Bn.x*=s.x/2,Bn.y*=s.y/2,Ln.x*=s.x/2,Ln.y*=s.y/2,On.start.copy(Bn),On.start.z=0,On.end.copy(Ln),On.end.z=0;const A=On.closestPointToPointParameter(Av,!0);On.at(A,DE);const g=Ft.lerp(Bn.z,Ln.z,A),y=g>=-1&&g<=1,v=Av.distanceTo(DE)<ml*.5;if(y&&v){On.start.fromBufferAttribute(l,d),On.end.fromBufferAttribute(c,d),On.start.applyMatrix4(a),On.end.applyMatrix4(a);const _=new S,b=new S;Ur.distanceSqToSegment(On.start,On.end,b,_),t.push({point:b,pointOnLine:_,distance:Ur.origin.distanceTo(b),object:r,face:null,faceIndex:d,uv:null,uv1:null})}}}class va extends _e{constructor(e=new Gs,t=new $c({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,t=e.attributes.instanceStart,i=e.attributes.instanceEnd,n=new Float32Array(2*t.count);for(let a=0,o=0,l=t.count;a<l;a++,o+=2)IE.fromBufferAttribute(t,a),PE.fromBufferAttribute(i,a),n[o]=o===0?0:n[o-1],n[o+1]=n[o]+IE.distanceTo(PE);const s=new Gu(n,2,1);return e.setAttribute("instanceDistanceStart",new Rn(s,1,0)),e.setAttribute("instanceDistanceEnd",new Rn(s,1,1)),this}raycast(e,t){const i=this.material.worldUnits,n=e.camera;n===null&&!i&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const s=e.params.Line2!==void 0&&e.params.Line2.threshold||0;Ur=e.ray;const a=this.matrixWorld,o=this.geometry,l=this.material;ml=l.linewidth+s,o.boundingSphere===null&&o.computeBoundingSphere(),Nm.copy(o.boundingSphere).applyMatrix4(a);let c;if(i)c=ml*.5;else{const u=Math.max(n.near,Nm.distanceToPoint(Ur.origin));c=RE(n,u,l.resolution)}if(Nm.radius+=c,Ur.intersectsSphere(Nm)===!1)return;o.boundingBox===null&&o.computeBoundingBox(),Fm.copy(o.boundingBox).applyMatrix4(a);let h;if(i)h=ml*.5;else{const u=Math.max(n.near,Fm.distanceToPoint(Ur.origin));h=RE(n,u,l.resolution)}Fm.expandByScalar(h),Ur.intersectsBox(Fm)!==!1&&(i?V3(this,t):H3(this,n,t))}onBeforeRender(e){const t=this.material.uniforms;t&&t.resolution&&(e.getViewport(gv),this.material.uniforms.resolution.value.set(gv.z,gv.w))}}var Q3=Object.defineProperty,j3=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Q3(e,t,n),n};const[BE,LE,OE,UE,FE,NE]=Array(6).fill(0).map((r,e)=>e),km=[new ee(16725587),new ee(9100032),new ee(2920447)],W3=new ku,oo=new S,gl=new $e,Gm=new $e,_v=new $e,ud=new S,q3=2*Math.PI,kE=new zu,vv=new K,dd=new ft;let bv=0;class wv extends ft{constructor(e,t,i="bottom-right",n=128,s=2){super(),this.orthoCamera=new Mr(-1.8,1.8,1.8,-1.8,0,4),this.isViewHelper=!0,this.animating=!1,this.target=new S,this.viewport=new et,this.offsetHeight=0,this.renderer=new hp({canvas:document.createElement("canvas"),alpha:!0,antialias:!0,preserveDrawingBuffer:!1}),this.renderer.setPixelRatio(s),this.camera=e,this.domElement=t,this.orthoCamera.position.set(0,0,2),this.backgroundSphere=$3(),this.axesLines=Y3(),this.spritePoints=K3(),this.add(this.backgroundSphere,this.axesLines,...this.spritePoints),this.domContainer=X3(i,n),this.domContainer.appendChild(this.renderer.domElement),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.domElement.parentElement.appendChild(this.domContainer),this.domRect=this.domContainer.getBoundingClientRect(),this.startListening(),this.update(),this.updateOrientation()}startListening(){this.domContainer.onpointermove=e=>this.onPointerMove(e),this.domContainer.onpointerleave=e=>this.onPointerLeave(e),this.domContainer.onclick=e=>this.handleClick(e)}onPointerMove(e){this.backgroundSphere.material.opacity=.4,this.handleHover(e),this.dispatchEvent({type:"update",event:e,change:"pointer"})}onPointerLeave(e){this.backgroundSphere.material.opacity=.2,VE(this.spritePoints),this.domContainer.style.cursor="",this.dispatchEvent({type:"update",event:e,change:"pointer"})}handleClick(e){const t=zE(e,this.domRect,this.orthoCamera,this.spritePoints);t&&this.setOrientation(t.userData.type)}handleHover(e){const t=zE(e,this.domRect,this.orthoCamera,this.spritePoints);VE(this.spritePoints),t?(t.material.map.offset.x=.5,t.scale.multiplyScalar(1.2),this.domContainer.style.cursor="pointer"):this.domContainer.style.cursor=""}render(){const e=W3.getDelta();this.animating&&this.animate(Math.min(e,1/30));const t=this.renderer.autoClear;this.renderer.autoClear=!1,this.renderer.render(this,this.orthoCamera),this.renderer.autoClear=t}updateOrientation(e=!0){e&&(this.quaternion.copy(this.camera.quaternion).invert(),this.updateMatrixWorld()),iN(this.spritePoints,this.camera)}update(){this.domRect=this.domContainer.getBoundingClientRect(),this.offsetHeight=this.domElement.offsetHeight,GE(this.camera,this.target),this.renderer.getViewport(this.viewport),this.updateOrientation()}animate(e){const t=e*q3;Gm.rotateTowards(_v,t),this.camera.position.set(0,0,1).applyQuaternion(Gm).multiplyScalar(bv).add(this.target),this.camera.quaternion.rotateTowards(gl,t),this.updateOrientation(),Gm.angleTo(_v)===0&&(this.animating=!1)}setOrientation(e){Z3(this.camera,this.target,e),this.animating=!0,this.dispatchEvent({type:"update",change:"orientation"})}dispose(){this.axesLines.geometry.dispose(),this.axesLines.material.dispose(),this.backgroundSphere.geometry.dispose(),this.backgroundSphere.material.dispose(),this.spritePoints.forEach(e=>{e.material.map.dispose(),e.material.dispose()}),this.domContainer.remove()}}j3([io()],wv.prototype,"animating");function X3(r,e){const t=document.createElement("div"),i=t.style;i.height=`${e}px`,i.width=`${e}px`,i.borderRadius="100%",i.position="absolute";const[n,s]=r.split("-");return i.transform="",i.left=s==="left"?"0":s==="center"?"50%":"",i.right=s==="right"?"0":"",i.transform+=s==="center"?"translateX(-50%)":"",i.top=n==="top"?"0":n==="bottom"?"":"50%",i.bottom=n==="bottom"?"0":"",i.transform+=n==="center"?"translateY(-50%)":"",t}function Y3(){const e=Array(3).fill(0).map((n,s)=>[s?0:.9,s===1?.9:0,s===2?.9:0,0,0,0]).flat(),t=Array(6).fill(0).map((n,s)=>s<2?km[0].toArray():s<4?km[1].toArray():km[2].toArray()).flat(),i=new Gs;return i.setPositions(e),i.setColors(t),new va(i,new $c({linewidth:.02,vertexColors:!0}))}function $3(){const r=new Is(1.6);return new _e(r,new is({color:16777215,side:In,transparent:!0,opacity:.2,depthTest:!1}))}function K3(){const r=["x","y","z"];return Array(6).fill(0).map((e,t)=>{const i=t<3,n=i?"+":"-",s=r[t%3],a=km[t%3],o=new mp(J3(a,i?s:null));return o.userData.type=`${n}${s}`,o.scale.setScalar(i?.6:.4),o.position[s]=i?1.2:-1.2,o.renderOrder=1,o})}function J3(r,e=null){const t=document.createElement("canvas"),i=0,n=1,s=0;t.width=128*n+4*i+s*2,t.height=64*n+2*i+s*2;const a=t.getContext("2d",{alpha:!0});a.beginPath(),a.arc(32*n+i,32*n+i,32*n-i,0,2*Math.PI),a.closePath(),a.fillStyle=r.getStyle(),a.fill(),a.beginPath(),a.arc(32*n+i,32*n+i,35*n-i,0,2*Math.PI),a.closePath(),a.fillStyle="#"+r.getHexString()+"01",a.fill(),a.beginPath(),a.arc(96*n+i*3+s,32*n+i+s,32*n-i-s,0,2*Math.PI),a.closePath(),a.fillStyle="#FFF",a.fill(),a.beginPath(),a.arc(96*n+i*3+s,32*n+i+s,35+n-i-s,0,2*Math.PI),a.closePath(),a.fillStyle="#FFFFFF01",a.fill(),e!==null&&(a.font="bold calc(44px * "+n+") Arial",a.textAlign="center",a.fillStyle="#111",a.fillText(e.toUpperCase(),32*n+i,48*n+i),a.fillText(e.toUpperCase(),96*n+i*3+s,48*n+i+s));const o=new qo(t);return o.wrapS=o.wrapT=Pn,o.repeat.x=.5,o.colorSpace=Ct,o.minFilter=at,o.magFilter=at,o.generateMipmaps=!1,o.needsUpdate=!0,new gu({map:o,toneMapped:!1,transparent:!0})}function Z3(r,e,t){switch(t){case"+x":oo.set(1,0,0),gl.setFromEuler(new Pt(0,Math.PI*.5,0));break;case"+y":oo.set(0,1,0),gl.setFromEuler(new Pt(-Math.PI*.5,0,0));break;case"+z":oo.set(0,0,1),gl.setFromEuler(new Pt);break;case"-x":oo.set(-1,0,0),gl.setFromEuler(new Pt(0,-Math.PI*.5,0));break;case"-y":oo.set(0,-1,0),gl.setFromEuler(new Pt(Math.PI*.5,0,0));break;case"-z":oo.set(0,0,-1),gl.setFromEuler(new Pt(0,Math.PI,0));break;default:console.error("ViewHelper: Invalid axis.")}GE(r,e),eN(r,e)}function GE(r,e){bv=r.position.distanceTo(e)}function eN(r,e){oo.multiplyScalar(bv).add(e),dd.position.copy(e),dd.lookAt(r.position),Gm.copy(dd.quaternion),dd.lookAt(oo),_v.copy(dd.quaternion)}function tN(r,e,t){vv.x=(r.clientX-e.left)/e.width*2-1,vv.y=-((r.clientY-e.top)/e.height)*2+1,kE.setFromCamera(vv,t)}function zE(r,e,t,i){tN(r,e,t);const n=kE.intersectObjects(i);return n.length?n[0].object:null}function VE(r){let e=r.length;for(;e--;){const t=e<3?.6:.4;r[e].scale.set(t,t,t),r[e].material.map.offset.x=1}}function iN(r,e){ud.set(0,0,1),ud.applyQuaternion(e.quaternion),ud.x>=0?(r[BE].material.opacity=1,r[UE].material.opacity=.5):(r[BE].material.opacity=.5,r[UE].material.opacity=1),ud.y>=0?(r[LE].material.opacity=1,r[FE].material.opacity=.5):(r[LE].material.opacity=.5,r[FE].material.opacity=1),ud.z>=0?(r[OE].material.opacity=1,r[NE].material.opacity=.5):(r[OE].material.opacity=.5,r[NE].material.opacity=1)}const Fb=class Fb extends Pu{constructor(){super(),this.type="CurvePath3"}};Lt.SerializableClasses.set("CurvePath3",Fb);let zm=Fb;function Vm(r,e){const t=e.getSize(new S);let i=1;if(r.isPerspectiveCamera&&t.length()>1e-4){const n=isFinite(r.aspect)?r.aspect:1,s=Math.max(1,r.fov)*(Math.PI/180),a=2*Math.atan(Math.tan(s/2)*n),o=t.z/2+Math.abs(t.x/2/Math.tan(a/2)),l=t.z/2+Math.abs(t.y/2/Math.tan(s/2));i=Math.max(o,l)}return i}const nN=r=>(e,t)=>t?.copy?.(e)??new r().copy(e),Jn=class Jn{static PrimitiveSerializer(e,t,i,n=1){return{priority:n,isType:s=>s?.[t],serialize:s=>{const a={[t]:!0};for(const o of i)a[o]=s[o];return a},deserialize:nN(e),type:t.startsWith("is")?t.slice(2):e.name}}static Init(){this._init||(this._init=!0,Ir.prototype.isSpherical=!0,Lt.RegisterSerializer(...Jn.Primitives.map(e=>Jn.PrimitiveSerializer(e[0],e[1],e[2],e[3]))),Lt.RegisterSerializer(Jn.Texture),Lt.RegisterSerializer(Jn.Material),Lt.RegisterSerializer(Jn.RenderTarget),Lt.SerializableClasses.set("Shape",rr),Lt.SerializableClasses.set("Curve",Ts),Lt.SerializableClasses.set("CurvePath",Pu),Lt.SerializableClasses.set("Path",Fc),Lt.SerializableClasses.set("ArcCurve",Ip),Lt.SerializableClasses.set("CatmullRomCurve3",Uc),Lt.SerializableClasses.set("CubicBezierCurve",Eu),Lt.SerializableClasses.set("CubicBezierCurve3",Dp),Lt.SerializableClasses.set("EllipseCurve",Xo),Lt.SerializableClasses.set("LineCurve",Yo),Lt.SerializableClasses.set("LineCurve3",$o),Lt.SerializableClasses.set("QuadraticBezierCurve",Mu),Lt.SerializableClasses.set("QuadraticBezierCurve3",Tu),Lt.SerializableClasses.set("SplineCurve",Iu),Lt.SerializableClasses.set("AnimationClip",Ja))}static MakeSerializable(e,t,i){e.prototype.serializableClassId=t,Lt.SerializableClasses.set(t,e),i&&Lt.TypeMap.set(e,i.map(n=>typeof n=="string"?[n,n]:n))}static Serialize(e,t,i=!1){return this._init||this.Init(),Lt.Serialize(e,t,i)}static Deserialize(e,t,i,n=!1){return this._init||this.Init(),Lt.Deserialize(e,t,i,n)}};Jn.Primitives=[[K,"isVector2",["x","y"],1],[S,"isVector3",["x","y","z"],1],[et,"isVector4",["x","y","z","w"],1],[$e,"isQuaternion",["x","y","z","w"],1],[Pt,"isEuler",["x","y","z","order"],1],[ee,"isColor",["r","g","b"],1],[im,"isMatrix2",["elements"],1],[At,"isMatrix3",["elements"],1],[fe,"isMatrix4",["elements"],1],[Ir,"isSpherical",["radius","phi","theta"],1]],Jn.Texture={priority:2,isType:e=>e.isTexture||e.metadata?.type==="Texture",serialize:(e,t)=>{if(!e?.isTexture)throw new Error("Expected a texture");if(e.isRenderTargetTexture)return;if(t?.textures[e.uuid])return{uuid:e.uuid,resource:"textures"};const i=e.source.data,n=!e.isRenderTargetTexture&&e.userData.rootPath&&typeof e.userData.rootPath=="string"&&Hc(e.userData.rootPath);let s={};const a=e.userData;try{n&&e.source.data&&(e.userData.embedUrlImagePreviews?e.source.data=Rm(e,16,e.flipY):e.source.data=null),e.userData={};const o={images:{}};s=e.toJSON(t||o),!t&&s.image&&(s.image=n&&!e.userData.embedUrlImagePreviews?void 0:o.images[s.image]),s.userData=Lt.Serialize(Cv({},a),t,!1)}catch(o){console.error("ThreeSerialization: Unable to serialize texture"),console.error(o)}return e.userData=a,n&&(t&&!e.userData.embedUrlImagePreviews&&delete t.images[e.source.uuid],e.source.data=i),t?.textures&&s&&!s.resource&&(t.textures[s.uuid]||(t.textures[s.uuid]=s),s={uuid:s.uuid,resource:"textures"}),s},deserialize:(e,t,i)=>{if(e.isTexture)return e;if(e.resource==="textures"&&i?.textures?.[e.uuid])return i.textures[e.uuid];console.warn("Cannot deserialize texture into object like primitive, since textures need to be loaded asynchronously. Trying with ObjectLoader. Load events might not work properly.",e,t);const n=i?._context.objectLoader??new Zp(i?._context.assetImporter?.loadingManager),s={...e};if(typeof s.image=="string"&&(i?.images?s.image=i.images[s.image]:console.error("ThreeSerialization: Cannot deserialize texture with image url without meta.images",s)),!s.image||typeof s.image=="string"||!s.image.isSource&&!s.image.url)return console.error("ThreeSerialization: Cannot deserialize texture",s),t;let a;i&&!s.image.isSource&&(i._context.imagePromises||(i._context.imagePromises=[]),i._context.imagePromises.push(new Promise(h=>{a=h})));const o=s.image.isSource?{[s.image.uuid]:s.image}:n.parseImages([s.image],a);s.image=Object.keys(o)[0],i?.images&&(i.images[s.image]=o[s.image]),s.userData&&(s.userData=Jn.Deserialize(s.userData,{},i));const l=n.parseTextures([s],o),c=Object.keys(l)[0];return!c||!l[c]?(console.error("ThreeSerialization: Cannot deserialize texture",s),t):(i?.textures&&(i.textures[c]=l[c]),l[c])}},Jn.SerializableMaterials=new Set,Jn.Material={priority:2,isType:e=>e.isMaterial||e.metadata?.type==="Material",serialize:(e,t)=>{if(!e?.isMaterial)throw new Error("Expected a material");if(t?.materials?.[e.uuid])return{uuid:e.uuid,resource:"materials"};const i=t??{textures:{},images:{}},n={},s={},a=Object.keys(e.constructor.MaterialProperties||e);for(const c of a){if(c.startsWith("__"))continue;const h=e[c];if(h?.isTexture){const u=Lt.Serialize(h,i);n[c]=u,s[c]=h,e[c]=u?{isTexture:!0,toJSON:()=>u}:null}}const o=e.userData;e.userData={};let l={};try{l=e.toJSON(t||i,!0),sN(l,o,t),l.userData.uuid=o.uuid,e.constructor.TYPE&&(l.type=e.constructor.TYPE);for(const c of Object.keys(l))l[c]===void 0&&delete l[c]}catch(c){console.error("ThreeSerialization: Unable to serialize material"),console.error(c)}e.userData=o;for(const[c,h]of Object.entries(s))e[c]=h,delete s[c];if(l)if(t){for(const[c,h]of Object.entries(n))h&&(l[c]=h);t.materials&&(t.materials[l.uuid]||(t.materials[l.uuid]=l),l={uuid:l.uuid,resource:"materials"})}else{for(const[c,h]of Object.entries(n))h&&(l[c]=h.uuid);l.textures=Object.values(i.textures),l.images=Object.values(i.images)}return l},deserialize:(e,t,i)=>{function n(m){if(m.isMaterial)return t?.isMaterial&&t.uuid===m.uuid?(t!==m&&typeof t.setValues=="function"&&(console.warn("ThreeSerialization: Material uuid already exists, copying values to old material"),t.setValues(m)),t):m}let s=n(e);if(s!==void 0)return s;if(e.resource==="materials"&&i?.materials?.[e.uuid]){if(s=n(i.materials[e.uuid]),s!==void 0)return s;console.error("ThreeSerialization: cannot find material in meta",e,s)}const a=e.type;if(!a)return console.error("ThreeSerialization: Cannot deserialize material without type",e),t;const o={...e};o.userData&&(o.userData=Lt.Deserialize(o.userData,void 0,i,!1));const l={};for(const[m,A]of Object.entries(o)){if(typeof A=="string"&&i?.textures?.[A]&&(o[m]=i.textures[A],l[m]=i.textures[A]),!A||!A.resource||typeof A.resource!="string")continue;const g=i?.[A.resource]?.[A.uuid];o[m]=g||null,A.resource==="textures"&&g?.isTexture&&(l[m]=g)}if((!t||!t.isMaterial||t.type!==a&&t.constructor?.TYPE!==a)&&(t&&Object.keys(t).length&&console.warn("ThreeSerialization: Material type mismatch during deserialize, creating a new material",t,o,a,t.constructor?.type),t=null),t&&(!o.uuid||t.uuid===o.uuid))return t.fromJSON?t.fromJSON(o,i,!0):t.setValues?t.setValues(o):console.error("ThreeSerialization: Cannot deserialize material, no fromJSON or setValues method",t,o),t;const c=e.isMaterial?void 0:e.uuid;let h=null;for(const m of Jn.SerializableMaterials)if(m.TYPE===a){h=m;break}if(!h){for(const m of Jn.SerializableMaterials)if(m.TypeAlias?.includes(a)){h=m;break}}if(h){const m=new h;if(m)return c&&an(m,"uuid",c,!0,!0),m.fromJSON?m.fromJSON(o,i,!0):m.setValues?m.setValues(o):console.error("ThreeSerialization: Cannot deserialize material, no fromJSON or setValues method",m,o),m}console.warn("Legacy three.js material deserialization");const u=new Nu;for(const[m,A]of Object.entries(l))o[m]=A.uuid;const d={...u.textures};u.setTextures(l);const p=u.parse(o);if(o.uuid&&an(p,"uuid",o.uuid,!0,!0),u.setTextures(d),s=n(p),s!==void 0)return s;console.error("ThreeSerialization: cannot deserialize material",e,s,p)}},Jn.RenderTarget={priority:2,isType:e=>e.isWebGLRenderTarget||e.metadata?.type==="RenderTarget",serialize:(e,t)=>{if(!e?.isWebGLRenderTarget||!e.uuid)throw new Error("Expected a IRenderTarget");if(t?.extras[e.uuid])return{uuid:e.uuid,resource:"extras"};const i=Array.isArray(e.texture)?e.texture[0]:e.texture;let n={metadata:{type:"RenderTarget"},uuid:e.uuid,width:e.width,height:e.height,depth:e.depth,sizeMultiplier:e.sizeMultiplier,count:Array.isArray(e.texture)?e.texture.length:void 0,isCubeRenderTarget:e.isWebGLCubeRenderTarget||void 0,isTemporary:e.isTemporary,textureName:Array.isArray(e.texture)?e.texture.map(s=>s.name):e.texture?.name,options:{wrapS:i?.wrapS,wrapT:i?.wrapT,magFilter:i?.magFilter,minFilter:i?.minFilter,format:i?.format,type:i?.type,anisotropy:i?.anisotropy,depthBuffer:!!e.depthBuffer,stencilBuffer:!!e.stencilBuffer,generateMipmaps:i?.generateMipmaps,depthTexture:!!e.depthTexture,colorSpace:i?.colorSpace,samples:e.samples}};return t?.extras&&(t.extras[n.uuid]||(t.extras[n.uuid]=n),n={uuid:n.uuid,resource:"extras"}),n},deserialize:(e,t,i)=>{if(t?.uuid===e.uuid)return t;if(e.isWebGLRenderTarget)return e;const n=i?._context.renderManager;if(!n)return console.error("ThreeSerialization: Cannot deserialize render target without render manager",e),t;if(e.isWebGLCubeRenderTarget||e.isTemporary)return console.warn("ThreeSerialization: Cannot deserialize WebGLCubeRenderTarget or temporary render target yet",e),t;const s=n.createTarget({sizeMultiplier:e.sizeMultiplier||void 0,size:e.sizeMultiplier?void 0:{width:e.width,height:e.height},textureCount:e.count,...e.options});if(e.textureName)if(Array.isArray(e.textureName)&&Array.isArray(s.texture))for(let a=0;a<e.textureName.length;a++)s.texture[a].name=e.textureName[a];else Array.isArray(s.texture)||(s.texture.name=Array.isArray(e.textureName)?e.textureName[0]:e.textureName);return s&&(s.uuid=e.uuid,i?.extras&&(i.extras[e.uuid]=s),s)}},Jn._init=!1;let We=Jn;function fd(r,e,t=[]){if(!e)return r;for(const i of Object.keys(e)){if(t.includes(i)||i.startsWith("__"))continue;const n=e[i];if(typeof r[i]=="function"||typeof n=="function")continue;const s=!n||n.isTexture||n.isObject3D||n.isMaterial||n.isBufferGeometry||n.userDataSkipClone;!s&&typeof n.clone=="function"?r[i]=n.clone():!s&&(n.constructor===Object||Array.isArray(n))?r[i]=fd(Array.isArray(n)?[]:{},n,[]):r[i]=n}return r}function Cv(r,e,t=["uuid"]){return fd(r,e,t)}function xv(r,e,t=["uuid"]){return fd(r,e,t)}function Hm(r,e,t=["uuid"]){return fd(r,e,t)}function sN(r,e,t){r.userData={},xv(r.userData,e);const i=t||{textures:Object.fromEntries(r.textures?.map(n=>[n.uuid,n])||[]),images:Object.fromEntries(r.images?.map(n=>[n.uuid,n])||[])};r.userData=Lt.Serialize(r.userData,i),t||(Object.keys(i.textures).length>0&&(r.textures=Object.values(i.textures)),Object.keys(i.images).length>0&&(r.images=Object.values(i.images)))}function Sv(r){Object.values(r).forEach(e=>{e&&Object.values(e).forEach(t=>{t.url&&(!(t.url.data instanceof ArrayBuffer)&&!Array.isArray(t.url.data)||(t.url.type==="Uint16Array"?(t.url.data instanceof Uint16Array||(t.url.data=new Uint16Array(t.url.data)),t.url.data="data:application/octet-stream;base64,"+um(t.url.data.buffer)):t.url.type==="Uint8Array"?(t.url.data instanceof Uint8Array||(t.url.data=new Uint8Array(t.url.data)),t.url.data="data:application/octet-stream;base64,"+um(t.url.data.buffer)):t.url.data instanceof ArrayBuffer?t.url.data="data:application/octet-stream;base64,"+um(t.url.data.buffer):console.warn("Unsupported buffer type",t.url.type)))})})}function HE(r){Object.values(r).forEach(e=>{e&&Object.values(e).forEach(t=>{if(!t||!t.url||typeof t.url.data!="string")return;const i=t.url.data.match(/^data:.*;base64,(.*)$/);i?.[1]?t.url.data=T_(i?.[1]):(t.url.type!=="Uint8Array"&&console.error("ThreeSerialization: Unsupported buffer type string for ",t.url.type,"use base64"),t.url.data=new TextEncoder().encode(t.url.data).buffer)})})}function Fr(r){return{geometries:{...r?.geometries},materials:{...r?.materials},textures:{...r?.textures},images:{...r?.images},shapes:{...r?.shapes},skeletons:{...r?.skeletons},animations:{...r?.animations},extras:{...r?.extras},typed:{...r?.typed},nodes:{...r?.nodes},_context:{}}}class Qm{static async ImportMeta(e,t){if(e.__isLoadedResources)return e;const i=Ev();i.__isLoadedResources=!0,i._context=e._context,HE(e);const n=e._context.assetImporter;if(!n)throw new Error("assetImporter not found in meta context, which is required for import meta.");const s=e._context.objectLoader||new Zp(n.loadingManager);i.animations=e.animations?s.parseAnimations(Object.values(e.animations)):{},t&&t.animations&&(i.animations={...i.animations,...t.animations}),i.shapes=e.shapes?s.parseShapes(Object.values(e.shapes)):{},t&&t.shapes&&(i.shapes={...i.shapes,...t.shapes}),i.geometries=e.geometries?s.parseGeometries(Object.values(e.geometries),i.shapes):{},t&&t.geometries&&(i.geometries={...i.geometries,...t.geometries}),i.images=e.images?await s.parseImagesAsync(Object.values(e.images)):{},t&&t.images&&(i.images={...i.images,...t.images}),Array.isArray(e.textures)&&(console.error("ThreeSerialization: TODO: check file format"),e.textures=e.textures.reduce((c,h)=>(h&&(c[h.uuid]=h),c))),await Qm.LoadRootPathTextures({textures:e.textures,images:i.images},n);const a=[];for(const c of Object.values(e.textures)){const h={...c};h.userData&&(h.userData=We.Deserialize(h.userData,{},i)),a.push(h)}i.textures=e.textures?s.parseTextures(a,i.images):{};for(const c of Object.keys(i.textures)){let h=i.textures[c];if(h){if(h.source.__texCtor){const u=new h.source.__texCtor(h.source.data);if(!u||typeof u.copy!="function")continue;u.copy(h),delete h.source.__texCtor,i.textures[c]=u,h=u}if(h.source.data instanceof HTMLCanvasElement&&!h.isCanvasTexture){const u=new qo(h.source.data).copy(h);i.textures[c]=u,h=u}}}const o={...i.textures};for(const c of Object.values(e.textures))c.rootPathPromise?.then(h=>{if(!h)return;const u=o[c.uuid];u.dispose(),u.source=h,u.source.needsUpdate=!0,u.needsUpdate=!0});for(const c of Object.entries(i.textures))c[1]=await n.processRawSingle(c[1],{}),c[1]?i.textures[c[0]]=c[1]:delete i.textures[c[0]];t&&t.textures&&(i.textures={...i.textures,...t.textures});const l=e.materials?Object.values(e.materials):[];i.materials={};for(const c of l)c?.uuid&&(i.materials[c.uuid]=We.Deserialize(c,void 0,i));if(t&&t.materials&&(i.materials={...i.materials,...t.materials}),e.object&&(i.object=s.parseObject(e.object,i.geometries,i.materials,i.textures,i.animations),e.skeletons&&(i.skeletons=s.parseSkeletons(Object.values(e.skeletons),i.object),s.bindSkeletons(i.object,i.skeletons))),e.extras){i.extras=e.extras;for(const c of Object.values(e.extras))if(c.uuid){if(!c.url){i.extras[c.uuid]=We.Deserialize(c,void 0,i);continue}if(typeof c.url=="string"){const h=await n.importSingle(c.url,c.userData?.rootPathOptions||{});h&&(i.extras[c.uuid]=h)}else if(c.url.data){const h=new File([pS(c.url.type,c.url.data)],c.url.path),u=await n.importSingle({path:h.name,file:h},c.userData?.rootPathOptions||{},void 0,!1);u&&(i.extras[c.uuid]=u)}else console.warn("invalid URL type while loading extra resource")}}if(t&&t.extras&&(i.extras={...i.extras,...t.extras}),i.typed={},e.typed)for(const[c,h]of Object.entries(e.typed))if(typeof h.rootPath=="string"&&h.external){const u=await n.importSingle(h.rootPath,h.rootPathOptions||{});u&&(i.typed[c]=u)}else i.typed[c]=We.Deserialize(h,void 0,i);return t&&t.typed&&(i.typed={...i.typed,...t.typed}),i}static async LoadRootPathTextures({textures:e,images:t},i,n=!0){const s=[];for(const a of Array.isArray(e)?e:Object.values(e??{})){const o=a?.userData?.rootPath,l=n&&a.image&&t[a.image];if(!o)continue;const c=i.importSingle(o,a.userData.rootPathOptions||{}).then(h=>{const u=h?.source;if(!h||!h.isTexture||!u){console.error("AssetImporter: Imported rootPath is not a Texture",o,h);return}const d=new ia(u.data);return a.image&&(d.uuid=a.image),a.image=d.uuid,h.constructor!==kt&&h.constructor!==Vn&&h.constructor!==wc&&(d.__texCtor=h.constructor),l||(t[d.uuid]=d),h.dispose(),d}).catch(h=>(console.error("ThreeSerialization: Error loading texture from rootPath",a.userData.rootPath),console.error(h),delete a.userData.rootPath,null));l?a.rootPathPromise=c:s.push(c)}await Promise.allSettled(s)}}function pd(r){if(!r)return{};const e={...r};return e._context&&delete e._context,e}function rN(r,e){for(const t of Object.keys(e))t!=="object"&&(r[t]||(r[t]={}),Object.assign(r[t],e[t]));return r}function Ev(r,e){return{...r,...Fr(r),_context:{assetManager:e?.assetManager,assetImporter:e?.assetManager.importer,renderManager:e?.renderManager,viewer:e}}}function Mv(r){const e=new Blob([JSON.stringify(r)],{type:"application/json"});return e.ext="json",e}function QE(r,e,t,i){if(e?.extras[r.uuid])return{uuid:r.uuid,resource:"extras"};let n="";if(r.source?._sourceImgBuffer||r.__sourceBuffer){const a=new Uint8Array(r.source?._sourceImgBuffer||r.__sourceBuffer),o=i||r.userData.mimeType||"";n={data:Array.from(a),type:a.constructor.name,path:r.userData.__sourceBlob?.name||r.userData.rootPath||"file."+o.split("/")[1]},o&&(n.mimeType=o)}else r.userData.rootPath?n=r.userData.rootPath:console.error("ThreeSerialization: Unable to serialize LUT texture, not loaded through asset manager.");const s={uuid:r.uuid,url:n,userData:Cv({},r.userData),type:r.type,name:t||r.name};return e?.extras?(e.extras[r.uuid]=s,{uuid:r.uuid,resource:"extras"}):s}function jE(r,e){const t={},i=Array.isArray(e)?e:[];for(const n of i){const s=n.startsWith("userData.");let a;s?a=ju(n.slice(9),r.userData,!1):a=r[n],a!==void 0&&(t[n]=a)}return t}function jm(r,e){for(const t of Object.keys(r)){const i=r[t];if(!t.startsWith("userData."))e[t]=i;else{const s=e.userData,a=t.split("."),o=a.slice(1,-1),l=a.length&&o.length?ju(o,s,!1):void 0;if(l!==void 0){const c=a[a.length-1];l[c]=i}else console.warn("ThreeSerialization: setSProps: invalid sProperty",t,"in",e)}}}const aN=!0,WE="shaderReplaceString: str must be passed if str is a RegExp and append/prepend is true";function bt(r,e,t,{replaceAll:i=!1,prepend:n=!1,append:s=!1,str:a=void 0,warn:o=!0}={}){const l=typeof e=="string";if(o&&aN&&(l?!r.includes(e):!e.test(r)))return console.error(`${e} not found in shader`),r;let c=t;if(a=a??(l?e:void 0),n){if(typeof a!="string")throw new Error(WE);c=t+a}else if(s){if(typeof a!="string")throw new Error(WE);c=a+t}return i?r.replaceAll(e,c):r.replace(e,c)}function qE(r,e=0){const t=oN(r.byteLength);if(t!==r.byteLength){const i=new Uint8Array(t);if(i.set(new Uint8Array(r)),e!==0)for(let n=r.byteLength;n<t;n++)i[n]=e;return i.buffer}return r.buffer}function oN(r){return Math.ceil(r/4)*4}const XE=12,lN=1179937895,cN=2,YE=8,hN=1313821514,uN=5130562;function $E(r,e){const t=qE(r),i=new DataView(new ArrayBuffer(YE));i.setUint32(0,t.byteLength,!0),i.setUint32(4,uN,!0);const n=new TextEncoder().encode(JSON.stringify(e||{})),s=qE(n,32),a=new DataView(new ArrayBuffer(YE));a.setUint32(0,s.byteLength,!0),a.setUint32(4,hN,!0);const o=new ArrayBuffer(XE),l=new DataView(o);l.setUint32(0,lN,!0),l.setUint32(4,cN,!0);const c=XE+a.byteLength+s.byteLength+i.byteLength+t.byteLength;l.setUint32(8,c,!0);const h=new Blob([o,a,s,i,t],{type:"model/gltf+binary"});return h.ext="glb",h}function KE(r,e){var t={};for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&e.indexOf(i)<0&&(t[i]=r[i]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(r);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(r,i[n])&&(t[i[n]]=r[i[n]]);return t}var JE=function(){};const Tv=(r,e,t)=>Math.min(Math.max(t,r),e),Iv=.001,dN=.01,fN=10,pN=.05,mN=1;function gN({duration:r=800,bounce:e=.25,velocity:t=0,mass:i=1}){let n,s,a=1-e;a=Tv(pN,mN,a),r=Tv(dN,fN,r/1e3),a<1?(n=c=>{const h=c*a,u=h*r,d=h-t,p=Pv(c,a),m=Math.exp(-u);return Iv-d/p*m},s=c=>{const u=c*a*r,d=u*t+t,p=Math.pow(a,2)*Math.pow(c,2)*r,m=Math.exp(-u),A=Pv(Math.pow(c,2),a);return(-n(c)+Iv>0?-1:1)*((d-p)*m)/A}):(n=c=>{const h=Math.exp(-c*r),u=(c-t)*r+1;return-Iv+h*u},s=c=>{const h=Math.exp(-c*r),u=(t-c)*(r*r);return h*u});const o=5/r,l=yN(n,s,o);if(r=r*1e3,isNaN(l))return{stiffness:100,damping:10,duration:r};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:a*2*Math.sqrt(i*c),duration:r}}}const AN=12;function yN(r,e,t){let i=t;for(let n=1;n<AN;n++)i=i-r(i)/e(i);return i}function Pv(r,e){return r*Math.sqrt(1-e*e)}const _N=["duration","bounce"],vN=["stiffness","damping","mass"];function ZE(r,e){return e.some(t=>r[t]!==void 0)}function bN(r){let e=Object.assign({velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1},r);if(!ZE(r,vN)&&ZE(r,_N)){const t=gN(r);e=Object.assign(Object.assign(Object.assign({},e),t),{velocity:0,mass:1}),e.isResolvedFromDuration=!0}return e}function Dv(r){var{from:e=0,to:t=1,restSpeed:i=2,restDelta:n}=r,s=KE(r,["from","to","restSpeed","restDelta"]);const a={done:!1,value:e};let{stiffness:o,damping:l,mass:c,velocity:h,duration:u,isResolvedFromDuration:d}=bN(s),p=eM,m=eM;function A(){const g=h?-(h/1e3):0,y=t-e,v=l/(2*Math.sqrt(o*c)),_=Math.sqrt(o/c)/1e3;if(n===void 0&&(n=Math.min(Math.abs(t-e)/100,.4)),v<1){const b=Pv(_,v);p=T=>{const E=Math.exp(-v*_*T);return t-E*((g+v*_*y)/b*Math.sin(b*T)+y*Math.cos(b*T))},m=T=>{const E=Math.exp(-v*_*T);return v*_*E*(Math.sin(b*T)*(g+v*_*y)/b+y*Math.cos(b*T))-E*(Math.cos(b*T)*(g+v*_*y)-b*y*Math.sin(b*T))}}else if(v===1)p=b=>t-Math.exp(-_*b)*(y+(g+_*y)*b);else{const b=_*Math.sqrt(v*v-1);p=T=>{const E=Math.exp(-v*_*T),M=Math.min(b*T,300);return t-E*((g+v*_*y)*Math.sinh(M)+b*y*Math.cosh(M))/b}}}return A(),{next:g=>{const y=p(g);if(d)a.done=g>=u;else{const v=m(g)*1e3,_=Math.abs(v)<=i,b=Math.abs(t-y)<=n;a.done=_&&b}return a.value=a.done?t:y,a},flipTarget:()=>{h=-h,[e,t]=[t,e],A()}}}Dv.needsInterpolation=(r,e)=>typeof r=="string"||typeof e=="string";const eM=r=>0,tM=(r,e,t)=>{const i=e-r;return i===0?1:(t-r)/i},Rv=(r,e,t)=>-t*r+t*e+r,iM=(r,e)=>t=>Math.max(Math.min(t,e),r),md=r=>r%1?Number(r.toFixed(5)):r,Wm=/(-)?([\d]*\.?[\d])+/g,Bv=/(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi,wN=/^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;function gd(r){return typeof r=="string"}const qm={test:r=>typeof r=="number",parse:parseFloat,transform:r=>r},nM=Object.assign(Object.assign({},qm),{transform:iM(0,1)});Object.assign(Object.assign({},qm),{default:1});const Ad=(r=>({test:e=>gd(e)&&e.endsWith(r)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${r}`}))("%");Object.assign(Object.assign({},Ad),{parse:r=>Ad.parse(r)/100,transform:r=>Ad.transform(r*100)});const Lv=(r,e)=>t=>!!(gd(t)&&wN.test(t)&&t.startsWith(r)||e&&Object.prototype.hasOwnProperty.call(t,e)),sM=(r,e,t)=>i=>{if(!gd(i))return i;const[n,s,a,o]=i.match(Wm);return{[r]:parseFloat(n),[e]:parseFloat(s),[t]:parseFloat(a),alpha:o!==void 0?parseFloat(o):1}},Al={test:Lv("hsl","hue"),parse:sM("hue","saturation","lightness"),transform:({hue:r,saturation:e,lightness:t,alpha:i=1})=>"hsla("+Math.round(r)+", "+Ad.transform(md(e))+", "+Ad.transform(md(t))+", "+md(nM.transform(i))+")"},CN=iM(0,255),Ov=Object.assign(Object.assign({},qm),{transform:r=>Math.round(CN(r))}),lo={test:Lv("rgb","red"),parse:sM("red","green","blue"),transform:({red:r,green:e,blue:t,alpha:i=1})=>"rgba("+Ov.transform(r)+", "+Ov.transform(e)+", "+Ov.transform(t)+", "+md(nM.transform(i))+")"};function xN(r){let e="",t="",i="",n="";return r.length>5?(e=r.substr(1,2),t=r.substr(3,2),i=r.substr(5,2),n=r.substr(7,2)):(e=r.substr(1,1),t=r.substr(2,1),i=r.substr(3,1),n=r.substr(4,1),e+=e,t+=t,i+=i,n+=n),{red:parseInt(e,16),green:parseInt(t,16),blue:parseInt(i,16),alpha:n?parseInt(n,16)/255:1}}const Uv={test:Lv("#"),parse:xN,transform:lo.transform},Xm={test:r=>lo.test(r)||Uv.test(r)||Al.test(r),parse:r=>lo.test(r)?lo.parse(r):Al.test(r)?Al.parse(r):Uv.parse(r),transform:r=>gd(r)?r:r.hasOwnProperty("red")?lo.transform(r):Al.transform(r)},rM="${c}",aM="${n}";function SN(r){var e,t,i,n;return isNaN(r)&&gd(r)&&((t=(e=r.match(Wm))===null||e===void 0?void 0:e.length)!==null&&t!==void 0?t:0)+((n=(i=r.match(Bv))===null||i===void 0?void 0:i.length)!==null&&n!==void 0?n:0)>0}function oM(r){typeof r=="number"&&(r=`${r}`);const e=[];let t=0;const i=r.match(Bv);i&&(t=i.length,r=r.replace(Bv,rM),e.push(...i.map(Xm.parse)));const n=r.match(Wm);return n&&(r=r.replace(Wm,aM),e.push(...n.map(qm.parse))),{values:e,numColors:t,tokenised:r}}function lM(r){return oM(r).values}function cM(r){const{values:e,numColors:t,tokenised:i}=oM(r),n=e.length;return s=>{let a=i;for(let o=0;o<n;o++)a=a.replace(o<t?rM:aM,o<t?Xm.transform(s[o]):md(s[o]));return a}}const EN=r=>typeof r=="number"?0:r;function MN(r){const e=lM(r);return cM(r)(e.map(EN))}const hM={test:SN,parse:lM,createTransformer:cM,getAnimatableNone:MN};function Fv(r,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?r+(e-r)*6*t:t<1/2?e:t<2/3?r+(e-r)*(2/3-t)*6:r}function uM({hue:r,saturation:e,lightness:t,alpha:i}){r/=360,e/=100,t/=100;let n=0,s=0,a=0;if(!e)n=s=a=t;else{const o=t<.5?t*(1+e):t+e-t*e,l=2*t-o;n=Fv(l,o,r+1/3),s=Fv(l,o,r),a=Fv(l,o,r-1/3)}return{red:Math.round(n*255),green:Math.round(s*255),blue:Math.round(a*255),alpha:i}}const TN=(r,e,t)=>{const i=r*r,n=e*e;return Math.sqrt(Math.max(0,t*(n-i)+i))},IN=[Uv,lo,Al],dM=r=>IN.find(e=>e.test(r)),fM=(r,e)=>{let t=dM(r),i=dM(e),n=t.parse(r),s=i.parse(e);t===Al&&(n=uM(n),t=lo),i===Al&&(s=uM(s),i=lo);const a=Object.assign({},n);return o=>{for(const l in a)l!=="alpha"&&(a[l]=TN(n[l],s[l],o));return a.alpha=Rv(n.alpha,s.alpha,o),t.transform(a)}},PN=r=>typeof r=="number",DN=(r,e)=>t=>e(r(t)),pM=(...r)=>r.reduce(DN);function mM(r,e){return PN(r)?t=>Rv(r,e,t):Xm.test(r)?fM(r,e):yM(r,e)}const gM=(r,e)=>{const t=[...r],i=t.length,n=r.map((s,a)=>mM(s,e[a]));return s=>{for(let a=0;a<i;a++)t[a]=n[a](s);return t}},RN=(r,e)=>{const t=Object.assign(Object.assign({},r),e),i={};for(const n in t)r[n]!==void 0&&e[n]!==void 0&&(i[n]=mM(r[n],e[n]));return n=>{for(const s in i)t[s]=i[s](n);return t}};function AM(r){const e=hM.parse(r),t=e.length;let i=0,n=0,s=0;for(let a=0;a<t;a++)i||typeof e[a]=="number"?i++:e[a].hue!==void 0?s++:n++;return{parsed:e,numNumbers:i,numRGB:n,numHSL:s}}const yM=(r,e)=>{const t=hM.createTransformer(e),i=AM(r),n=AM(e);return i.numHSL===n.numHSL&&i.numRGB===n.numRGB&&i.numNumbers>=n.numNumbers?pM(gM(i.parsed,n.parsed),t):a=>`${a>0?e:r}`},BN=(r,e)=>t=>Rv(r,e,t);function LN(r){if(typeof r=="number")return BN;if(typeof r=="string")return Xm.test(r)?fM:yM;if(Array.isArray(r))return gM;if(typeof r=="object")return RN}function ON(r,e,t){const i=[],n=t||LN(r[0]),s=r.length-1;for(let a=0;a<s;a++){let o=n(r[a],r[a+1]);if(e){const l=Array.isArray(e)?e[a]:e;o=pM(l,o)}i.push(o)}return i}function UN([r,e],[t]){return i=>t(tM(r,e,i))}function FN(r,e){const t=r.length,i=t-1;return n=>{let s=0,a=!1;if(n<=r[0]?a=!0:n>=r[i]&&(s=i-1,a=!0),!a){let l=1;for(;l<t&&!(r[l]>n||l===i);l++);s=l-1}const o=tM(r[s],r[s+1],n);return e[s](o)}}function _M(r,e,{clamp:t=!0,ease:i,mixer:n}={}){const s=r.length;JE(s===e.length),JE(!i||!Array.isArray(i)||i.length===s-1),r[0]>r[s-1]&&(r=[].concat(r),e=[].concat(e),r.reverse(),e.reverse());const a=ON(e,i,n),o=s===2?UN(r,a):FN(r,a);return t?l=>o(Tv(r[0],r[s-1],l)):o}const Ym=r=>e=>1-r(1-e),Nv=r=>e=>e<=.5?r(2*e)/2:(2-r(2*(1-e)))/2,NN=r=>e=>Math.pow(e,r),vM=r=>e=>e*e*((r+1)*e-r),kN=r=>{const e=vM(r);return t=>(t*=2)<1?.5*e(t):.5*(2-Math.pow(2,-10*(t-1)))},bM=1.525,GN=4/11,zN=8/11,VN=9/10,HN=r=>r,kv=NN(2),QN=Ym(kv),wM=Nv(kv),CM=r=>1-Math.sin(Math.acos(r)),xM=Ym(CM),jN=Nv(xM),Gv=vM(bM),WN=Ym(Gv),qN=Nv(Gv),XN=kN(bM),YN=4356/361,$N=35442/1805,KN=16061/1805,$m=r=>{if(r===1||r===0)return r;const e=r*r;return r<GN?7.5625*e:r<zN?9.075*e-9.9*r+3.4:r<VN?YN*e-$N*r+KN:10.8*r*r-20.52*r+10.72},JN=Ym($m),ZN=r=>r<.5?.5*(1-$m(1-r*2)):.5*$m(r*2-1)+.5;function ek(r,e){return r.map(()=>e||wM).splice(0,r.length-1)}function tk(r){const e=r.length;return r.map((t,i)=>i!==0?i/(e-1):0)}function ik(r,e){return r.map(t=>t*e)}function yd({from:r=0,to:e=1,ease:t,offset:i,duration:n=300}){const s={done:!1,value:r},a=Array.isArray(e)?e:[r,e],o=ik(i&&i.length===a.length?i:tk(a),n);function l(){return _M(o,a,{ease:Array.isArray(t)?t:ek(a,t)})}let c=l();return{next:h=>(s.value=c(h),s.done=h>=n,s),flipTarget:()=>{a.reverse(),c=l()}}}function nk({velocity:r=0,from:e=0,power:t=.8,timeConstant:i=350,restDelta:n=.5,modifyTarget:s}){const a={done:!1,value:e};let o=t*r;const l=e+o,c=s===void 0?l:s(l);return c!==l&&(o=c-e),{next:h=>{const u=-o*Math.exp(-h/i);return a.done=!(u>n||u<-n),a.value=a.done?c:c+u,a},flipTarget:()=>{}}}const SM={keyframes:yd,spring:Dv,decay:nk};function sk(r){if(Array.isArray(r.to))return yd;if(SM[r.type])return SM[r.type];const e=new Set(Object.keys(r));return e.has("ease")||e.has("duration")&&!e.has("dampingRatio")?yd:e.has("dampingRatio")||e.has("stiffness")||e.has("mass")||e.has("damping")||e.has("restSpeed")||e.has("restDelta")?Dv:yd}const EM=1/60*1e3,rk=typeof performance<"u"?()=>performance.now():()=>Date.now(),MM=typeof window<"u"?r=>window.requestAnimationFrame(r):r=>setTimeout(()=>r(rk()),EM);function ak(r){let e=[],t=[],i=0,n=!1,s=!1;const a=new WeakSet,o={schedule:(l,c=!1,h=!1)=>{const u=h&&n,d=u?e:t;return c&&a.add(l),d.indexOf(l)===-1&&(d.push(l),u&&n&&(i=e.length)),l},cancel:l=>{const c=t.indexOf(l);c!==-1&&t.splice(c,1),a.delete(l)},process:l=>{if(n){s=!0;return}if(n=!0,[e,t]=[t,e],t.length=0,i=e.length,i)for(let c=0;c<i;c++){const h=e[c];h(l),a.has(h)&&(o.schedule(h),r())}n=!1,s&&(s=!1,o.process(l))}};return o}const ok=40;let zv=!0,_d=!1,Vv=!1;const vd={delta:0,timestamp:0},bd=["read","update","preRender","render","postRender"],Km=bd.reduce((r,e)=>(r[e]=ak(()=>_d=!0),r),{}),lk=bd.reduce((r,e)=>{const t=Km[e];return r[e]=(i,n=!1,s=!1)=>(_d||uk(),t.schedule(i,n,s)),r},{}),ck=bd.reduce((r,e)=>(r[e]=Km[e].cancel,r),{});bd.reduce((r,e)=>(r[e]=()=>Km[e].process(vd),r),{});const hk=r=>Km[r].process(vd),TM=r=>{_d=!1,vd.delta=zv?EM:Math.max(Math.min(r-vd.timestamp,ok),1),vd.timestamp=r,Vv=!0,bd.forEach(hk),Vv=!1,_d&&(zv=!1,MM(TM))},uk=()=>{_d=!0,zv=!0,Vv||MM(TM)};function IM(r,e,t=0){return r-e-t}function dk(r,e,t=0,i=!0){return i?IM(e+-r,e,t):e-(r-e)+t}function fk(r,e,t,i){return i?r>=e+t:r<=-t}const pk=r=>{const e=({delta:t})=>r(t);return{start:()=>lk.update(e,!0),stop:()=>ck.update(e)}};function Hv(r){var e,t,{from:i,autoplay:n=!0,driver:s=pk,elapsed:a=0,repeat:o=0,repeatType:l="loop",repeatDelay:c=0,onPlay:h,onStop:u,onComplete:d,onRepeat:p,onUpdate:m}=r,A=KE(r,["from","autoplay","driver","elapsed","repeat","repeatType","repeatDelay","onPlay","onStop","onComplete","onRepeat","onUpdate"]);let{to:g}=A,y,v=0,_=A.duration,b,T=!1,E=!0,M;const I=sk(A);!((t=(e=I).needsInterpolation)===null||t===void 0)&&t.call(e,i,g)&&(M=_M([0,100],[i,g],{clamp:!1}),i=0,g=100);const C=I(Object.assign(Object.assign({},A),{from:i,to:g}));function x(){v++,l==="reverse"?(E=v%2===0,a=dk(a,_,c,E)):(a=IM(a,_,c),l==="mirror"&&C.flipTarget()),T=!1,p&&p()}function D(){y.stop(),d&&d()}function U(N){E||(N=-N),a+=N;const H=Math.max(0,a);if(!T||H<=(_||0)){const V=C.next(H);b=V.value,M&&(b=M(b)),T=E?V.done:a<=0}m?.(b),T&&(v===0&&(_??(_=a)),v<o?fk(a,_,c,E)&&x():D())}function O(){h?.(),y=s(U),y.start()}return n&&O(),{stop:()=>{u?.(),y.stop()}}}const Kc={linear:HN,easeIn:kv,easeOut:QN,easeInOut:wM,circIn:CM,circOut:xM,circInOut:jN,backIn:Gv,backOut:WN,backInOut:qN,anticipate:XN,bounceOut:$m,bounceIn:JN,bounceInOut:ZN,easeInOutSine:r=>-(Math.cos(Math.PI*r)-1)/2};function Qv(r,e,t){const i=r[e],n=()=>{t?.()},s=typeof i=="boolean";return i&&i.isColor?a=>{i.set(a),n()}:i&&typeof i.copy=="function"?a=>{i.copy(a),n()}:a=>{r[e]=s?!!a:a,n()}}async function mk(r,e,t,i,n=!1){e in r||console.error("invalid key",e,r);const s=Qv(r,e),a=n||t.from===void 0?r[e]:t.from,o=l=>{s(l),t.onUpdate&&t.onUpdate(l)};if(typeof a=="boolean"){const{duration:l}=t;return Qn(l??0).then(()=>o(t.to))}else return typeof t.to=="function"&&(t={...t,to:t.to(a,r)}),PM({...t,from:a,onUpdate:o},i)}async function PM(r,e){const t=r.onComplete,i=r.onStop,n=r.onEnd;return r={...r},new Promise((s,a)=>{const o=()=>{try{n?.()}catch(c){return a(c),!1}return!0};r.onComplete=()=>{try{t?.()}catch(c){if(!o())return;a(c);return}o()&&s()},r.onStop=()=>{try{i?.()}catch(c){if(!o())return;a(c);return}o()&&s()};const l=Hv(r);e&&e.push(l)})}function jv(r,e,t){const i=e-r;return i>=Math.PI?r+(i-Math.PI*2)*t:i<=-Math.PI?r+(i+Math.PI*2)*t:r+i*t}const Jm=Ft.lerp;function gk({from:r,autoplay:e=!0,driver:t,elapsed:i=0,onPlay:n,onStop:s,onComplete:a,onUpdate:o,delay:l=0,canComplete:c=!0,...h}){const{to:u}=h;let d;const p=h.duration||0;let m,A=!1;const g=yd({...h,from:r,to:u});function y(){d.stop(),a&&a()}function v(b){const T=i>=l;if(i+=b,i<l&&!T)return;const E=Math.max(0,i-l);if(!A||E<=(p||0)){const M=g.next(E);m=M.value,A=M.done}o?.(m),A&&c&&y()}function _(){n?.(),d=t(v),d.start()}return e&&_(),{stop:()=>{s?.(),d.stop()}}}function Wv(r){const e=r.position.clone();e.sub(r.target);const t=new Ir().setFromVector3(e);return t.makeSafe(),t}function DM(r,e){const t=r.parent,i=r.target.clone(),n=r.getWorldPosition(new S),s={target:i,zoom:r.zoom,spherical:Wv({position:n,target:i})},a={position:new S,target:new S,zoom:1,spherical:new Ir},o={position:e.position,target:e.target,zoom:e.zoom,spherical:Wv(e)};function l(){r.position.copy(t?t.worldToLocal(a.position):a.position),r.target.copy(a.target),r.zoom=a.zoom,r.setDirty()}return{from:0,to:1,onUpdate:c=>{a.spherical.phi=jv(s.spherical.phi,o.spherical.phi,c),a.spherical.theta=jv(s.spherical.theta,o.spherical.theta,c),a.spherical.radius=Jm(s.spherical.radius,o.spherical.radius,c),a.target.copy(s.target).lerp(o.target,c),a.position.setFromSpherical(a.spherical),a.position.add(a.target),a.zoom=Jm(s.zoom,o.zoom,c),l()},onComplete:()=>{a.position.copy(o.position),a.target.copy(o.target),a.zoom=o.zoom,l()},onStop:()=>{throw new Error("Animation Stopped")}}}function RM(r,e){const t=r.parent,i=r.target.clone(),n=r.getWorldPosition(new S),s=r.getWorldQuaternion(new $e),a={position:n,target:i,quaternion:s,zoom:r.zoom},o={position:new S,target:new S,quaternion:new $e,zoom:1},l=e;function c(){r.position.copy(t?t.worldToLocal(o.position):o.position),r.target.copy(o.target),r.quaternion.copy(t?bE(t,o.quaternion,r.quaternion):o.quaternion),r.zoom=o.zoom,r.setDirty()}return{from:0,to:1,onUpdate:h=>{o.position.lerpVectors(a.position,l.position,h),o.target.lerpVectors(a.target,l.target,h),o.quaternion.slerpQuaternions(a.quaternion,l.quaternion,h),o.zoom=Jm(a.zoom,l.zoom,h),c()},onComplete:()=>{o.position.copy(l.position),o.target.copy(l.target),o.quaternion.copy(l.quaternion),o.zoom=l.zoom,c()},onStop:()=>{throw new Error("Animation Stopped")}}}function Zm(r,e,t){return typeof e=="number"&&typeof t=="number"?Jc(r,e,t):typeof e?.r=="number"&&typeof t?.r=="number"?new ee().set(Jc(r.from?{...r,from:r.from.r}:r,e.r,t.r),Jc(r.from?{...r,from:r.from.g}:r,e.g,t.g),Jc(r.from?{...r,from:r.from.b}:r,e.b,t.b)):e?.toArray&&t?.toArray&&e.clone&&e.fromArray?qv(r,e,t):r.t>=1?t:e}function Jc(r,e,t){const{t:i,dt:n}=r;let s;if(i<=0)s=r.from!==void 0?r.from:e;else if(i>=1)s=t;else if(r.from!==void 0)s=r.from*(1-i)+t*i;else{const a=1-i,o=Math.max(0,Math.min(n,a)/a);s=e+(t-e)*o}return s}function qv(r,e,t){const i=e.toArray(),n=t.toArray(),s=r.from?r.from.toArray():void 0,a=i.map((l,c)=>Zm(s?{...r,from:s[c]}:r,l,n[c]));return e.clone().fromArray(a)}function BM(r,e,t){if(!r.rm)return console.warn("MaterialManager: RenderManager is required for interpolating textures"),t;const{t:i,dt:n}=r;let s;const a=r.from!==void 0?r.from:e;if(i<=0||i>.99||a===t){s=i<=0?a:t;let o;e&&e.userData?._lerpTexture&&e.isRenderTargetTexture&&(o=e._target),o&&r.rm.releaseTempTarget(o)}else{const o=a||Lm;let l=!1,c;if(e&&e.userData?._lerpTexture&&e.isRenderTargetTexture)c=e._target;else{const h=a||t||Lm,u={width:h.image?.width||h.image?.naturalWidth||h.image?.videoWidth||1,height:h.image?.height||h.image?.naturalHeight||h.image?.videoHeight||1};c=r.rm.getTempTarget({size:u,colorSpace:h.colorSpace,type:h.type,format:h.format,generateMipmaps:h.generateMipmaps,minFilter:h.minFilter,magFilter:h.magFilter,wrapS:h.wrapS,wrapT:h.wrapT}),c.texture.userData._lerpTexture=!0,l=!0}if(c){(r.from!==void 0||l)&&r.rm.blit(c,{source:o,respectColorSpace:!1,transparent:!0,clear:!0});const h=1-i,u=Math.max(0,Math.min(n,h)/h);r.rm.blit(c,{source:t||Lm,respectColorSpace:!1,transparent:!0,clear:!1,blendAlpha:r.from!==void 0?i:u}),s=c.texture}else s=e}return s}function LM(r,e,t,i){for(const n of Object.keys(r)){if(!t.has(n))continue;const s=e[n];if(s===void 0)continue;const a=i.from?{...i,from:i.from[n]}:i,o=r[n];if(typeof s=="number"&&typeof o=="number"){const l=Jc(a,s,o);l===s?delete r[n]:r[n]=l}if(s?.isColor&&o?.isColor){const l=Zm(a,s,o);l.getHex()===s.getHex()?delete r[n]:r[n]=l}if((s==null||s.isTexture)&&(o==null||o.isTexture)&&(s||o)){const l=BM(a,s||null,o||null);l===s?delete r[n]:r[n]=l}if(s?.toArray&&o?.toArray&&s.clone&&s.fromArray&&s.equals){const l=qv(a,s,o);l.equals(s)?delete r[n]:r[n]=l}if(Array.isArray(s)&&Array.isArray(o)&&s.length===o.length){const l=s.map((c,h)=>Zm(a,c,o[h]));l.every((c,h)=>c===s[h])?delete r[n]:r[n]=l}}}function OM(r,e){return r.multiplyScalar(r.w*e),r.w=1,r}function Ak(r,e){return OM(r,e),new ee(r.x,r.y,r.z)}function UM(r,e){const t=Math.max(r.x,Math.max(r.y,r.z));let i=Math.max(Math.min(t/e,1),0);return i=Math.ceil(i*255)/255,r.divideScalar(i*e),r.w=i,r}function yk(r,e){return UM(new et(r.r,r.g,r.b,1),e)}function FM(){return navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}const Nb=class Nb{static async GetClonedCanvas(e,{rect:t={x:0,y:0,width:e.width,height:e.height,assumeClientRect:!1,normalized:!1},displayPixelRatio:i=1,scale:n=1}){t={...t};const s=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");t.normalized?(t.x=Math.floor(t.x*e.width),t.y=Math.floor(t.y*e.height),t.width=Math.floor(t.width*e.width),t.height=Math.floor(t.height*e.height),t.assumeClientRect&&console.warn("CanvasSnapshot: rect.assumeClientRect is ignored when rect is normalized")):t.assumeClientRect&&(t.x=Math.floor(t.x*e.width/(i*e.clientWidth)),t.y=Math.floor(t.y*e.height/(i*e.clientHeight)),t.width=Math.floor(t.width*e.width/(i*e.clientWidth)),t.height=Math.floor(t.height*e.height/(i*e.clientHeight))),s.width=Math.floor(t.width*n*i),s.height=Math.floor(t.height*n*i);const a=s.getContext("2d");if(!a)return console.error("snapshot: cannot create context"),s;const o=e.style.background||e.parentElement?.style.background||"";if(o.includes("url")){const c=/url\("(.*)"\)/ig.exec(o)?.[1];if(c){const h=new Image;h.src=c,await new Promise((u,d)=>{h.onload=()=>u(),h.onerror=()=>d(),h.complete&&u()}),a.drawImage(h,Math.floor(h.width*t.x*i/e.width),Math.floor(h.height*t.y*i/e.height),Math.floor(h.width*t.width*i/e.width),Math.floor(h.height*t.height*i/e.height),0,0,s.width,s.height)}}else a.fillStyle=e.style.background||e.parentElement?.style.backgroundColor||"#00000000",a.fillRect(0,0,s.width,s.height);return a?.drawImage(e,Math.floor(t.x*i),Math.floor(t.y*i),Math.floor(t.width*i),Math.floor(t.height*i),0,0,s.width,s.height),this.Debug&&(document.body.appendChild(s),s.style.position="absolute",s.style.top="0",s.style.left="0",s.style.borderWidth="2px",s.style.borderColor="#ff00ff",setTimeout(()=>s.remove(),5e3)),s}static async GetDataUrl(e,{mimeType:t="image/png",quality:i,...n}){const s=FM()||n.cloneCanvas||n.rect||n.scale||n.displayPixelRatio;!s&&(n.rect||n.scale||n.displayPixelRatio)&&console.warn("CanvasSnapshot: rect, scale and displayPixelRatio are ignored when cloneCanvas is false");const a=s?await this.GetClonedCanvas(e,n):e,o=a.toDataURL(t,i);return!this.Debug&&a!==e&&a.remove(),o}static async GetImage(e,t={}){const i=await this.GetDataUrl(e,t);return new Promise((n,s)=>{const a=new Image;a.onload=()=>n(a),a.onerror=()=>s(),a.src=i})}static async GetBlob(e,t={}){const i=FM()||t.cloneCanvas||t.rect||t.scale||t.displayPixelRatio;!i&&(t.rect||t.scale||t.displayPixelRatio)&&console.warn("rect, scale and displayPixelRatio are ignored when cloneCanvas is false");const n=i?await this.GetClonedCanvas(e,t):e,s=await new Promise((a,o)=>{n.toBlob(l=>{l?a(l):o(new Error("CanvasSnapshot Failed to export blob from canvas"))},t.mimeType??"image/png",t.quality)});return!this.Debug&&n!==e&&n.remove(),s}static async GetFile(e,t="image",i={}){const n="."+(i.mimeType?.split("/")[1]?.toLowerCase()||"png"),s=t.toLowerCase().endsWith(n)?t:t+n;return i.getDataUrl?await this.GetDataUrl(e,i):new File([await this.GetBlob(e,i)],s,{type:i.mimeType??"image/png",lastModified:Cn()})}static async GetTiledFiles(e,t="image",i=2,n=2,s={}){const a=s.rect??{x:0,y:0,width:1,height:1,assumeClientRect:!1,normalized:!0},o=[];for(let l=0;l<n;l++)for(let c=0;c<i;c++){const h=s.mimeType?.split("/")[1]??"png",u=await this.GetFile(e,`${t}_${l}_${c}.${h}`,{rect:{x:a.x+l*a.width/n,y:a.y+c*a.height/i,width:a.width/n,height:a.height/i,assumeClientRect:a.assumeClientRect,normalized:a.normalized}}).catch(d=>(console.error(`CanvasSnapshot - Error exporting tiled file ${l}, ${c}`,d),null));u&&o.push(u)}return o}};Nb.Debug=!1;let wd=Nb;var _k=Object.defineProperty,vk=Object.getOwnPropertyDescriptor,Ui=(r,e,t,i)=>{for(var n=i>1?void 0:i?vk(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&_k(e,t,n),n};const NM={None:"","Background Color":"scene.backgroundColor","Environment Rotation":"scene.environmentRotation.y","Environment Intensity":"scene.environmentIntensity","Camera Position":"scene.mainCamera.position","Camera Rotation":"scene.mainCamera.rotation","Camera Zoom":"scene.mainCamera.zoom","Camera FOV":"scene.mainCamera.fov","Tonemap Exposure":"plugins.Tonemap.exposure","Tonemap Saturation":"plugins.Tonemap.saturation","Tonemap Contrast":"plugins.Tonemap.contrast","Tonemap Tone Mapping":"plugins.Tonemap.toneMapping","SSR Intensity":"plugins.SSReflection.passes.ssr.passObject.intensity","SSR Boost":"plugins.SSReflection.passes.ssr.passObject.boost","Chromatic Aberration Intensity":"plugins.ChromaticAberration.intensity","Film Grain Intensity":"plugins.FilmicGrain.intensity","Vignette Color":"plugins.Vignette.color","Vignette Power":"plugins.Vignette.power","Depth of Field Focal Point":"plugins.DepthOfField._focalPointHit","Depth of Field Near Far Blur Scale X":"plugins.DepthOfField.pass.nearFarBlurScale.x","Depth of Field Near Far Blur Scale Y":"plugins.DepthOfField.pass.nearFarBlurScale.y","Depth of Field Focal Depth Range Y":"plugins.DepthOfField.pass.focalDepthRange.y","Bloom Intensity":"plugins.Bloom.pass.intensity","Bloom Radius":"plugins.Bloom.pass.radius","Bloom Power":"plugins.Bloom.pass.power"};function Xv(r,e){let t=Array.from((r.access??"").split(new RegExp("(?<!\\\\)\\."))),i=r.targetObject,n;const s=t.pop()?.replace(/\\\./g,".");if(!s||s.length===0)return{key:void 0,tar:i};e=e??i?._animGetters;const a=t.length>=1?t[0]:void 0,o=t.length>=2?t[1]?.replace(/\\\./g,"."):void 0;if(e&&a&&a in e&&o){t=t.slice(2);const l=e[a](o,t);l?(i=l.tar,t=l.acc,n=l.onChange??n):i=l}return i=ju(t,i),{key:s,tar:i,onChange:n}}f.AnimationObject=class extends xi{constructor(e,t,i=""){super(),this.uuid=Oi(),this.setDirty=()=>{this.updater=[],this.options&&(this.options.repeatType=this.repeatType,this.options.repeat=this.repeat),this._upfn&&(this.updateScene&&this.updater.push(this._upfn.scene),this.updateCamera&&this.updater.push(this._upfn.camera),this.updateViewer&&this.updater.push(this._upfn.viewer),this.updateTarget&&this.updater.push(this._upfn.target),this.dispatchEvent({type:"update"}))},this.name="",this.access="",this.values=[],this.offsets=[],this.options={},this.duration=1e3,this.delay=0,this.repeat=0,this.repeatDelay=0,this.repeatType="reverse",this.ease="easeInOutSine",this.updater=[],this.updateScene=!1,this.updateCamera=!1,this.updateViewer=!1,this.updateTarget=!1,this._lastAccess="",this._lastTarget=void 0,this._upfn={viewer:()=>this.getViewer()?.setDirty(),renderer:()=>this.getViewer()?.renderManager.reset(),scene:()=>{this.getViewer()?.scene.setDirty()},camera:()=>this.getViewer()?.scene.mainCamera.setDirty(),target:()=>{const n=this.targetObject;n&&typeof n.setDirty=="function"&&n.setDirty({frameFade:!1,refreshScene:!1,source:"AnimationObject",key:this.access})}},this.animSetParallel=!1,this.animSet=[],this.uiConfig={type:"folder",label:()=>this.name||this.access||"Animation",children:[()=>this.target?null:{type:"input",label:"Property",property:[this,"access"],children:Object.entries(NM).map(([n,s])=>({label:n,value:s}))},()=>this.values.flatMap((n,s)=>[{...ii(this.values,s+"",void 0,n),label:s===0?"From":s===this.values.length-1?"To":"Key "+s,onChange:()=>this.setDirty()},s>0&&s<this.values.length-1?{type:"number",label:"Offset "+s,property:[this.offsets,s+""],bounds:[0,1],onChange:()=>this.setDirty()}:null]),bi(this)],uuid:Oi()},this.target=e,this.viewer=t,this.name=i,this.dispatchEvent=this.dispatchEvent.bind(this)}get targetObject(){return tt(this.target)??this.parent?.targetObject}getViewer(){return this.viewer?tt(this.viewer):this.parent?.getViewer()}fromJSON(e,t){let i={...e};return i.access!==void 0&&(this.access=i.access,delete i.access),i.from!==void 0&&(i={...i},i.values=[i.from,i.to],i.offsets=[0,1],delete i.from,delete i.to),We.Deserialize(i,this,t,!0),this.animSet.map(n=>{n.parent=this}),this}_onAccessChanged(){const e=this.targetObject;if(e&&e===this.getViewer()&&!Object.values(NM).includes(this.access)){this.access="";return}if(e&&e===this.getViewer()&&this.access==="scene.environment.rotation"){this.access="scene.environmentRotation.y";return}if(e&&e===this.getViewer()&&this.access==="scene.envMapIntensity"){this.access="scene.environmentIntensity";return}if(this.access!==this._lastAccess||!this.values.length||this._lastTarget!==e&&e&&this._lastTarget){this._lastAccess=this.access;const t=this.values;this.values=[],this.offsets=[];const i=this._thisValueCloner();if(!i){this.refreshUi();return}this.values=[i(),i()],t.length>=2&&typeof t[0]==typeof this.values[0]&&(typeof t[0]!="object"||t[0].type&&t[0].type===this.values[0]?.type)&&(this.values=t),this.offsets=this.offsets.length===this.values.length?this.offsets:[0,1],this.refreshUi()}}_thisValueCloner(){const{key:e,tar:t}=Xv(this),i=t&&e!==void 0?t[e]:null;return i==null?null:()=>i&&(i.isColor?"#"+i.getHexString():typeof i.clone=="function"?i.clone():typeof i=="object"?{...i}:i)}addKeyframe(e){if(this.values.length<2){console.warn("AnimationObject: Values not initialized, cannot add keyframe",this);return}const t=this._thisValueCloner();if(!t){console.warn("AnimationObject: No value to add keyframe for",this);return}const i=e-this.delay,n=this.duration,s=this.delay,a=[...this.offsets],o=[...this.values];let l=i/this.duration,c,h=n,u=s;const d=[...this.values],p=[...this.offsets];if(l<0){const y=-l;l=0;for(let v=0;v<a.length;v++)p[v]=(a[v]+y)/(1+y);h=n-i,u=s+i,c=0}else if(l>1){const y=l-1;l=1;for(let v=0;v<a.length;v++)p[v]=a[v]/(1+y);h=i,c=a.length}else if(c=a.findIndex(y=>y>=l),c<0)c=this.offsets.length;else if(this.offsets[c]===l){console.warn("AnimationObject: Keyframe already exists at offset",l,this);return}const m=t();d.splice(c,0,m),p.splice(c,0,l);const A=()=>{this.duration=h,this.delay=u,this.values=d,this.offsets=p,this.setDirty()},g=()=>{this.duration=n,this.delay=s,this.values=o,this.offsets=a,this.setDirty()};return A(),{undo:g,redo:A}}updateKeyframe(e){if(e<0||e>=this.values.length){console.warn("AnimationObject: Invalid keyframe index",e,this);return}const t=this._thisValueCloner();if(!t){console.warn("AnimationObject: No value to update keyframe for",this);return}const i=this.values[e],n=t(),s=()=>{this.values[e]=n,this.setDirty()},a=()=>{this.values[e]=i,this.setDirty()};return s(),{undo:a,redo:s}}isValueSame(e){if(e<0||e>=this.values.length)return console.warn("AnimationObject: Invalid keyframe index",e,this),!1;const t=this._thisValueCloner();if(!t)return console.warn("AnimationObject: No value to update keyframe for",this),!1;const i=this.values[e],n=t();if(i===n)return!0;if(typeof i!=typeof n)return!1;if(typeof i=="object"&&typeof n=="object"){if(i?.equals)return i.equals(n);if(n?.equals)return n.equals(i)}return!1}refreshUi(){this.setDirty(),this.uiConfig?.uiRefresh?.(!0,"postFrame",1)}add(e){this.animSet.push(e),e.parent=this,this.dispatchEvent({type:"animationAdd",animation:e}),e.addEventListener("update",this.dispatchEvent),e.addEventListener("animationAdd",this.dispatchEvent),e.addEventListener("animationRemove",this.dispatchEvent),this.refreshUi()}remove(e,t=!1){const i=this.animSet.indexOf(e);i>=0&&(this.animSet.splice(i,1),e.parent=void 0,this.dispatchEvent({type:"animationRemove",animation:e,fromChild:t}),e.removeEventListener("update",this.dispatchEvent),e.removeEventListener("animationAdd",this.dispatchEvent),e.removeEventListener("animationRemove",this.dispatchEvent),this.refreshUi())}animate(e=0,t=!0){(typeof e!="number"||isNaN(e))&&(e=0),t&&this.result&&(console.warn("AnimationObject: Already animating, stopping previous animation"),this.stop());const i=this.getViewer(),n=i?.getPlugin("PopmotionPlugin");if(!n){console.error(`AnimationObject: No ${i?"PopmotionPlugin":"viewer"}`);const s=Oi();return{id:s,options:this.options,stop:()=>{},promise:Promise.resolve(s),anims:[]}}return n.animateObject(this,0,t,void 0,e)}stop(){this.result&&(this.result.stop(),this.result=void 0)}async removeFromParent2(){const e=this.getViewer();this.parent&&e&&await e.dialog.confirm(`Delete: Are you sure you want to delete the animation ${this.name}?`)&&this.removeFromParent()}removeFromParent(){this.parent&&this.parent.remove(this,!0)}addAnimation(){const e=new f.AnimationObject(this.target);return this.add(e),e}},Ui([G(),he("setDirty")],f.AnimationObject.prototype,"name",2),Ui([G(),he(f.AnimationObject.prototype._onAccessChanged)],f.AnimationObject.prototype,"access",2),Ui([G()],f.AnimationObject.prototype,"values",2),Ui([G()],f.AnimationObject.prototype,"offsets",2),Ui([G()],f.AnimationObject.prototype,"options",2),Ui([G(),Fe(void 0,[0,1e4],1,r=>({hidden:()=>!r.access})),he("setDirty")],f.AnimationObject.prototype,"duration",2),Ui([G(),Fe(void 0,[0,1e4],1,r=>({hidden:()=>!r.access})),he("setDirty")],f.AnimationObject.prototype,"delay",2),Ui([G(),he("setDirty")],f.AnimationObject.prototype,"repeat",2),Ui([G(),he("setDirty")],f.AnimationObject.prototype,"repeatDelay",2),Ui([G(),he("setDirty")],f.AnimationObject.prototype,"repeatType",2),Ui([G(),Li("ease",Object.keys(Kc).map(r=>({label:r})),r=>({hidden:()=>!r.access})),he("setDirty")],f.AnimationObject.prototype,"ease",2),Ui([G(),se(void 0,r=>({hidden:()=>!r.access})),he("setDirty")],f.AnimationObject.prototype,"updateScene",2),Ui([G(),se(void 0,r=>({hidden:()=>!r.access})),he("setDirty")],f.AnimationObject.prototype,"updateCamera",2),Ui([G(),se(void 0,r=>({hidden:()=>!r.access})),he("setDirty")],f.AnimationObject.prototype,"updateViewer",2),Ui([G(),he("setDirty")],f.AnimationObject.prototype,"updateTarget",2),Ui([he(f.AnimationObject.prototype._onAccessChanged)],f.AnimationObject.prototype,"target",2),Ui([he(f.AnimationObject.prototype._onAccessChanged)],f.AnimationObject.prototype,"viewer",2),Ui([ct("Animate")],f.AnimationObject.prototype,"animate",1),Ui([ct("Stop")],f.AnimationObject.prototype,"stop",1),Ui([ct("Delete")],f.AnimationObject.prototype,"removeFromParent2",1),Ui([G()],f.AnimationObject.prototype,"animSetParallel",2),Ui([G()],f.AnimationObject.prototype,"animSet",2),f.AnimationObject=Ui([Vc("AnimationObject")],f.AnimationObject);function kM(r){return{processObject:e=>{const t=tt(r);if(!(!t||e.userData.autoRegisterInManager===!1)&&(t.object3dManager.registerObject(e),e.material)){if(!t.assetManager){console.error("AssetManager is not initialized yet, cannot register material",e.material);return}const i=Array.isArray(e.material)?e.material:[e.material];for(const n of i)n.userData.autoRegisterInManager!==!1&&t.assetManager.materials.registerMaterial(n)}}}}function GM(r,{autoCenter:e=!1,centerGeometries:t=!1,centerGeometriesKeepPosition:i=!0,autoScale:n=!1,autoScaleRadius:s=2,license:a}){a&&(r.userData.license=[r.userData.license,a].filter(l=>l).join(", "));const o=()=>{e&&!r.userData.isCentered&&!r.userData.pseudoCentered&&!r.isLight?r.autoCenter&&r.autoCenter():r.userData.isCentered=!0,n&&!r.userData.autoScaled&&!r.isLight?r.autoScale&&r.autoScale(r.userData.autoScaleRadius||s):r.userData.autoScaled=!0,t&&!r.userData.geometriesCentered&&Yv(r,i),r.userData.geometriesCentered=!0};r._loadingPromise?r._loadingPromise.finally(o):o()}function Yv(r,e){const t=new Set;r.traverseModels&&r.traverseModels(n=>{n.geometry&&t.add(n.geometry)},{visible:!1,widgets:!1});const i=[];return t.forEach(n=>i.push(n.center2(void 0,e))),()=>i.forEach(n=>n())}class bk extends ti{constructor(e){super(e),this.responseType="blob"}load(e,t,i,n){return super.load(e,s=>{try{t?.(dm(s))}catch(a){n?.(a)}},i,n)}}var wk=Object.defineProperty,Ck=Object.getOwnPropertyDescriptor,Fi=(r,e,t,i)=>{for(var n=i>1?void 0:i?Ck(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&wk(e,t,n),n};const Qi=r=>({onChange:e=>{e.last&&r.onChange()}});f.TextSVGOptions=class{constructor(){this.text="Custom Text",this.fontSize=100,this.width=1024,this.height=1024,this.xOffset=0,this.yOffset=0,this.boxWidth=1024,this.boxHeight=1024,this.textAnchor="middle",this.fontFamily="",this.fontPath="",this.fontWeight="normal",this.fontStyle="normal",this.lineHeight="normal",this.letterSpacing="normal",this.whiteSpace="normal",this.direction="ltr",this.maskText=!1,this.innerShadow=!1,this.textColor="#000000",this.bgFillColor="#ffffff",this.svgBackground="#ffffff",this.onChange=()=>{}}set(e){Object.assign(this,e)}reset(){const e=this.onChange;Object.assign(this,new f.TextSVGOptions),this.onChange=e}toJSON(){return{text:this.text,fontFamily:this.fontFamily,fontPath:this.fontPath,svgBackground:this.svgBackground,width:this.width,height:this.height,xOffset:this.xOffset,yOffset:this.yOffset,boxWidth:this.boxWidth,boxHeight:this.boxHeight,fontSize:this.fontSize,fontWeight:this.fontWeight,fontStyle:this.fontStyle,lineHeight:this.lineHeight,letterSpacing:this.letterSpacing,whiteSpace:this.whiteSpace,direction:this.direction,maskText:this.maskText,innerShadow:this.innerShadow,bgFillColor:this.bgFillColor,textColor:this.textColor,textAnchor:this.textAnchor}}},Fi([He("Text",Qi)],f.TextSVGOptions.prototype,"text",2),Fi([Fe("Font Size",[2,1024],1,Qi)],f.TextSVGOptions.prototype,"fontSize",2),Fi([Fe("Width",[2,4096],1,Qi)],f.TextSVGOptions.prototype,"width",2),Fi([Fe("Height",[2,4096],1,Qi)],f.TextSVGOptions.prototype,"height",2),Fi([Fe("X Offset",[-1024,1024],1,Qi)],f.TextSVGOptions.prototype,"xOffset",2),Fi([Fe("Y Offset",[-1024,1024],1,Qi)],f.TextSVGOptions.prototype,"yOffset",2),Fi([Fe("V-Width",[2,4096],1,Qi)],f.TextSVGOptions.prototype,"boxWidth",2),Fi([Fe("V-Height",[2,4096],1,Qi)],f.TextSVGOptions.prototype,"boxHeight",2),Fi([Li("Text Anchor",["start","middle","end"].map(r=>({label:r})),Qi)],f.TextSVGOptions.prototype,"textAnchor",2),Fi([He("Font",Qi)],f.TextSVGOptions.prototype,"fontFamily",2),Fi([He("Font Url",Qi)],f.TextSVGOptions.prototype,"fontPath",2),Fi([He("Font Weight",Qi)],f.TextSVGOptions.prototype,"fontWeight",2),Fi([Li("Font Style",["normal","italic","oblique"].map(r=>({label:r})),Qi)],f.TextSVGOptions.prototype,"fontStyle",2),Fi([He("Line Height",Qi)],f.TextSVGOptions.prototype,"lineHeight",2),Fi([He("Letter Spacing",Qi)],f.TextSVGOptions.prototype,"letterSpacing",2),Fi([Li("White Space",["normal","pre","nowrap","pre-wrap","pre-line"].map(r=>({label:r})),Qi)],f.TextSVGOptions.prototype,"whiteSpace",2),Fi([Li("Direction",["auto","ltr","rtl"].map(r=>({label:r})),Qi)],f.TextSVGOptions.prototype,"direction",2),Fi([se("Mask Text",Qi)],f.TextSVGOptions.prototype,"maskText",2),Fi([se("Inner Shadow",Qi)],f.TextSVGOptions.prototype,"innerShadow",2),Fi([He("Text Color",Qi)],f.TextSVGOptions.prototype,"textColor",2),Fi([He("BG Fill",Qi)],f.TextSVGOptions.prototype,"bgFillColor",2),Fi([He("SVG BG",Qi)],f.TextSVGOptions.prototype,"svgBackground",2),f.TextSVGOptions=Fi([vt("Text SVG Options")],f.TextSVGOptions);const zM={woff:"woff",woff2:"woff2",ttf:"truetype",otf:"opentype",eot:"embedded-opentype"};function VM({text:r="Custom Text",svgBackground:e="#ffffff",xOffset:t=0,yOffset:i=0,width:n=1024,height:s=1024,boxWidth:a=1024,boxHeight:o=1024,fontFamily:l="",fontSize:c=32,fontWeight:h="normal",fontStyle:u="normal",lineHeight:d="normal",letterSpacing:p="normal",whiteSpace:m="normal",direction:A="auto",maskText:g=!1,innerShadow:y=!1,bgFillColor:v="#000000",textColor:_="#ffffff",textAnchor:b="middle",style:T=""}){return`
<svg style="background-color:${e}" width="${n}" height="${s}" viewBox="0 0 ${a} ${o}"
 xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
     <defs>
        <style>
        ${T}
        .text-g{
            overflow:hidden; text-anchor: ${b}; 
            font-size: ${c}px;
            font-family: ${JSON.stringify(l||"Arial")};
            font-weight: ${h};
            font-style: ${u};
            line-height: ${d};
            letter-spacing: ${p};
            white-space: ${m};
            direction: ${A};
        }
        </style>
    </defs>

    <g class="text-g">
        <defs>

`+(g?`
<mask id="textMask">
<text style="fill:white; font-size: ${c}px; font-weight: ${h}; font-style: ${u}; line-height: ${d}; letter-spacing: ${p}; white-space: ${m}; direction: ${A};" x="${t+a/2}" y="${o/2+i+c/4}" > ${r} </text>
</mask>
`:"")+`

`+(y?`
<filter id="innerShadow" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur in="SourceGraphic" stdDeviation="0.5" result="blur"/>
<feOffset in="blur" dx="1.5" dy="1.5"/>
</filter>
`:"")+`

        </defs>

`+(g?`
        <g mask="url(#textMask)">
`:"")+`

        <rect x="0" y="0" width="${a}" height="${o}" style="fill:${v}"/>
        <text style="${y?"filter: url(#innerShadow);":""} fill:${_}; font-weight: ${h}; font-style: ${u}; line-height: ${d}; letter-spacing: ${p}; white-space: ${m}; direction: ${A};" x="${t+a/2}" y="${o/2+i+c/4}"> ${r} </text>

`+(g?`
        </g>
`:"")+`

    </g>
</svg>
`}const xk={roboto:"https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2"};async function Sk(r,e){const t=r.fontFamily||"Arial";let i=r.fontPath||xk[t]||"",n=r.style||"";if(i.length>0){!Hc(i)&&!i.startsWith("blob:")&&!i.startsWith("ftp:")&&globalThis.window&&(i=new URL(i,window.location.href).href);const o=Vu(i)||"woff";n+=`
`+(i.length>0?`
            @font-face {
                font-family: ${JSON.stringify(t)};
                src: url(${i}) format(${zM[o]||o});
            }`:"")}let s=VM({...r,fontFamily:t,style:n});s=await OS(s,async o=>Ek(o,e)),s=I_(s);const a=await e.importSingle(s);return a?(a.generateMipmaps=!1,a.minFilter=at,a.flipY=!0,a.needsUpdate=!0,a):null}async function Ek(r,e){if(r.startsWith("http://www.w3.org"))return r;if(!e)throw new Error("no importer");const t={fileHandler:new bk(e.loadingManager),processRaw:!1};try{return await e.importSingle(r,t)}catch(i){return console.error(i),""}}const kb=class kb extends xi{constructor(){super(...arguments),this._dirty=!1,this.uiConfig=void 0,this._viewerListeners={},this._onViewerEvent=e=>{const t=e.eType;return t&&this._viewerListeners[t]?.(e),e},this._disabledBy=new Set,this.disable=(e,t=!0)=>{const i=this._disabledBy.size;this._disabledBy.add(e),t&&this.setDirty&&i!==this._disabledBy.size&&this.setDirty()},this.enable=(e,t=!0)=>{const i=this._disabledBy.size;this._disabledBy.delete(e),t&&this.setDirty&&i!==this._disabledBy.size&&this.setDirty()},this.isDisabled=()=>this._disabledBy.size>0||!this.enabled}dispose(){}toJSON(e){const t=We.Serialize(this,e,!0);return t.type=this.constructor.PluginType,t.assetType="config",this.dispatchEvent({type:"serialize",data:t}),t}fromJSON(e,t){return e.type!==this.constructor.PluginType&&e.type!==this.constructor.OldPluginType?null:(We.Deserialize(e,this,t,!0),this.dispatchEvent({type:"deserialize",data:e,meta:t}),this)}_storeKey(e){return(e??"webgi")+"_"+(this.constructor.PluginType||this.constructor.name)}exportState(){return this._viewer?.exportPluginConfig(this)??this.toJSON?.()}async importState(e){this._viewer?await this._viewer.importPluginConfig(e,this):this.fromJSON?.(e)}get dirty(){return this.enabled&&this._dirty}set dirty(e){this._dirty=e}};kb.PluginType="AViewerPlugin";let Zc=kb;class mt extends Zc{constructor(){super(...arguments),this.isViewerPluginSync=!0}onAdded(e){this._viewer=e,this._viewer.addEventListener("*",this._onViewerEvent)}onRemove(e){this._viewer!==e&&e.console.error("Wrong viewer"),this._viewer?.removeEventListener("*",this._onViewerEvent),this._viewer=void 0}}class Mk extends Zc{constructor(){super(...arguments),this.isViewerPluginSync=!1}async onAdded(e){this._viewer=e,this._viewer.addEventListener("*",this._onViewerEvent)}async onRemove(e){this._viewer!==e&&e.console.error("Wrong viewer"),this._viewer?.removeEventListener("*",this._onViewerEvent),this._viewer=void 0}}function eg(){return[{type:"checkbox",label:"Auto LookAt Target",getValue:()=>this.userData.autoLookAtTarget??!1,setValue:r=>{this.userData.autoLookAtTarget=r,this.uiConfig?.uiRefresh?.(!0,"postFrame")}},{type:"input",label:"Auto Near Far",property:[this,"autoNearFar"]},{type:"number",label:"Min Near",hidden:()=>!this.autoNearFar,getValue:()=>this.userData.minNearPlane??ht.defaultMinNear,setValue:r=>{r===ht.defaultMinNear?delete this.userData.minNearPlane:this.userData.minNearPlane=r}},{type:"number",label:"Max Far",hidden:()=>!this.autoNearFar,getValue:()=>this.userData.maxFarPlane??ht.defaultMaxFar,setValue:r=>{r===ht.defaultMaxFar?delete this.userData.maxFarPlane:this.userData.maxFarPlane=r}},{type:"number",label:"Near",readOnly:()=>this.autoNearFar,property:[this,"near"]},{type:"number",label:"Far",readOnly:()=>this.autoNearFar,property:[this,"far"]},()=>({type:"dropdown",label:"Controls Mode",property:[this,"controlsMode"],children:["","orbit",...this.controlsCtors.keys()].map(r=>({label:r===""?"none":r,value:r})),onChange:()=>this.refreshCameraControls()}),{type:"button",label:"Set View",tags:["context-menu"],value:()=>{this.setViewToMain({ui:!0}),this.uiConfig?.uiRefresh?.(!0,"postFrame")}},{type:"button",label:"Activate main",hidden:()=>this?.isMainCamera,tags:["context-menu"],value:()=>{this.activateMain({ui:!0}),this.uiConfig?.uiRefresh?.(!0,"postFrame")}},{type:"button",label:"Deactivate main",tags:["context-menu"],hidden:()=>!this?.isMainCamera,value:()=>{this.deactivateMain({ui:!0}),this.uiConfig?.uiRefresh?.(!0,"postFrame")}}]}function HM(r){if(!this)return{};if(this.uiConfig)return this.uiConfig;const e={type:"folder",label:()=>this.name||"unnamed",expanded:!0,onChange:t=>{if(!t.config||t.config.onChange)return;let i=Array.isArray(t.config.property)?t.config.property[1]:t.config.property;i=typeof i=="string"?i:void 0,this.setDirty&&this.setDirty({uiChangeEvent:t,refreshScene:!1,refreshUi:!!t.last,change:i})},children:[{type:"checkbox",label:"Visible",property:[this,"visible"],onChange:t=>{this.setDirty?.({uiChangeEvent:t,refreshScene:!0,refreshUi:!0,change:"visible"})}},{type:"input",property:[this,"uuid"],disabled:!0,tags:["advanced"]},{type:"input",label:"Name",property:[this,"name"],onChange:t=>{t.last&&this.setDirty?.({uiChangeEvent:t,refreshScene:!0,frameFade:!1,refreshUi:!0,change:"name"})}},{type:"checkbox",label:"Casts Shadow",hidden:()=>!this.isMesh,property:[this,"castShadow"],onChange:t=>{this.setDirty?.({uiChangeEvent:t,refreshScene:!0,refreshUi:!0,change:"castShadow"})}},{type:"checkbox",label:"Receive Shadow",hidden:()=>!this.isMesh,property:[this,"receiveShadow"],onChange:t=>{this.setDirty?.({uiChangeEvent:t,refreshScene:!0,refreshUi:!0,change:"receiveShadow"})}},{type:"checkbox",label:"Frustum culled",property:[this,"frustumCulled"]},{type:"vec3",label:"Position",property:[this,"position"]},{type:"vec3",label:"Rotation",property:[this,"rotation"]},{type:"vec3",label:"Scale",property:[this,"scale"]},{type:"input",label:"Render Order",property:[this,"renderOrder"]},{type:"button",label:"Scale to Radius",tags:["context-menu","interaction"],hidden:()=>!this.autoScale,value:async()=>{const t=(this.userData.autoScaleRadius||2)+"",i=await f.ThreeViewer.Dialog.prompt("Auto Scale Radius: Object will be scaled to the given radius",t);if(i===null)return;const n=parseFloat(i||t);if(Math.abs(n)>0)return{action:()=>this.autoScale?.(n),undo:()=>this.autoScale?.(n,void 0,void 0,!0)}}},{type:"button",label:"Auto Center",tags:["context-menu","interaction"],hidden:()=>!this.autoCenter,value:()=>({action:()=>this.autoCenter?.(!0),undo:()=>this.autoCenter?.(!0,!0)})},{type:"button",label:"Pivot to Node Center",tags:["context-menu","interaction"],value:async()=>{if(await f.ThreeViewer.Dialog.confirm("Pivot to Center: Adjust the pivot to bounding box center. The object will rotate around the new pivot, are you sure you want to proceed?"))return this.pivotToBoundsCenter?.(!0)}},...co.call(this),{type:"folder",label:"Rotate model",children:["X +","X -","Y +","Y -","Z +","Z -"].map(t=>({type:"button",label:"Rotate "+t+"90",value:()=>{const i=new S(t.includes("X")?1:0,t.includes("Y")?1:0,t.includes("Z")?1:0),n=Math.PI/2*(t.includes("-")?-1:1);return{action:()=>{this.rotateOnAxis(i,n),this.setDirty?.({refreshScene:!0,refreshUi:!1})},undo:()=>{this.rotateOnAxis(i,-n),this.setDirty?.({refreshScene:!0,refreshUi:!1})}}}}))},this.userData.license!==void 0?{type:"input",label:"License/Credits",property:[this.userData,"license"]}:{}]};if((this.isLine||this.isMesh)&&r!==!1){const t=[()=>{const i=Object.entries(this.morphTargetDictionary||{});return i.length?{label:"Morph Targets",type:"folder",children:i.map(([n,s])=>({type:"slider",label:n,bounds:[0,1],stepSize:1e-4,property:[this.morphTargetInfluences,s],onChange:a=>{this.setDirty?.({refreshScene:a.last,frameFade:!1,refreshUi:!1})}}))}:void 0},{type:"divider"}];e.children.push(...t)}if(this.isCamera){const t=eg.call(this);e.children.push(...t)}return e.children.push(tg.call(this)),this.uiConfig=e,e}function tg(){return r=>this.objectExtensions?.flatMap(e=>(e.uuid=e.uuid||Oi(),this.__objExtUiConfigs=this.__objExtUiConfigs||{},this.__objExtUiConfigs[e.uuid]||(this.__objExtUiConfigs[e.uuid]=e.getUiConfig?e.getUiConfig(this,this.uiConfig?.uiRefresh):void 0),this.__objExtUiConfigs[e.uuid]?.flatMap(t=>tt(t,r)))).filter(e=>e)}function ig(r,e,t){t=t??r.name;const i=t.match(/\(copy( (\d+))?\)$/);if(i){let n=i[2]?parseInt(i[2])+1:2,s=t.replace(/\(copy( \d+)?\)$/,`(copy ${n})`);const a=r.parent;if(a&&a!==e.parent){const o=new Set(a.children.filter(l=>l!==r).map(l=>l.name));for(let l=0;l<1e3&&o.has(s);l++)n++,s=t.replace(/\(copy( \d+)?\)$/,`(copy ${n})`)}e.name=s}else e.name=t+" (copy)"}function co(){return[{type:"button",label:"Duplicate Object",tags:["context-menu"],value:async r=>qe.duplicateObject(this,r)},{type:"button",label:"Delete Object",tags:["context-menu"],value:async r=>qe.deleteObject(this,r)}]}const ni={setDirty:function(r){this.dispatchEvent({bubbleToObject:!0,...r,type:"geometryUpdate",geometry:this}),this.refreshUi()},refreshUi:function(){this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},dispose:r=>function(e=!0){!e&&this.userData.disposeOnIdle===!1||r.call(this)},clone:r=>function(){return ni.upgradeGeometry.call(r.call(this))},upgradeGeometry:Tk,center:r=>function(e,t=!1,i=!0){if(t){e=e?e.clone():new S,r.call(this,e),e.negate();const n=this.appliedMeshes;for(const s of n)s.updateMatrix(),s.position.copy(e).applyMatrix4(s.matrix),i&&s.setDirty&&s.setDirty()}else r.call(this,e);return i&&this.setDirty(),this},center2:function(r,e=!1,t=!0){const i=r||new S;if(e){this.center(i,!1,!1);const n=this.appliedMeshes,s=new WeakMap;for(const a of n)a.updateMatrix(),s.set(a,a.position.clone()),a.position.set(-i.x,-i.y,-i.z).applyMatrix4(a.matrix),t&&a.setDirty&&a.setDirty();return t&&this.setDirty&&this.setDirty(),()=>{for(const a of n){const o=s.get(a);if(!o){console.warn("GeometryCommons: No position found for mesh",a);continue}a.position.copy(o),t&&a.setDirty&&a.setDirty()}t&&this.setDirty&&this.setDirty()}}else return this.center(i,!1,!1),t&&this.setDirty&&this.setDirty(),()=>{this.translate(-i.x,-i.y,-i.z),t&&this.setDirty&&this.setDirty()}},makeUiConfig:function(){return this.uiConfig?this.uiConfig:{label:"Geometry",uuid:"geom",type:"folder",children:[{type:"input",property:[this,"name"]},{type:"input",property:[this,"uuid"],disabled:!0,tags:["advanced"]},()=>this.groups.length?{type:"folder",label:"Groups",uuid:"groups",tags:["advanced"],children:this.groups.map((r,e)=>({type:"folder",label:`Group ${e}`,uuid:"group-"+e,tags:["advanced"],children:[{type:"input",label:"Start",uuid:"start",getValue:()=>r.start,setValue:t=>{r.start=t,this.setDirty&&this.setDirty()}},{type:"input",label:"Count",uuid:"count",getValue:()=>r.count,setValue:t=>{r.count=t,this.setDirty&&this.setDirty()}},{type:"input",label:"Material Index",uuid:"mi",getValue:()=>r.materialIndex,setValue:t=>{r.materialIndex=t,this.setDirty&&this.setDirty()}}]}))}:null,{type:"divider"},{type:"button",label:"Center Geometry",tags:["context-menu"],value:async()=>{if(await f.ThreeViewer.Dialog.confirm("This will move the objects based on the geometry center, do you want to continue?"))return this.center2()}},{type:"button",label:"Center Geometry (keep position)",tags:["context-menu"],value:async()=>{if(await f.ThreeViewer.Dialog.confirm("This will move the geometry center keeping the object position, do you want to continue?"))return this.center2(void 0,!0)}},{type:"button",label:"Compute vertex normals",tags:["context-menu"],value:async()=>{this.hasAttribute("normal")&&!await f.ThreeViewer.Dialog.confirm(`Normals already exist, replace with computed normals?
This action cannot be undone.`)||(this.computeVertexNormals(),this.setDirty&&this.setDirty())}},{type:"button",label:"Compute vertex tangents",tags:["context-menu"],value:async()=>{this.hasAttribute("tangent")&&!await f.ThreeViewer.Dialog.confirm(`Tangents already exist, replace with computed tangents?
This action cannot be undone.`)||(this.computeTangents(),this.setDirty&&this.setDirty())}},{type:"button",label:"Normalize normals",tags:["context-menu"],value:()=>{this.normalizeNormals(),this.setDirty&&this.setDirty()}},{type:"button",label:"Convert to indexed",hidden:()=>!!this.index,tags:["context-menu"],value:async()=>{if(this.attributes.index)return;const r=parseFloat(await f.ThreeViewer.Dialog.prompt("Convert to Indexed: Tolerance?","-1")??"-1");lv(this,r),this.setDirty&&this.setDirty()}},{type:"button",label:"Convert to non-indexed",hidden:()=>!this.index,tags:["context-menu"],value:()=>{this.attributes.index&&(this.toNonIndexed(),this.setDirty&&this.setDirty())}},{type:"button",label:"Create uv1 from uv",tags:["context-menu"],value:async()=>{this.hasAttribute("uv1")&&!await f.ThreeViewer.Dialog.confirm(`uv1 already exists, replace with uv data?
This action cannot be undone.`)||(this.setAttribute("uv1",this.getAttribute("uv")),this.setDirty&&this.setDirty())}},{type:"button",label:"Remove vertex color attribute",hidden:()=>!this.hasAttribute("color"),tags:["context-menu"],value:async()=>{if(!this.hasAttribute("color")){await f.ThreeViewer.Dialog.alert("No color attribute found");return}await f.ThreeViewer.Dialog.confirm("Remove color attribute?")&&(this.deleteAttribute("color"),this.setDirty&&this.setDirty())}},{type:"button",label:"Auto GPU Instances",hidden:()=>!this.appliedMeshes||this.appliedMeshes.size<2,tags:["context-menu"],value:async()=>{await f.ThreeViewer.Dialog.confirm("This will automatically create Instanced Mesh from geometry instances. This action is irreversible, do you want to continue?")&&pv(this)}},{type:"input",label:"Mesh count",getValue:()=>this.appliedMeshes?.size??0,disabled:!0}]}}};function Tk(){return this.assetType==="geometry"?this:this.isBufferGeometry?(this.assetType="geometry",this.dispose=ni.dispose(this.dispose),this.center=ni.center(this.center),this.clone=ni.clone(this.clone),this.center2||(this.center2=ni.center2),this.setDirty||(this.setDirty=ni.setDirty),this.refreshUi||(this.refreshUi=ni.refreshUi),this.appliedMeshes||(this.appliedMeshes=new Set),this.userData||(this.userData={}),this.uiConfig=ni.makeUiConfig.call(this),this):(console.error("Geometry is not a BufferGeometry",this),this)}const Gb=class Gb{static ApplyMaterialExtensions(e,t,i,n){for(const s of i)this.ApplyMaterialExtension(e,t,s,n)}static ApplyMaterialExtension(e,t,i,n){let s=tt(i.parsFragmentSnippet,n,e)??"";s.length&&(t.fragmentShader=bt(t.fragmentShader,this.VoidMain,`
`+s+`
`,{prepend:!0})),s=tt(i.parsVertexSnippet,n,e)??"",s.length&&(t.vertexShader=bt(t.vertexShader,this.VoidMain,`
`+s+`
`,{prepend:!0})),i.extraUniforms&&(t.uniforms=Object.assign(t.uniforms,ES(i.extraUniforms,a=>tt(a,t)||{value:null}))),i.extraDefines&&ba(i.extraDefines,e),i.shaderExtender&&i.shaderExtender(t,e,n),e.lastShader=t}static CacheKeyForExtensions(e,t){let i="";for(const n of t)i+=this.CacheKeyForExtension(e,n);return i}static CacheKeyForExtension(e,t){let i="";return t.computeCacheKey?i+=tt(t.computeCacheKey,e):i+=t.uuid,t.extraDefines&&(i+=Object.values(t.extraDefines).map(n=>tt(n)??"").join("")),i}static RegisterExtensions(e,t){const i=[];if(Array.isArray(e.materialExtensions)||(e.materialExtensions=[]),t)for(const n of t)e.materialExtensions.includes(n)||n.isCompatible!==void 0&&(!n.isCompatible||!n.isCompatible(e))||(i.push(n),n.uuid||(n.uuid=Oi()),n.__setDirty||(n.__setDirty=()=>{n.updateVersion||(n.updateVersion=0),n.updateVersion++}),n.setDirty||(n.setDirty=n.__setDirty));if(!i.length)return[];e.materialExtensions=[...e.materialExtensions||[],...i].sort((n,s)=>(s.priority||0)-(n.priority||0)),e.__extListen||(e.__extListen=!0,e.addEventListener("beforeRender",QM),e.addEventListener("afterRender",jM),e.addEventListener("addToMesh",WM),e.addEventListener("removeFromMesh",qM),e.addEventListener("materialUpdate",XM));for(const n of i)n.onRegister&&n.onRegister(e);return e.needsUpdate=!0,i}static UnregisterExtensions(e,t){if(t){e.materialExtensions=e.materialExtensions?.filter(i=>!t.includes(i))||[];for(const i of t)i.onUnregister&&i.onUnregister(e)}!e.materialExtensions?.length&&e.__extListen&&(e.removeEventListener("beforeRender",QM),e.removeEventListener("afterRender",jM),e.removeEventListener("addToMesh",WM),e.removeEventListener("removeFromMesh",qM),e.removeEventListener("materialUpdate",XM),delete e.__extListen)}};Object.assign(lt,V_),Gb.VoidMain="void main()";let yl=Gb;function ba(r,e){if(!r||!e)return;(e.defines===void 0||e.defines===null)&&(e.defines={});let t=!1;const i=Object.entries(r);for(const[n,s]of i){const a=tt(s);a===void 0?e.defines[n]!==void 0&&(delete e.defines[n],t=!0):e.defines[n]!==a&&(e.defines[n]=typeof a=="boolean"?+a:a,t=!0)}t&&(e.needsUpdate=!0)}function QM({target:r,object:e,renderer:t}){const i=r,n=t;if(!i||!e||!n)throw new Error("Invalid material, object or renderer");if(i.materialExtensions)for(const s of i.materialExtensions){if(s.onObjectRender&&s.onObjectRender(e,i,n),i.lastShader){const o=tt(s.updaters)||[];for(const l of o)l&&l.updateShaderProperties(i.lastShader)}const a="_"+s.uuid+"_version";s.updateVersion!==i.userData[a]&&(i.userData[a]=s.updateVersion,i.needsUpdate=!0)}}function jM({target:r,object:e,renderer:t}){const i=r,n=t;if(!i||!e||!n)throw new Error("Invalid material, object or renderer");if(i.materialExtensions)for(const s of i.materialExtensions)s.onAfterRender&&s.onAfterRender(e,i,n)}function WM({target:r,object:e}){const t=r;if(!t||!e)throw new Error("Invalid material or object");if(t.materialExtensions)for(const i of t.materialExtensions)i.onAddToMesh&&i.onAddToMesh(e,t)}function qM({target:r,object:e}){const t=r;if(!t||!e)throw new Error("Invalid material or object");if(t.materialExtensions)for(const i of t.materialExtensions)i.onRemoveFromMesh&&i.onRemoveFromMesh(e,t)}function XM({target:r}){const e=r;if(!e)throw new Error("Invalid material");if(e.materialExtensions)for(const t of e.materialExtensions)t.onMaterialUpdate&&t.onMaterialUpdate(e)}function YM(r,e){const t=e||Oi();return{uuid:t,getUiConfig:i=>{if(i.__uiConfigs||(i.__uiConfigs={}),i.__uiConfigs[t])return i.__uiConfigs[t];const n=r(i);return i.__uiConfigs[t]=n,n},isCompatible:()=>!0}}function Ii(r,e,t,i,n=()=>r.setDirty&&r.setDirty()){return{type:"folder",label:t??e+" Sampler",hidden:()=>!r[e]||i&&i(),onChange:n,children:[()=>({type:"vec2",label:"Repeat",stepSize:.001,property:[r[e],"repeat"]}),()=>({type:"vec2",label:"Offset",stepSize:.001,property:[r[e],"offset"]}),()=>({type:"vec2",label:"Center",stepSize:.001,property:[r[e],"center"]}),()=>({type:"input",label:"Rotation",stepSize:.001,bounds:[-Math.PI,Math.PI],property:[r[e],"rotation"]}),()=>({type:"dropdown",label:"Color space",property:[r[e],"colorSpace"],children:[["Linear",Bt],["sRGB",Ct]].map(s=>({label:s[0],value:s[1]})),onChange:[()=>{const s=r[e];s&&(s.needsUpdate=!0)}]}),()=>({type:"dropdown",label:"UV Channel",property:[r[e],"channel"],children:[0,1,2,3].map(s=>({label:s.toString(),value:s})),onChange:()=>{const s=r[e];s&&(s.needsUpdate=!0)}}),()=>({type:"checkbox",label:"Flip Y",getValue:()=>r[e]?.flipY??!1,setValue:s=>{const a=r[e];if(a&&a.flipY!==s)if(a.image&&ImageBitmap&&a.image instanceof ImageBitmap){const o=a,l=a.source.data;createImageBitmap(l,{imageOrientation:"flipY"}).then(c=>{l.close&&l.close(),o.flipY=s,o.source.data=c,o.source.needsUpdate=!0,o.needsUpdate=!0,n()})}else a.flipY=s,a.needsUpdate=!0,n()}}),()=>({type:"dropdown",label:"Wrap S",property:[r[e],"wrapS"],children:[["ClampToEdge",di],["MirroredRepeat",Kr],["Repeat",Pn]].map(s=>({label:s[0],value:s[1]})),onChange:[()=>{r[e]&&(r[e].needsUpdate=!0)}]}),()=>({type:"dropdown",label:"Wrap T",property:[r[e],"wrapT"],children:[["ClampToEdge",di],["MirroredRepeat",Kr],["Repeat",Pn]].map(s=>({label:s[0],value:s[1]})),onChange:[()=>{r[e]&&(r[e].needsUpdate=!0)}]}),()=>({type:"input",label:"Anisotropy",bounds:[1,6],stepSize:1,property:[r[e],"anisotropy"],onChange:[()=>{r[e]&&(r[e].needsUpdate=!0),r.needsUpdate=!0}]}),()=>({type:"dropdown",label:"Min Filter",property:[r[e],"minFilter"],children:[["Linear",at],["Nearest",mi],["NearestMipmapNearest",Jh],["NearestMipmapLinear",Na],["LinearMipmapNearest",Io],["LinearMipmapLinear",Dn]].map(s=>({label:s[0],value:s[1]})),onChange:[()=>{r[e]&&(r[e].needsUpdate=!0)}]}),()=>({type:"dropdown",label:"Mag Filter",property:[r[e],"magFilter"],children:[["Linear",at],["Nearest",mi]].map(s=>({label:s[0],value:s[1]})),onChange:[()=>{r[e]&&(r[e].needsUpdate=!0)}]})]}}const Xt={base:r=>[{type:"input",property:[r,"name"]},{type:"checkbox",property:[r,"wireframe"]},{type:"checkbox",property:[r,"vertexColors"]},{type:"color",property:[r,"color"]},r.flatShading!==void 0?{type:"checkbox",property:[r,"flatShading"]}:{},{type:"image",property:[r,"map"]},Ii(r,"map")],blending:r=>({type:"folder",label:"Blending",children:[{type:"slider",bounds:[0,1],property:[r,"opacity"]},{type:"checkbox",property:[r,"transparent"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"transparent"})},{type:"dropdown",property:[r,"depthFunc"],children:[["Never",mw],["Always",gw],["Less",Aw],["LessEqual",Yl],["Equal",yw],["GreaterEqual",_w],["Greater",vw],["NotEqual",bw]].map(e=>({label:e[0],value:e[1]}))},{type:"checkbox",property:[r,"depthTest"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"depthTest"})},{type:"checkbox",property:[r,"depthWrite"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"depthWrite"})},{type:"checkbox",property:[r,"colorWrite"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"colorWrite"})},{type:"slider",bounds:[0,1],stepSize:.001,property:[r,"alphaTest"]},{type:"checkbox",property:[r,"alphaHash"]},{type:"checkbox",property:[r,"dithering"]},{type:"dropdown",label:"Blending",property:[r,"blending"],children:[["None",gn],["Normal",Sr],["Additive",df],["Subtractive",ff],["Multiply",pf],["Custom",er]].map(e=>({label:e[0],value:e[1]}))},{type:"dropdown",hidden:()=>r.blending!==er,property:[r,"blendingEquation"],children:[["Add",Er],["Subtract",hw],["Reverse Subtract",uw],["Min",dw],["Max",fw]].map(e=>({label:e[0],value:e[1]}))},{type:"dropdown",property:[r,"blendSrc"],hidden:()=>r.blending!==er,children:[["Zero",SA],["One",EA],["Src Color",MA],["One Minus Src Color",TA],["Src Alpha",jl],["One Minus Src Alpha",Wl],["Dst Alpha",IA],["One Minus Dst Alpha",PA],["Dst Color",DA],["One Minus Dst Color",RA],["Src Alpha Saturate",pw],["Constant Color",Yh],["One Minus Constant Color",$h],["Constant Alpha",ql],["One Minus Constant Alpha",Xl]].map(e=>({label:e[0],value:e[1]}))},{type:"dropdown",property:[r,"blendDst"],hidden:()=>r.blending!==er,children:[["Zero",SA],["One",EA],["Src Color",MA],["One Minus Src Color",TA],["Src Alpha",jl],["One Minus Src Alpha",Wl],["Dst Alpha",IA],["One Minus Dst Alpha",PA],["Dst Color",DA],["One Minus Dst Color",RA],["Constant Color",Yh],["One Minus Constant Color",$h],["Constant Alpha",ql],["One Minus Constant Alpha",Xl]].map(e=>({label:e[0],value:e[1]}))},{type:"slider",bounds:[0,1],hidden:()=>r.blending!==er,property:[r,"blendSrcAlpha"]},{type:"slider",bounds:[0,1],hidden:()=>r.blending!==er,property:[r,"blendDstAlpha"]},{type:"color",hidden:()=>r.blending!==er||r.blendSrc!==Yh&&r.blendSrc!==$h&&r.blendDst!==Yh&&r.blendDst!==$h,property:[r,"blendColor"]},{type:"slider",hidden:()=>r.blending!==er||r.blendSrc!==ql&&r.blendSrc!==Xl&&r.blendDst!==ql&&r.blendDst!==Xl,bounds:[0,1],property:[r,"blendAlpha"]},r.alphaMap!==void 0?{type:"image",property:[r,"alphaMap"]}:{},r.alphaMap!==void 0?Ii(r,"alphaMap"):{},{type:"checkbox",label:"Render to Gbuffer",getValue:()=>r.userData.renderToGBuffer===!0,setValue:e=>{!e&&r.userData.renderToGBuffer===!1||(r.userData.renderToGBuffer=e,r.setDirty({change:"userData",key:"renderToGBuffer"}))}},{type:"checkbox",label:"Render to Depth",hidden:()=>r.userData.renderToDepth===void 0,getValue:()=>r.userData.renderToDepth===!0,setValue:e=>{!e&&r.userData.renderToDepth===!1||(r.userData.renderToDepth=e,r.setDirty({change:"userData",key:"renderToDepth"}))}},{type:"input",label:"Forced Linear Depth",getValue:()=>r.userData.forcedLinearDepth??-1,setValue:e=>{e<0&&r.userData.forcedLinearDepth===void 0||(e>=0?r.userData.forcedLinearDepth=e:delete r.userData.forcedLinearDepth,r.setDirty({change:"userData",key:"forcedLinearDepth"}))}},r.isPhysicalMaterial?{type:"checkbox",label:"Inverse AlphaMap",hidden:()=>!r.transparent,getValue:()=>r.userData.inverseAlphaMap===!0,setValue:e=>{r.userData.inverseAlphaMap=e||void 0,r.setDirty({change:"userData",key:"inverseAlphaMap"})}}:{}]}),polygonOffset:r=>({type:"folder",label:"Polygon Offset",children:[{type:"checkbox",label:"Polygon Offset",property:[r,"polygonOffset"]},{type:"slider",label:"Polygon Offset Factor",bounds:[-10,10],property:[r,"polygonOffsetFactor"]},{type:"slider",label:"Polygon Offset Units",bounds:[-10,10],property:[r,"polygonOffsetUnits"]}]}),aoLightMap:r=>({type:"folder",label:"AO/Lightmap",children:[{type:"slider",bounds:[0,2],property:[r,"aoMapIntensity"]},{type:"image",property:[r,"aoMap"]},Ii(r,"aoMap"),{type:"slider",bounds:[0,2],property:[r,"lightMapIntensity"]},{type:"image",property:[r,"lightMap"]},Ii(r,"lightMap")]}),environment:r=>({type:"folder",label:"Environment",children:[{type:"checkbox",label:"Override Environment",getValue:()=>r.userData.separateEnvMapIntensity===!0,setValue:e=>{r.userData.separateEnvMapIntensity=e,e||delete r.userData.separateEnvMapIntensity}},{type:"slider",bounds:[0,20],hidden:()=>!r.userData.separateEnvMapIntensity,label:"Environment Intensity",property:[r,"envMapIntensity"]},{type:"dropdown",hidden:()=>!r.userData.separateEnvMapIntensity&&!r.userData.envMapSlotKey,label:"Environment Map",children:["","environment1","environment2"].map(e=>({label:e||"default",value:e})),getValue:()=>r.userData.envMapSlotKey||"",setValue:e=>{r.userData.envMapSlotKey=e,e||delete r.userData.envMapSlotKey,r.setDirty({change:"userData",key:"envMapSlotKey"})}}]}),misc:r=>[()=>r.materialExtensions?.map(e=>(e.uuid=e.uuid||Oi(),r.__matExtUiConfigs=r.__matExtUiConfigs||{},r.__matExtUiConfigs[e.uuid]||(r.__matExtUiConfigs[e.uuid]=e.getUiConfig?.(r,r.uiConfig?.uiRefresh)),r.__matExtUiConfigs[e.uuid])).filter(e=>e),{type:"dropdown",label:"Side",property:[r,"side"],children:[["Front",us],["Back",In],["Double",Zi]].map(e=>({label:e[0],value:e[1]}))},{type:"input",label:"Mesh count",getValue:()=>r.appliedMeshes.size||0,disabled:!0},{type:"button",label:`Download ${r.constructor.TypeSlug}`,value:()=>{const e=new Blob([JSON.stringify(r.toJSON(),null,2)],{type:"application/json"});Qu(e,`material.${r.constructor.TypeSlug}`)}},{type:"button",label:`Select ${r.constructor.TypeSlug}`,value:async()=>yS(!1,!1,r.constructor.TypeSlug).then(async e=>e?.[0]?.text()).then(e=>{if(!e)return;const t=JSON.parse(e);t.uuid&&delete t.uuid;const i=r.toJSON();return r.fromJSON(t,Fr()),{undo:()=>r.fromJSON(i,Fr()),redo:()=>r.fromJSON(t,Fr())}})}],roughMetal:r=>({type:"folder",label:"Rough/Metal",children:[{type:"slider",bounds:[0,1],property:[r,"roughness"]},{type:"slider",bounds:[0,1],property:[r,"metalness"]},{type:"image",property:[r,"roughnessMap"]},Ii(r,"roughnessMap"),{type:"image",property:[r,"metalnessMap"]},Ii(r,"metalnessMap")]}),bumpNormal:r=>({type:"folder",label:"Bump/Normal",children:[{type:"slider",bounds:[-500,500],stepSize:.001,property:[r,"bumpScale"],hidden:()=>!r.bumpMap},{type:"image",property:[r,"bumpMap"]},Ii(r,"bumpMap"),{type:"image",property:[r,"normalMap"]},{type:"vec2",property:[r,"normalScale"],hidden:()=>!r.normalMap},{type:"dropdown",hidden:()=>!r.normalMap,property:[r,"normalMapType"],children:[["TangentSpace",Us],["ObjectSpace",Fw]].map(e=>({label:e[0],value:e[1]}))},Ii(r,"normalMap"),{type:"input",property:[r,"displacementScale"],hidden:()=>!r.displacementMap},{type:"image",property:[r,"displacementMap"]},Ii(r,"displacementMap")]}),emission:r=>({type:"folder",label:"Emission",children:[{type:"color",property:[r,"emissive"]},{type:"slider",bounds:[0,100],property:[r,"emissiveIntensity"]},{type:"image",property:[r,"emissiveMap"]},Ii(r,"emissiveMap")]}),transmission:r=>({type:"folder",label:"Refraction",children:[{type:"slider",bounds:[0,4],property:[r,"ior"]},{type:"slider",bounds:[0,1],property:[r,"transmission"]},{type:"slider",bounds:[0,1],stepSize:.001,property:[r,"thickness"]},{type:"image",property:[r,"transmissionMap"]},Ii(r,"transmissionMap"),{type:"image",property:[r,"thicknessMap"]},Ii(r,"thicknessMap"),{type:"number",property:[r,"attenuationDistance"]},{type:"color",property:[r,"attenuationColor"]}]}),clearcoat:r=>({type:"folder",label:"Clearcoat",children:[{type:"slider",bounds:[0,1],property:[r,"clearcoat"]},{type:"slider",bounds:[0,1],hidden:()=>r.clearcoat<.001,property:[r,"clearcoatRoughness"]},{type:"image",property:[r,"clearcoatMap"]},Ii(r,"clearcoatMap"),{type:"slider",bounds:[0,1],property:[r,"clearcoatRoughness"]},{type:"image",property:[r,"clearcoatRoughnessMap"]},Ii(r,"clearcoatRoughnessMap"),{type:"image",property:[r,"clearcoatNormalMap"]},{type:"vec2",property:[r,"clearcoatNormalScale"],hidden:()=>!r.clearcoatNormalMap},Ii(r,"clearcoatNormalMap")]}),iridescence:r=>({type:"folder",label:"Iridescence",children:[{type:"slider",bounds:[0,3],label:"Intensity",property:[r,"iridescence"]},{type:"slider",bounds:[0,3],label:"IOR",property:[r,"iridescenceIOR"]},{type:"slider",bounds:[0,500],label:"Thickness0",property:[r.iridescenceThicknessRange,"0"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"iridescenceThicknessRange",key:"0"})},{type:"slider",bounds:[0,500],label:"Thickness1",property:[r.iridescenceThicknessRange,"1"],onChange:e=>r.setDirty({uiChangeEvent:e,change:"iridescenceThicknessRange",key:"1"})},{type:"image",property:[r,"iridescenceMap"]},Ii(r,"iridescenceMap"),{type:"image",property:[r,"iridescenceThicknessMap"]},Ii(r,"iridescenceThicknessMap")]}),sheen:r=>({type:"folder",label:"Sheen",children:[{type:"slider",bounds:[0,1],property:[r,"sheen"]},{type:"color",hidden:()=>r.sheen<.001,property:[r,"sheenColor"]},{type:"image",property:[r,"sheenColorMap"]},Ii(r,"sheenColorMap"),{type:"slider",bounds:[0,1],property:[r,"sheenRoughness"]},{type:"image",property:[r,"sheenRoughnessMap"]},Ii(r,"sheenRoughnessMap")]})},It={name:"",blending:Sr,side:us,vertexColors:!1,opacity:1,transparent:!1,blendSrc:jl,blendDst:Wl,blendEquation:Er,blendSrcAlpha:null,blendDstAlpha:null,blendEquationAlpha:null,blendColor:"#000000",blendAlpha:0,depthFunc:Yl,depthTest:!0,depthWrite:!0,stencilWriteMask:255,stencilFunc:ly,stencilRef:0,stencilFuncMask:255,stencilFail:Zr,stencilZFail:Zr,stencilZPass:Zr,stencilWrite:!1,clippingPlanes:null,clipIntersection:!1,clipShadows:!1,shadowSide:null,colorWrite:!0,precision:null,polygonOffset:!1,polygonOffsetFactor:0,polygonOffsetUnits:0,dithering:!1,alphaToCoverage:!1,premultipliedAlpha:!1,forceSinglePass:!1,allowOverride:!0,visible:!0,toneMapped:!0,userData:{},alphaTest:0,alphaHash:!1},wa=["opacity","blendColor","blendAlpha","alphaTest"],Ar=class Ar extends is{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isUnlitMaterial=!0,this.appliedMeshes=new Set,this.setDirty=ve.setDirty,this.envMap=null,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=ve.registerMaterialExtensions,this.unregisterMaterialExtensions=ve.unregisterMaterialExtensions,this.onBeforeRender=ve.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=ve.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Unlit Material",uuid:"MBM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[...Xt.base(this),...bi(this),Xt.blending(this),Xt.aoLightMap(this),Xt.polygonOffset(this),...Xt.misc(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),ve.upgradeMaterial.call(this),this.setValues(t)}dispose(){return ve.dispose(super.dispose).call(this)}clone(e=!1){return ve.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+ve.customProgramCacheKey.call(this)}onBeforeCompile(e,t){const i=[["vec3 outgoingLight = ","afterModulation"],["#include <aomap_fragment>","beforeModulation"],["ReflectedLight reflectedLight = ","beforeAccumulation"],["#include <clipping_planes_fragment>","mainStart"]],n=[["#include <uv_vertex>","mainStart"]];for(const s of n)e.vertexShader=bt(e.vertexShader,s[0],"#glMarker "+s[1]+`
`+s[0]);for(const s of i)e.fragmentShader=bt(e.fragmentShader,s[0],"#glMarker "+s[1]+`
`+s[0]);ve.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}setValues(e,t=!0,i=void 0,n){return e?e.type&&!t&&!["MeshBasicMaterial","MeshBasicMaterial2",this.constructor.TYPE,this.type].includes(e.type)?(console.error("Material type is not supported:",e.type),this):(ve.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...We.Serialize(this,e,!0)}:We.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(We.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};Ar.TypeSlug="bmat",Ar.TYPE="UnlitMaterial",Ar.TypeAlias=["unlit","basic",Ar.TYPE,Ar.TypeSlug,"MeshBasicMaterial","MeshBasicMaterial2"],We.SerializableMaterials.add(Ar),Ar.MaterialProperties={...It,color:new ee(16777215),map:null,lightMap:null,lightMapIntensity:1,aoMap:null,aoMapIntensity:1,specularMap:null,alphaMap:null,envMap:null,combine:$l,envMapIntensity:1,reflectivity:1,refractionRatio:.98,wireframe:!1,wireframeLinewidth:1,wireframeLinecap:"round",wireframeLinejoin:"round",skinning:!1,fog:!0,flatShading:!1},Ar.MapProperties=["map","aoMap","lightMap","specularMap","alphaMap","envMap"],Ar.InterpolateProperties=[...wa,"color","color","specular","emissive","reflectivity","refractionRatio","envMapIntensity","lightMapIntensity","aoMapIntensity","wireframeLinewidth"];let gs=Ar;class Ik extends gs{constructor(e){super(e),console.error("MeshBasicMaterial2 is deprecated, use UnlitMaterial instead")}}const ve={threeMaterialPropList:It,threeMaterialInterpolateProps:wa,setDirty:function(r){r?.needsUpdate!==!1&&(this.needsUpdate=!0),ve.refreshTextureRefs.call(this),this.dispatchEvent({bubbleToObject:!0,bubbleToParent:!0,...r,type:"materialUpdate"}),r?.last!==!1&&r?.refreshUi!==!1&&this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},setValues:r=>function(e,t,i,n){i===void 0&&(i=e.isMaterial),i&&(this.userData={});const s=e?.metadata&&e?.metadata.version<=4.5,a=Nt.enabled;s&&(Nt.enabled=!1);const o=this.constructor.MaterialProperties,l=o?wS(e,{},Array.from(Object.keys(o))):{...e};for(const d of Object.keys(l))l[d]===void 0&&delete l[d];const c=l.userData;delete l.userData;const h=new Set([...this.constructor.InterpolateProperties||gs.InterpolateProperties,...this.constructor.MapProperties||gs.MapProperties]);return n&&LM(l,this,h,n),r.call(this,l),c&&xv(this.userData,c),this.userData.uuid=this.uuid,(e?.metadata&&e?.metadata.version<=4.6||this.userData.legacyBumpScale)&&this?.bumpScale!==void 0&&this?.bumpMap&&this.defines&&(console.warn("MaterialManager: Old format material loaded, bump map might be incorrect.",e,e.bumpScale),this.defines.BUMP_MAP_SCALE_LEGACY="1",this.userData.legacyBumpScale=!0,this.needsUpdate=!0),s&&(Nt.enabled=a),this.setDirty&&this.setDirty(),this},dispose:r=>function(e=!0){!e&&this.userData.disposeOnIdle===!1||r.call(this)},clone:r=>function(e=!1){e&&(this.userData.cloneId||(this.userData.cloneId="0"),this.userData.cloneCount||(this.userData.cloneCount=0),this.userData.cloneCount+=1);let t;return this.constructor.prototype?.setValues?(t=new this.constructor,t.setValues(this,!1)):t=r.call(this),e&&(t.userData.cloneId=t.userData.cloneId+"_"+this.userData.cloneCount,t.userData.cloneCount=0,t.name=(t.name||"mat")+"_"+t.userData.cloneId),t},dispatchEvent:r=>function(e){r.call(this,e);const t=e.type;e.bubbleToObject&&(t==="beforeDeserialize"||t==="materialUpdate"||t==="textureUpdate"||t==="select")&&this.appliedMeshes.forEach(i=>i.dispatchEvent({...e,material:this,type:t}))},customProgramCacheKey:function(){return yl.CacheKeyForExtensions(this,this.materialExtensions)+this.userData.inverseAlphaMap},registerMaterialExtensions:function(r){yl.RegisterExtensions(this,r)},unregisterMaterialExtensions:function(r){yl.UnregisterExtensions(this,r)},onBeforeCompile:function(r,e){this.materialExtensions&&yl.ApplyMaterialExtensions(this,r,this.materialExtensions,e),this.dispatchEvent({type:"beforeCompile",shader:r,renderer:e}),r.fragmentShader=r.fragmentShader.replaceAll("#glMarker","// "),r.vertexShader=r.vertexShader.replaceAll("#glMarker","// ")},onBeforeRender:function(r,e,t,i,n){this.defines&&this.envMap!==void 0&&e.fixedEnvMapDirection!==void 0&&(e.fixedEnvMapDirection?this.defines.FIX_ENV_DIRECTION||(this.defines.FIX_ENV_DIRECTION="1",this.needsUpdate=!0):this.defines.FIX_ENV_DIRECTION!==void 0&&(delete this.defines.FIX_ENV_DIRECTION,this.needsUpdate=!0)),this.dispatchEvent({type:"beforeRender",renderer:r,scene:e,camera:t,geometry:i,object:n})},onAfterRender:function(r,e,t,i,n){this.dispatchEvent({type:"afterRender",renderer:r,scene:e,camera:t,geometry:i,object:n})},onBeforeCompileOverride:r=>function(e,t){ve.onBeforeCompile.call(this,e,t),r.call(this,e,t)},onBeforeRenderOverride:r=>function(...e){r.call(this,...e),ve.onBeforeRender.call(this,...e)},onAfterRenderOverride:r=>function(...e){r.call(this,...e),ve.onAfterRender.call(this,...e)},customProgramCacheKeyOverride:r=>function(){return r.call(this)+ve.customProgramCacheKey.call(this)},upgradeMaterial:JM,getMapsForMaterial:function(){const r=new Map;for(const e of this.constructor?.MapProperties||$M)cd(e,this,r);if(this.userData)for(const e of KM)cd(e,this.userData,r,!0);return r},refreshTextureRefs:function(){this.__textureUpdate||(this.__textureUpdate=Pk.bind(this));const r=ve.getMapsForMaterial.call(this),e=new Set([...r.values()]),t=this._mapRefs||new Set;let i=!1;const n=new Set,s=new Set;for(const a of e)!a||!a.isTexture||(a.addEventListener("update",this.__textureUpdate),!t.has(a)&&(i=!0,n.add(a)));for(const a of t)e.has(a)||(a.removeEventListener("update",this.__textureUpdate),i=!0,s.add(a));this._mapRefs=e,i&&this.dispatchEvent({type:"texturesChanged",textures:e,oldTextures:t,addedTextures:n,removedTextures:s,material:this,bubbleToObject:!0,bubbleToParent:!0})}},Pk=function(r){!this||this.assetType!=="material"||this.dispatchEvent({texture:r.target,bubbleToParent:!0,bubbleToObject:!0,...r,type:"textureUpdate"})},$M=new Set([]),KM=new Set([]);function JM(){if(!this.isMaterial)return console.error("Material is not a material",this),this;if(this.setDirty||(this.setDirty=ve.setDirty),this.appliedMeshes||(this.appliedMeshes=new Set),this.userData||(this.userData={}),this.userData.uuid=this.uuid,this.__upgradeSetup||(this.dispatchEvent=ve.dispatchEvent(this.dispatchEvent),this.__upgradeSetup=!0),this.assetType==="material")return this;this.assetType="material",this.setValues=ve.setValues(this.setValues),this.dispose=ve.dispose(this.dispose),this.clone=ve.clone(this.clone),this.extraUniformsToUpload||(this.extraUniformsToUpload={}),this.materialExtensions||(this.materialExtensions=[]),this.registerMaterialExtensions||(this.registerMaterialExtensions=ve.registerMaterialExtensions),this.unregisterMaterialExtensions||(this.unregisterMaterialExtensions=ve.unregisterMaterialExtensions);const r=!this.isDerivedMaterial;return this.onBeforeCompile=r?ve.onBeforeCompileOverride(this.onBeforeCompile):ve.onBeforeCompile,this.onBeforeRender=ve.onBeforeRenderOverride(this.onBeforeRender),this.onAfterRender=ve.onAfterRenderOverride(this.onAfterRender),this.customProgramCacheKey=ve.customProgramCacheKeyOverride(this.customProgramCacheKey),this.setDirty({change:"upgradeMaterial"}),this}const Dk=`
#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>
#glMarker importsEnd
#define DEPTH_NORMAL
#define IS_DEPTH_MATERIAL
varying vec3 vViewPosition;
#ifdef USE_ALPHAMAP
#define USE_UV
#endif
void main(){
#include <uv_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>
#glMarker beforeOutput
vViewPosition=-mvPosition.xyz;}`,Rk=`
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
#glMarker importsEnd
#define DEPTH_NORMAL
#define IS_DEPTH_MATERIAL
varying vec3 vViewPosition;
#ifdef USE_ALPHAMAP
#define USE_UV
#include <packing>
#endif
#if IS_GLSL3 > 0
#ifndef gl_FragColor
layout(location=0)out vec4 gDepthNormal;layout(location=1)out vec4 gFlags;
#endif
#endif
uniform vec2 cameraNearFar;uniform vec4 flags;vec2 pack16(float value){float f=clamp(value,0.0,1.0)*255.0;float digitLow=fract(f);float digitHigh=floor(f)/255.0;return vec2(digitHigh,digitLow);}vec2 packNormal(vec3 n){float p=sqrt(n.z*8.0+8.0);return vec2(n.xy/p+0.5);}float linstep(float edge0,float edge1,float value){return clamp((value-edge0)/(edge1-edge0),0.0,1.0);}void main(){
#glMarker mainStart
#include <clipping_planes_fragment>
vec4 diffuseColor=vec4(1.0);
#include <map_fragment>
#ifdef USE_ALPHAMAP
float alphaMapValue=
#ifdef ALPHA_I_RGBA_PACKING
1.-unpackRGBAToDepth(texture2D(alphaMap,vAlphaMapUv));
#else
texture2D(alphaMap,vAlphaMapUv).g;
#endif
#if defined(INVERSE_ALPHAMAP) && INVERSE_ALPHAMAP >= 1
diffuseColor.a*=1.0-alphaMapValue;
#else
diffuseColor.a*=alphaMapValue;
#endif
#endif
#include <alphatest_fragment>
#include <logdepthbuf_fragment>
#include <normal_fragment_begin>
#include <normal_fragment_maps>
#glMarker beforeOutput
#ifdef FORCED_LINEAR_DEPTH
float linearZ=float(FORCED_LINEAR_DEPTH);
#else
float linearZ=linstep(-cameraNearFar.x,-cameraNearFar.y,-vViewPosition.z);
#endif
vec2 packedZ=pack16(pow(max(0.,linearZ),0.5));vec2 packedNormal=packNormal(normal);
#if IS_GLSL3 > 0
#ifndef gl_FragColor
gDepthNormal=vec4(packedZ.x,packedZ.y,packedNormal.x,packedNormal.y);gFlags=flags;
#else
gl_FragColor=vec4(packedZ.x,packedZ.y,packedNormal.x,packedNormal.y);
#endif
#else
gl_FragColor=vec4(packedZ.x,packedZ.y,packedNormal.x,packedNormal.y);
#endif
}`,Fh=class Fh extends nn{constructor({customMaterialExtensions:e,...t}={},i=!1){super(),this.assetType="material",this.isAShaderMaterial=!0,this.appliedMeshes=new Set,this.setDirty=ve.setDirty,this.type="ShaderMaterial",this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=ve.registerMaterialExtensions,this.unregisterMaterialExtensions=ve.unregisterMaterialExtensions,this.isRawShaderMaterial=i,i&&(this.type="RawShaderMaterial"),e&&this.registerMaterialExtensions(e),ve.upgradeMaterial.call(this),this.setValues(t)}dispose(){return ve.dispose(super.dispose).call(this)}clone(e=!1){return ve.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+ve.customProgramCacheKey.call(this)}onBeforeCompile(e,t){ve.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}onBeforeRender(e,t,i,n,s,a){super.onBeforeRender(e,t,i,n,s,a),ve.onBeforeRender.call(this,e,t,i,n,s,a)}onAfterRender(e,t,i,n,s,a){super.onAfterRender(e,t,i,n,s,a),ve.onAfterRender.call(this,e,t,i,n,s,a)}setValues(e){return ve.setValues(super.setValues).call(this,e)}toJSON(e){throw new Error("Method not supported for this material.")}fromJSON(e,t){throw new Error("Method not supported for this material.")}get materialObject(){return this}};Fh.TypeSlug="shaderMat",Fh.TYPE="ShaderMaterial2",Fh.MaterialProperties={...It,fragmentShader:"",vertexShader:"",uniforms:{},defines:{},extensions:{},isRawShaderMaterial:!1,uniformsGroups:{},wireframe:!1,wireframeLinewidth:1,clipping:!1,lights:!1,fog:!1,glslVersion:null,defaultAttributeValues:{}},Fh.InterpolateProperties=[...wa,"wireframeLinewidth"];let Cd=Fh;class ng extends Cd{constructor(e=!0,t){super({vertexShader:Dk,fragmentShader:Rk,uniforms:ko.merge([De.common,De.bumpmap,De.normalmap,De.displacementmap,{cameraNearFar:{value:new K(.1,1e3)},flags:{value:new et(255,255,255,255)}}]),defines:{IS_GLSL3:e?"1":"0"},glslVersion:e?cy:lD,...t}),this.flagUpdaters=new Map,this.normalMapType=Us,this.flatShading=!1,this.reset()}onBeforeRender(e,t,i,n,s,a){super.onBeforeRender(e,t,i,n,s,a);let o=!1,l=s.material;if(Array.isArray(l)&&(l=l[0]),l===this&&(l=s.currentMaterial,o=!0),Array.isArray(l)&&(l=l[0]),!l)return;if(o)ba({FORCED_LINEAR_DEPTH:l.userData.forcedLinearDepth??void 0},this);else{const h=u=>{const d=l[u];d&&(this.uniforms[u].value=d,this.uniforms[u+"Transform"]?d.isTexture&&e.materials.refreshTransformUniform(d,this.uniforms[u+"Transform"]):console.error("GBufferMaterial: "+u+"Transform is not defined in uniform"))};h("map"),l.side!==void 0&&(this.side=l.side??Zi),h("alphaMap"),l.alphaTest!==void 0&&(this.alphaTest=l.alphaTest<1e-4?1e-4:l.alphaTest),l.alphaHash!==void 0&&(this.alphaHash=l.alphaHash),h("bumpMap"),l.bumpScale!==void 0&&(this.uniforms.bumpScale.value=l.bumpScale),h("normalMap"),l.normalScale!==void 0&&this.uniforms.normalScale.value.copy(l.normalScale),l.normalMapType!==void 0&&(this.normalMapType=l.normalMapType),l.flatShading!==void 0&&(this.flatShading=l.flatShading),h("displacementMap"),l.displacementScale!==void 0&&(this.uniforms.displacementScale.value=l.displacementScale),l.displacementBias!==void 0&&(this.uniforms.displacementBias.value=l.displacementBias),l.wireframe!==void 0&&(this.wireframe=l.wireframe),l.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=l.wireframeLinewidth),ba({ALPHAMAP_UV:this.uniforms.alphaMap.value?"uv":void 0,USE_DISPLACEMENTMAP:this.uniforms.displacementMap.value?1:void 0,DISPLACEMENTMAP_UV:this.uniforms.displacementMap.value?"uv":void 0,ALPHA_I_RGBA_PACKING:l.userData.ALPHA_I_RGBA_PACKING?1:void 0,FORCED_LINEAR_DEPTH:l.userData.forcedLinearDepth??void 0},this)}const c=this.uniforms.flags.value;this._updateFlagsUniform(c,l,e,t,i,n,s),i.updateShaderProperties(this),this.uniformsNeedUpdate=!0,l.materialExtensions?.length&&this.registerMaterialExtensions(l.materialExtensions),this.needsUpdate=!0,e.resetCurrentMaterial&&e.resetCurrentMaterial()}_updateFlagsUniform(e,t,i,n,s,a,o){e.set(255,255,255,255);const l=t.userData.gBufferData?.materialId??t.userData.matId;e.z=l||0,this.flagUpdaters.forEach(c=>c(e,{material:t,renderer:i,scene:n,camera:s,geometry:a,object:o})),e.x/=255,e.y/=255,e.z/=255,e.w/=255}onAfterRender(e,t,i,n,s,a){super.onAfterRender(e,t,i,n,s,a);let o=s.material;Array.isArray(o)&&(o=o[0]),!(!o||o===this)&&(o.materialExtensions?.length&&this.unregisterMaterialExtensions(o.materialExtensions),this.reset())}reset(){this.uniforms.map.value=null,this.side=Zi,this.uniforms.alphaMap.value=null,this.alphaTest=.001,this.alphaHash=!1,this.uniforms.bumpMap.value=null,this.uniforms.bumpScale.value=1,this.uniforms.normalMap.value=null,this.uniforms.normalScale.value.set(1,1),this.normalMapType=Us,this.flatShading=!1,this.uniforms.displacementMap.value=null,this.uniforms.displacementScale.value=1,this.uniforms.displacementBias.value=0,this.uniforms.flags.value.set(255,255,255,255),this.wireframe=!1,this.wireframeLinewidth=1}}class Bk extends ng{constructor(e,t){super(e,t),console.warn("DepthNormalMaterial is deprecated, use GBufferMaterial instead")}}function Lk(r,e=new ng(!0,{blending:gn,transparent:!1})){return e.onBeforeCompile=t=>{if(t.__modified)return;t.__modified=!0;let i=r.material;if(i===e&&(i=r.currentMaterial),!i.isLineMaterial)return;t.uniforms={...i.uniforms,...t.uniforms};const n=t.fragmentShader.split("void main()")[0].split("#glMarker importsEnd")[1]||"",s=`
vec3 normal = vec3(0.,0.,1.);
`+t.fragmentShader.split("#glMarker beforeOutput")[1];t.fragmentShader=bt(i.fragmentShader,"void main()",n+`
`,{prepend:!0}),t.fragmentShader=bt(t.fragmentShader,"#include <logdepthbuf_fragment>",s+`
//end-frag-patch
`,{append:!0}),t.fragmentShader=t.fragmentShader.split("//end-frag-patch")[0];const a=t.vertexShader.split("void main()")[0].split("#glMarker importsEnd")[1]||"",o=t.vertexShader.split("#glMarker beforeOutput")[1].replace(/}\s*$/,"")+`
`;t.vertexShader=bt(i.vertexShader,"void main()",a,{prepend:!0}),t.vertexShader=bt(t.vertexShader,"#include <clipping_planes_vertex>",o,{append:!0})},e}function Ok(r,e=new Ec({depthPacking:sc,blending:gn,transparent:!1})){return e.onBeforeCompile=t=>{if(t.__modified)return;t.__modified=!0;let i=r.material;if(i===e&&(i=r.currentMaterial),!i.isLineMaterial)return;t.uniforms={...i.uniforms,...t.uniforms},t.defines={...i.defines,...t.defines};const n=`
varying vec2 vHighPrecisionZW;
#include <packing>
`,s=t.fragmentShader.split("#include <logdepthbuf_fragment>")[1];t.fragmentShader=bt(i.fragmentShader,"void main()",n,{prepend:!0}),t.fragmentShader=bt(t.fragmentShader,"#include <logdepthbuf_fragment>",s+`
//end-frag-patch
`,{append:!0}),t.fragmentShader=t.fragmentShader.split("//end-frag-patch")[0];const a=`
varying vec2 vHighPrecisionZW;
`,o=`
vHighPrecisionZW = gl_Position.zw;
`;t.vertexShader=bt(i.vertexShader,"void main()",a,{prepend:!0}),t.vertexShader=bt(t.vertexShader,"#include <clipping_planes_vertex>",o,{append:!0})},e}const qe={setDirty:function(r,...e){typeof r=="string"&&(r={change:r}),this.dispatchEvent({bubbleToParent:this.userData?.autoUpdateParent??!0,object:this,...r,type:"objectUpdate",args:e}),r?.refreshUi!==!1&&r?.last!==!1&&this.refreshUi&&this.refreshUi()},upgradeObject3D:nT,makeUiConfig:HM,autoCenter:function(r=!0,e=!1){if(e){if(!this.userData.autoCentered||!this.userData._lastCenter)return this;if(!isFinite(this.userData._lastCenter.lengthSq()))return this;this.position.add(this.userData._lastCenter),delete this.userData.autoCentered,delete this.userData.isCentered,delete this.userData._lastCenter}else{const i=new En().expandByObject(this,!0,!0).getCenter(new S);if(!isFinite(i.lengthSq()))return this;this.userData._lastCenter=i,this.position.sub(i),this.userData.autoCentered=!0,this.userData.isCentered=!0}return this.updateMatrix(),r&&this.setDirty&&this.setDirty({change:"autoCenter",undo:e}),this},autoScale:function(r,e,t=!0,i=!1){let n=1;if(i){if(!this.userData.autoScaled||!this.userData._lastScaleRadius)return this;const s=this.userData.autoScaleRadius||r||1;if(n=this.userData._lastScaleRadius/s,!isFinite(n))return this;this.userData.autoScaled=!0,this.userData.autoScaleRadius=r,delete this.userData._lastScaleRadius}else{const a=new En().expandByObject(this,!0,!0).getSize(new S).length()*.5;if(r===void 0&&(r=this.userData.autoScaleRadius||1),n=r/a,!isFinite(n))return this;this.userData.autoScaled=!0,this.userData.autoScaleRadius=r,this.userData._lastScaleRadius=a}return this.userData.pseudoCentered?this.children.forEach(s=>{s.scale.multiplyScalar(n)}):this.scale.multiplyScalar(n),(e||this.userData.isCentered)&&this.position.multiplyScalar(n),this.traverse(s=>{const a=s;a.isLight&&a.shadow?.camera?.right&&(a.shadow.camera.right*=n,a.shadow.camera.left*=n,a.shadow.camera.top*=n,a.shadow.camera.bottom*=n,s.setDirty&&s.setDirty()),a.isCamera&&a.right&&(a.right*=n,a.left*=n,a.top*=n,a.bottom*=n,s.setDirty&&s.setDirty())}),t&&this.setDirty&&this.setDirty({change:"autoScale",undo:i}),this},pivotToBoundsCenter:function(r=!0){const t=new En().expandByObject(this,!0,!0).getCenter(new S);return qe.pivotToPoint.call(this,t,r)},pivotToPoint:function(r,e=!0,t=!0){const i=new S().copy(r),n=new S().copy(i),s=new fe().copy(this.matrixWorld).invert(),a=this.parent?.matrixWorld,o=new fe;a!==void 0&&o.copy(a).invert(),i.applyMatrix4(o);const l=this.position.clone();this.position.copy(i),n.applyMatrix4(s).negate();const c=new Map;if(this.geometry){const h=t?this.geometry.appliedMeshes:void 0;if(h)for(const u of h){if(u===this)continue;c.set(u,u.position.clone()),u.updateMatrix();const d=new S(-n.x,-n.y,-n.z).applyMatrix4(u.matrix);u.position.copy(d),e&&u.setDirty&&u.setDirty({change:"pivotToPoint"})}this.geometry.translate(n.x,n.y,n.z)}return this.children.forEach(h=>{h.position.add(n)}),e&&this.setDirty&&this.setDirty({change:"pivotToPoint",undo:!1}),()=>{if(this.position.copy(l),this.geometry){this.geometry.translate(-n.x,-n.y,-n.z);for(const[h,u]of c)h.position.copy(u),e&&h.setDirty&&h.setDirty({change:"pivotToPoint"})}this.children.forEach(h=>{h.position.sub(n)}),e&&this.setDirty&&this.setDirty({change:"pivotToPoint",undo:!0})}},traverseModels:function(r,{visible:e=!1,widgets:t=!1,...i}){if(!this.assetType||!t&&this.assetType==="widget"||e&&!this.visible||r(this)===!1)return;const s=this.children;for(let a=0,o=s.length;a<o;a++){const l=s[a];!l.assetType||!l.traverseModels||l.traverseModels(r,{visible:e,widgets:t,...i})}},eventCallbacks:{onAddedToParent:function(r){const e=this.parent?.parentRoot??this.parent;e!==this.parentRoot&&this.traverse(t=>{const i=t.parentRoot;i!==e&&(t.parentRoot=e,t.dispatchEvent({...r,type:"parentRootChanged",object:t,oldParentRoot:i||void 0,bubbleToParent:!1}))}),!this.objectProcessor&&e?.objectProcessor&&this.traverse(t=>{t.objectProcessor=e.objectProcessor,t.objectProcessor?.processObject(t)}),this.setDirty?.({...r,change:"addedToParent"})},onRemovedFromParent:function(r){this.setDirty?.({...r,change:"removedFromParent"}),this.parentRoot&&this.traverse(e=>{const t=e.parentRoot;t&&(e.parentRoot=void 0,e.dispatchEvent({...r,type:"parentRootChanged",object:e,oldParentRoot:t||void 0,bubbleToParent:!1}))})},onGeometryUpdate:function(r){r.bubbleToObject&&this.dispatchEvent({bubbleToParent:!0,...r,object:this,geometry:r.geometry})}},initMaterial:function(){if(Wn(this,"_currentMaterial"))return;this._currentMaterial=null;const{protoDesc:r}=z_(this,"material"),e=this.material;delete this.material,Object.defineProperty(this,"currentMaterial",{configurable:!0,enumerable:!0,get(){return r?.get?r.get.call(this):qe.getMaterial.call(this)},set(t){qe.setMaterial.call(this,t),r?.set?.call(this,t)}}),Object.defineProperty(this,"material",{configurable:!0,enumerable:!0,get(){return this.forcedOverrideMaterial??this.currentMaterial},set(t){this.forcedOverrideMaterial&&console.warn("IObject3D: Material is being set on an object with forcedOverrideMaterial set"),this.currentMaterial=t}}),Object.defineProperty(this,"materials",{configurable:!0,enumerable:!0,get:qe.getMaterials,set:qe.setMaterials}),this.material=e,(this.isLineSegments2||this.isLine2||this.isWireframe)&&(Object.defineProperty(this,"customDepthMaterial",{configurable:!0,enumerable:!0,get:()=>this._customDepthMaterial?this._customDepthMaterial:(this._customDepthMaterial=Ok(this),this._customDepthMaterial),set:t=>{this._customDepthMaterial=t,t&&(t.needsUpdate=!0),this.setDirty&&this.setDirty({change:"customDepthMaterial"})}}),Object.defineProperty(this,"customGBufferMaterial",{configurable:!0,enumerable:!0,get:()=>this._customGBufferMaterial?this._customGBufferMaterial:(this._customGBufferMaterial=Lk(this),this._customGBufferMaterial),set:t=>{this._customGBufferMaterial=t,t&&(t.needsUpdate=!0),this.setDirty&&this.setDirty({change:"customDepthMaterial"})}})),this.setMaterial||(this.setMaterial=t=>{const i=this.material;return console.error("IObject3D: setMaterial is deprecated, use material property directly"),this.material=t,i})},getMaterial:function(){return this._currentMaterial||void 0},getMaterials:function(){const r=this.currentMaterial;return r?Array.isArray(r)?[...r]:[r]:[]},setMaterial:function(r){const e=(Array.isArray(r)?r:[r]).filter(o=>o);if(this.material==e||e.length===1&&this.material===e[0])return[];const t=this.material,i=Array.isArray(t)?[...t]:[t];let n=[];const s=[];for(const o of i)o&&n.push(o);const a=[];for(const o of e)o&&(o.assetType||ve.upgradeMaterial.call(o),n.includes(o)?n=n.filter(l=>l!==o):s.push(o),a.push(o));for(const o of n)o.dispatchEvent({type:"removeFromMesh",object:this});for(const o of s)o.dispatchEvent({type:"addToMesh",object:this});this._currentMaterial=a.length?a.length!==1?a:a[0]||null:null,this.dispatchEvent({type:"materialChanged",material:this._currentMaterial??null,oldMaterial:t??null,object:this,bubbleToParent:!0}),this.refreshUi&&this.refreshUi()},setMaterials:function(r){this.currentMaterial=r||void 0},initGeometry:function(){this._currentGeometry=null;const{protoDesc:r}=z_(this,"geometry"),e=this.geometry;delete this.geometry,Object.defineProperty(this,"geometry",{configurable:!0,enumerable:!0,get(){return this.forcedOverrideGeometry??(r?.get?r.get.call(this):qe.getGeometry.call(this))},set(t){this.forcedOverrideGeometry&&console.warn("IObject3D: Geometry is being set on an object with forcedOverrideGeometry set"),qe.setGeometry.call(this,t),r?.set?.call(this,t)}}),this.geometry=e,this.setGeometry||(this.setGeometry=t=>{const i=this.geometry;return console.error("IObject3D: setGeometry is deprecated, use geometry property directly"),this.geometry=t,i})},getGeometry:function(){return this._currentGeometry||void 0},setGeometry:function(r){const e=this.geometry||void 0;e!==r&&(e&&this._onGeometryUpdate&&e.removeEventListener("geometryUpdate",this._onGeometryUpdate),r&&(r.assetType||ni.upgradeGeometry.call(r)),this._currentGeometry=r||null,r&&this._onGeometryUpdate&&r.addEventListener("geometryUpdate",this._onGeometryUpdate),this.dispatchEvent({type:"geometryChanged",geometry:r??null,oldGeometry:e,bubbleToParent:!0,object:this}),this.refreshUi&&this.refreshUi())},refreshUi:function(){this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},dispatchEvent:r=>function(e){if(!(e.target&&e.target!==this&&this.acceptChildEvents===!1)){if(e.bubbleToParent||this.userData?.__autoBubbleToParentEvents?.includes(e.type)){const t=this.parentRoot||this.parent;this.parentRoot!==this&&t?.dispatchEvent(e)}r.call(this,e)}},clone:r=>function(e,...t){const i=this.userData;this.userData={};const n=r.call(this,e,...t);if(this.userData=i,Hm(n.userData,i),qe.upgradeObject3D.call(n),n.userData.cloneParent=this.uuid,this._sChildren)if(e){n._sChildren=[];for(const s of this._sChildren){if(!s)continue;let a;if(this.children.includes(s)){const o=this.children.indexOf(s);a=n.children[o]}else a=s.clone(!0);n._sChildren.push(a)}}else n._sChildren=[...this._sChildren];return n},copy:r=>function(e,...t){const i=this.isLight?this.target:null,n=e.userData;e.userData={};const s=this.userData;return r.call(this,e,...t),this.userData=s,e.userData=n,Hm(this.userData,e.userData),i&&this.target&&(i.position.copy(this.target.position),i.updateMatrixWorld(),this.target=i),this},add:r=>function(...e){if(this.autoUpgradeChildren!==!1)for(const t of e)qe.upgradeObject3D.call(t);return r.call(this,...e)},dispose:r=>function(e=!0){e&&this.parent&&(this.removeFromParent(),delete this.parentRoot),this.dispatchEvent({type:"dispose",bubbleToParent:!1});for(const t of[...this.children])t?.dispose&&t.dispose(!1);return r&&r.call(this),this},getMapsForObject3D:function(){const r=new Map;for(const e of this.constructor?.MapProperties||iT)cd(e,this,r);if(this.isScene)for(const e of tT)cd(e,this,r);return r},deleteObject:async(r,e)=>{if(!(e?.shiftKey?!0:await f.ThreeViewer.Dialog.confirm("Delete Object: Are you sure you want to delete this object?")))return;const i=r.parent;return r.dispose&&r.dispose(!0),()=>{i&&i.add(r)}},duplicateObject:async(r,e)=>{const t=r.parent,i=r.clone(!0);ig(r,i);const n=e?!e.shiftKey:!1;return{action:()=>{t&&!i.parent&&t.add(i),n&&i.dispatchEvent({type:"select",value:i,object:i,ui:!!e,bubbleToParent:!0,trackUndo:!1})},undo:()=>{i.parent===t&&i.removeFromParent()}}}};function xd(r){const e=new Set(r);return r.filter(t=>{let i=t.parent;for(;i;){if(e.has(i))return!1;i=i.parent}return!0})}async function ZM(r){const e=xd(r);if(!e.length)return;const t=e.map(s=>s.name||s.uuid.slice(0,8)).join(", ");if(!await f.ThreeViewer.Dialog.confirm(`Delete ${e.length} object${e.length>1?"s":""}: ${t}?`))return;const n=new Map;for(const s of e)n.set(s,s.parent);for(const s of e)s.dispose&&s.dispose(!0);return{undo:()=>{for(const s of e){const a=n.get(s);a&&a.add(s)}},redo:()=>{for(const s of e)s.dispose&&s.dispose(!0)}}}function eT(r){const e=xd(r),t=[],i=new Map;for(const n of e){const s=n.clone(!0);ig(n,s),i.set(s,n.parent),t.push(s)}for(const n of t){const s=i.get(n);s&&!n.parent&&s.add(n)}return{clones:t,undo:()=>{for(const n of t)n.removeFromParent()},redo:()=>{for(const n of t){const s=i.get(n);s&&!n.parent&&s.add(n)}}}}const tT=new Set(["environmentMap","background"]),iT=new Set([]);function nT(r){if(!this)return this;if(this.userData||(this.userData={}),this.__objectSetup)return this;if(this.__objectSetup=!0,this.objectExtensions||(this.objectExtensions=[]),this.userData.__autoBubbleToParentEvents||(this.userData.__autoBubbleToParentEvents=["select"]),this.isLight?this.assetType="light":this.isCamera?this.assetType="camera":this.isWidget?this.assetType="widget":this.assetType="model",r&&(this.parentRoot=r.parentRoot||r),this.dispatchEvent=qe.dispatchEvent(this.dispatchEvent),this.dispose=qe.dispose(this.dispose),this.clone=qe.clone(this.clone),this.copy=qe.copy(this.copy),this.add=qe.add(this.add),this.setDirty||(this.setDirty=qe.setDirty),this.refreshUi||(this.refreshUi=qe.refreshUi),this.autoScale||(this.autoScale=qe.autoScale.bind(this)),this.autoCenter||(this.autoCenter=qe.autoCenter.bind(this)),this.pivotToBoundsCenter||(this.pivotToBoundsCenter=qe.pivotToBoundsCenter.bind(this)),this.pivotToPoint||(this.pivotToPoint=qe.pivotToPoint.bind(this)),this.traverseModels||(this.traverseModels=qe.traverseModels.bind(this)),this.addEventListener("added",qe.eventCallbacks.onAddedToParent),this.addEventListener("removed",qe.eventCallbacks.onRemovedFromParent),(this.isLineSegments2||this.isLine2)&&(this.isMesh=!0),(this.isMesh||this.isLine)&&!this.__meshSetup){if(this.__meshSetup=!0,this._onGeometryUpdate=e=>qe.eventCallbacks.onGeometryUpdate.call(this,e),qe.initMaterial.call(this),qe.initGeometry.call(this),!this.userData.__keepShadowDef){const e=Array.isArray(this.material)?this.material[0]:this.material;this.castShadow=!e||!e.transparent&&!e.transmission,this.receiveShadow=!0,this.userData.__keepShadowDef=!0}this.addEventListener("dispose",()=>{(this.materials||[this.material]).forEach(e=>e?.dispose(!1)),this.geometry?.dispose(!1)})}if(!this.uiConfig&&(this.assetType==="model"||this.assetType==="camera")&&qe.makeUiConfig.call(this),this.autoUpgradeChildren!==!1){const e=[...this.children];for(const t of e)nT.call(t,this)}return!this.modelObject&&Object.defineProperty(this,"modelObject",{get:()=>(console.error("IObject3D: modelObject is deprecated, use object directly"),this)}),this}var Uk=Object.defineProperty,Fk=Object.getOwnPropertyDescriptor,zs=(r,e,t,i)=>{for(var n=i>1?void 0:i?Fk(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Uk(e,t,n),n};f.CameraView=class extends xi{constructor(e,t,i,n,s,a=1,o){super(),this.uuid=Oi(),this.name="Camera View",this.position=new S,this.target=new S,this.quaternion=new $e,this.zoom=1,this.duration=1,this.isWorldSpace=!0,this.set=l=>this.dispatchEvent({type:"setView",camera:l,view:this}),this.update=l=>this.dispatchEvent({type:"updateView",camera:l,view:this}),this.delete=l=>this.dispatchEvent({type:"deleteView",camera:l,view:this}),this.animate=(l,c)=>this.dispatchEvent({type:"animateView",camera:l,duration:c,view:this}),this.setDirty=l=>{this.dispatchEvent({...l,type:"update"}),this.uiConfig&&(l?.key==="name"?(this.uiConfig.label=this.name,this.uiConfig.uiRefresh?.()):this.uiConfig.uiRefresh?.(!0,"postFrame"))},e!==void 0&&(this.name=e),t&&this.position.copy(t),i&&this.target.copy(i),n&&this.quaternion.copy(n),s!==void 0&&(this.zoom=s),a!==void 0&&a!==0&&(this.duration=a),o!==void 0&&(this.isWorldSpace=o)}clone(){return new f.CameraView(this.name,this.position,this.target,this.quaternion,this.zoom,this.duration,this.isWorldSpace)}},zs([rt("setDirty"),G(),He()],f.CameraView.prototype,"name",2),zs([rt("setDirty"),G(),yi()],f.CameraView.prototype,"position",2),zs([rt("setDirty"),G(),yi()],f.CameraView.prototype,"target",2),zs([rt("setDirty"),G(),yi()],f.CameraView.prototype,"quaternion",2),zs([rt("setDirty"),G(),Ot()],f.CameraView.prototype,"zoom",2),zs([rt("setDirty"),G(),Ot()],f.CameraView.prototype,"duration",2),zs([rt("setDirty"),G()],f.CameraView.prototype,"isWorldSpace",2),zs([ct()],f.CameraView.prototype,"set",2),zs([ct()],f.CameraView.prototype,"update",2),zs([ct()],f.CameraView.prototype,"delete",2),zs([ct()],f.CameraView.prototype,"animate",2),f.CameraView=zs([Vc("CameraView"),Aa("Camera View")],f.CameraView);function sT(r){const e="chordal",t=r.map(l=>l.position.clone()),i=new Uc(t,!0,e,.75),n=(l,c,h)=>{h=h||new S;const u=1/t.length,p=((c===0?t.length:c)-1)*u;return i.getPointAt(p+l*u,h),h},s=r.map(l=>l.target.clone()),a=new Uc(s,!0,e,.75);return{getPosition:n,getTarget:(l,c,h)=>{h=h||new S;const u=1/s.length,p=((c===0?s.length:c)-1)*u;return a.getPointAt(p+l*u,h),h}}}const ht={setDirty:function(r){if(!this._positionWorld)return;const e=typeof r=="string",t=e?r:r?.change??r?.key;let i=!1;r?.projectionUpdated!==!1&&(!t||["zoom","fov","left","right","top","bottom","aspect","frustumSize","view","coordinateSystem","projection","activateMain","deactivateMain","near","far","nearFar","deserialize"].includes(t))&&(this.updateProjectionMatrix(),i=!0),i=i||r?.projectionUpdated||!1,e&&(r=void 0),this.getWorldPosition(this._positionWorld),this.controls&&this.controls.target&&this.controls.enabled!==!1&&this.target!==this.controls.target?this.controls.target.copy(this.target):this.userData.autoLookAtTarget&&this.lookAt(this.target),this.dispatchEvent({...r,type:"update",bubbleToParent:!1,camera:this}),this.dispatchEvent({...r,type:"cameraUpdate",projectionUpdated:i,bubbleToParent:!0,camera:this}),qe.setDirty.call(this,{refreshScene:!1,...r,projectionUpdated:i})},activateMain:function(r={},e=!1,t=!0,i){if(!e)return r.camera===null?this.deactivateMain(r,e,t):this.dispatchEvent({type:"activateMain",...r,camera:this,bubbleToParent:!0});this.userData.__isMainCamera||(this.userData.__isMainCamera=!0,this.userData.__lastScale=this.scale.clone(),this.scale.divide(this.getWorldScale(new S)),i&&this.setCanvas?this.setCanvas(i,t):t&&(this.refreshCameraControls(!1),this.refreshAspect(!1)),this.setDirty({change:"activateMain",...r}))},deactivateMain:function(r={},e=!1,t=!0,i=!1){if(!e)return this.dispatchEvent({type:"activateMain",...r,camera:void 0,bubbleToParent:!0});this.userData.__isMainCamera&&(this.userData.__isMainCamera=!1,this.userData.__lastScale&&(this.scale.copy(this.userData.__lastScale),delete this.userData.__lastScale),i?this.setCanvas(void 0,t):t&&this.refreshCameraControls(!1),t&&this.refreshCameraControls(!1),this.setDirty({change:"deactivateMain",...r}))},refreshUi:function(){this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},refreshTarget:function(r=4,e=!0){this.controls?.enabled&&this.controls.target?this.controls.target!==this.target&&this.target.copy(this.controls.target):this.getWorldDirection(this.target).multiplyScalar(r).add(this.getWorldPosition(new S)),e&&this.setDirty({change:"target"})},refreshAspect:function(r=!0){if(this.autoAspect)if(!this._canvas)console.warn("ICamera: cannot calculate aspect ratio without canvas/container");else{let e=this._canvas.clientWidth/this._canvas.clientHeight;isFinite(e)||(e=1),this.aspect=e,this.refreshFrustum&&this.refreshFrustum(!1)}r&&this.setDirty({change:"aspect"})},updateShaderProperties:function(r){return r.uniforms.cameraPositionWorld?.value?.copy(this._positionWorld),r.uniforms.cameraNearFar?.value?.set(this.near,this.far),r.uniforms.projection&&(r.uniforms.projection.value=this.projectionMatrix),r.defines.PERSPECTIVE_CAMERA=this.type==="PerspectiveCamera"?"1":"0",r.defines.ORTHOGRAPHIC_CAMERA=this.type==="OrthographicCamera"?"1":"0",this},upgradeCamera:Nk,copy:r=>function(e,t,i,n,...s){if(!e.isCamera)return console.error("ICamera.copy: camera is not a Camera",e),this;if(r.call(this,e,t,...s),e.target?.isVector3)this.target.copy(e.target);else{const a=this.controls?.minDistance??i??4;e.getWorldDirection(this.target).multiplyScalar(a).add(this.getWorldPosition(new S))}if(n){const a=e.getWorldPosition(this.position);this.parent&&this.position.copy(this.parent.worldToLocal(a))}return this.updateMatrixWorld(!0),this.updateProjectionMatrix(),this.refreshAspect(!1),this.setDirty(),this},getView:function(r=!0,e){const t=new S;this.updateWorldMatrix(!0,!1);const i=this.matrixWorld;t.x=i.elements[4],t.y=i.elements[5],t.z=i.elements[6],t.normalize();const n=e||new f.CameraView;n.name=this.name,n.position.copy(this.position),n.target.copy(this.target),n.quaternion.copy(this.quaternion),n.zoom=this.zoom;const s=this.parent;return s&&(r?(n.position.applyMatrix4(s.matrixWorld),this.getWorldQuaternion(n.quaternion)):t.transformDirection(s.matrixWorld.clone().invert())),n.isWorldSpace=r,n},setView:function(r){this.position.copy(r.position),this.target.copy(r.target),this.quaternion.copy(r.quaternion),this.zoom=r.zoom,this.setDirty()},fitObject:function(r,e=1.5,t){const i=Array.isArray(r)?r:[r];if(!i.length)return;const n=new En().expandByObject(i[0],!1,!0);for(let p=1;p<i.length;p++)n.expandByObject(i[p],!1,!0);const s=Vm(this,n),a=n.getCenter(new S);n.getSize(new S).lengthSq()<=0&&i[0].getWorldPosition(a);const l=t?.min??.5,c=t?.max??50,h=Math.min(c,Math.max(l,s*e)),u=this.getView(!0);u.target.copy(a);const d=new S().subVectors(u.target,u.position).normalize();u.position.copy(d.multiplyScalar(-h).add(u.target)),this.setView(u)},setViewFromCamera:function(r,e,t=!0){this.copy(r,void 0,e,t)},setViewToMain:function(r){this.dispatchEvent({type:"setView",...r,camera:this,bubbleToParent:!0})},setNearFar(r,e,t,i,n){const s=Math.abs(r.near-e)+Math.abs(r.far-t)>.001;return r.near=e,r.far=t,i&&s&&r.setDirty?(r.setDirty({change:"nearFar",source:n}),!0):(r.updateProjectionMatrix(),!1)},defaultMinNear:.1,defaultMaxFar:1e3};function Nk(){if(!this.isCamera){console.error("Object is not a camera",this);return}this.userData.__cameraSetup||(this.userData.__cameraSetup=!0,qe.upgradeObject3D.call(this),this.copy=ht.copy(this.copy),this.target||(this.target=new S),this._positionWorld||(this._positionWorld=new S),this.refreshTarget||(this.refreshTarget=ht.refreshTarget),this.refreshAspect||(this.refreshAspect=ht.refreshAspect),this.updateShaderProperties||(this.updateShaderProperties=ht.updateShaderProperties),this.activateMain||(this.activateMain=ht.activateMain),this.deactivateMain||(this.deactivateMain=ht.deactivateMain),this.refreshUi||(this.refreshUi=ht.refreshUi),this.setDirty||(this.setDirty=ht.setDirty),this.getView||(this.getView=ht.getView),this.setView||(this.setView=ht.setView),this.fitObject||(this.fitObject=ht.fitObject),this.setViewFromCamera||(this.setViewFromCamera=ht.setViewFromCamera),this.setViewToMain||(this.setViewToMain=ht.setViewToMain),this.setCanvas||(this.setCanvas=()=>eh("setCanvas")),this.setControlsCtor||(this.setControlsCtor=()=>eh("setControlsCtor")),this.removeControlsCtor||(this.removeControlsCtor=()=>eh("removeControlsCtor")),this.refreshCameraControls||(this.refreshCameraControls=()=>eh("refreshCameraControls")),this.setInteractions||(this.setInteractions=()=>eh("setInteractions")),this.dispose||(this.dispose=()=>eh("dispose")),this.assetType="camera")}function eh(r){console.warn(`ICamera.${r} is not supported on this object. Please use objects of PerspectiveCamera2 or OrthographicCamera2 classes.`)}var kk=Object.defineProperty,_n=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&kk(e,t,n),n};const Pi=class extends zi{constructor(e,t,i,n,s){super(n,s),this.assetType="camera",this._currentControlsMode="",this.userData={},this.target=new S(0,0,0),this.near=.1,this.far=2e3,this.autoLookAtTarget=!1,this.autoNearFar=!0,this.minNearPlane=void 0,this.maxFarPlane=void 0,this.dollyFov=!1,this._interactionsDisabledBy=new Set,this.refreshAspect=ht.refreshAspect,this.refreshUi=ht.refreshUi,this.refreshTarget=ht.refreshTarget,this.activateMain=ht.activateMain,this.deactivateMain=ht.deactivateMain,this.updateShaderProperties=ht.updateShaderProperties,this.controlsCtors=new Map([["orbit",(a,o)=>{const l=o?o.ownerDocument?o:o.documentElement:document.body,c=new f.OrbitControls3(a,l);return l.tabIndex===-1&&(l.tabIndex=1e3,l.style.outline="none"),c.listenToKeyEvents(l),c.screenSpacePanning=!0,c}]]),this._controlsChanged=()=>{this._controls&&this._controls.target&&this.refreshTarget(void 0,!1),this.setDirty({change:"controls"})},this.getView=ht.getView,this.setView=ht.setView,this.fitObject=ht.fitObject,this.setViewFromCamera=ht.setViewFromCamera,this.setViewToMain=ht.setViewToMain,this._positionWorld=new S,this._camUi=[...bi(this)||[],{type:"input",label:"Dolly FoV",property:[this,"dollyFov"]},...eg.call(this),tg.call(this)],this.uiConfig={type:"folder",label:()=>this.name||"Camera",children:[...this._camUi,()=>this._controls?.zoomIn?{type:"button",label:"Zoom in",value:()=>this._controls?.zoomIn(1)}:{},()=>this._controls?.zoomOut?{type:"button",label:"Zoom out",value:()=>this._controls?.zoomOut(1)}:{},()=>this._controls?.uiConfig]},this._canvas=t,this.autoAspect=i??!!t,ht.upgradeCamera.call(this),this.controlsMode=e||"",this.refreshTarget(void 0,!1),this.setDirty()}get controls(){return this._controls}get isMainCamera(){return this.userData&&this.userData.__isMainCamera||!1}get interactionsEnabled(){return this._interactionsDisabledBy.size===0}setInteractions(e,t,i=!0){const n=this._interactionsDisabledBy.size;e?this._interactionsDisabledBy.delete(t):this._interactionsDisabledBy.add(t),n!==this._interactionsDisabledBy.size&&this.refreshCameraControls(i)}get canUserInteract(){return this._interactionsDisabledBy.size===0&&this.isMainCamera&&this.controlsMode!==""}setDirty(e){ht.setDirty.call(this,e),e?.last!==!1&&this._camUi?.forEach(t=>t?.uiRefresh?.(!1,"postFrame",1))}setControlsCtor(e,t,i=!1){if(!i&&this.controlsCtors.has(e)){console.error("PerspectiveCamera2: "+e+" already exists.");return}this.controlsCtors.set(e,t)}removeControlsCtor(e){this.controlsCtors.delete(e)}_initCameraControls(){const e=this.controlsMode;this._controls=this.controlsCtors.get(e)?.(this,this._canvas)??void 0,!this._controls&&e!==""&&console.error("ICamera - Unable to create controls with mode "+e+". Are you missing a plugin?"),this._controls?.addEventListener&&this._controls.addEventListener("change",this._controlsChanged),this._currentControlsMode=this._controls?e:""}_disposeCameraControls(){this._controls&&(this._controls.target===this.target&&(this._controls.target=new S),this._controls.removeEventListener&&this._controls.removeEventListener("change",this._controlsChanged),this._controls.dispose&&this._controls.dispose()),this._currentControlsMode="",this._controls=void 0}refreshCameraControls(e=!0){if(this.controlsCtors){if(this._controls?(this._currentControlsMode!==this.controlsMode||this!==this._controls.object||this._controls.domElement&&this._canvas!==this._controls.domElement)&&(this._disposeCameraControls(),this._initCameraControls()):this._initCameraControls(),this._controls){const t=this.canUserInteract;this._controls.enabled=t,t&&this.up.copy(ft.DEFAULT_UP)}e&&this.setDirty(),this.refreshUi()}}toJSON(e,t=!1){return t?{...super.toJSON(e),...We.Serialize(this,e,!0)}:We.Serialize(this,e,!1)}fromJSON(e,t){if((e.camOptions||e.aspect==="auto")&&(e={...e}),e.camOptions){const i=e.camOptions;i.fov&&(e.fov=i.fov),i.focus&&(e.focus=i.focus),i.zoom&&(e.zoom=i.zoom),i.aspect&&(e.aspect=i.aspect),i.controlsMode&&(e.controlsMode=i.controlsMode),delete e.camOptions}return e.aspect==="auto"&&(e.aspect=this.aspect,this.autoAspect=!0),We.Deserialize(e,this,t,!0),this.refreshAspect(!1),this.setDirty({change:"deserialize"}),this}dispose(){this._disposeCameraControls()}setCanvas(e,t=!0){this._canvas=e,t&&(this.refreshCameraControls(),this.refreshAspect(!1))}get isActiveCamera(){return this.isMainCamera}getControls(){return this._controls}get cameraObject(){return this}get modelObject(){return this}targetUpdated(e=!0){e&&this.setDirty()}};_n([He("Name")],Pi.prototype,"name"),_n([G("camControls")],Pi.prototype,"_controls"),_n([Li("Controls Mode",void 0,r=>({children:["none",...r.controlsCtors.keys()].map(e=>({label:e,value:e==="none"?"":e}))})),G(),Zt(Pi.prototype.refreshCameraControls)],Pi.prototype,"controlsMode"),_n([G()],Pi.prototype,"userData"),_n([rt(Pi.prototype.setDirty),Fe("Field Of View",[1,180],.001),G()],Pi.prototype,"fov"),_n([rt(Pi.prototype.setDirty),G()],Pi.prototype,"focus"),_n([rt(Pi.prototype.setDirty),Ot("FoV Zoom"),G()],Pi.prototype,"zoom"),_n([yi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"position"})})),G()],Pi.prototype,"position"),_n([yi("Up",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"up"})})),G()],Pi.prototype,"up"),_n([yi("Rotation",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"rotation"}),disabled:()=>r.autoLookAtTarget}))],Pi.prototype,"rotation"),_n([yi("Target",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"target"}),disabled:()=>!r.autoLookAtTarget})),G()],Pi.prototype,"target"),_n([G(),Zt("refreshAspect"),se("Auto Aspect")],Pi.prototype,"autoAspect"),_n([G(),Zt("refreshAspect"),Ot("Aspect Ratio",r=>({hidden:()=>r.autoAspect}))],Pi.prototype,"aspect"),_n([jt({obj:"userData",onChange:"setDirty"})],Pi.prototype,"autoLookAtTarget"),_n([jt({obj:"userData",onChange:"setDirty"})],Pi.prototype,"autoNearFar"),_n([jt({obj:"userData",onChange:"setDirty"})],Pi.prototype,"minNearPlane"),_n([jt({obj:"userData",onChange:"setDirty"})],Pi.prototype,"maxFarPlane"),_n([jt({obj:"userData"})],Pi.prototype,"dollyFov"),_n([he((r,e)=>{e||console.warn("Setting camera invisible is not supported",r,e)})],Pi.prototype,"visible");let th=Pi;class rT extends th{constructor(e,t,i,n){super(void 0,void 0,void 0,e,t||1),this.dollyFov=!1,(i||n)&&(this.autoNearFar=!1,i&&(this.near=i,this.minNearPlane=i),n&&(this.far=n,this.maxFarPlane=n))}}var Gk=Object.defineProperty,zk=Object.getOwnPropertyDescriptor,on=(r,e,t,i)=>{for(var n=i>1?void 0:i?zk(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Gk(e,t,n),n};const pi=class extends Mr{constructor(e,t,i,n,s,a,o,l,c,h,u){super(s,a,o,l,c,h),this.assetType="camera",this._currentControlsMode="",this.userData={},this._frustumSize=void 0,this.target=new S(0,0,0),this.near=.1,this.far=2e3,this.autoLookAtTarget=!1,this.autoNearFar=!0,this.minNearPlane=void 0,this.maxFarPlane=void 0,this._interactionsDisabledBy=new Set,this.refreshAspect=ht.refreshAspect,this.refreshUi=ht.refreshUi,this.refreshTarget=ht.refreshTarget,this.activateMain=ht.activateMain,this.deactivateMain=ht.deactivateMain,this.updateShaderProperties=ht.updateShaderProperties,this.controlsCtors=new Map([["orbit",(d,p)=>{const m=p?p.ownerDocument?p:p.documentElement:document.body,A=new f.OrbitControls3(d,m);return m.tabIndex===-1&&(m.tabIndex=1e3,m.style.outline="none"),A.listenToKeyEvents(m),A.screenSpacePanning=!0,A}]]),this._controlsChanged=()=>{this._controls&&this._controls.target&&this.refreshTarget(void 0,!1),this.setDirty({change:"controls"})},this.getView=ht.getView,this.setView=ht.setView,this.fitObject=ht.fitObject,this.setViewFromCamera=ht.setViewFromCamera,this.setViewToMain=ht.setViewToMain,this._positionWorld=new S,this._camUi=[...bi(this)||[],...eg.call(this),tg.call(this)],this.uiConfig={type:"folder",label:()=>this.name||"Camera",children:[...this._camUi,()=>this._controls?.uiConfig]},this._canvas=t,this.aspect=u||1,this._frustumSize=n??4,this.autoAspect=i??!!t,ht.upgradeCamera.call(this),this.controlsMode=e||"",this.refreshTarget(void 0,!1),this.refreshFrustum(!1),this.setDirty()}get controls(){return this._controls}get isMainCamera(){return this.userData&&this.userData.__isMainCamera||!1}get frustumSize(){return this._frustumSize??0}set frustumSize(e){this._frustumSize=e<=0?void 0:e,this.refreshFrustum(!1),this.setDirty()}get interactionsEnabled(){return this._interactionsDisabledBy.size===0}setInteractions(e,t){const i=this._interactionsDisabledBy.size;e?this._interactionsDisabledBy.delete(t):this._interactionsDisabledBy.add(t),i!==this._interactionsDisabledBy.size&&this.refreshCameraControls(!0)}get canUserInteract(){return this._interactionsDisabledBy.size===0&&this.isMainCamera&&this.controlsMode!==""}setDirty(e){ht.setDirty.call(this,e),e?.last!==!1&&this._camUi?.forEach(t=>t?.uiRefresh?.(!1,"postFrame",1))}refreshFrustum(e=!0){this._frustumSize!==void 0&&(this.top=this._frustumSize/2,this.bottom=-this.top,this.left=this.bottom*this.aspect,this.right=this.top*this.aspect,e&&this.setDirty())}setControlsCtor(e,t,i=!1){if(!i&&this.controlsCtors.has(e)){console.error("OrthographicCamera2: "+e+" already exists.");return}this.controlsCtors.set(e,t)}removeControlsCtor(e){this.controlsCtors.delete(e)}_initCameraControls(){const e=this.controlsMode;this._controls=this.controlsCtors.get(e)?.(this,this._canvas)??void 0,!this._controls&&e!==""&&console.error("ICamera - Unable to create controls with mode "+e+". Are you missing a plugin?"),this._controls?.addEventListener&&this._controls.addEventListener("change",this._controlsChanged),this._currentControlsMode=this._controls?e:""}_disposeCameraControls(){this._controls&&(this._controls.target===this.target&&(this._controls.target=new S),this._controls.removeEventListener&&this._controls.removeEventListener("change",this._controlsChanged),this._controls.dispose&&this._controls.dispose()),this._currentControlsMode="",this._controls=void 0}refreshCameraControls(e=!0){if(this.controlsCtors){if(this._controls?(this._currentControlsMode!==this.controlsMode||this!==this._controls.object||this._controls.domElement&&this._canvas!==this._controls.domElement)&&(this._disposeCameraControls(),this._initCameraControls()):this._initCameraControls(),this._controls){const t=this.canUserInteract;this._controls.enabled=t,t&&this.up.copy(ft.DEFAULT_UP)}e&&this.setDirty(),this.refreshUi()}}toJSON(e,t=!1){return t?{...super.toJSON(e),...We.Serialize(this,e,!0)}:We.Serialize(this,e,!1)}fromJSON(e,t){return We.Deserialize(e,this,t,!0),this.setDirty({change:"deserialize"}),this}dispose(){this._disposeCameraControls()}setCanvas(e,t=!0){this._canvas=e,t&&(this.refreshCameraControls(),this.refreshAspect(!1))}get isActiveCamera(){return this.isMainCamera}getControls(){return this._controls}get cameraObject(){return this}get modelObject(){return this}targetUpdated(e=!0){e&&this.setDirty()}};on([He("Name")],pi.prototype,"name",2),on([G("camControls")],pi.prototype,"_controls",2),on([Li("Controls Mode",void 0,r=>({children:["none",...r.controlsCtors.keys()].map(e=>({label:e,value:e==="none"?"":e}))})),G(),Zt(pi.prototype.refreshCameraControls)],pi.prototype,"controlsMode",2),on([G()],pi.prototype,"userData",2),on([rt(pi.prototype.setDirty),Ot("Zoom"),G()],pi.prototype,"zoom",2),on([rt(pi.prototype.setDirty),Ot("Left",r=>({hidden:()=>r._frustumSize!==void 0})),G()],pi.prototype,"left",2),on([rt(pi.prototype.setDirty),Ot("Right",r=>({hidden:()=>r._frustumSize!==void 0})),G()],pi.prototype,"right",2),on([rt(pi.prototype.setDirty),Ot("Top",r=>({hidden:()=>r._frustumSize!==void 0})),G()],pi.prototype,"top",2),on([rt(pi.prototype.setDirty),Ot("Bottom",r=>({hidden:()=>r._frustumSize!==void 0})),G()],pi.prototype,"bottom",2),on([He("Frustum Size")],pi.prototype,"frustumSize",1),on([yi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"position"})})),G()],pi.prototype,"position",2),on([yi("Up",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"up"})})),G()],pi.prototype,"up",2),on([yi("Rotation",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"rotation"}),disabled:()=>r.autoLookAtTarget}))],pi.prototype,"rotation",2),on([yi("Target",void 0,void 0,r=>({onChange:()=>r.setDirty({change:"target"}),disabled:()=>!r.autoLookAtTarget})),G()],pi.prototype,"target",2),on([G(),Zt("refreshAspect"),se("Auto Aspect")],pi.prototype,"autoAspect",2),on([G(),Zt("refreshAspect"),Ot("Aspect Ratio",r=>({hidden:()=>r.autoAspect}))],pi.prototype,"aspect",2),on([jt({obj:"userData",onChange:"setDirty"})],pi.prototype,"autoLookAtTarget",2),on([jt({obj:"userData",onChange:"setDirty"})],pi.prototype,"autoNearFar",2),on([jt({obj:"userData",onChange:"setDirty"})],pi.prototype,"minNearPlane",2),on([jt({obj:"userData",onChange:"setDirty"})],pi.prototype,"maxFarPlane",2),on([he((r,e)=>{e||console.warn("Setting camera invisible is not supported",r,e)})],pi.prototype,"visible",2);let Sd=pi;class aT extends Sd{constructor(e,t,i,n,s,a){super(void 0,void 0,void 0,void 0,e,t,i,n,s,a,1),(s!==void 0||a)&&(this.autoNearFar=!1,s&&(this.near=s,this.minNearPlane=s),a&&(this.far=a,this.maxFarPlane=a))}}class oT extends Cd{constructor(e,t,i=!1){super(e,i),this.textures=[],this.setTextureIds(t)}setTextureIds(e){this.textures.map(t=>t.id).join(";")!==e.join(";")&&(this.textures=e.map(t=>({id:t,colorSpace:Bt})),this.setDirty())}_setUniformTexSize(e,t){if(!t||!e)return;const i=t?.width??512,n=t?.height??512,s=e.value;s.isVector2||console.warn("uniform is not a Vector2"),s&&Math.abs(s.x-i)+Math.abs(s.y-n)>.1&&(s.x=i,s.y=n,this.uniformsNeedUpdate=!0)}onBeforeRender(e,t,i,n,s,a){this.uniforms.screenSize&&this._setUniformTexSize(this.uniforms.screenSize,e.getRenderTarget()??e.getSize(new K));for(const o of this.textures){const l=o.id,c=this.uniforms[l]?.value;c&&(this._setUniformTexSize(this.uniforms[l+"Size"],c.image),c.colorSpace!==o.colorSpace&&(o.colorSpace=c.colorSpace,this.needsUpdate=!0))}super.onBeforeRender(e,t,i,n,s,a)}onBeforeCompile(e,t){const i=`
`+this.textures.map(n=>`uniform sampler2D ${n.id}; 
`+av(n.id??"input",n.colorSpace)).join(`
`);e.fragmentShader.includes("#include <encodings_pars_fragment>")?e.fragmentShader=bt(e.fragmentShader,"#include <encodings_pars_fragment>",i,{append:!0}):e.fragmentShader.includes("precision highp float;")?e.fragmentShader=bt(e.fragmentShader,"precision highp float;",i,{append:!0}):e.fragmentShader=i+e.fragmentShader,super.onBeforeCompile(e,t)}customProgramCacheKey(){return super.customProgramCacheKey()+this.textures.map(e=>e.id+e.colorSpace).join(";")}}const yr=class yr extends Jo{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isPhysicalMaterial=!0,this.appliedMeshes=new Set,this.setDirty=ve.setDirty,this.map=null,this.alphaMap=null,this.roughnessMap=null,this.metalnessMap=null,this.normalMap=null,this.bumpMap=null,this.displacementMap=null,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=ve.registerMaterialExtensions,this.unregisterMaterialExtensions=ve.unregisterMaterialExtensions,this.onAfterRender=ve.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Physical Material",uuid:"MPM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[...Xt.base(this),...bi(this),Xt.blending(this),Xt.roughMetal(this),Xt.bumpNormal(this),Xt.emission(this),Xt.transmission(this),Xt.environment(this),Xt.aoLightMap(this),Xt.clearcoat(this),Xt.iridescence(this),Xt.sheen(this),Xt.polygonOffset(this),...Xt.misc(this)]},this.fog=!1,this.attenuationDistance=0,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),ve.upgradeMaterial.call(this),this.setValues(t)}dispose(){return ve.dispose(super.dispose).call(this)}clone(e=!1){return ve.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+ve.customProgramCacheKey.call(this)}onBeforeCompile(e,t){const i=[["vec3 totalDiffuse = ","afterModulation"],["#include <aomap_fragment>","beforeModulation"],["#include <lights_physical_fragment>","beforeAccumulation"],["#include <clipping_planes_fragment>","mainStart"]],n=[["#include <uv_vertex>","mainStart"]];for(const s of n)e.vertexShader=bt(e.vertexShader,s[0],"#glMarker "+s[1]+`
`+s[0]);for(const s of i)e.fragmentShader=bt(e.fragmentShader,s[0],"#glMarker "+s[1]+`
`+s[0]);e.fragmentShader=bt(e.fragmentShader,"#include <opaque_fragment>",`gl_FragColor = clamp(gl_FragColor, 0.0, 1000.0);
`,{append:!0}),ve.onBeforeCompile.call(this,e,t),e.defines&&(e.defines.INVERSE_ALPHAMAP=this.userData.inverseAlphaMap?1:0),super.onBeforeCompile(e,t)}onBeforeRender(e,t,i,n,s,a){super.onBeforeRender(e,t,i,n,s,a),ve.onBeforeRender.call(this,e,t,i,n,s,a);const o=this.userData.inverseAlphaMap?1:0;o!==this.defines.INVERSE_ALPHAMAP&&(this.defines.INVERSE_ALPHAMAP=o,this.needsUpdate=!0)}setValues(e,t=!0,i=void 0,n){if(e){if(e.type&&!t&&!["MeshPhysicalMaterial","MeshStandardMaterial","MeshStandardMaterial2",this.constructor.TYPE,this.type].includes(e.type)){console.error("Material type is not supported:",e.type);return}typeof e.normalScale=="number"&&(e.normalScale=[e.normalScale,e.normalScale]),e.ior!==void 0&&(this.ior=e.ior),ve.setValues(super.setValues).call(this,e,t,i,n),isFinite(this.attenuationDistance)||(this.attenuationDistance=0),this.userData.uuid=this.uuid}}copy(e){return this.setValues(e,!1),this}toJSON(e,t=!1){return t?{...super.toJSON(e),...We.Serialize(this,e,!0)}:We.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(We.Deserialize(e,this,t,!0),this.setValues(e),this):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};yr.TypeSlug="pmat",yr.TYPE="PhysicalMaterial",yr.TypeAlias=["physical","standard",yr.TYPE,yr.TypeSlug,"MeshStandardMaterial","MeshStandardMaterial2","MeshPhysicalMaterial"],We.SerializableMaterials.add(yr),yr.MaterialProperties={...It,color:new ee(16777215),roughness:1,metalness:0,map:null,lightMap:null,lightMapIntensity:1,aoMap:null,aoMapIntensity:1,emissive:"#000000",emissiveIntensity:1,emissiveMap:null,bumpMap:null,bumpScale:1,normalMap:null,normalMapType:Us,normalScale:new K(1,1),displacementMap:null,displacementScale:1,displacementBias:0,roughnessMap:null,metalnessMap:null,alphaMap:null,envMap:null,envMapRotation:new Pt,envMapIntensity:1,wireframe:!1,wireframeLinewidth:1,wireframeLinecap:"round",wireframeLinejoin:"round",flatShading:!1,fog:!0,clearcoat:0,clearcoatMap:null,clearcoatRoughness:0,clearcoatRoughnessMap:null,clearcoatNormalScale:new K(1,1),clearcoatNormalMap:null,dispersion:0,reflectivity:.5,iridescence:0,iridescenceMap:null,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],iridescenceThicknessMap:null,sheen:0,sheenColor:new ee(0),sheenColorMap:null,sheenRoughness:1,sheenRoughnessMap:null,transmission:0,transmissionMap:null,thickness:0,thicknessMap:null,attenuationDistance:1/0,attenuationColor:new ee(1,1,1),specularIntensity:1,specularIntensityMap:null,specularColor:new ee(1,1,1),specularColorMap:null,anisotropy:0,anisotropyRotation:0,anisotropyMap:null},yr.MapProperties=["map","lightMap","aoMap","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap","envMap","clearcoatMap","clearcoatRoughnessMap","clearcoatNormalMap","iridescenceMap","iridescenceThicknessMap","sheenColorMap","sheenRoughnessMap","transmissionMap","thicknessMap","specularIntensityMap","specularColorMap","anisotropyMap"],yr.InterpolateProperties=[...wa,"color","emissive","roughness","metalness","lightMapIntensity","aoMapIntensity","emissiveIntensity","bumpScale","normalScale","displacementScale","displacementBias","envMapIntensity","wireframeLinewidth","reflectivity","clearcoat","clearcoatRoughness","clearcoatNormalScale","iridescence","iridescenceIOR","iridescenceThicknessRange","sheen","sheenColor","sheenRoughness","transmission","thickness","attenuationDistance","attenuationColor","specularIntensity","specularColor","anisotropy","anisotropyRotation"];let si=yr;class Vk extends si{constructor(e){super(e),console.error("MeshStandardMaterial2 is deprecated, use UnlitMaterial instead")}}const Vr=class Vr extends nn{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isObjectShaderMaterial=!0,this.appliedMeshes=new Set,this.setDirty=ve.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=ve.registerMaterialExtensions,this.unregisterMaterialExtensions=ve.unregisterMaterialExtensions,this.onBeforeRender=ve.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=ve.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Shader Material",uuid:"OSM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[...bi(this),...Xt.base(this),Xt.blending(this),Xt.polygonOffset(this),...Xt.misc(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),ve.upgradeMaterial.call(this),this.setValues(t)}dispose(){return ve.dispose(super.dispose).call(this)}clone(e=!1){return ve.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+ve.customProgramCacheKey.call(this)}onBeforeCompile(e,t){ve.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}setValues(e,t=!0,i=void 0,n){return e?e.type&&!t&&!["ShaderMaterial","ShaderMaterial2","ExtendedShaderMaterial",this.constructor.TYPE,this.type].includes(e.type)?(console.error("Material type is not supported:",e.type),this):(ve.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...We.Serialize(this,e,!0)}:We.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(We.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};Vr.TypeSlug="shmat",Vr.TYPE="ObjectShaderMaterial",Vr.TypeAlias=["shader",Vr.TYPE,Vr.TypeSlug,"ShaderMaterial"],We.SerializableMaterials.add(Vr),Vr.MaterialProperties={...It,defines:{},uniforms:{},uniformsGroups:[],vertexShader:"",fragmentShader:"",linewidth:1,wireframe:!1,wireframeLinewidth:1,fog:!1,lights:!1,clipping:!1,forceSinglePass:!0,extensions:{derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1},defaultAttributeValues:{color:[1,1,1],uv:[0,0],uv1:[0,0]},index0AttributeName:void 0,uniformsNeedUpdate:!1,glslVersion:null,flatShading:!1},Vr.InterpolateProperties=[...wa,"linewidth","wireframeLinewidth"];let $v=Vr;const _r=class _r extends Mi{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isUnlitLineMaterial=!0,this.appliedMeshes=new Set,this.setDirty=ve.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=ve.registerMaterialExtensions,this.unregisterMaterialExtensions=ve.unregisterMaterialExtensions,this.onBeforeRender=ve.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=ve.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Unlit Line Material",uuid:"MBLM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[{type:"input",property:[this,"name"]},{type:"checkbox",property:[this,"vertexColors"]},{type:"color",property:[this,"color"]},Ii(this,"map"),{type:"number",property:[this,"linewidth"]},{type:"dropdown",property:[this,"linecap"],children:["butt","round","square"].map(i=>({label:i}))},{type:"dropdown",property:[this,"linejoin"],children:["bevel","round","miter"].map(i=>({label:i}))},Xt.blending(this),Xt.polygonOffset(this),...Xt.misc(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),ve.upgradeMaterial.call(this),this.setValues(t)}dispose(){return ve.dispose(super.dispose).call(this)}clone(e=!1){return ve.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+ve.customProgramCacheKey.call(this)}onBeforeCompile(e,t){const i=[["vec3 outgoingLight = ","afterModulation"],["#include <aomap_fragment>","beforeModulation"],["ReflectedLight reflectedLight = ","beforeAccumulation"],["#include <clipping_planes_fragment>","mainStart"]],n=[["#include <uv_vertex>","mainStart"]];for(const s of n)e.vertexShader=bt(e.vertexShader,s[0],"#glMarker "+s[1]+`
`+s[0]);for(const s of i)e.fragmentShader=bt(e.fragmentShader,s[0],"#glMarker "+s[1]+`
`+s[0]);ve.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}setValues(e,t=!0,i=void 0,n){return e?e.type&&!t&&!["LineBasicMaterial","LineBasicMaterial2",this.constructor.TYPE,this.type].includes(e.type)?(console.error("Material type is not supported:",e.type),this):(ve.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...We.Serialize(this,e,!0)}:We.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(We.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};_r.TypeSlug="blmat",_r.TYPE="UnlitLineMaterial",_r.TypeAlias=["unlitline","basicline",_r.TYPE,_r.TypeSlug,"LineBasicMaterial"],We.SerializableMaterials.add(_r),_r.MaterialProperties={...It,color:new ee(16777215),map:null,linewidth:1,linecap:"round",linejoin:"round",fog:!0},_r.MapProperties=["map"],_r.InterpolateProperties=[...wa,"color","linewidth"];let Yn=_r;class Hk extends Yn{constructor(e){super(e),console.error("LineBasicMaterial2 is deprecated, use UnlitLineMaterial instead")}}var Qk=Object.defineProperty,cr=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Qk(e,t,n),n};const Vs=(Os=class extends $c{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isLineMaterial2=!0,this.appliedMeshes=new Set,this.setDirty=ve.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=ve.registerMaterialExtensions,this.unregisterMaterialExtensions=ve.unregisterMaterialExtensions,this.autoUpdateResolution=!0,this.uiConfig={type:"folder",label:"Line Material",uuid:"MPM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[...bi(this)||[],Xt.blending(this),Xt.polygonOffset(this),...Xt.misc(this)]},this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),ve.upgradeMaterial.call(this),this.setValues(t)}dispose(){return ve.dispose(super.dispose).call(this)}clone(e=!1){return ve.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+ve.customProgramCacheKey.call(this)}onBeforeCompile(e,t){const i=[["vec4 diffuseColor = ","beforeAccumulation"],["#include <clipping_planes_fragment>","mainStart"]],n=[["#ifdef USE_COLOR","mainStart"]];for(const s of n)e.vertexShader=bt(e.vertexShader,s[0],"#glMarker "+s[1]+`
`+s[0]);for(const s of i)e.fragmentShader=bt(e.fragmentShader,s[0],"#glMarker "+s[1]+`
`+s[0]);ve.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}onBeforeRender(e,t,i,n,s,a){this.autoUpdateResolution&&e.getSize(this.resolution),super.onBeforeRender(e,t,i,n,s,a),ve.onBeforeRender.call(this,e,t,i,n,s,a)}onAfterRender(e,t,i,n,s,a){super.onAfterRender(e,t,i,n,s,a),ve.onAfterRender.call(this,e,t,i,n,s,a)}setValues(e,t=!0,i=void 0,n){return e?e.type&&!t&&!["LineMaterial",this.constructor.TYPE,this.type].includes(e.type)&&!e.isLineMaterial&&!e.isLineMaterial2?(console.error("Material type is not supported:",e.type),this):(ve.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...We.Serialize(this,e,!0)}:We.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(We.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}},Os.TypeSlug="lmat",Os.TYPE="LineMaterial2",Os.TypeAlias=["line",Os.TYPE,Os.TypeSlug,"LineMaterial"],We.SerializableMaterials.add(Os),Os.MaterialProperties={...It,color:new ee(16777215),dashed:!1,dashScale:1,dashSize:1,dashOffset:0,gapSize:1,linewidth:1,resolution:new K(1,1),alphaToCoverage:!1,worldUnits:!1,uniforms:{},defines:{},extensions:{},clipping:!1,fog:!0,fragmentShader:"",vertexShader:""},Os.InterpolateProperties=[...wa,"color","dashScale","dashSize","dashOffset","gapSize","linewidth","resolution"],Os);cr([He()],Vs.prototype,"name"),cr([xn()],Vs.prototype,"color"),cr([se()],Vs.prototype,"dashed"),cr([Ot()],Vs.prototype,"dashScale"),cr([Ot()],Vs.prototype,"dashSize"),cr([Ot()],Vs.prototype,"dashOffset"),cr([Ot()],Vs.prototype,"gapSize"),cr([Ot()],Vs.prototype,"linewidth"),cr([yi()],Vs.prototype,"resolution"),cr([se()],Vs.prototype,"alphaToCoverage"),cr([se()],Vs.prototype,"worldUnits");let ji=Vs;class jk extends ji{}const vr=class vr extends Zo{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isLegacyPhongMaterial=!0,this.appliedMeshes=new Set,this.setDirty=ve.setDirty,this.envMap=null,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=ve.registerMaterialExtensions,this.unregisterMaterialExtensions=ve.unregisterMaterialExtensions,this.onBeforeRender=ve.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=ve.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Phong Material",uuid:"MBM2_"+this.uuid,expanded:!0,onChange:i=>{if(!i.config||i.config.onChange)return;let n=Array.isArray(i.config.property)?i.config.property[1]:i.config.property;n=typeof n=="string"?n:void 0,this.setDirty({uiChangeEvent:i,needsUpdate:!!i.last,refreshUi:!!i.last,change:n})},children:[...Xt.base(this),Xt.blending(this),Xt.polygonOffset(this),Xt.aoLightMap(this),{type:"folder",label:"Specular",children:[{type:"color",property:[this,"specular"]},{type:"image",property:[this,"specularMap"]},Ii(this,"specularMap"),{type:"slider",label:"Shininess",property:[this,"shininess"],bounds:[0,100],stepSize:.1},{type:"slider",label:"Reflectivity",property:[this,"reflectivity"],bounds:[0,1],stepSize:.01},{type:"slider",label:"Refraction Ratio",property:[this,"refractionRatio"],bounds:[0,3],stepSize:.01}]},Xt.bumpNormal(this),Xt.emission(this),{type:"folder",label:"Env Map",children:[{type:"image",property:[this,"envMap"]},Ii(this,"envMap"),{type:"slider",label:"Env Map Intensity",property:[this,"envMapIntensity"],bounds:[0,5],stepSize:.01}]},...Xt.misc(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),ve.upgradeMaterial.call(this),this.setValues(t)}dispose(){return ve.dispose(super.dispose).call(this)}clone(e=!1){return ve.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+ve.customProgramCacheKey.call(this)}onBeforeCompile(e,t){const i=[["vec3 outgoingLight = ","afterModulation"],["#include <aomap_fragment>","beforeModulation"],["ReflectedLight reflectedLight = ","beforeAccumulation"],["#include <clipping_planes_fragment>","mainStart"]],n=[["#include <uv_vertex>","mainStart"]];for(const s of n)e.vertexShader=bt(e.vertexShader,s[0],"#glMarker "+s[1]+`
`+s[0]);for(const s of i)e.fragmentShader=bt(e.fragmentShader,s[0],"#glMarker "+s[1]+`
`+s[0]);ve.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}setValues(e,t=!0,i=void 0,n){return e?e.type&&!t&&!["MeshPhongMaterial","MeshPhongMaterial2",this.constructor.TYPE,this.type].includes(e.type)?(console.error("Material type is not supported:",e.type),this):(ve.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...We.Serialize(this,e,!0)}:We.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(We.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};vr.TypeSlug="phongmat",vr.TYPE="LegacyPhongMaterial",vr.TypeAlias=["phong",vr.TYPE,vr.TypeSlug,"MeshPhongMaterial"],We.SerializableMaterials.add(vr),vr.MaterialProperties={...It,color:new ee(16777215),specular:new ee(1118481),shininess:30,map:null,lightMap:null,lightMapIntensity:1,aoMap:null,aoMapIntensity:1,emissive:new ee(0),emissiveIntensity:1,emissiveMap:null,bumpMap:null,bumpScale:1,normalMap:null,normalMapType:"TangentSpaceNormalMap",normalScale:new K(1,1),displacementMap:null,displacementScale:1,displacementBias:0,specularMap:null,alphaMap:null,envMap:null,combine:$l,envMapIntensity:1,reflectivity:1,refractionRatio:.98,wireframe:!1,wireframeLinewidth:1,wireframeLinecap:"round",wireframeLinejoin:"round",skinning:!1,fog:!0,flatShading:!1},vr.MapProperties=["map","lightMap","aoMap","emissiveMap","bumpMap","normalMap","displacementMap","specularMap","alphaMap","envMap"],vr.InterpolateProperties=[...wa,"color","specular","emissive","shininess","lightMapIntensity","aoMapIntensity","emissiveIntensity","bumpScale","normalScale","displacementScale","displacementBias","envMapIntensity","reflectivity","refractionRatio","wireframeLinewidth"];let sg=vr;class lT extends ft{constructor(){super(),this.assetType="model",this.setDirty=qe.setDirty,this.refreshUi=qe.refreshUi,qe.upgradeObject3D.call(this)}get modelObject(){return this}dispose(){}}class _l extends Vi{constructor(){super(),this.assetType="model",this.setDirty=qe.setDirty,this.refreshUi=qe.refreshUi,qe.upgradeObject3D.call(this)}get modelObject(){return this}dispose(){}}class rg extends _e{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=qe.setDirty,this.refreshUi=qe.refreshUi,qe.upgradeObject3D.call(this)}get modelObject(){return this}}class Wk extends Oc{constructor(e,t,i=1){super(e,t,i),this.assetType="model",this.setDirty=qe.setDirty,this.refreshUi=qe.refreshUi,qe.upgradeObject3D.call(this)}get modelObject(){return this}}class Ed extends Gs{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(e){const t=e.length-3,i=new Float32Array(2*t);for(let n=0;n<t;n+=3)i[2*n]=e[n],i[2*n+1]=e[n+1],i[2*n+2]=e[n+2],i[2*n+3]=e[n+3],i[2*n+4]=e[n+4],i[2*n+5]=e[n+5];return super.setPositions(i),this}setColors(e){const t=e.length-3,i=new Float32Array(2*t);for(let n=0;n<t;n+=3)i[2*n]=e[n],i[2*n+1]=e[n+1],i[2*n+2]=e[n+2],i[2*n+3]=e[n+3],i[2*n+4]=e[n+4],i[2*n+5]=e[n+5];return super.setColors(i),this}fromLine(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}}class ag extends va{constructor(e=new Ed,t=new $c({color:Math.random()*16777215})){super(e,t),this.isLine2=!0,this.type="Line2"}}class Kv extends ag{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=qe.setDirty,this.refreshUi=qe.refreshUi,this.isMeshLine=!0,qe.upgradeObject3D.call(this)}get modelObject(){return this}}class cT extends va{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=qe.setDirty,this.refreshUi=qe.refreshUi,this.isMeshLineSegments=!0,qe.upgradeObject3D.call(this)}get modelObject(){return this}}class Md extends Je{constructor(){super(),this.center2=ni.center2,this.setDirty=ni.setDirty,this.refreshUi=ni.refreshUi,this.appliedMeshes=new Set,ni.upgradeGeometry.call(this)}}class Jv extends Ed{constructor(){super(),this.center2=ni.center2,this.setDirty=ni.setDirty,this.refreshUi=ni.refreshUi,this.appliedMeshes=new Set,ni.upgradeGeometry.call(this)}getPositions(){return hT(this.attributes.instanceStart)}getColors(){return hT(this.attributes.instanceColorStart)}}function hT(r){const e=r?.data.array;if(!e)return null;const t=e.length/2+3,i=new Float32Array(t);i[0]=e[0],i[1]=e[1],i[2]=e[2];for(let n=3;n<t;n+=3){const s=2*n-3;i[n]=e[s],i[n+1]=e[s+1],i[n+2]=e[s+2]}return i}class uT extends Gs{constructor(){super(),this.center2=ni.center2,this.setDirty=ni.setDirty,this.refreshUi=ni.refreshUi,this.appliedMeshes=new Set,ni.upgradeGeometry.call(this)}getPositions(){return this.attributes.instanceStart?.data.array||null}getColors(){return this.attributes.instanceColorStart?.data.array||null}}class Zv extends Gs{constructor(e){super(),this.isWireframeGeometry2=!0,this.type="WireframeGeometry2",this.fromWireframeGeometry(new Xp(e))}}class qk extends Zv{constructor(e){super(e),this.center2=ni.center2,this.setDirty=ni.setDirty,this.refreshUi=ni.refreshUi,this.appliedMeshes=new Set,ni.upgradeGeometry.call(this)}}class dT extends Je{constructor(e,t,i=32,n=64,s=!1,a=new K(1,1),o="shape"){super(),this.type="TubeShapeGeometry",this.parameters={path:t,shape:e,shapeSegments:i,tubularSegments:n,closed:s,primary:o,shapeScale:a.clone()};const l=t.computeFrenetFrames(n,s);this.frames=l;const c=new S,h=new S,u=new S,d=new K;let p=new S;const m=[],A=[],g=[],y=e.getSpacedPoints(i);for(const I of y)I.multiply(a);_(),this.setIndex(g),this.setAttribute("position",new Ee(m,3)),this.setAttribute("uv",new Ee(A,2)),this.computeVertexNormals();const v=this.attributes.normal;M();function _(){for(let I=0;I<n;I++)b(I);b(s===!1?n:0),E(),T()}function b(I){p=t.getPointAt(I/n,p);const C=l.normals[I],x=l.binormals[I];for(let D=0;D<=i;D++){const U=y[D%i];h.set(0,0,0).addScaledVector(C,U.x).addScaledVector(x,U.y),c.copy(p).add(h),m.push(c.x,c.y,c.z)}}function T(){const I=o==="shape",C=I?i:n,x=I?n:i;for(let D=1;D<=C;D++)for(let U=1;U<=x;U++){const[O,N]=I?[U,D]:[D,U],H=(i+1)*(O-1)+(N-1),V=(i+1)*O+(N-1),X=(i+1)*O+N,W=(i+1)*(O-1)+N;g.push(H,V,W),g.push(V,X,W)}}function E(){for(let I=0;I<=n;I++)for(let C=0;C<=i;C++)d.x=I/n,d.y=C/i,A.push(d.x,d.y)}function M(){for(let C=1;C<i;C++){const x=C+n*(i+1);h.fromBufferAttribute(v,C),u.fromBufferAttribute(v,x),h.add(u).normalize(),v.setXYZ(C,h.x,h.y,h.z),v.setXYZ(x,h.x,h.y,h.z)}for(let C=1;C<n;C++){const x=C*(i+1),D=x+i;h.fromBufferAttribute(v,x),u.fromBufferAttribute(v,D),h.add(u).normalize(),v.setXYZ(x,h.x,h.y,h.z),v.setXYZ(D,h.x,h.y,h.z)}h.fromBufferAttribute(v,0),u.fromBufferAttribute(v,i),h.add(u);const I=n*(i+1);u.fromBufferAttribute(v,I),h.add(u),u.fromBufferAttribute(v,I+i),h.add(u),h.normalize(),v.setXYZ(0,h.x,h.y,h.z),v.setXYZ(i,h.x,h.y,h.z),v.setXYZ(I,h.x,h.y,h.z),v.setXYZ(I+i,h.x,h.y,h.z),v.needsUpdate=!0}}createSplits(e){this.clearGroups();const t=this.parameters.primary==="shape"?this.parameters.shapeSegments:this.parameters.tubularSegments,i=this.index.count,n=[...e,1].sort((o,l)=>o-l);let s=0,a=0;for(const o of n){const l=Math.round(t*o)*i/t;this.addGroup(s,l-s,a++),s=l}return this.groups.length}toJSON(){const e=super.toJSON();return e.path=this.parameters.path.toJSON(),e.shape=this.parameters.shape.toJSON(),e}}const zb=class zb extends Xo{constructor(e,t,i,n,s,a,o,l){super(e,t,i,n,s,a,o,l),this.type="EllipseCurve3D"}getPoint(e,t){return super.getPoint(e,t||new S)}};Lt.SerializableClasses.set("EllipseCurve3D",zb);let vl=zb;const pn={setDirty:function(r,...e){typeof r=="string"&&(r={change:r}),qe.setDirty.call(this,r,...e)},upgradeLight:Xk,refreshUi:qe.refreshUi};function Xk(r){this&&qe.upgradeObject3D.call(this,r)}var Yk=Object.defineProperty,og=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Yk(e,t,n),n};class bl extends Kp{constructor(e,t){super(e,t),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"Ambient Light",children:[...bi(this),...co.call(this)]},this.isAmbientLight2=!0,pn.upgradeLight.call(this)}autoScale(){console.warn("AutoScale not supported on Lights")}autoCenter(){console.warn("AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}}og([se("Enabled"),rt("setDirty")],bl.prototype,"visible"),og([He("Name"),rt("setDirty")],bl.prototype,"name"),og([xn("Color",r=>({onChange:()=>r.setDirty()}))],bl.prototype,"color"),og([Ot("Intensity"),rt("setDirty")],bl.prototype,"intensity");var $k=Object.defineProperty,As=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&$k(e,t,n),n};const vn=class extends sl{constructor(e,t){super(e,t),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"Directional Light",children:[...bi(this),...co.call(this)]},this.isDirectionalLight2=!0,this.target.position.set(0,0,-1),this.add(this.target),pn.upgradeLight.call(this),this.shadowFrustum=10}_mapSizeChanged(){this.shadow.map?.dispose(),this.shadow.mapPass?.dispose(),this.shadow.map=null,this.shadow.mapPass=null,this.setDirty({change:"shadowMapSize"})}_shadowFrustumChanged(){const e=this.shadowFrustum;this.shadow.camera.left=-e/2,this.shadow.camera.right=e/2,this.shadow.camera.top=e/2,this.shadow.camera.bottom=-e/2,this.shadow.camera.updateProjectionMatrix(),this.setDirty({change:"shadowFrustum"})}_shadowCamUpdate(e){this.shadow.camera.updateProjectionMatrix(),this.setDirty({change:e})}autoScale(){console.warn("DirectionalLight2: AutoScale not supported on Lights")}autoCenter(){console.warn("DirectionalLight2: AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}};As([se("Enabled"),rt("setDirty")],vn.prototype,"visible"),As([He("Name"),rt("setDirty")],vn.prototype,"name"),As([xn("Color",r=>({onChange:()=>r.setDirty()}))],vn.prototype,"color"),As([Fe("Intensity",[0,100],.01),rt("setDirty")],vn.prototype,"intensity"),As([yi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],vn.prototype,"position"),As([yi("Rotation",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],vn.prototype,"rotation"),As([se("Cast Shadow"),rt("setDirty")],vn.prototype,"castShadow"),As([yi("Shadow Map Size",void 0,void 0,r=>({onChange:()=>r._mapSizeChanged()})),jt({obj:"shadow",key:"mapSize",onChange:vn.prototype._mapSizeChanged,onChangeParams:!1})],vn.prototype,"shadowMapSize"),As([Fe("Shadow Bias",[-.001,.001],1e-5),jt({obj:"shadow",key:"bias",onChange:"setDirty"})],vn.prototype,"shadowBias"),As([Fe("Shadow Normal Bias",[-.1,.1],.005),jt({obj:"shadow",key:"normalBias",onChange:"setDirty"})],vn.prototype,"shadowNormalBias"),As([Fe("Shadow Radius",[0,5],.01),jt({obj:"shadow",key:"radius",onChange:"setDirty"})],vn.prototype,"shadowRadius"),As([Ot("Shadow Frustum"),Zt(vn.prototype._shadowFrustumChanged)],vn.prototype,"shadowFrustum"),As([Ot("Shadow Near"),jt({obj:"shadow",key:["camera","near"],onChange:vn.prototype._shadowCamUpdate})],vn.prototype,"shadowNear"),As([Ot("Shadow Far"),jt({obj:"shadow",key:["camera","far"],onChange:vn.prototype._shadowCamUpdate})],vn.prototype,"shadowFar");let lg=vn;var Kk=Object.defineProperty,ih=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Kk(e,t,n),n};class Ca extends $p{constructor(e,t,i){super(e,t,i),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"Hemisphere Light",children:[...bi(this),...co.call(this)]},this.isHemisphereLight2=!0,pn.upgradeLight.call(this)}autoScale(){console.warn("AutoScale not supported on Lights")}autoCenter(){console.warn("AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}}ih([se("Enabled"),rt("setDirty")],Ca.prototype,"visible"),ih([He("Name"),rt("setDirty")],Ca.prototype,"name"),ih([xn("Sky Color",r=>({onChange:()=>r.setDirty()}))],Ca.prototype,"color"),ih([xn("Ground Color",r=>({onChange:()=>r.setDirty()}))],Ca.prototype,"groundColor"),ih([Ot("Intensity"),rt("setDirty")],Ca.prototype,"intensity"),ih([yi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],Ca.prototype,"position");var Jk=Object.defineProperty,$n=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Jk(e,t,n),n};const Wi=class extends nl{constructor(e,t,i,n){super(e,t,i,n),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"Point Light",children:[...bi(this),...co.call(this)]},this.isPointLight2=!0,pn.upgradeLight.call(this)}_mapSizeChanged(){this.shadow.map?.dispose(),this.shadow.mapPass?.dispose(),this.shadow.map=null,this.shadow.mapPass=null,this.setDirty({change:"shadowMapSize"})}_shadowCamUpdate(e){this.shadow.camera.updateProjectionMatrix(),this.setDirty({change:e})}autoScale(){console.warn("AutoScale not supported on Lights")}autoCenter(){console.warn("AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}};$n([se("Enabled"),rt("setDirty")],Wi.prototype,"visible"),$n([He("Name"),rt("setDirty")],Wi.prototype,"name"),$n([xn("Color",r=>({onChange:()=>r.setDirty()}))],Wi.prototype,"color"),$n([Ot("Intensity"),rt("setDirty")],Wi.prototype,"intensity"),$n([Ot("Distance"),rt("setDirty")],Wi.prototype,"distance"),$n([Ot("Decay"),rt("setDirty")],Wi.prototype,"decay"),$n([Ot("Power"),rt("setDirty")],Wi.prototype,"power"),$n([yi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],Wi.prototype,"position"),$n([se("Cast Shadow"),rt("setDirty")],Wi.prototype,"castShadow"),$n([yi("Shadow Map Size",void 0,void 0,r=>({onChange:()=>r._mapSizeChanged()})),jt({obj:"shadow",key:"mapSize",onChange:Wi.prototype._mapSizeChanged,onChangeParams:!1})],Wi.prototype,"shadowMapSize"),$n([Fe("Shadow Bias",[-.001,.001],1e-5),jt({obj:"shadow",key:"bias",onChange:"setDirty"})],Wi.prototype,"shadowBias"),$n([Fe("Shadow Radius",[0,5],.01),jt({obj:"shadow",key:"radius",onChange:"setDirty"})],Wi.prototype,"shadowRadius"),$n([Ot("Shadow Near"),jt({obj:"shadow",key:["camera","near"],onChange:Wi.prototype._shadowCamUpdate})],Wi.prototype,"shadowNear"),$n([Ot("Shadow Far"),jt({obj:"shadow",key:["camera","far"],onChange:Wi.prototype._shadowCamUpdate})],Wi.prototype,"shadowFar"),$n([Ot("Shadow Aspect"),jt({obj:"shadow",key:"aspect",onChange:Wi.prototype._shadowCamUpdate})],Wi.prototype,"shadowAspect"),$n([Fe("Shadow FOV",[1,179],1),jt({obj:"shadow",key:"fov",onChange:Wi.prototype._shadowCamUpdate})],Wi.prototype,"shadowFov");let cg=Wi;var Zk=Object.defineProperty,wl=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Zk(e,t,n),n};class Nr extends Jp{constructor(e,t,i,n){super(e,t,i,n),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"RectArea Light",children:[...bi(this),...co.call(this)]},this.isRectAreaLight2=!0,pn.upgradeLight.call(this)}autoScale(){console.warn("AutoScale not supported on Lights")}autoCenter(){console.warn("AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}}wl([se("Enabled"),rt("setDirty")],Nr.prototype,"visible"),wl([He("Name"),rt("setDirty")],Nr.prototype,"name"),wl([xn("Color",r=>({onChange:()=>r.setDirty()}))],Nr.prototype,"color"),wl([Ot("Intensity"),rt("setDirty")],Nr.prototype,"intensity"),wl([Ot("Width"),rt("setDirty")],Nr.prototype,"width"),wl([Ot("Height"),rt("setDirty")],Nr.prototype,"height"),wl([Ot("Power"),rt("setDirty")],Nr.prototype,"power");var eG=Object.defineProperty,bn=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&eG(e,t,n),n};const Si=class extends zc{constructor(e,t,i,n,s,a){super(e,t,i,n,s,a),this.assetType="light",this.setDirty=pn.setDirty,this.refreshUi=pn.refreshUi,this.uiConfig={type:"folder",label:"Spot Light",children:[...bi(this),...co.call(this)]},this.isSpotLight2=!0,this.target.position.set(0,0,-1),this.add(this.target),pn.upgradeLight.call(this)}_mapSizeChanged(){this.shadow.map?.dispose(),this.shadow.mapPass?.dispose(),this.shadow.map=null,this.shadow.mapPass=null,this.setDirty({change:"shadowMapSize"})}_shadowCamUpdate(e){this.shadow.camera.updateProjectionMatrix(),this.setDirty({change:e})}autoScale(){console.warn("AutoScale not supported on Lights")}autoCenter(){console.warn("AutoCenter not supported on Lights")}get lightObject(){return this}get modelObject(){return this}};bn([se("Enabled"),rt("setDirty")],Si.prototype,"visible"),bn([He("Name"),rt("setDirty")],Si.prototype,"name"),bn([xn("Color",r=>({onChange:()=>r.setDirty()}))],Si.prototype,"color"),bn([Ot("Intensity"),rt("setDirty")],Si.prototype,"intensity"),bn([Fe("Angle",[0,2],.01),rt("setDirty")],Si.prototype,"angle"),bn([Fe("Penumbra",[0,.9999],.01),rt("setDirty")],Si.prototype,"penumbra"),bn([He("Distance"),rt("setDirty")],Si.prototype,"distance"),bn([He("Decay"),rt("setDirty")],Si.prototype,"decay"),bn([yi("Position",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],Si.prototype,"position"),bn([yi("Rotation",void 0,void 0,r=>({onChange:()=>r.setDirty()}))],Si.prototype,"rotation"),bn([se("Cast Shadow"),rt("setDirty")],Si.prototype,"castShadow"),bn([yi("Shadow Map Size",void 0,void 0,r=>({onChange:()=>r._mapSizeChanged()})),jt({obj:"shadow",key:"mapSize",onChange:Si.prototype._mapSizeChanged,onChangeParams:!1})],Si.prototype,"shadowMapSize"),bn([Fe("Shadow Bias",[-.001,.001],1e-5),jt({obj:"shadow",key:"bias",onChange:"setDirty"})],Si.prototype,"shadowBias"),bn([Fe("Shadow Radius",[0,5],.01),jt({obj:"shadow",key:"radius",onChange:"setDirty"})],Si.prototype,"shadowRadius"),bn([Fe("Shadow Focus",[0,1],.001),jt({obj:"shadow",key:"focus",onChange:"setDirty"})],Si.prototype,"shadowFocus"),bn([Ot("Shadow Near"),jt({obj:"shadow",key:["camera","near"],onChange:Si.prototype._shadowCamUpdate})],Si.prototype,"shadowNear"),bn([Ot("Shadow Far"),jt({obj:"shadow",key:["camera","far"],onChange:Si.prototype._shadowCamUpdate})],Si.prototype,"shadowFar"),bn([Ot("Shadow Aspect"),jt({obj:"shadow",key:"aspect",onChange:Si.prototype._shadowCamUpdate})],Si.prototype,"shadowAspect"),bn([Fe("Shadow FOV",[1,179],1),jt({obj:"shadow",key:"fov",onChange:Si.prototype._shadowCamUpdate})],Si.prototype,"shadowFov");let hg=Si;function Td(){this.assetType="texture",this.userData||(this.userData={}),this.appliedObjects||(this.appliedObjects=new Set),this.setDirty||(this.setDirty=()=>this.needsUpdate=!0)}function fT(r){return this.userData?.__isIWebGLRenderer?this:(this.userData||(this.userData={__isIWebGLRenderer:!0}),this.userData.__isIWebGLRenderer=!0,this.renderWithModes||(this.renderWithModes=pT),this.renderManager=r,this.baseRenderer||Object.defineProperty(this,"baseRenderer",{get:()=>(console.warn("IWebGLRenderer.baseRenderer is deprecated, use IWebGLRenderer.renderManager instead"),this.renderManager)}),this)}function pT(r,e){const t=this.userData,{backgroundRender:i,transparentRender:n,shadowMapRender:s,mainRenderPass:a,opaqueRender:o,transmissionRender:l,sceneRender:c,screenSpaceRendering:h}=t;r.backgroundRender!==void 0&&(t.backgroundRender=r.backgroundRender),r.transparentRender!==void 0&&(t.transparentRender=r.transparentRender),r.shadowMapRender!==void 0&&(t.shadowMapRender=r.shadowMapRender),r.mainRenderPass!==void 0&&(t.mainRenderPass=r.mainRenderPass),r.opaqueRender!==void 0&&(t.opaqueRender=r.opaqueRender),r.sceneRender!==void 0&&(t.sceneRender=r.sceneRender),r.transmissionRender!==void 0&&(t.transmissionRender=r.transmissionRender),r.screenSpaceRendering!==void 0&&(t.screenSpaceRendering=r.screenSpaceRendering),e(),t.backgroundRender=i,t.transparentRender=n,t.shadowMapRender=s,t.mainRenderPass=a,t.opaqueRender=o,t.sceneRender=c,t.transmissionRender=l,t.screenSpaceRendering=h}const tG=pT;var iG=Object.defineProperty,nG=Object.getOwnPropertyDescriptor,Un=(r,e,t,i)=>{for(var n=i>1?void 0:i?nG(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&iG(e,t,n),n};f.RootScene=class extends Qo{constructor(e,t){super(),this.isRootScene=!0,this.assetType="model",this._mainCamera=null,this.backgroundColor=null,this.background=null,this.backgroundIntensity=1,this.backgroundTonemap=!0,this._environment=null,this.environmentIntensity=1,this.textureSlots={},this.fixedEnvMapDirection=!1,this.autoDisposeSceneMaps=!0,this._dummyCam=new th(""),this._mainCameraUpdate=i=>{this._mainCamera?.parent||this.setDirty({refreshScene:!1}),this.dispatchEvent({...i,type:"mainCameraUpdate"}),this.dispatchEvent({...i,type:"activeCameraUpdate"}),i.source!=="RootScene"&&(i.key==="fov"&&this.dollyActiveCameraFov()||this.refreshActiveCameraNearFar(!i.projectionUpdated))},this._sceneBounds=new En,this._sceneBoundingRadius=0,this.refreshUi=qe.refreshUi.bind(this),this.traverseModels=qe.traverseModels.bind(this),this._v1=new S,this._v2=new S,this._autoNearFarDisabled=new Set,this.overrideRenderEnvironment=null,this._isMainRendering=!1,this.setDirty=this.setDirty.bind(this),this.name="RootScene",this.objectProcessor=t,qe.upgradeObject3D.call(this),this.objectProcessor?.processObject(this),this.addEventListener("materialUpdate",i=>this.dispatchEvent({...i,type:"sceneMaterialUpdate"})),this.addEventListener("objectUpdate",this.refreshScene),this.addEventListener("geometryUpdate",this.refreshScene),this.addEventListener("geometryChanged",this.refreshScene),this.environmentRotation?._onChange(()=>{this.setDirty({key:"environmentRotation",value:this.environmentRotation})}),this.backgroundRotation?._onChange(()=>{this.setDirty({key:"backgroundRotation",value:this.backgroundRotation})}),this.defaultCamera=e,this.modelRoot=new ft,this.modelRoot.userData.rootSceneModelRoot=!0,this.modelRoot.name="Scene",this.add(this.modelRoot),this.add(this.defaultCamera),this.mainCamera=this.defaultCamera,Object.defineProperty(this,"environment",{configurable:!0,enumerable:!0,get:()=>this._isMainRendering&&this.overrideRenderEnvironment!==null?this.overrideRenderEnvironment:this._environment,set:i=>{const n=this._environment;this._environment=i,this._onEnvironmentChange({key:"environment",value:i,oldValue:n,target:this})}})}get _backgroundColorUi(){return"#"+(this.backgroundColor?.getHexString()??"000000")}set _backgroundColorUi(e){this.setBackgroundColor(e)}toggleTransparentBackground(){this.backgroundColor?(this.background=null,this.backgroundColor=null):this.backgroundColor=new ee(16777215),this.refreshUi?.(),this.setDirty()}toggleEnvironmentBackground(){this.background==="environment"?this.background=null:this.background="environment"}get mainCamera(){return this._mainCamera||this._dummyCam}set mainCamera(e){const t=this.mainCamera;e||(e=this.defaultCamera),t!==e&&(t&&(t.deactivateMain(void 0,!0),t.removeEventListener("cameraUpdate",this._mainCameraUpdate)),e?(this._mainCamera=e,e.addEventListener("cameraUpdate",this._mainCameraUpdate),e.activateMain(void 0,!0),!e._canvas&&e!==this.defaultCamera&&console.warn("RootScene: mainCamera does not have a canvas set, some controls might not work properly.")):this._mainCamera=null,this.dispatchEvent({type:"activeCameraChange",lastCamera:t,camera:e}),this.dispatchEvent({type:"mainCameraChange",lastCamera:t,camera:e}),this.setDirty())}get renderCamera(){return this._renderCamera??this.mainCamera}set renderCamera(e){const t=this._renderCamera;this._renderCamera=e,this.dispatchEvent({type:"renderCameraChange",lastCamera:t,camera:e})}addObject(e,t){return(t?.clearSceneObjects||t?.disposeSceneObjects)&&this.clearSceneModels(t.disposeSceneObjects),e&&(e.isObject3D?(this._addObject3D(e,t),this.dispatchEvent({type:"addSceneObject",object:e,options:t}),e):(console.error("Invalid object, cannot add to scene.",e),e))}loadModelRoot(e,t){if((t?.clearSceneObjects||t?.disposeSceneObjects)&&this.clearSceneModels(t.disposeSceneObjects),e.userData?.rootSceneModelRoot||console.error("RootScene: Invalid model root scene object. Trying to add anyway.",e),e.userData&&(e.userData.__importData&&(this.modelRoot.userData.__importData={...this.modelRoot.userData.__importData,...e.userData.__importData}),e.userData.gltfAsset&&(this.modelRoot.userData.gltfAsset={...this.modelRoot.userData.gltfAsset,...e.userData.gltfAsset,extras:{...this.modelRoot.userData.gltfAsset?.extras,...e.userData.gltfAsset.extras}}),e.userData.gltfExtras&&(this.modelRoot.userData.gltfExtras={...this.modelRoot.userData.gltfExtras,...e.userData.gltfExtras})),e.userData?.gltfAsset?.copyright&&e.children.forEach(n=>!n.userData.license&&(n.userData.license=e.userData.gltfAsset?.copyright)),e.animations){this.modelRoot.animations||(this.modelRoot.animations=[]);for(const n of e.animations)this.modelRoot.animations.includes(n)||this.modelRoot.animations.push(n)}return e._loadingPromise&&(this.modelRoot._loadingPromise?this.modelRoot._loadingPromise=Promise.allSettled([this.modelRoot._loadingPromise,e._loadingPromise]):this.modelRoot._loadingPromise=e._loadingPromise),(e._childrenCopy||[...e.children]).map(n=>this.addObject(n,{...t,clearSceneObjects:!1,disposeSceneObjects:!1}))}_addObject3D(e,{addToRoot:t=!1,...i}={}){const n=e;if(!n||!n.isObject3D){console.error("RootScene: Invalid object, cannot add to scene.");return}const s=t?this:this.modelRoot;if(s.add(n),i.indexInParent!==void 0){const a=i.indexInParent,o=s.children.indexOf(n);a>=0&&o>=0&&a!==o&&a<s.children.length&&(s.children.splice(o,1),s.children.splice(a,0,n))}GM(n,i),this.setDirty({refreshScene:!0})}centerAllGeometries(e=!0,t){return Yv(t??this.modelRoot,e)}clearSceneModels(e=!1,t=!0){if(e)return this.disposeSceneModels(t);this.modelRoot.clear(),this.modelRoot.children=[],t&&this.setDirty({refreshScene:!0})}disposeSceneModels(e=!0,t=!0){if(t){for(const i of[...this.modelRoot.children])i.dispose?i.dispose():i.removeFromParent();this.modelRoot.clear(),e&&this.setDirty({refreshScene:!0})}else for(const i of this.modelRoot.children)i.dispose&&i.dispose(!1)}_onEnvironmentChange(e){e?.oldValue&&e.oldValue!==e.value&&this.autoDisposeSceneMaps&&typeof e.oldValue.dispose=="function"&&e.oldValue.dispose(),this.environment?.mapping===Kh&&(this.environment.mapping=$r,this.environment.needsUpdate=!0),this.dispatchEvent({type:"environmentChanged",oldTexture:e?.oldValue?.isTexture?e.oldValue:null,texture:this.environment?.isTexture?this.environment:null,environment:this.environment}),this.setDirty({refreshScene:!0,geometryChanged:!1}),this.refreshUi?.()}onBackgroundChange(e){e?.oldValue&&e.oldValue!==e.value&&this.autoDisposeSceneMaps&&typeof e.oldValue.dispose=="function"&&e.oldValue.dispose(),this.dispatchEvent({type:"backgroundChanged",oldTexture:e?.oldValue&&e.oldValue.isTexture?e.oldValue:null,texture:this.background?.isTexture?this.background:null,background:this.background,backgroundColor:this.backgroundColor}),this.setDirty({refreshScene:!0,geometryChanged:!1}),this.refreshUi?.()}add(...e){const t=e.filter(i=>i.parent!==this);return t.length&&super.add(...t),this}setBackgroundColor(e){const t=e||typeof e=="number"?new ee(e):null;(t&&this.backgroundColor&&!t.equals(this.backgroundColor)||(!t||!this.backgroundColor)&&t!==this.backgroundColor)&&(this.backgroundColor=t)}setDirty(e){return e?.sceneUpdate&&(console.warn("sceneUpdate is deprecated, use refreshScene instead."),e.refreshScene=!0),this.dispatchEvent({type:"update",bubbleToParent:!1,object:this}),qe.setDirty.call(this,{...e,scene:this}),this}refreshScene(e){const t=e&&e.type==="objectUpdate"&&(e.object===this||e.target===this);return e?.sceneUpdate===!1||e?.refreshScene===!1||e?.object?.isCamera?t?this:this.setDirty(e):(this.refreshActiveCameraNearFar(),this._sceneBounds=this.getBounds(!1,!0),this._sceneBoundingRadius=this._sceneBounds.getSize(new S).length()/2,this.dispatchEvent({...e,type:"sceneUpdate",hierarchyChanged:["addedToParent","removedFromParent"].includes(e?.change||"")}),t||qe.setDirty.call(this,{...e,scene:this}),this)}dispose(e=!0){this.disposeSceneModels(!1,e),e&&([...this.children].forEach(t=>t.dispose?t.dispose():t.removeFromParent()),this.clear()),this.disposeTextures(e)}disposeTextures(e=!0){this.environment?.dispose(),this.background?.isTexture&&this.background?.dispose?.(),e&&(this.environment=null,this.background=null)}getBounds(e=!1,t=!0,i=!0,n){return new En().expandByObject(this,e,t,s=>i&&(s.isWidget||s.assetType==="widget")?!0:n?.(s)??!1)}getModelBounds(e=!1,t=!0,i=!0,n){return this.modelRoot==null?new En:new En().expandByObject(this.modelRoot,e,t,s=>i&&s.assetType==="widget"?!0:n?.(s)??!1)}autoGPUInstanceMeshes(){const e=new Set;this.modelRoot.traverseModels(t=>{t.geometry&&e.add(t.geometry)},{visible:!1,widgets:!1}),e.forEach(t=>pv(t))}disableAutoNearFar(e="default"){const t=this._autoNearFarDisabled.size===0;this._autoNearFarDisabled.add(e);const i=this.mainCamera;if(t&&i.userData.autoNearFar!==!1){let n=i.near,s=i.far;n=i.userData.minNearPlane??ht.defaultMinNear,s=i.userData.maxFarPlane??ht.defaultMaxFar,ht.setNearFar(i,n,s,!0,"RootScene")}}enableAutoNearFar(e="default"){if(!this._autoNearFarDisabled.has(e))return;this._autoNearFarDisabled.delete(e);const t=this.mainCamera;this._autoNearFarDisabled.size===0&&t&&this.setDirty()}refreshActiveCameraNearFar(e=!0){const t=this.mainCamera;if(!t)return!1;let i=t.near,n=t.far;if(t.userData.minNearPlane!==void 0&&(i=t.userData.minNearPlane),t.userData.maxFarPlane!==void 0&&(n=t.userData.maxFarPlane),this._autoNearFarDisabled.size!==0||t.userData.autoNearFar===!1)return ht.setNearFar(t,i,n,e,"RootScene");const s=this.getBounds(!1),a=s.getSize(this._v2).length();if(a<.001)return ht.setNearFar(t,i,n,e,"RootScene");t.getWorldPosition(this._v1).sub(s.getCenter(this._v2));const o=1.5*Math.max(.25,a)/2,l=this._v1.length(),c=Math.max(.1,-this._v1.normalize().dot(t.getWorldDirection(new S)));return i=Math.max(Math.max(t.userData.minNearPlane??ht.defaultMinNear,.001),c*(l-o)),n=Math.min(Math.max(i+o,c*(l+o)),t.userData.maxFarPlane??ht.defaultMaxFar),(n<i||n-i<.1)&&(n=i+.1),ht.setNearFar(t,i,n,e,"RootScene")}dollyActiveCameraFov(){const e=this.mainCamera;if(!e||!e.userData.dollyFov)return!1;const t=this.getModelBounds(!1,!0,!0),i=Vm(e,t)*1.5,n=new S().subVectors(e.target,e.position).normalize();return e.position.copy(n.multiplyScalar(-i).add(e.target)),e.setDirty({change:"position",source:"RootScene"}),!0}updateShaderProperties(e){return e.uniforms.sceneBoundingRadius?e.uniforms.sceneBoundingRadius.value=this._sceneBoundingRadius:console.warn("RootScene: no uniform: sceneBoundingRadius"),this}toJSON(e){const t=We.Serialize(this,e,!0);return t.envMapIntensity=t.environmentIntensity,t}fromJSON(e,t){const i=e.environment;return i!==void 0&&(this.environment=We.Deserialize(i,this.environment,t,!1),delete e.environment,t?._configMetadata&&t._configMetadata.version<2&&this.environment?.rotation&&(this.environmentRotation.y=this.environment.rotation,this.environment.rotation=0)),e.environmentIntensity!==void 0&&e.envMapIntensity!==void 0&&(e={...e},delete e.envMapIntensity),We.Deserialize(e,this,t,!0),e.environment=i,this}addEventListener(e,t){e==="activeCameraChange"&&console.error("activeCameraChange is deprecated. Use mainCameraChange instead."),e==="activeCameraUpdate"&&console.error("activeCameraUpdate is deprecated. Use mainCameraUpdate instead."),e==="sceneMaterialUpdate"&&console.error("sceneMaterialUpdate is deprecated. Use materialUpdate instead."),e==="update"&&console.error("update is deprecated. Use sceneUpdate instead."),super.addEventListener(e,t)}findObjectsByName(e,t,i=!1){const n=[],s=o=>{o.name===e&&n.push(o)},a=t??this;return i&&a.traverseModels?a.traverseModels(s,{visible:!1,widgets:!0}):a.traverse(s),n}resetCamera(e=void 0,t=new S(1,1,1),i=new S(0,0,0)){if(this._mainCamera){this.matrixWorldNeedsUpdate=!0,this.updateMatrixWorld(!0);const n=e?new En().expandByObject(e,!0,!0):this.getBounds(!0),s=n.getCenter(new S),a=n.getSize(new S).length()*.5;s.add(i.clone().multiplyScalar(a)),this._mainCamera.position=new S(s.x+t.x*a,s.y+t.y*a,s.z+t.z*a),this._mainCamera.target=s,this.setDirty()}}get minNearDistance(){return console.error("minNearDistance is deprecated. Use camera.userData.minNearPlane instead"),this.mainCamera.userData.minNearPlane??.02}set minNearDistance(e){console.error("minNearDistance is deprecated. Use camera.userData.minNearPlane instead"),this.mainCamera&&(this.mainCamera.userData.minNearPlane=e)}get activeCamera(){return console.error("activeCamera is deprecated. Use mainCamera instead."),this.mainCamera}set activeCamera(e){console.error("activeCamera is deprecated. Use mainCamera instead."),this.mainCamera=e}get modelObject(){return this}addSceneObject(e,t){return this.addObject(e,t)}updateScene(e){return console.warn("updateScene is deprecated. Use refreshScene instead"),this.refreshScene(e||{})}removeSceneModels(){this.clearSceneModels()}get autoNearFarEnabled(){return this._autoNearFarDisabled.size===0}set autoNearFarEnabled(e){e?this.enableAutoNearFar("default"):this.disableAutoNearFar("default")}get envMapIntensity(){return console.warn("RootScene.envMapIntensity is deprecated, use environmentIntensity instead."),this.environmentIntensity}set envMapIntensity(e){console.warn("RootScene.envMapIntensity is deprecated, use environmentIntensity instead."),this.environmentIntensity=e}},Un([G(),Zt(f.RootScene.prototype.onBackgroundChange)],f.RootScene.prototype,"backgroundColor",2),Un([xn("Background Color",r=>({hidden:()=>r.backgroundColor===null||r.backgroundColor===void 0||r.background==="environment"}))],f.RootScene.prototype,"_backgroundColorUi",1),Un([rt(f.RootScene.prototype.onBackgroundChange),G(),Dr("Background Image",r=>({hidden:()=>r.backgroundColor===null||r.backgroundColor===void 0||r.background==="environment"}))],f.RootScene.prototype,"background",2),Un([ct(void 0,r=>({label:()=>r.backgroundColor?"Set Transparent BG":"Set Color Background",tags:["context-menu"]}))],f.RootScene.prototype,"toggleTransparentBackground",1),Un([ct(void 0,r=>({label:()=>r.background==="environment"?"Remove Env Background":"Set Env Background",disabled:()=>!r.environment,tags:["context-menu"]}))],f.RootScene.prototype,"toggleEnvironmentBackground",1),Un([G(),rt(f.RootScene.prototype.setDirty),Fe("Background Intensity",[0,10],.01)],f.RootScene.prototype,"backgroundIntensity",2),Un([se("Background Tonemap"),rt(f.RootScene.prototype.setDirty),G()],f.RootScene.prototype,"backgroundTonemap",2),Un([Dr("Environment"),G()],f.RootScene.prototype,"environment",2),Un([Fe("Environment Intensity",[0,10],.01),G(),rt(f.RootScene.prototype.setDirty)],f.RootScene.prototype,"environmentIntensity",2),Un([G(),yi("Environment Rotation",void 0,void 0,r=>({disabled:()=>r.fixedEnvMapDirection||!r.environment}))],f.RootScene.prototype,"environmentRotation",2),Un([G(),yi("Background Rotation",void 0,void 0,r=>({hidden:()=>!r.background||r.background==="environment"||!r.background.isTexture||r.background.mapping!==$r}))],f.RootScene.prototype,"backgroundRotation",2),Un([G()],f.RootScene.prototype,"textureSlots",2),Un([se("Fixed Env Direction"),G(),rt(f.RootScene.prototype.setDirty)],f.RootScene.prototype,"fixedEnvMapDirection",2),Un([Bi(),G()],f.RootScene.prototype,"defaultCamera",2),Un([ct("Center All Geometries",{sendArgs:!1,tags:["context-menu"]})],f.RootScene.prototype,"centerAllGeometries",1),Un([ct("Auto GPU Instance Meshes",{tags:["context-menu"]})],f.RootScene.prototype,"autoGPUInstanceMeshes",1),f.RootScene=Un([vt("Root Scene")],f.RootScene);class Id{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const sG=new Mr(-1,1,1,-1,0,1);class rG extends Je{constructor(){super(),this.setAttribute("position",new Ee([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Ee([0,2,0,0,2,0],2))}}const aG=new rG;class e0{constructor(e){this._mesh=new _e(aG,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,sG)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class t0 extends Id{constructor(e,t,i=null,n=null,s=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=i,this.clearColor=n,this.clearAlpha=s,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this._oldClearColor=new ee}render(e,t,i,n,s,a){if(!this.scene||!this.camera)return;const o=e.autoClear;e.autoClear=!1;let l,c;if(this.overrideMaterial!==null&&(c=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),this.clearColor!==null&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),this.clearAlpha!==null&&(l=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),this.clearDepth==!0&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:i),a){const h=e.getContext();h.framebufferRenderbuffer(h.FRAMEBUFFER,h.DEPTH_ATTACHMENT,h.RENDERBUFFER,a)}if(this.clear===!0&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),a){const h=e.getContext();h.framebufferRenderbuffer(h.FRAMEBUFFER,h.DEPTH_ATTACHMENT,h.RENDERBUFFER,null)}this.clearColor!==null&&e.setClearColor(this._oldClearColor),this.clearAlpha!==null&&e.setClearAlpha(l),this.overrideMaterial!==null&&(this.scene.overrideMaterial=c),e.autoClear=o}}const Cl={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,fragmentShader:`

		uniform float opacity;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 texel = texture2D( tDiffuse, vUv );
			gl_FragColor = opacity * texel;


		}`};class i0 extends Id{constructor(e,t){super(),this.textureID=t!==void 0?t:"tDiffuse",e instanceof nn?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=ko.clone(e.uniforms),this.material=new nn({name:e.name!==void 0?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this.fsQuad=new e0(this.material),this.useExistingRenderTarget=!1}render(e,t,i){this.uniforms[this.textureID]&&i&&(this.uniforms[this.textureID].value=i.texture),this.fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this.fsQuad.render(e)):(this.useExistingRenderTarget||e.setRenderTarget(t||null),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this.fsQuad.render(e))}dispose(){this.material.dispose(),this.fsQuad.dispose()}}var oG=Object.defineProperty,lG=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&oG(e,t,n),n};const n0=(kl=class extends i0{constructor(e,...t){super(e.isMaterial?e:new oT(e,t),t.length<1?kl.DEFAULT_TEX_ID:t[0]),this.overrideReadBuffer=null,this.isExtendedShaderPass=!0,this.enabled=!0,this.onDirty=[],this.setDirty=this.setDirty.bind(this)}render(e,t,i,n,s){this.enabled&&e.renderWithModes({backgroundRender:!1},()=>{super.render(e,t||null,this.overrideReadBuffer||i,n,s)})}updateShaderProperties(e){e&&(Array.isArray(e)||(e=[e]),e.forEach(t=>t?.updateShaderProperties(this.material)))}dispose(){this.material?.dispose?.(),this.fsQuad?.dispose?.(),this.onDirty=[]}setDirty(){this.material&&(this.material.needsUpdate=!0),this.onDirty?.forEach(e=>e())}get isShaderPass2(){return console.error("isShaderPass2 is deprecated, use isExtendedShaderPass instead"),!0}},kl.DEFAULT_TEX_ID="tDiffuse",kl);lG([se("Enabled"),G(),Zt(n0.prototype.setDirty)],n0.prototype,"enabled");let nh=n0;class mT extends nh{constructor(e,t="c = a + b;",i="",n,s=120){super({vertexShader:Cl.vertexShader,fragmentShader:`
                varying vec2 vUv;
                ${i}
                void main() {
                    vec4 a = tDiffuseTexelToLinear ( texture2D( tDiffuse, vUv ) );
                    vec4 b = tDiffuse2TexelToLinear ( texture2D( tDiffuse2, vUv ) );
                    vec4 c = vec4(0);
                    ${t}
                    c = clamp(c, vec4(0), vec4(MAX_INTENSITY));
                    gl_FragColor = c;
                    #include <colorspace_fragment>
                }
            `,uniforms:{tDiffuse:{value:null},tDiffuse2:{value:n},...e},defines:{MAX_INTENSITY:s}},"tDiffuse","tDiffuse2"),this.clear=!1,this.needsSwap=!0}}var cG=Object.defineProperty,hG=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&cG(e,t,n),n};class s0 extends t0{constructor(e,t,i=new ee(0,0,0),n=0){super(void 0,void 0,t,i,n),this.isExtendedRenderPass=!0,this.enabled=!0,this.passId="render",this._doTransmissionFix=!0,this.blurTransmissionTarget=!0,this.preserveTransparentTarget=!1,this.preserveOpaqueTarget=!1,this.renderBackground=!0,this.onDirty=[],this.uiConfig={label:"Render Pass",type:"folder",children:bi(this)},this.renderManager=e,this._blendPass=new mT({},"c = vec4(a.rgb * (1. - b.a) + b.rgb * b.a, 1.);","",void 0,e.maxHDRIntensity),this.setDirty=this.setDirty.bind(this)}get transparentTarget(){if(!this._transparentTarget){const e=this.renderManager.msaa;this._transparentTarget=this.renderManager.getTempTarget({sizeMultiplier:1,samples:e?typeof e!="number"?f.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:e:0,stencilBuffer:this.renderManager.composerTarget.stencilBuffer,colorSpace:ai,type:this.renderManager.renderer.extensions.has("EXT_color_buffer_half_float")?Yt:Qt,format:qt,minFilter:at,magFilter:at,depthBuffer:!1})}return this._transparentTarget}_releaseTransparentTarget(){this._transparentTarget&&this.renderManager.releaseTempTarget(this._transparentTarget),this._transparentTarget=void 0}get opaqueTarget(){if(!this._opaqueTarget){const e=this.renderManager.composerTarget,t=this.renderManager.msaa;this._opaqueTarget=this.renderManager.getTempTarget({sizeMultiplier:1,samples:t?typeof t!="number"?f.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:t:0,stencilBuffer:this.renderManager.composerTarget.stencilBuffer,colorSpace:e.texture.colorSpace,type:this.renderManager.rgbm?Qt:Yt,format:e.texture.format,minFilter:e.texture.minFilter,magFilter:e.texture.magFilter,depthBuffer:e.depthBuffer,generateMipmaps:e.texture.generateMipmaps})}return this._opaqueTarget}_releaseOpaqueTarget(){this._opaqueTarget&&this.renderManager.releaseTempTarget(this._opaqueTarget),this._opaqueTarget=void 0}render(e,t,i,n,s){if(!this.enabled)return;let a=!1;if(e.userData.mainRenderPass=!0,!this._doTransmissionFix&&!this.renderManager.rgbm){super.render(e,t||null,i,n,s),this.needsSwap=a,e.userData.mainRenderPass=void 0;return}const o=e.userData;o||console.error("threejs is not patched. Use three-modded (npm install three@npm:three-modded) for this functionality.");const l=(this.renderManager.zPrepass||!this.renderManager.depthBuffer)&&this.renderManager.gbufferTarget;let c;if(l){const d=this.renderManager.gbufferTarget;if(d){const p=e.properties.get(d);c=p.__webglDepthRenderbuffer||p.__webglDepthbuffer}c||console.warn("No depth/gbuffer present for zPrepass.")}const h=i;i=this.renderManager.msaa?this.opaqueTarget:i;let u=()=>{super.render(e,null,i,n,s,c)};if(this.renderManager.rgbm){if(this.renderManager.rgbm){a=!1;const d=this.renderToScreen;if(d&&!t&&console.error("ExtendedRenderPass: renderToScreen is true but writeBuffer is not set, which is required for rgbm"),this.renderToScreen=!1,e.info&&!e.info.autoReset)throw"renderer.info.autoReset must be true";{const p=e.autoClearDepth;e.autoClearDepth=!l,e.renderWithModes({shadowMapRender:!0,backgroundRender:this.renderBackground,opaqueRender:!0,transparentRender:!1,transmissionRender:!1},u),e.autoClearDepth=p}if(!l&&i){const p=e.properties.get(i);c=p.__webglDepthRenderbuffer||p.__webglDepthbuffer}u=()=>{super.render(e,null,this.transparentTarget,n,s,c)};{const p=this.clear,m=e.autoClearDepth;e.autoClearDepth=!1,this.clear=!0,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!1,transparentRender:!0,transmissionRender:!1},u),this.clear=p,e.autoClearDepth=m}(!e.info||e.info.render.calls>0)&&(this._blendPass.uniforms.tDiffuse2.value=this.transparentTarget.texture,this._blendPass.render(e,t,i,n,s),a=!0);{const p=this.clear;this.clear=!1,o.transmissionRenderTarget=a?t:i,o.blurTransmissionTarget=this.blurTransmissionTarget&&o.transmissionRenderTarget.samples===0,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!1,transparentRender:!1,transmissionRender:!0},u),o.blurTransmissionTarget=void 0,o.transmissionRenderTarget=void 0,this.clear=p}if((!e.info||e.info.render.calls>0)&&(this._blendPass.uniforms.tDiffuse2.value=this.transparentTarget.texture,this._blendPass.render(e,t,i,n,s),a=!0),d){this.renderToScreen=!0;const p=a?t?.texture:i?.texture,m=Array.isArray(p)?p[0]:p;m&&this.renderManager.blit(void 0,{source:m,respectColorSpace:!0})}}}else{{const d=this.clear,p=e.autoClearDepth;e.autoClearDepth=!l,this.clear=!0,e.renderWithModes({shadowMapRender:!0,backgroundRender:this.renderBackground,opaqueRender:!0,transparentRender:!0,transmissionRender:!1},u),this.clear=d,e.autoClearDepth=p}{const d=i?i.texture:void 0;this.renderManager.blit(t,{clear:!0,source:d});const p=this.clear;this.clear=!1,o.transmissionRenderTarget=t,o.blurTransmissionTarget=this.blurTransmissionTarget&&o.transmissionRenderTarget.samples===0,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!1,transparentRender:!1,transmissionRender:!0},u),o.blurTransmissionTarget=void 0,o.transmissionRenderTarget=void 0,this.clear=p}a=!1}if(!a&&h!==i&&i){const d=Array.isArray(i.texture)?i.texture[0]:i.texture;d&&this.renderManager.blit(h,{source:d,clear:!0}),i=h}this.preserveTransparentTarget||this._releaseTransparentTarget(),this.preserveOpaqueTarget||this._releaseOpaqueTarget(),this.needsSwap=a,e.userData.mainRenderPass=void 0}dispose(){this._releaseTransparentTarget(),this.onDirty=[],this.scene=void 0,this.camera=void 0,super.dispose?.()}setDirty(){this.onDirty.forEach(e=>e())}beforeRender(e,t,i){this.scene=e,this.camera=t}get isRenderPass2(){return console.error("isRenderPass2 is deprecated, use isExtendedRenderPass instead"),!0}}hG([se("Enabled"),G()],s0.prototype,"enabled");class r0 extends nh{constructor(e,t=!0){super({uniforms:ko.clone(Cl.uniforms),vertexShader:Cl.vertexShader,fragmentShader:ma`
                uniform float opacity;
                #include <alphatest_pars_fragment>
                varying vec2 vUv;
                void main() {
                    ${t?"vec4 diffuseColor = tDiffuseTexelToLinear(texture2D(tDiffuse, vUv)) * opacity;":"vec4 diffuseColor = texture2D(tDiffuse, vUv) * opacity;"}
                    #include <alphatest_fragment>
                    ${e?tt(e,"diffuseColor"):""}
                    #ifdef OPAQUE
                    diffuseColor.a = 1.0;
                    #endif
                    gl_FragColor = diffuseColor;
                    ${t?"#include <colorspace_fragment>":""}
                }
            `},"tDiffuse")}}var uG=Object.defineProperty,dG=Object.getOwnPropertyDescriptor,gT=(r,e,t,i)=>{for(var n=i>1?void 0:i?dG(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&uG(e,t,n),n};f.GBufferRenderPass=class extends t0{constructor(e,t,i,n=new ee(1,1,1),s=1){super(void 0,void 0,i,n,s),this.passId=e,this.target=t,this.isGBufferRenderPass=!0,this.enabled=!0,this._transparentMats=new Set,this._transmissiveMats=new Set,this.preprocessMaterial=(a,o)=>{o=o??a.userData.renderToGBuffer,a.userData.pluginsDisabled&&(o=!1),(a.transparent&&(o||a.opacity>.99&&!a.map&&!a.alphaMap)||!a.transparent&&!a.transmission&&o===!1)&&(this._transparentMats.add(a),a.transparent=!a.transparent),a.transmission&&Math.abs(a.transmission||0)>0&&o&&(this._transmissiveMats.add([a,a.transmission]),a.transmission=0)},this.preprocessObject=a=>{if(a.customDepthMaterial){const o=a.customDepthMaterial;o.allowOverride=!1;const l=a.material;a.forcedOverrideMaterial=o;const c=Array.isArray(l)?l[0]:l;return c&&(o.userData.renderToGBuffer=c.userData.renderToGBuffer,o.userData.renderToDepth=c.userData.renderToDepth,o.userData.pluginsDisabled=c.userData.pluginsDisabled,o.side=c.side),o}return a.material},this.postprocessObject=a=>{a.customDepthMaterial&&delete a.forcedOverrideMaterial}}render(e,t,i,n,s){if(!this.scene||!this.camera)return;const a=e.getRenderTarget(),o=e.getActiveCubeFace(),l=e.getActiveMipmapLevel(),c=new Set;this.scene.traverse(h=>{if(!h.visible)return;c.add(h);const u=this.preprocessObject(h);u&&(Array.isArray(u)?u.forEach(d=>this.preprocessMaterial(d)):this.preprocessMaterial(u))}),e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!0,transparentRender:!1,transmissionRender:!1,mainRenderPass:!1},()=>super.render(e,null,tt(this.target),n,s)),this._transparentMats.forEach(h=>h.transparent=!h.transparent),this._transparentMats.clear(),this._transmissiveMats.forEach(([h,u])=>h.transmission=u),this._transmissiveMats.clear(),e.setRenderTarget(a,o,l),c.forEach(h=>this.postprocessObject(h))}beforeRender(e,t,i){this.scene=e,this.camera=t}},gT([se("Enabled")],f.GBufferRenderPass.prototype,"enabled",2),f.GBufferRenderPass=gT([vt(r=>r.passId+" Render Pass")],f.GBufferRenderPass);const fG=`#include <packing>
varying vec2 vUv;
#include <alphatest_pars_fragment>
void main(){vec4 diffuseColor=tDiffuseTexelToLinear(texture2D(tDiffuse,vUv));
#ifdef HAS_TRANSPARENT_TARGET
vec4 transparentColor=tTransparentTexelToLinear(texture2D(tTransparent,vUv));
#else
vec4 transparentColor=vec4(0.0);
#endif
#ifdef HAS_GBUFFER
float depth=getDepth(vUv);bool isBackground=depth>0.99&&transparentColor.a<0.001;
#endif
#glMarker
#ifdef HAS_GBUFFER
#if (defined(CLIP_BACKGROUND) && CLIP_BACKGROUND > 0) || defined(CLIP_BACKGROUND_FORCE)
if(isBackground)diffuseColor.a=0.0;if(depth>0.99&&transparentColor.a>=0.001)diffuseColor.a=transparentColor.a;
#endif
if(depth<0.00001)diffuseColor.a=0.0;
#endif
#include <alphatest_fragment>
#ifdef OPAQUE
diffuseColor.a=1.0;
#endif
gl_FragColor=diffuseColor;
#include <colorspace_fragment>
}`;var pG=Object.defineProperty,mG=Object.getOwnPropertyDescriptor,ug=(r,e,t,i)=>{for(var n=i>1?void 0:i?mG(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&pG(e,t,n),n};f.ScreenPass=class extends nh{constructor(e="",...t){super(e?.fragmentShader||e?.isShaderMaterial?e:gG(e),...t.length?t:["tDiffuse","tTransparent"]),this.passId="screen",this.after=["render"],this.required=["render"],this.outputColorSpace=Ct,this._needsReRender=!1,this.clipBackgroundForce=!1,this.clipBackground=!1,this.material.addEventListener("materialUpdate",this.setDirty)}render(e,t,i,n,s){const a=e.outputColorSpace;(!t||this.renderToScreen)&&(e.outputColorSpace=this.outputColorSpace),super.render(e,t,i,n,s),this._lastReadBuffer=i,e.outputColorSpace=a,this._needsReRender=!1}reRender(e,t,i,n){this._lastReadBuffer&&this.render(e,t,this._lastReadBuffer,i,n)}onPostFrame(e){this._needsReRender&&(this._needsReRender=!1,this.reRender(e.renderer),this.clipBackground&&!e.gbufferTarget&&console.warn("ScreenPass: clipBackground set to true but no gbufferTarget set. Try adding GBufferPlugin."))}dispose(){this._lastReadBuffer=void 0,super.dispose()}beforeRender(e,t,i){this.material.uniforms.tTransparent&&(this.material.uniforms.tTransparent.value=i.renderPass.preserveTransparentTarget&&i.renderPass.transparentTarget?.texture||null,this.material.defines.HAS_TRANSPARENT_TARGET=this.material.uniforms.tTransparent.value?1:void 0,this.material.defines.HAS_TRANSPARENT_TARGET||delete this.material.defines.HAS_TRANSPARENT_TARGET)}setDirty(){super.setDirty(),this._needsReRender=!0}},ug([Li("Output Color Space",dv.ColorSpace.uiConfig,r=>({onChange:r.setDirty}))],f.ScreenPass.prototype,"outputColorSpace",2),ug([Im("CLIP_BACKGROUND_FORCE",void 0,void 0,f.ScreenPass.prototype.setDirty,!0)],f.ScreenPass.prototype,"clipBackgroundForce",2),ug([Im("CLIP_BACKGROUND",void 0,void 0,f.ScreenPass.prototype.setDirty),se()],f.ScreenPass.prototype,"clipBackground",2),f.ScreenPass=ug([vt("Screen Pass")],f.ScreenPass);function gG(r){const e=bt(fG,"void main()",(Array.isArray(r)?r[0]:r?.pars||"")+`
`,{prepend:!0}),t=e.includes("#glMarker")?bt(e,"#glMarker",(Array.isArray(r)?r[1]:typeof r=="string"?r:r?.main||"")+`
`,{prepend:!0}):e;return{...Cl,fragmentShader:t,uniforms:{tDiffuse:{value:null},tTransparent:{value:null}},transparent:!0,blending:gn,side:us}}function AT(r){const e=[],t={};for(const i of r)i.passId&&(t[i.passId]={after:i.after??[],before:i.before??[],dependencies:new Set(i.required??[])});for(const[i,n]of Object.entries(t)){const s=new Set([...n.after,...n.before]);n.dependencies.forEach(a=>s.has(a)&&s.delete(a)),s.forEach(a=>{const o=t[a];if(o){if(o.dependencies.has(i))throw console.error("cyclic",i,a),"Encountered cyclic dependency when sorting passes";n.dependencies.add(a)}})}for(;;){let i=!1;const n=[...Object.entries(t)];for(const[s,a]of n)if(!e.includes(s)&&CS(e,a.dependencies.values())){const o=Math.max(-1,...a.after.map(c=>e.indexOf(c))),l=Math.min(e.length,...a.before.map(c=>{const h=e.indexOf(c);return h<0?e.length:h}));if(o>=l)throw console.error(a,r,e,o,l),"Unknown error when sorting passes";e.splice(a.after.length>0?o+1:l,0,s),i=!0,delete t[s]}if(Object.keys(t).length<1)break;if(!i)throw console.error(n,t,e),"Required pass dependency removed unexpectedly"}return e}class yT extends Id{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,i){const n=e.getContext(),s=e.state;s.buffers.color.setMask(!1),s.buffers.depth.setMask(!1),s.buffers.color.setLocked(!0),s.buffers.depth.setLocked(!0);let a,o;this.inverse?(a=0,o=1):(a=1,o=0),s.buffers.stencil.setTest(!0),s.buffers.stencil.setOp(n.REPLACE,n.REPLACE,n.REPLACE),s.buffers.stencil.setFunc(n.ALWAYS,a,4294967295),s.buffers.stencil.setClear(o),s.buffers.stencil.setLocked(!0),e.setRenderTarget(i),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),s.buffers.color.setLocked(!1),s.buffers.depth.setLocked(!1),s.buffers.color.setMask(!0),s.buffers.depth.setMask(!0),s.buffers.stencil.setLocked(!1),s.buffers.stencil.setFunc(n.EQUAL,1,4294967295),s.buffers.stencil.setOp(n.KEEP,n.KEEP,n.KEEP),s.buffers.stencil.setLocked(!0)}}class AG extends Id{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class _T{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){const i=e.getSize(new K);this._width=i.width,this._height=i.height,t=new ds(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Yt}),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 i0(Cl),this.copyPass.material.blending=gn,this.clock=new ku}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);t!==-1&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){e===void 0&&(e=this.clock.getDelta());const t=this.renderer.getRenderTarget();let i=!1;for(let n=0,s=this.passes.length;n<s;n++){const a=this.passes[n];if(a.enabled!==!1){if(a.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(n),a.render(this.renderer,this.writeBuffer,this.readBuffer,e,i),a.needsSwap){if(i){const o=this.renderer.getContext(),l=this.renderer.state.buffers.stencil;l.setFunc(o.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),l.setFunc(o.EQUAL,1,4294967295)}this.swapBuffers()}yT!==void 0&&(a instanceof yT?i=!0:a instanceof AG&&(i=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(e===void 0){const t=this.renderer.getSize(new K);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,e=this.renderTarget1.clone(),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=e,this.renderTarget2=e.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const i=this._width*this._pixelRatio,n=this._height*this._pixelRatio;this.renderTarget1.setSize(i,n),this.renderTarget2.setSize(i,n);for(let s=0;s<this.passes.length;s++)this.passes[s].setSize(i,n)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class vT extends _T{constructor(e,t){super(e,t),this.copyPass2=new r0}setPixelRatio(e,t=!0){const i=this.setSize;t||(this.setSize=()=>{}),super.setPixelRatio(e),t||(this.setSize=i)}}function bT(r={}){return[r.sizeMultiplier,r.samples,r.colorSpace,r.type,r.format,r.depthBuffer,r.depthTexture,r.textureCount,r.size?.width,r.size?.height].join(";")}class wT extends xi{constructor(){super(),this._trackedTargets=[],this._trackedTempTargets=[],this._releasedTempTargets={},this.maxTempPerKey=5,this._processNewTarget=this._processNewTarget.bind(this),this._processNewTempTarget=this._processNewTempTarget.bind(this),this.trackTarget=this.trackTarget.bind(this),this.disposeTarget=this.disposeTarget.bind(this),this.createTarget=this.createTarget.bind(this),this.createTargetCustom=this.createTargetCustom.bind(this)}trackTarget(e){this._trackedTargets.push(e)}removeTrackedTarget(e){const t=this._trackedTargets.indexOf(e);t>=0&&this._trackedTargets.splice(t,1)}createTarget({sizeMultiplier:e=void 0,samples:t=0,colorSpace:i=ai,type:n=Qt,format:s=qt,stencilBuffer:a=!1,depthBuffer:o=!0,depthTexture:l=!1,depthTextureType:c=tr,depthTextureFormat:h=Do,size:u=void 0,textureCount:d=1,...p}={},m=!0){this.isWebGL2||(t=0),e!==void 0&&u!==void 0&&console.error("Both sizeMultiplier and size are defined. sizeMultiplier will be ignored."),u=u||this.renderSize.clone().multiplyScalar(this.renderScale*(e=e||1)),u.width=Math.floor(u.width),u.height=Math.floor(u.height);const A=l?new ap(u.width,u.height,c):null;A&&(A.format=h);const g=this.createTargetCustom(u,{samples:t,colorSpace:i,type:n,format:s,depthBuffer:o,count:d,depthTexture:A,stencilBuffer:a});return this._processNewTarget(g,e,m),this._setTargetOptions(g,p),g}disposeTarget(e,t=!0){if(e){if(e.isTemporary)return this.releaseTempTarget(e);t&&this.removeTrackedTarget(e),e.dispose(!1)}}getTempTarget(e={}){const t=bT(e);let i;return this._releasedTempTargets[t]?.length&&(i=this._releasedTempTargets[t].pop()),i?this._setTargetOptions(i,e):(i=this.createTarget(e),this._processNewTempTarget(i,t)),i}releaseTempTarget(e){const t=e.targetKey;if(!t||!e.isTemporary)throw"Not a temp target";this._releasedTempTargets[t].length>this.maxTempPerKey?(this.removeTrackedTarget(e),e.dispose()):this._releasedTempTargets[t].push(e)}createTargetCustom({width:e,height:t},i={},n){let s=[e,t];if(n?.prototype===Py.prototype){if(e!==t)throw"Width and height of cube render target must be equal";s=[e]}return this._createTargetClass(n??ds,s,{format:qt,minFilter:at,magFilter:at,generateMipmaps:!1,type:Qt,colorSpace:ai,...i})}dispose(e=!0){this._trackedTargets.forEach(t=>t.dispose()),Object.values(this._trackedTempTargets).forEach(t=>t.dispose()),e&&(this._trackedTargets=[],this._releasedTempTargets={},this._trackedTempTargets=[])}resizeTrackedTargets(){for(const e of this._trackedTargets)this.resizeTrackedTarget(e)}resizeTrackedTarget(e){const t=e.sizeMultiplier;if(t){const i=this.renderSize.clone().multiplyScalar(this.renderScale*t);e.setSize(Math.floor(i.width),Math.floor(i.height))}}_processNewTempTarget(e,t){return e.isTemporary=!0,e.targetKey=t,this._releasedTempTargets[t]===void 0&&(this._releasedTempTargets[t]=[]),this._trackedTempTargets.push(e),e}_setTargetOptions(e,t){const i=e.texture;for(const n of Array.isArray(i)?i:[i])this._setTargetTextureOptions(n,t)}_setTargetTextureOptions(e,t){e.minFilter=t.minFilter??at,e.magFilter=t.magFilter??at,e.wrapS=t.wrapS??di,e.wrapT=t.wrapT??di,e.generateMipmaps=t.generateMipmaps??!1,e.generateMipmaps&&e.minFilter===at&&(e.minFilter=Tw),!e.generateMipmaps&&e.minFilter===Tw&&(e.minFilter=at)}_processNewTarget(e,t,i){return t!==void 0&&(e.sizeMultiplier=t),i&&this.trackTarget(e),e}}class qi{constructor(e,t,i,n,s){this.extensions=[],this.cls=e,this.ext=t,this.mime=i.filter(Boolean).map(a=>a.toLowerCase()),this.root=n,this.onCtor=s}ctor(e){const t=this.cls&&new this.cls(e.loadingManager);return typeof this.onCtor=="function"?this.onCtor(t,e,this):t}}const Hr=class Hr extends xi{constructor(e=!1,{simpleCache:t=!1,storage:i}={}){super(),this._logger=console.log,this._loaderCache=[],this._fileDatabase=new Map,this._cachedAssets=[],this.cacheImportedAssets=!0,this.importers=[new qi(ti,["txt"],["text/plain"],!1)],this.autoSetName=!0,this._urlModifiers=[],e||(this._logger=()=>{}),this._onLoad=this._onLoad.bind(this),this._onProgress=this._onProgress.bind(this),this._onError=this._onError.bind(this),this._onStart=this._onStart.bind(this),this._urlModifier=this._urlModifier.bind(this),this._loadingManager=new Yp(this._onLoad,this._onProgress,this._onError),this._loadingManager.onStart=this._onStart;const n=this._loadingManager.itemStart;this._loadingManager.itemStart=l=>{this.dispatchEvent({type:"importFile",path:l,state:"downloading",progress:0}),n.call(this._loadingManager,l)};let s=[];const a=this._loadingManager.itemEnd;this._loadingManager.itemEnd=l=>{if(s.includes(l)){s=s.filter(c=>c!==l),a.call(this._loadingManager,l);return}this.dispatchEvent({type:"importFile",path:l,state:"downloading",progress:1}),a.call(this._loadingManager,l),this.dispatchEvent({type:"importFile",path:l,state:"done"})};const o=this._loadingManager.itemError;this._loadingManager.itemError=l=>{s.push(l),this.dispatchEvent({type:"importFile",path:l,state:"error"}),o.call(this._loadingManager,l)},this._loadingManager.setURLModifier(this._urlModifier),this._initCacheStorage(t,i??!0)}get storage(){return this._storage}get loadingManager(){return this._loadingManager}get cachedAssets(){return this._cachedAssets}addImporter(...e){for(const t of e){if(this.importers.includes(t)){console.warn("AssetImporter: Importer already added",t);return}this.importers.push(t)}}removeImporter(...e){for(const t of e){const i=this.importers.indexOf(t);i>=0&&this.importers.splice(i,1),this._loaderCache=this._loaderCache.filter(n=>n.importer!==t?!0:(this._disposeLoader(n),!1))}}async import(e,t,i,n){return e?Array.isArray(e)?(await Promise.all(e.map(async s=>this.import(s,t,i,n)))).flat(1):e instanceof File?await this.importFile(e,t,i):typeof e=="object"?await this.importAsset(e,t,i,n):typeof e=="string"?await this.importPath(e,t,i):(console.error("AssetImporter: Invalid asset or path",e),[]):[]}async importSingle(e,t,i,n){return(await this.import(e,t,i,n))?.[0]}async importPath(e,t={},i){const n=this._serializeOptions(t),s=this._cachedAssets.find(o=>o.path===e&&o._options===n);let a;return s?a=s:a={path:e},a._options=n,t.importedFile&&(a.file=t.importedFile),await this.importAsset(a,t,i,!1)}_serializeOptions(e){const{pathOverride:t,forceImport:i,reimportDisposed:n,fileHandler:s,importedFile:a,...o}=e;return JSON.stringify(o)}async importAsset(e,t={},i,n){if(!e)return[];if(!e.path&&!e.file&&!t.pathOverride)return[e];if(t.cacheAsset!==!1&&this.cacheImportedAssets&&!this._cachedAssets.includes(e)){if(Object.entries(e).length===1&&e.path){const l=this._cachedAssets.find(c=>c.path===e.path);l&&Object.assign(e,l)}const o=this._cachedAssets.findIndex(l=>l.path===e.path);o>=0&&this._cachedAssets.splice(o,1),this._cachedAssets.push(e)}let s=e?.preImported;!s&&e?.preImportedRaw&&(s=await e.preImportedRaw);const a=t.pathOverride||e.path;if(!t.forceImport&&s)return await this.processRaw(s,t,a);if(n===void 0&&(n=typeof e.file?.arrayBuffer=="function"),e.preImportedRaw=this._loadFile(a,typeof e.file?.arrayBuffer=="function"?e.file:void 0,t,i,n),s=await e.preImportedRaw,this.cacheImportedAssets||(e.preImportedRaw=void 0),s&&(s=await this.processRaw(s,t,a)),s){t.processRaw!==!1&&this.cacheImportedAssets&&(e.preImported=s);const o=[],l=c=>{c.userData?.rootSceneModelRoot?o.push(...c.children):o.push(c)};Array.isArray(s)?s.map(l):l(s),o.forEach(c=>c?.addEventListener&&c.addEventListener("dispose",()=>{e?.preImportedRaw&&(e.preImportedRaw=void 0),e?.preImported&&(e.preImported=void 0)}))}return s}async importFile(e,t={},i){return e?e instanceof File?this.importAsset(this._cachedAssets.find(n=>n.file===e)??{path:t.pathOverride||e.name||e.webkitRelativePath,file:e},t,i,!0):(console.error("AssetImporter: Invalid file",e),[]):[]}async importFiles(e,t={}){const i=new Map;let{allowedExtensions:n}=t;if(n&&n.length<1&&(n=void 0),e.size===0)return i;this.dispatchEvent({type:"importFiles",files:e,state:"start"});const s=[],a=[];if(e.forEach((o,l)=>{this.registerFile(l,o);const c=o.ext,h=o.mime;(c||h)&&(n?.includes((c||h||"").toLowerCase())??!0)&&(this._isRootFile(c)?s.push(l):a.push(l))}),s.length>0)for(const o of s){let l=await this._loadFile(o,void 0,t,void 0,!0);l&&(l=await this.processRaw(l,t,o)),i.set(o,l)}else for(const o of a){let l=await this._loadFile(o,void 0,t,void 0,!0);l&&(l=await this.processRaw(l,t,o)),i.set(o,l)}return this.dispatchEvent({type:"importFiles",files:e,state:"end"}),e.forEach((o,l)=>this.unregisterFile(l)),i}async _loadFile(e,t,i={},n,s=!1){this._cacheStoreInitPromise&&await this._cacheStoreInitPromise,this.dispatchEvent({type:"importFile",path:e,state:"downloading",progress:0});let a;try{const o=this.registerFile(e,t,i.fileExtension,i.fileHandler);if(!o)throw new Error("AssetImporter: Unable to find loader for "+e);this._rootContext={path:e,rootUrl:Ps.extractUrlBase(e)},o.importOptions=i,a=await o.loadAsync(e+(i.queryString?(e.includes("?")?"&":"?")+i.queryString:""),l=>{n&&n(l);const c=l.lengthComputable?l.total:void 0;this.dispatchEvent({type:"importFile",path:e,state:"downloading",loadedBytes:l.loaded||void 0,totalBytes:c&&c<l.loaded?l.loaded:l.total||void 0,progress:c&&c>0&&c>l.loaded?l.loaded/c:1})}),o.transform&&(a=await o.transform(a,i)),delete o.importOptions,this._rootContext=void 0,t?this._logger("AssetImporter: loaded",e):this._logger("AssetImporter: downloaded",e),t&&this.unregisterFile(e)}catch(o){return console.error("AssetImporter: Unable to import file",e,t),console.error(o),console.error(o?.stack),this.dispatchEvent({type:"importFile",path:e,state:"error",error:o}),t&&this.unregisterFile(e),[]}if(a&&typeof a=="object"&&!Array.isArray(a)){if(i.fileHandler&&!i.fileExtension&&console.warn("AssetImporter - Pass fileExtension to options when using fileHandler to be able to use `rootPath`",i.fileHandler,e),!s&&!e.startsWith("blob:")&&!e.startsWith("data:")&&(a.__rootPath=e,i)){const l=this._serializeOptions(i);l&&(a.__rootPathOptions=JSON.parse(l))}const o=t||this._fileDatabase.get(e);o&&(a.__rootBlob=o)}return a}registerFile(e,t,i,n){const s=e.startsWith("data:")||!1;s||(e=e.replace(/\?.*$/,""));const a=i||(s?void 0:t?.ext??Vu(t?.name??e.trim())?.toLowerCase()),o=(t?.mime??s)&&e.slice(0,e.indexOf(";")).split(":")[1]||void 0;return t&&(t.name===void 0&&(t.name=e),t.ext||(t.ext=a),t.mime||(t.mime=o),this._fileDatabase.has(e)&&(console.warn("AssetImporter: File already registered, replacing",e),this.unregisterFile(e)),this._fileDatabase.set(e,t)),n||this._getLoader(e,a,o)||this._createLoader(e,a,o)}unregisterFile(e){e=e.replace(/\?.*$/,"");const t=this._fileDatabase.get(e);t?.objectUrl&&(URL.revokeObjectURL(t.objectUrl),t.objectUrl=void 0),t&&this._fileDatabase.delete(e)}async processRaw(e,t,i){if(!e)return[];if(t.processImported!==void 0&&(console.error("AssetImporter: processImported is deprecated, use processRaw instead"),t.processRaw=t.processImported),Array.isArray(e)){const o=[];for(const l of e)o.push(...await this.processRaw(l,t,i));return o}if(t.processRaw===!1)return[e];if(e.assetImporterProcessed&&!t.forceImporterReprocess)return[e];const n=e.__rootPath,s=e.__rootPathOptions,a=e.__rootBlob;if(e.userData){const o=e.userData;!o.rootPath&&n&&!n.startsWith("blob:")&&(o.rootPath=n,s&&(o.rootPathOptions=s)),a&&(o.__sourceBlob=a,o.__needsSourceBuffer&&(o.__sourceBuffer=await a.arrayBuffer(),delete o.__needsSourceBuffer))}return!i&&e.userData?.rootPath&&(i=e.userData.rootPath),this.dispatchEvent({type:"processRawStart",data:e,options:t,path:i}),e.isTexture&&t._testDataTextureComplete&&(e.isDataTexture&&e.image?.data&&(e.image.complete=!0),e.image?.complete&&(e.needsUpdate=!0)),e?.userData&&e.userData.rootSceneModelRoot&&(e._childrenCopy=[...e.children]),this.autoSetName&&e.name===""&&(e.name=(a?.filePath||a?.name||n||"").replace(/^\/|\/$/,"").split("/").pop()),e.assetImporterProcessed=!0,this.dispatchEvent({type:"processRaw",data:e,options:t,path:i}),e instanceof Map&&t.autoImportZipContents!==!1?[...(await this.importFiles(e,t)).values()].flat():[e]}async processRawSingle(e,t,i){return(await this.processRaw(e,t,i))[0]}dispose(){this.clearCache()}clearCache(){this._cachedAssets=[],this.unregisterAllFiles(),this.clearLoaderCache()}unregisterAllFiles(){const e=[...this._fileDatabase.keys()];for(const t of e)this.unregisterFile(t)}clearLoaderCache(){for(const e of this._loaderCache)this._disposeLoader(e);this._loaderCache=[]}_disposeLoader(e){for(const t of e.handlers)this._loadingManager.removeHandler(t);e.loader?.dispose&&e.loader?.dispose()}resolveURL(e){return this._loadingManager.resolveURL(e)}addURLModifier(e){this._urlModifiers.push(e)}removeURLModifier(e){const t=this._urlModifiers.indexOf(e);t>=0&&this._urlModifiers.splice(t,1)}_urlModifier(e){e=this._urlModifiers.reduce((a,o)=>o(a),e);let t=decodeURI(e);const i=this._rootContext?.rootUrl;!t.includes("://")&&i&&!t.startsWith(i)&&(t=i+t),t=t.replace("./",""),t=t.replace(/^(\/\/)/,"/"),t=t.replace(/\?.*$/,"");const n=this._fileDatabase.get(t);return n?n.ext?(n.objectUrl||(n.objectUrl=URL.createObjectURL(n)+"#"+t),n.objectUrl):(console.error("Unable to determine file extension",n),e):e}_isRootFile(e,t){return t=t?.toLowerCase(),e=e?.toLowerCase(),this.importers.find(i=>i.root&&(e&&tt(i.ext)?.includes(e.toLowerCase())||t&&i.mime.includes(t.toLowerCase())))!=null}_getImporter(e,t,i,n=!1){return i=i?.toLowerCase(),t=t?.toLowerCase(),this.importers.find(s=>n&&!s.root?!1:!!(i&&s.mime?.find(a=>i===a)||tt(s.ext)?.find(a=>t?a===t:e?.toLowerCase()?.endsWith("."+a)||a?.startsWith("data:")&&e?.startsWith(a))))}_getLoader(e,t,i){return!t&&!i&&e&&(t=Vu(e).toLowerCase()),i=i?.toLowerCase().trim(),t=t?.toLowerCase().trim(),(e?this._loadingManager.getHandler(e.trim()):void 0)||this._loaderCache.find(n=>t&&n.ext.includes(t)||i&&n.mime.includes(i))?.loader}_createLoader(e,t,i){const n=this._getImporter(e,t,i);if(!n)return;const s=n.ctor(this);if(!s)return;const a=[];return tt(n.ext)?.forEach(o=>{const l=new RegExp(o.startsWith("data:")?"^"+Hu(o)+"[\\/\\+\\:\\,\\;]":"\\."+o+"$","i");this._loadingManager.addHandler(l,s),a.push(l)}),n.mime?.forEach(o=>{const l=new RegExp("^data:"+Hu(o)+"[\\/\\+\\:\\,\\;]","i");this._loadingManager.addHandler(l,s),a.push(l)}),this._loaderCache.push({loader:s,ext:tt(n.ext)||[],mime:n.mime,importer:n,handlers:a}),this.dispatchEvent({type:"loaderCreate",loader:s}),s}_initCacheStorage(e,t){if(t===!0&&window?.caches){this._cacheStoreInitPromise=window.caches.open?.("threepipe-assetmanager").then(i=>{this._initCacheStorage(e,i),this._storage=i,this._cacheStoreInitPromise=void 0});return}if(e||t){e&&(Ai.enabled=!0);const i=t&&window.Cache&&typeof window.Cache=="function"&&t instanceof window.Cache?t:void 0;gE(i)}this._storage=typeof t=="boolean"?void 0:t}addEventListener(e,t){if(super.addEventListener(e,t),e==="loaderCreate")for(const i of this._loaderCache)this.dispatchEvent({type:"loaderCreate",loader:i.loader})}_onLoad(){this.dispatchEvent({type:"onLoad"})}_onProgress(e,t,i){this.dispatchEvent({type:"onProgress",url:e,loaded:t,total:i})}_onError(e){this.dispatchEvent({type:"onError",url:e})}_onStart(e,t,i){this.dispatchEvent({type:"onStart",url:e,loaded:t,total:i})}async processImported(e,t,i){return console.error("processImported is deprecated. Use processRaw instead."),await this.processRaw(e,t,i)}};Hr.DummyMaterial=new gs({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),Hr.DummyLineBasicMaterial=new Yn({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),Hr.DummyLineMaterial=new ji({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),Hr.DummyGeometry=new Je,Hr.DummyMaterial.uiConfig={},Hr.DummyLineBasicMaterial.uiConfig={},Hr.DummyLineMaterial.uiConfig={},Hr.DummyGeometry.uiConfig={};let Ds=Hr,Pd,a0,sh,dg;function o0(r,e=1/0,t=null){a0||(a0=new ca(2,2,1,1)),sh||(sh=new nn({uniforms:{blitTexture:new tm(r)},vertexShader:`
			varying vec2 vUv;
			void main(){
				vUv = uv;
				gl_Position = vec4(position.xy * 1.0,0.,.999999);
			}`,fragmentShader:`
			uniform sampler2D blitTexture; 
			varying vec2 vUv;

			void main(){ 
				gl_FragColor = vec4(vUv.xy, 0, 1);
				
				#ifdef IS_SRGB
				gl_FragColor = sRGBTransferOETF( texture2D( blitTexture, vUv) );
				#else
				gl_FragColor = texture2D( blitTexture, vUv);
				#endif
			}`})),sh.uniforms.blitTexture.value=r,sh.defines.IS_SRGB=r.colorSpace==Ct,sh.needsUpdate=!0,dg||(dg=new _e(a0,sh),dg.frustumCulled=!1);const i=new zi,n=new Qo;n.add(dg),t===null&&(t=Pd=new hp({antialias:!1}));const s=Math.min(r.image.width,e),a=Math.min(r.image.height,e);t.setSize(s,a),t.clear(),t.render(n,i);const o=document.createElement("canvas"),l=o.getContext("2d");o.width=s,o.height=a,l.drawImage(t.domElement,0,0,s,a);const c=new qo(o);return c.minFilter=r.minFilter,c.magFilter=r.magFilter,c.wrapS=r.wrapS,c.wrapT=r.wrapT,c.name=r.name,Pd&&(Pd.forceContextLoss(),Pd.dispose(),Pd=null),c}const CT={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class Dd{constructor(){this.pluginCallbacks=[],this.register(function(e){return new EG(e)}),this.register(function(e){return new MG(e)}),this.register(function(e){return new DG(e)}),this.register(function(e){return new RG(e)}),this.register(function(e){return new BG(e)}),this.register(function(e){return new LG(e)}),this.register(function(e){return new TG(e)}),this.register(function(e){return new IG(e)}),this.register(function(e){return new PG(e)}),this.register(function(e){return new OG(e)}),this.register(function(e){return new UG(e)}),this.register(function(e){return new FG(e)}),this.register(function(e){return new NG(e)}),this.register(function(e){return new kG(e)})}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,n,s){const a=s||new PT,o=[];for(let l=0,c=this.pluginCallbacks.length;l<c;l++)o.push(this.pluginCallbacks[l](a));a.setPlugins(o),a.write(e,t,n).catch(i)}parseAsync(e,t){const i=this;return new Promise(function(n,s){i.parse(e,n,s,t)})}}const Gt={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,INT:5124,UNSIGNED_INT:5125,FLOAT:5126,ARRAY_BUFFER:34962,ELEMENT_ARRAY_BUFFER:34963,NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987,CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497},l0="KHR_mesh_quantization",Rs={};Rs[mi]=Gt.NEAREST,Rs[Jh]=Gt.NEAREST_MIPMAP_NEAREST,Rs[Na]=Gt.NEAREST_MIPMAP_LINEAR,Rs[at]=Gt.LINEAR,Rs[Io]=Gt.LINEAR_MIPMAP_NEAREST,Rs[Dn]=Gt.LINEAR_MIPMAP_LINEAR,Rs[di]=Gt.CLAMP_TO_EDGE,Rs[Pn]=Gt.REPEAT,Rs[Kr]=Gt.MIRRORED_REPEAT;const xT={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},yG=new ee,ST=12,_G=1179937895,vG=2,ET=8,bG=1313821514,wG=5130562;function Rd(r,e){return r.length===e.length&&r.every(function(t,i){return t===e[i]})}function CG(r){return new TextEncoder().encode(r).buffer}function xG(r){return Rd(r.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function SG(r,e,t){const i={min:new Array(r.itemSize).fill(Number.POSITIVE_INFINITY),max:new Array(r.itemSize).fill(Number.NEGATIVE_INFINITY)};for(let n=e;n<e+t;n++)for(let s=0;s<r.itemSize;s++){let a;r.itemSize>4?a=r.array[n*r.itemSize+s]:(s===0?a=r.getX(n):s===1?a=r.getY(n):s===2?a=r.getZ(n):s===3&&(a=r.getW(n)),r.normalized===!0&&(a=Ft.normalize(a,r.array))),i.min[s]=Math.min(i.min[s],a),i.max[s]=Math.max(i.max[s],a)}return i}function MT(r){return Math.ceil(r/4)*4}function fg(r,e=0){const t=MT(r.byteLength);if(t!==r.byteLength){const i=new Uint8Array(t);if(i.set(new Uint8Array(r)),e!==0)for(let n=r.byteLength;n<t;n++)i[n]=e;return i.buffer}return r}function TT(){return typeof document>"u"&&typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas")}function IT(r,e){if(r.toBlob!==void 0)return new Promise(i=>r.toBlob(i,e));let t;return e==="image/jpeg"?t=.92:e==="image/webp"&&(t=.8),r.convertToBlob({type:e,quality:t})}class PT{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter r168"}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map}}setPlugins(e){this.plugins=e}async write(e,t,i={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1,ignoreInvalidMorphTargetTracks:!1,ignoreEmptyTextures:!1},i),this.options.animations.length>0&&(this.options.trs=!0),this.processInput(e),await Promise.all(this.pending);const n=this,s=n.buffers,a=n.json;i=n.options;const o=n.extensionsUsed,l=n.extensionsRequired,c=new Blob(s,{type:"application/octet-stream"}),h=Object.keys(o),u=Object.keys(l);if(h.length>0&&(a.extensionsUsed=h),u.length>0&&(a.extensionsRequired=u),a.buffers&&a.buffers.length>0&&(a.buffers[0].byteLength=c.size),i.binary===!0){const d=new FileReader;d.readAsArrayBuffer(c),d.onloadend=function(){const p=fg(d.result),m=new DataView(new ArrayBuffer(ET));m.setUint32(0,p.byteLength,!0),m.setUint32(4,wG,!0);const A=fg(CG(JSON.stringify(a)),32),g=new DataView(new ArrayBuffer(ET));g.setUint32(0,A.byteLength,!0),g.setUint32(4,bG,!0);const y=new ArrayBuffer(ST),v=new DataView(y);v.setUint32(0,_G,!0),v.setUint32(4,vG,!0);const _=ST+g.byteLength+A.byteLength+m.byteLength+p.byteLength;v.setUint32(8,_,!0);const b=new Blob([y,g,A,m,p],{type:"application/octet-stream"}),T=new FileReader;T.readAsArrayBuffer(b),T.onloadend=function(){t(T.result)}}}else if(a.buffers&&a.buffers.length>0){const d=new FileReader;d.readAsDataURL(c),d.onloadend=function(){const p=d.result;a.buffers[0].uri=p,t(a)}}else t(a)}serializeUserData(e,t){if(Object.keys(e.userData).length===0)return;const i=this.options,n=this.extensionsUsed;try{const s=JSON.parse(JSON.stringify(e.userData));if(i.includeCustomExtensions&&s.gltfExtensions){t.extensions===void 0&&(t.extensions={});for(const a in s.gltfExtensions)t.extensions[a]=s.gltfExtensions[a],n[a]=!0;delete s.gltfExtensions}Object.keys(s).length>0&&(t.extras=s)}catch(s){console.warn("THREE.GLTFExporter: userData of '"+e.name+"' won't be serialized because of JSON.stringify error - "+s.message),console.warn({...e.userData})}}getUID(e,t=!1){if(this.uids.has(e)===!1){const n=new Map;n.set(!0,this.uid++),n.set(!1,this.uid++),this.uids.set(e,n)}return this.uids.get(e).get(t)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;const i=new S;for(let n=0,s=e.count;n<s;n++)if(Math.abs(i.fromBufferAttribute(e,n).length()-1)>5e-4)return!1;return!0}createNormalizedNormalAttribute(e){const t=this.cache;if(t.attributesNormalized.has(e))return t.attributesNormalized.get(e);const i=e.clone(),n=new S;for(let s=0,a=i.count;s<a;s++)n.fromBufferAttribute(i,s),n.x===0&&n.y===0&&n.z===0?n.setX(1):n.normalize(),i.setXYZ(s,n.x,n.y,n.z);return t.attributesNormalized.set(e,i),i}applyTextureTransform(e,t){let i=!1;const n={};(t.offset.x!==0||t.offset.y!==0)&&(n.offset=t.offset.toArray(),i=!0),t.rotation!==0&&(n.rotation=t.rotation,i=!0),(t.repeat.x!==1||t.repeat.y!==1)&&(n.scale=t.repeat.toArray(),i=!0),i&&(e.extensions=e.extensions||{},e.extensions.KHR_texture_transform=n,this.extensionsUsed.KHR_texture_transform=!0)}buildMetalRoughTexture(e,t){if(e===t)return e;function i(p){return p.colorSpace===Ct?function(A){return A<.04045?A*.0773993808:Math.pow(A*.9478672986+.0521327014,2.4)}:function(A){return A}}console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."),e instanceof ua&&(e=o0(e)),t instanceof ua&&(t=o0(t));const n=e?e.image:null,s=t?t.image:null,a=Math.max(n?n.width:0,s?s.width:0),o=Math.max(n?n.height:0,s?s.height:0),l=TT();l.width=a,l.height=o;const c=l.getContext("2d",{willReadFrequently:!0});c.fillStyle="#00ffff",c.fillRect(0,0,a,o);const h=c.getImageData(0,0,a,o);if(n){c.drawImage(n,0,0,a,o);const p=i(e),m=c.getImageData(0,0,a,o).data;for(let A=2;A<m.length;A+=4)h.data[A]=p(m[A]/256)*256}if(s){c.drawImage(s,0,0,a,o);const p=i(t),m=c.getImageData(0,0,a,o).data;for(let A=1;A<m.length;A+=4)h.data[A]=p(m[A]/256)*256}c.putImageData(h,0,0);const d=(e||t).clone();return d.source=new ia(l),d.colorSpace=ai,d.channel=(e||t).channel,e&&t&&e.channel!==t.channel&&console.warn("THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match."),d}processBuffer(e){const t=this.json,i=this.buffers;return t.buffers||(t.buffers=[{byteLength:0}]),i.push(e),0}processBufferView(e,t,i,n,s){const a=this.json;a.bufferViews||(a.bufferViews=[]);let o;switch(t){case Gt.BYTE:case Gt.UNSIGNED_BYTE:o=1;break;case Gt.SHORT:case Gt.UNSIGNED_SHORT:o=2;break;default:o=4}let l=e.itemSize*o;s===Gt.ARRAY_BUFFER&&(l=Math.ceil(l/4)*4);const c=MT(n*l),h=new DataView(new ArrayBuffer(c));let u=0;for(let m=i;m<i+n;m++){for(let A=0;A<e.itemSize;A++){let g;e.itemSize>4?g=e.array[m*e.itemSize+A]:(A===0?g=e.getX(m):A===1?g=e.getY(m):A===2?g=e.getZ(m):A===3&&(g=e.getW(m)),e.normalized===!0&&(g=Ft.normalize(g,e.array))),t===Gt.FLOAT?h.setFloat32(u,g,!0):t===Gt.INT?h.setInt32(u,g,!0):t===Gt.UNSIGNED_INT?h.setUint32(u,g,!0):t===Gt.SHORT?h.setInt16(u,g,!0):t===Gt.UNSIGNED_SHORT?h.setUint16(u,g,!0):t===Gt.BYTE?h.setInt8(u,g):t===Gt.UNSIGNED_BYTE&&h.setUint8(u,g),u+=o}u%l!==0&&(u+=l-u%l)}const d={buffer:this.processBuffer(h.buffer),byteOffset:this.byteOffset,byteLength:c};return s!==void 0&&(d.target=s),s===Gt.ARRAY_BUFFER&&(d.byteStride=l),this.byteOffset+=c,a.bufferViews.push(d),{id:a.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const t=this,i=t.json;return i.bufferViews||(i.bufferViews=[]),new Promise(function(n){const s=new FileReader;s.readAsArrayBuffer(e),s.onloadend=function(){const a=fg(s.result),o={buffer:t.processBuffer(a),byteOffset:t.byteOffset,byteLength:a.byteLength};t.byteOffset+=a.byteLength,n(i.bufferViews.push(o)-1)}})}processBufferViewImageBuffer(e){const t=this,i=t.json;i.bufferViews||(i.bufferViews=[]),e=fg(e);const n={buffer:t.processBuffer(e),byteOffset:t.byteOffset,byteLength:e.byteLength};return t.byteOffset+=e.byteLength,i.bufferViews.push(n)-1}processAccessor(e,t,i,n){const s=this.json,a={1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"};let o;if(e.array.constructor===Float32Array)o=Gt.FLOAT;else if(e.array.constructor===Int32Array)o=Gt.INT;else if(e.array.constructor===Uint32Array)o=Gt.UNSIGNED_INT;else if(e.array.constructor===Int16Array)o=Gt.SHORT;else if(e.array.constructor===Uint16Array)o=Gt.UNSIGNED_SHORT;else if(e.array.constructor===Int8Array)o=Gt.BYTE;else if(e.array.constructor===Uint8Array)o=Gt.UNSIGNED_BYTE;else throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);if(i===void 0&&(i=0),(n===void 0||n===1/0)&&(n=e.count),n===0)return null;const l=SG(e,i,n);let c;t!==void 0&&(c=e===t.index?Gt.ELEMENT_ARRAY_BUFFER:Gt.ARRAY_BUFFER);const h=this.processBufferView(e,o,i,n,c),u={bufferView:h.id,byteOffset:h.byteOffset,componentType:o,count:n,max:l.max,min:l.min,type:a[e.itemSize]};return e.normalized===!0&&(u.normalized=!0),s.accessors||(s.accessors=[]),s.accessors.push(u)-1}processImage(e,t,i,n="image/png",s=void 0,a=void 0){if(e!==null){const o=this,l=o.cache,c=o.json,h=o.options,u=o.pending;l.images.has(e)||l.images.set(e,{});const d=l.images.get(e),p=n+":flipY/"+i.toString()+(s||a?";"+s+";"+a:"");if(d[p]!==void 0)return d[p];c.images||(c.images=[]);const m={mimeType:n},A=TT();A.width=Math.min(s||e.width,h.maxTextureSize),A.height=Math.min(a||e.height,h.maxTextureSize);const g=A.getContext("2d",{willReadFrequently:!0});if(i===!0&&(g.translate(0,A.height),g.scale(1,-1)),e.data!==void 0){t!==qt&&console.error("GLTFExporter: Only RGBAFormat is supported.",t),(e.width>h.maxTextureSize||e.height>h.maxTextureSize)&&console.warn("GLTFExporter: Image size is bigger than maxTextureSize",e);const v=new Uint8ClampedArray(e.height*e.width*4);for(let _=0;_<v.length;_+=4)v[_+0]=e.data[_+0],v[_+1]=e.data[_+1],v[_+2]=e.data[_+2],v[_+3]=e.data[_+3];g.putImageData(new ImageData(v,e.width,e.height),0,0)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)g.drawImage(e,0,0,A.width,A.height);else throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.");h.binary===!0?u.push(IT(A,n).then(v=>o.processBufferViewImage(v)).then(v=>{m.bufferView=v})):A.toDataURL!==void 0?m.uri=A.toDataURL(n):u.push(IT(A,n).then(v=>new FileReader().readAsDataURL(v)).then(v=>{m.uri=v}));const y=c.images.push(m)-1;return d[p]=y,y}else throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){const t=this.json;t.samplers||(t.samplers=[]);const i={magFilter:Rs[e.magFilter],minFilter:Rs[e.minFilter],wrapS:Rs[e.wrapS],wrapT:Rs[e.wrapT]};return t.samplers.push(i)-1}processTexture(e){const i=this.options,n=this.cache,s=this.json;if(n.textures.has(e))return n.textures.get(e);s.textures||(s.textures=[]),e instanceof ua&&!e.source._canSerialize&&(e=o0(e,i.maxTextureSize));let a=e.userData.mimeType;a==="image/webp"&&(a="image/png"),a==="image/jpg"&&(a="image/jpeg");const o=["image/jpeg","image/png"],l={sampler:this.processSampler(e),source:!a||o.includes(a)?this.processImage(e.image,e.format,e.flipY,a):null};e.name&&(l.name=e.name),this._invokeAll(function(h){h.writeTexture&&h.writeTexture(e,l)}),l.source===null&&console.error("GLTFExporter: Unsupported mime type: "+a+". Cannot export texture.",e);const c=s.textures.push(l)-1;return n.textures.set(e,c),c}processMaterial(e){const t=this.cache,i=this.json;if(t.materials.has(e))return t.materials.get(e);if(e.isShaderMaterial)return console.warn("GLTFExporter: THREE.ShaderMaterial not supported."),null;i.materials||(i.materials=[]);const n={pbrMetallicRoughness:{}};e.isMeshStandardMaterial!==!0&&e.isMeshBasicMaterial!==!0&&console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");const s=e.color.toArray().concat([e.opacity]);if(Rd(s,[1,1,1,1])||(n.pbrMetallicRoughness.baseColorFactor=s),e.isMeshStandardMaterial?(n.pbrMetallicRoughness.metallicFactor=e.metalness,n.pbrMetallicRoughness.roughnessFactor=e.roughness):(n.pbrMetallicRoughness.metallicFactor=.5,n.pbrMetallicRoughness.roughnessFactor=.5),this.checkEmptyMap(e.metalnessMap)||this.checkEmptyMap(e.roughnessMap)){const o=this.buildMetalRoughTexture(e.metalnessMap,e.roughnessMap),l={index:this.processTexture(o),channel:o.channel};this.applyTextureTransform(l,o),n.pbrMetallicRoughness.metallicRoughnessTexture=l}if(this.checkEmptyMap(e.map)){const o={index:this.processTexture(e.map),texCoord:e.map.channel};this.applyTextureTransform(o,e.map),n.pbrMetallicRoughness.baseColorTexture=o}if(e.emissive){const o=e.emissive;if(Math.max(o.r,o.g,o.b)>0&&(n.emissiveFactor=e.emissive.toArray()),this.checkEmptyMap(e.emissiveMap)){const c={index:this.processTexture(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(c,e.emissiveMap),n.emissiveTexture=c}}if(this.checkEmptyMap(e.normalMap)){const o={index:this.processTexture(e.normalMap),texCoord:e.normalMap.channel};e.normalScale&&e.normalScale.x!==1&&(o.scale=e.normalScale.x),this.applyTextureTransform(o,e.normalMap),n.normalTexture=o}if(this.checkEmptyMap(e.aoMap)){const o={index:this.processTexture(e.aoMap),texCoord:e.aoMap.channel};e.aoMapIntensity!==1&&(o.strength=e.aoMapIntensity),this.applyTextureTransform(o,e.aoMap),n.occlusionTexture=o}e.transparent?n.alphaMode="BLEND":e.alphaTest>0&&(n.alphaMode="MASK",n.alphaCutoff=e.alphaTest),e.side===Zi&&(n.doubleSided=!0),e.name!==""&&(n.name=e.name),this.serializeUserData(e,n),this._invokeAll(function(o){o.writeMaterial&&o.writeMaterial(e,n)});const a=i.materials.push(n)-1;return t.materials.set(e,a),a}processMesh(e){const t=this.cache,i=this.json,n=[e.geometry.uuid];if(Array.isArray(e.material))for(let b=0,T=e.material.length;b<T;b++)n.push(e.material[b].uuid);else n.push(e.material.uuid);const s=n.join(":");if(t.meshes.has(s))return t.meshes.get(s);const a=e.geometry;let o;e.isLineSegments?o=Gt.LINES:e.isLineLoop?o=Gt.LINE_LOOP:e.isLine?o=Gt.LINE_STRIP:e.isPoints?o=Gt.POINTS:o=e.material.wireframe?Gt.LINES:Gt.TRIANGLES;const l={},c={},h=[],u=[],d={uv:"TEXCOORD_0",uv1:"TEXCOORD_1",uv2:"TEXCOORD_2",uv3:"TEXCOORD_3",color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},p=a.getAttribute("normal");p!==void 0&&!this.isNormalizedNormalAttribute(p)&&(console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."),a.setAttribute("normal",this.createNormalizedNormalAttribute(p)));let m=null;for(let b in a.attributes){if(b.slice(0,5)==="morph")continue;const T=a.attributes[b];if(b=d[b]||b.toUpperCase(),/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.test(b)||(b="_"+b),t.attributes.has(this.getUID(T))){c[b]=t.attributes.get(this.getUID(T));continue}m=null;const M=T.array;b==="JOINTS_0"&&!(M instanceof Uint16Array)&&!(M instanceof Uint8Array)&&(console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'),m=new Ze(new Uint16Array(M),T.itemSize,T.normalized));const I=this.processAccessor(m||T,a);I!==null&&(b.startsWith("_")||this.detectMeshQuantization(b,T),c[b]=I,t.attributes.set(this.getUID(T),I))}if(p!==void 0&&a.setAttribute("normal",p),Object.keys(c).length===0)return null;if(e.morphTargetInfluences!==void 0&&e.morphTargetInfluences.length>0){const b=[],T=[],E={};if(e.morphTargetDictionary!==void 0)for(const M in e.morphTargetDictionary)E[e.morphTargetDictionary[M]]=M;for(let M=0;M<e.morphTargetInfluences.length;++M){const I={};let C=!1;for(const x in a.morphAttributes){if(x!=="position"&&x!=="normal"){C||(console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."),C=!0);continue}const D=a.morphAttributes[x][M],U=x.toUpperCase(),O=a.attributes[x];if(t.attributes.has(this.getUID(D,!0))){I[U]=t.attributes.get(this.getUID(D,!0));continue}const N=D.clone();if(!a.morphTargetsRelative)for(let H=0,V=D.count;H<V;H++)for(let X=0;X<D.itemSize;X++)X===0&&N.setX(H,D.getX(H)-O.getX(H)),X===1&&N.setY(H,D.getY(H)-O.getY(H)),X===2&&N.setZ(H,D.getZ(H)-O.getZ(H)),X===3&&N.setW(H,D.getW(H)-O.getW(H));I[U]=this.processAccessor(N,a),t.attributes.set(this.getUID(O,!0),I[U])}u.push(I),b.push(e.morphTargetInfluences[M]),e.morphTargetDictionary!==void 0&&T.push(E[M])}l.weights=b,T.length>0&&(l.extras={},l.extras.targetNames=T)}const A=Array.isArray(e.material);if(A&&a.groups.length===0)return null;let g=!1;if(A&&a.index===null){const b=[];for(let T=0,E=a.attributes.position.count;T<E;T++)b[T]=T;a.setIndex(b),g=!0}const y=A?e.material:[e.material],v=A?a.groups:[{materialIndex:0,start:void 0,count:void 0}];for(let b=0,T=v.length;b<T;b++){const E={mode:o,attributes:c};if(this.serializeUserData(a,E),u.length>0&&(E.targets=u),a.index!==null){let I=this.getUID(a.index);(v[b].start!==void 0||v[b].count!==void 0)&&(I+=":"+v[b].start+":"+v[b].count),t.attributes.has(I)?E.indices=t.attributes.get(I):(E.indices=this.processAccessor(a.index,a,v[b].start,v[b].count),t.attributes.set(I,E.indices)),E.indices===null&&delete E.indices}const M=this.processMaterial(y[v[b].materialIndex]);M!==null&&(E.material=M),h.push(E)}g===!0&&a.setIndex(null),l.primitives=h,i.meshes||(i.meshes=[]),this._invokeAll(function(b){b.writeMesh&&b.writeMesh(e,l)});const _=i.meshes.push(l)-1;return t.meshes.set(s,_),_}detectMeshQuantization(e,t){if(this.extensionsUsed[l0])return;let i;switch(t.array.constructor){case Int8Array:i="byte";break;case Uint8Array:i="unsigned byte";break;case Int16Array:i="short";break;case Uint16Array:i="unsigned short";break;default:return}t.normalized&&(i+=" normalized");const n=e.split("_",1)[0];CT[n]&&CT[n].includes(i)&&(this.extensionsUsed[l0]=!0,this.extensionsRequired[l0]=!0)}processCamera(e){const t=this.json;t.cameras||(t.cameras=[]);const i=e.isOrthographicCamera,n={type:i?"orthographic":"perspective"};return i?n.orthographic={xmag:e.right*2,ymag:e.top*2,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:n.perspective={aspectRatio:e.aspect,yfov:Ft.degToRad(e.fov),zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near},e.name!==""&&(n.name=e.type),t.cameras.push(n)-1}processAnimation(e,t){const i=this.json,n=this.nodeMap;i.animations||(i.animations=[]);try{e=Dd.Utils.mergeMorphTargetTracks(e.clone(),t)}catch(c){if(console.warn('THREE.GLTFExporter: Could not export animation clip "%s".',e.name),!this.options.ignoreInvalidMorphTargetTracks)throw c;return console.error(c),null}const s=e.tracks,a=[],o=[];for(let c=0;c<s.length;++c){const h=s[c],u=Et.parseTrackName(h.name);let d=Et.findNode(t,u.nodeName);const p=xT[u.propertyName];if(u.objectName==="bones"&&(d.isSkinnedMesh===!0?d=d.skeleton.getBoneByName(u.objectIndex):d=void 0),!d||!p){console.warn('THREE.GLTFExporter: Could not export animation track "%s".',h.name);continue}const m=1;let A=h.values.length/h.times.length;p===xT.morphTargetInfluences&&(A/=d.morphTargetInfluences.length);let g;h.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline===!0?(g="CUBICSPLINE",A/=3):h.getInterpolation()===ec?g="STEP":g="LINEAR",o.push({input:this.processAccessor(new Ze(h.times,m)),output:this.processAccessor(new Ze(h.values,A)),interpolation:g}),a.push({sampler:o.length-1,target:{node:n.get(d),path:p}})}const l={name:e.name||"clip_"+i.animations.length,samplers:o,channels:a};return this.serializeUserData(e,l),i.animations.push(l),i.animations.length-1}processSkin(e){const t=this.json,i=this.nodeMap,n=t.nodes[i.get(e)],s=e.skeleton;if(s===void 0)return null;const a=e.skeleton.bones[0];if(a===void 0)return null;const o=[],l=new Float32Array(s.bones.length*16),c=new fe;for(let u=0;u<s.bones.length;++u)o.push(i.get(s.bones[u])),c.copy(s.boneInverses[u]),c.multiply(e.bindMatrix).toArray(l,u*16);return t.skins===void 0&&(t.skins=[]),t.skins.push({inverseBindMatrices:this.processAccessor(new Ze(l,16)),joints:o,skeleton:i.get(a)}),n.skin=t.skins.length-1}processNode(e){const t=this.json,i=this.options,n=this.nodeMap;t.nodes||(t.nodes=[]);const s={};if(i.trs){const o=e.quaternion.toArray(),l=e.position.toArray(),c=e.scale.toArray();Rd(o,[0,0,0,1])||(s.rotation=o),Rd(l,[0,0,0])||(s.translation=l),Rd(c,[1,1,1])||(s.scale=c)}else e.matrixAutoUpdate&&e.updateMatrix(),xG(e.matrix)===!1&&(s.matrix=e.matrix.elements);if(e.name!==""&&(s.name=String(e.name)),this.serializeUserData(e,s),e.isMesh||e.isLine||e.isPoints){const o=this.processMesh(e);o!==null&&(s.mesh=o)}else e.isCamera&&(s.camera=this.processCamera(e));if(e.isSkinnedMesh&&this.skins.push(e),e.children.length>0){const o=[];for(let l=0,c=e.children.length;l<c;l++){const h=e.children[l];if(h.visible||i.onlyVisible===!1){const u=this.processNode(h);u!==null&&o.push(u)}}o.length>0&&(s.children=o)}this._invokeAll(function(o){o.writeNode&&o.writeNode(e,s)});const a=t.nodes.push(s)-1;return n.set(e,a),a}processScene(e){const t=this.json,i=this.options;t.scenes||(t.scenes=[],t.scene=0);const n={};e.name!==""&&(n.name=e.name),t.scenes.push(n);const s=[];for(let a=0,o=e.children.length;a<o;a++){const l=e.children[a];if(l.visible||i.onlyVisible===!1){const c=this.processNode(l);c!==null&&s.push(c)}}s.length>0&&(n.nodes=s),this.serializeUserData(e,n)}processObjects(e){const t=new Qo;t.name="AuxScene";for(let i=0;i<e.length;i++)t.children.push(e[i]);this.processScene(t)}processInput(e){const t=this.options;e=e instanceof Array?e:[e],this._invokeAll(function(n){n.beforeParse&&n.beforeParse(e)});const i=[];for(let n=0;n<e.length;n++)e[n]instanceof Qo?this.processScene(e[n]):i.push(e[n]);i.length>0&&this.processObjects(i);for(let n=0;n<this.skins.length;++n)this.processSkin(this.skins[n]);for(let n=0;n<t.animations.length;++n)this.processAnimation(t.animations[n],e[0]);this._invokeAll(function(n){n.afterParse&&n.afterParse(e)})}_invokeAll(e){for(let t=0,i=this.plugins.length;t<i;t++)e(this.plugins[t])}checkEmptyMap(e){return!!e&&(!this.options.ignoreEmptyTextures||!!e.image)}}class EG{constructor(e){this.writer=e,this.name="KHR_lights_punctual"}writeNode(e,t){if(!e.isLight)return;if(!e.isDirectionalLight&&!e.isPointLight&&!e.isSpotLight){console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.",e);return}const i=this.writer,n=i.json,s=i.extensionsUsed,a={};e.name&&(a.name=e.name),a.color=e.color.toArray(),a.intensity=e.intensity,e.isDirectionalLight?a.type="directional":e.isPointLight?(a.type="point",e.distance>0&&(a.range=e.distance)):e.isSpotLight&&(a.type="spot",e.distance>0&&(a.range=e.distance),a.spot={},a.spot.innerConeAngle=(1-e.penumbra)*e.angle,a.spot.outerConeAngle=e.angle),e.decay!==void 0&&e.decay!==2&&console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2."),e.target&&(e.target.parent!==e||e.target.position.x!==0||e.target.position.y!==0||e.target.position.z!==-1)&&console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, make light.target a child of the light with position 0,0,-1."),s[this.name]||(n.extensions=n.extensions||{},n.extensions[this.name]={lights:[]},s[this.name]=!0);const o=n.extensions[this.name].lights;o.push(a),t.extensions=t.extensions||{},t.extensions[this.name]={light:o.length-1}}}let MG=class{constructor(e){this.writer=e,this.name="KHR_materials_unlit"}writeMaterial(e,t){if(!e.isMeshBasicMaterial)return;const n=this.writer.extensionsUsed;t.extensions=t.extensions||{},t.extensions[this.name]={},n[this.name]=!0,t.pbrMetallicRoughness.metallicFactor=0,t.pbrMetallicRoughness.roughnessFactor=.9}},TG=class{constructor(e){this.writer=e,this.name="KHR_materials_clearcoat"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.clearcoat===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(s.clearcoatFactor=e.clearcoat,i.checkEmptyMap(e.clearcoatMap)){const a={index:i.processTexture(e.clearcoatMap),texCoord:e.clearcoatMap.channel};i.applyTextureTransform(a,e.clearcoatMap),s.clearcoatTexture=a}if(s.clearcoatRoughnessFactor=e.clearcoatRoughness,i.checkEmptyMap(e.clearcoatRoughnessMap)){const a={index:i.processTexture(e.clearcoatRoughnessMap),texCoord:e.clearcoatRoughnessMap.channel};i.applyTextureTransform(a,e.clearcoatRoughnessMap),s.clearcoatRoughnessTexture=a}if(i.checkEmptyMap(e.clearcoatNormalMap)){const a={index:i.processTexture(e.clearcoatNormalMap),texCoord:e.clearcoatNormalMap.channel};e.clearcoatNormalScale.x!==1&&(a.scale=e.clearcoatNormalScale.x),i.applyTextureTransform(a,e.clearcoatNormalMap),s.clearcoatNormalTexture=a}t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},IG=class{constructor(e){this.writer=e,this.name="KHR_materials_dispersion"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.dispersion===0)return;const n=this.writer.extensionsUsed,s={};s.dispersion=e.dispersion,t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},PG=class{constructor(e){this.writer=e,this.name="KHR_materials_iridescence"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.iridescence===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(s.iridescenceFactor=e.iridescence,i.checkEmptyMap(e.iridescenceMap)){const a={index:i.processTexture(e.iridescenceMap),texCoord:e.iridescenceMap.channel};i.applyTextureTransform(a,e.iridescenceMap),s.iridescenceTexture=a}if(s.iridescenceIor=e.iridescenceIOR,s.iridescenceThicknessMinimum=e.iridescenceThicknessRange[0],s.iridescenceThicknessMaximum=e.iridescenceThicknessRange[1],i.checkEmptyMap(e.iridescenceThicknessMap)){const a={index:i.processTexture(e.iridescenceThicknessMap),texCoord:e.iridescenceThicknessMap.channel};i.applyTextureTransform(a,e.iridescenceThicknessMap),s.iridescenceThicknessTexture=a}t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},DG=class{constructor(e){this.writer=e,this.name="KHR_materials_transmission"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.transmission===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(s.transmissionFactor=e.transmission,i.checkEmptyMap(e.transmissionMap)){const a={index:i.processTexture(e.transmissionMap),texCoord:e.transmissionMap.channel};i.applyTextureTransform(a,e.transmissionMap),s.transmissionTexture=a}t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},RG=class{constructor(e){this.writer=e,this.name="KHR_materials_volume"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.transmission===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(s.thicknessFactor=e.thickness,i.checkEmptyMap(e.thicknessMap)){const a={index:i.processTexture(e.thicknessMap),texCoord:e.thicknessMap.channel};i.applyTextureTransform(a,e.thicknessMap),s.thicknessTexture=a}e.attenuationDistance!==1/0&&(s.attenuationDistance=e.attenuationDistance),s.attenuationColor=e.attenuationColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},BG=class{constructor(e){this.writer=e,this.name="KHR_materials_ior"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.ior===1.5)return;const n=this.writer.extensionsUsed,s={};s.ior=e.ior,t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},LG=class{constructor(e){this.writer=e,this.name="KHR_materials_specular"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.specularIntensity===1&&e.specularColor.equals(yG)&&!e.specularIntensityMap&&!e.specularColorMap)return;const i=this.writer,n=i.extensionsUsed,s={};if(i.checkEmptyMap(e.specularIntensityMap)){const a={index:i.processTexture(e.specularIntensityMap),texCoord:e.specularIntensityMap.channel};i.applyTextureTransform(a,e.specularIntensityMap),s.specularTexture=a}if(i.checkEmptyMap(e.specularColorMap)){const a={index:i.processTexture(e.specularColorMap),texCoord:e.specularColorMap.channel};i.applyTextureTransform(a,e.specularColorMap),s.specularColorTexture=a}s.specularFactor=e.specularIntensity,s.specularColorFactor=e.specularColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},OG=class{constructor(e){this.writer=e,this.name="KHR_materials_sheen"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.sheen<.001)return;const i=this.writer,n=i.extensionsUsed,s={};if(i.checkEmptyMap(e.sheenRoughnessMap)){const a={index:i.processTexture(e.sheenRoughnessMap),texCoord:e.sheenRoughnessMap.channel};i.applyTextureTransform(a,e.sheenRoughnessMap),s.sheenRoughnessTexture=a}if(i.checkEmptyMap(e.sheenColorMap)){const a={index:i.processTexture(e.sheenColorMap),texCoord:e.sheenColorMap.channel};i.applyTextureTransform(a,e.sheenColorMap),s.sheenColorTexture=a}s.sheenRoughnessFactor=e.sheenRoughness,s.sheenColorFactor=e.sheenColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=s,t.extras=t.extras||{},t.extras.sheenFactor=e.sheen,n[this.name]=!0}},UG=class{constructor(e){this.writer=e,this.name="KHR_materials_anisotropy"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||e.anisotropy==0)return;const i=this.writer,n=i.extensionsUsed,s={};if(i.checkEmptyMap(e.anisotropyMap)){const a={index:i.processTexture(e.anisotropyMap)};i.applyTextureTransform(a,e.anisotropyMap),s.anisotropyTexture=a}s.anisotropyStrength=e.anisotropy,s.anisotropyRotation=e.anisotropyRotation,t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},FG=class{constructor(e){this.writer=e,this.name="KHR_materials_emissive_strength"}writeMaterial(e,t){if(!e.isMeshStandardMaterial||e.emissiveIntensity===1)return;const n=this.writer.extensionsUsed,s={};s.emissiveStrength=e.emissiveIntensity,t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},NG=class{constructor(e){this.writer=e,this.name="EXT_materials_bump"}writeMaterial(e,t){if(!e.isMeshStandardMaterial||e.bumpScale===1&&!e.bumpMap)return;const i=this.writer,n=i.extensionsUsed,s={};if(e.bumpMap){const a={index:i.processTexture(e.bumpMap),texCoord:e.bumpMap.channel};i.applyTextureTransform(a,e.bumpMap),s.bumpTexture=a}s.bumpFactor=e.bumpScale,t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0}},kG=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(!e.isInstancedMesh)return;const i=this.writer,n=e,s=new Float32Array(n.count*3),a=new Float32Array(n.count*4),o=new Float32Array(n.count*3),l=new fe,c=new S,h=new $e,u=new S;for(let p=0;p<n.count;p++)n.getMatrixAt(p,l),l.decompose(c,h,u),c.toArray(s,p*3),h.toArray(a,p*4),u.toArray(o,p*3);const d={TRANSLATION:i.processAccessor(new Ze(s,3)),ROTATION:i.processAccessor(new Ze(a,4)),SCALE:i.processAccessor(new Ze(o,3))};n.instanceColor&&(d._COLOR_0=i.processAccessor(n.instanceColor)),t.extensions=t.extensions||{},t.extensions[this.name]={attributes:d},i.extensionsUsed[this.name]=!0,i.extensionsRequired[this.name]=!0}};Dd.Utils={GLTFWriter:PT,insertKeyframe:function(r,e){const i=r.getValueSize(),n=new r.TimeBufferType(r.times.length+1),s=new r.ValueBufferType(r.values.length+i),a=r.createInterpolant(new r.ValueBufferType(i));let o;if(r.times.length===0){n[0]=e;for(let l=0;l<i;l++)s[l]=0;o=0}else if(e<r.times[0]){if(Math.abs(r.times[0]-e)<.001)return 0;n[0]=e,n.set(r.times,1),s.set(a.evaluate(e),0),s.set(r.values,i),o=0}else if(e>r.times[r.times.length-1]){if(Math.abs(r.times[r.times.length-1]-e)<.001)return r.times.length-1;n[n.length-1]=e,n.set(r.times,0),s.set(r.values,0),s.set(a.evaluate(e),r.values.length),o=n.length-1}else for(let l=0;l<r.times.length;l++){if(Math.abs(r.times[l]-e)<.001)return l;if(r.times[l]<e&&r.times[l+1]>e){n.set(r.times.slice(0,l+1),0),n[l+1]=e,n.set(r.times.slice(l+1),l+2),s.set(r.values.slice(0,(l+1)*i),0),s.set(a.evaluate(e),(l+1)*i),s.set(r.values.slice((l+1)*i),(l+2)*i),o=l+1;break}}return r.times=n,r.values=s,o},mergeMorphTargetTracks:function(r,e){const t=[],i={},n=r.tracks;for(let s=0;s<n.length;++s){let a=n[s];const o=Et.parseTrackName(a.name),l=Et.findNode(e,o.nodeName);if(o.propertyName!=="morphTargetInfluences"||o.propertyIndex===void 0){t.push(a);continue}if(a.createInterpolant!==a.InterpolantFactoryMethodDiscrete&&a.createInterpolant!==a.InterpolantFactoryMethodLinear){if(a.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline)throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.");console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead."),a=a.clone(),a.setInterpolation(tc)}const c=l.morphTargetInfluences.length,h=l.morphTargetDictionary[o.propertyIndex];if(h===void 0)throw new Error("THREE.GLTFExporter: Morph target name not found: "+o.propertyIndex);let u;if(i[l.uuid]===void 0){u=a.clone();const p=new u.ValueBufferType(c*u.times.length);for(let m=0;m<u.times.length;m++)p[m*c+h]=u.values[m];u.name=(o.nodeName||"")+".morphTargetInfluences",u.values=p,i[l.uuid]=u,t.push(u);continue}const d=a.createInterpolant(new a.ValueBufferType(1));u=i[l.uuid];for(let p=0;p<u.times.length;p++)u.values[p*c+h]=d.evaluate(u.times[p]);for(let p=0;p<a.times.length;p++){const m=this.insertKeyframe(u,a.times[p]);u.values[m*c+h]=a.values[p]}}return r.tracks=t,r}};class DT extends Dd.Utils.GLTFWriter{constructor(){super(),this.TPAssetVersion=1,this.serializationMeta=Fr(),this._defaultMaterial=new Ya,this.json.asset.subversion=this.TPAssetVersion}serializeUserData(e,t){const i=e.userData,n={};i.__disposed&&console.error("Serializing a disposed object",e),Object.entries(i).forEach(([a,o])=>{(!o||typeof o=="function"||o.isObject3D||o.isTexture||o.isMaterial||o.assetType!=null||a.startsWith("_"))&&(n[a]=o,delete i[a])});const s=We.Serialize(i,this.serializationMeta);Object.entries(n).forEach(([a,o])=>{i[a]=o,delete n[a]}),e.userData=s,super.serializeUserData(e,t),e.userData=i}processObjects(e){e.length===1&&e[0]?.userData.rootSceneModelRoot?this.processScene(e[0]):super.processObjects(e)}processMaterial(e){if(this.cache.materials.has(e))return this.cache.materials.get(e);let t=e;(!t||t.isShaderMaterial)&&(t=this._defaultMaterial);const i=super.processMaterial(t);if(i===null)return console.error("GLTFWriter2: Unexpected error: Failed to process material",e),null;if(!e||t===e)return i;const n=JSON.stringify(this.json.materials[i]),s=JSON.parse(n),a=e.color?.isColor?e.color.toArray().concat([e.opacity]):null;a&&!a.every(l=>l===1)&&s.pbrMetallicRoughness&&(s.pbrMetallicRoughness.baseColorFactor=a),this.serializeUserData(e,s),this._invokeAll(l=>{l.writeMaterial&&l.writeMaterial(e,s)});const o=this.json.materials.push(s)-1;return this.cache.materials.set(e,o),o}processImageBlob(e,t){if(!e)return-1;const i=this.cache,n=this.options,s=this.pending,a=this.json,o=t.image;i.images.has(o)||i.images.set(o,{});const l=i.images.get(o),c=e.type+":flipY/"+t.flipY.toString();if(l[c]!==void 0)return l[c];a.images||(a.images=[]);const h={mimeType:e.type};n.binary===!0?s.push(new Promise(d=>{this.processBufferViewImage(e).then(p=>{h.bufferView=p,d()})})):s.push(dm(e).then(d=>{h.uri=d}));const u=a.images.push(h)-1;return l[c]=u,u}processSampler(e){return super.processSampler(e)}processTexture(e){const t=this.cache,i=this.json;if(t.textures.has(e))return t.textures.get(e);const n=e.source.data,s=e.userData.mimeType,a=!e.isRenderTargetTexture&&e.userData.rootPath&&typeof e.userData.rootPath=="string"&&Hc(e.userData.rootPath);a&&!this.options.exporterOptions.embedUrlImages&&(e.source.data&&(!this.options.exporterOptions.embedUrlImagePreviews||e.isDataTexture?e.source.data=null:e.source.data._savePreview=!0),delete e.userData.mimeType);const o=super.processTexture(e),l=i.textures[o];if(!l)return console.error("No texture def",o,e),o;if(a&&!this.options.exporterOptions.embedUrlImages){if(e.source.data?delete e.source.data._savePreview:e.source.data=n,e.userData.mimeType=s,!l)return console.error("textureDef is null",o,e),o;let c=e.userData.rootPath;const h=this.options.exporterOptions._basePath;if(h&&typeof c=="string"&&c.startsWith(h)&&(c=c.slice(h.length)),l.source>=0){const u=this.json.images[l.source];u.uri?console.warn("uri already set",u.uri):(u.uri=c,u.mimeType=s,u.extras||(u.extras={}),u.extras.flipY=e.flipY,u.extras.uri=c)}else l.source=this.processImageUri(e.image,c,e.flipY,s)}if(l.source<0)console.error("textureDef.source cannot be saved",l,e),delete l.source;else{const c=i.images?i.images[l.source]:null;c&&(c.extras||(c.extras={}),e.source&&(c.extras.uuid=e.source.uuid),c.extras.t_uuid=e.uuid)}return o}processImage(e,t,i,n="image/png"){return e?super.processImage(e,t,i,n,e._savePreview?32:void 0,e._savePreview?32:void 0):-1}processImageUri(e,t,i,n="image/png"){const s=this.cache,a=this.json;s.images.has(e)||s.images.set(e,{});const o=s.images.get(e),l=n+":flipY/"+i.toString();if(o[l]!==void 0)return o[l];a.images||(a.images=[]);const c={mimeType:n,uri:t,extras:{flipY:i}},h=a.images.push(c)-1;return o[l]=h,h}}const br=class br{};br.WebGiLightExtrasExtension="WEBGI_light_extras",br.Import=e=>({name:"__"+br.WebGiLightExtrasExtension,afterRoot:async t=>{(t.scenes||(t.scene?[t.scene]:[])).forEach(n=>{n.traverse(s=>{if(!s.isLight)return;const a=s.userData?.gltfExtensions?.[br.WebGiLightExtrasExtension];a&&(!s.shadow&&a.shadow&&console.error("Light has no shadow, cannot import",s,a),a.shadow&&s.shadow&&(a.shadow.bias!==void 0&&(s.shadow.bias=a.shadow.bias),a.shadow.normalBias!==void 0&&(s.shadow.normalBias=a.shadow.normalBias),a.shadow.radius!==void 0&&(s.shadow.radius=a.shadow.radius),a.shadow.mapSize!==void 0&&s.shadow.mapSize.fromArray(a.shadow.mapSize),a.shadow.camera!==void 0&&(s.shadow.camera=new Zp().parseObject(a.shadow.camera,{},{},{},{}))),delete s.userData.gltfExtensions[br.WebGiLightExtrasExtension])})})}}),br.Export=e=>({writeNode:(t,i)=>{if(!t?.isLight)return;i.extensions||(i.extensions={});const n={};t.shadow&&(n.shadow=t.shadow.toJSON()),Object.keys(n).length>0&&(i.extensions[br.WebGiLightExtrasExtension]=n,e.extensionsUsed[br.WebGiLightExtrasExtension]=!0)}}),br.Textures=void 0;let Bd=br;const cs=class cs{};cs.WebGiMaterialExtrasExtension="WEBGI_material_extras",cs.Import=e=>t=>({name:"__"+cs.WebGiMaterialExtrasExtension,afterRoot:async i=>{const n=i.scenes||(i.scene?[i.scene]:[]);for(const s of n){const a=s.userData?.gltfExtensions?.[cs.WebGiMaterialExtrasExtension],o=a?.resources?await e(a.resources):{};s.traverse(l=>{const c=l?.material;if(!c?.isMaterial)return;const h=c.userData?.gltfExtensions?.[cs.WebGiMaterialExtrasExtension];if(!h)return;h.emissiveIntensity!==void 0&&(c.emissiveIntensity=h.emissiveIntensity),h.fog!==void 0&&(c.fog=h.fog),h.flatShading!==void 0&&(c.flatShading=h.flatShading),h.blending!==void 0&&(c.blending=h.blending),h.side!==void 0&&(c.side=h.side),h.shadowSide!==void 0&&(c.shadowSide=h.shadowSide),h.depthFunc!==void 0&&(c.depthFunc=h.depthFunc),h.depthTest!==void 0&&(c.depthTest=h.depthTest),h.depthWrite!==void 0&&(c.depthWrite=h.depthWrite),h.colorWrite!==void 0&&(c.colorWrite=h.colorWrite),h.vertexColors!==void 0&&(c.vertexColors=h.vertexColors),h.alphaTest!==void 0&&(c.alphaTest=h.alphaTest),h.alphaHash!==void 0&&(c.alphaHash=h.alphaHash),h.envMapIntensity!==void 0&&(c.envMapIntensity=h.envMapIntensity),h.envMapRotation!==void 0&&Array.isArray(h.envMapRotation)&&c.envMapRotation?.fromArray&&c.envMapRotation.fromArray(h.envMapRotation),h.blendSrc!==void 0&&(c.blendSrc=h.blendSrc),h.blendDst!==void 0&&(c.blendDst=h.blendDst),h.blendEquation!==void 0&&(c.blendEquation=h.blendEquation),h.blendSrcAlpha!==void 0&&(c.blendSrcAlpha=h.blendSrcAlpha),h.blendDstAlpha!==void 0&&(c.blendDstAlpha=h.blendDstAlpha),h.blendEquationAlpha!==void 0&&(c.blendEquationAlpha=h.blendEquationAlpha),h.blendColor!==void 0&&c.blendColor!==void 0&&c.blendColor.setHex(h.blendColor),h.blendAlpha!==void 0&&(c.blendAlpha=h.blendAlpha),h.stencilWrite!==void 0&&(c.stencilWrite=h.stencilWrite),h.stencilWriteMask!==void 0&&(c.stencilWriteMask=h.stencilWriteMask),h.stencilFunc!==void 0&&(c.stencilFunc=h.stencilFunc),h.stencilRef!==void 0&&(c.stencilRef=h.stencilRef),h.stencilFuncMask!==void 0&&(c.stencilFuncMask=h.stencilFuncMask),h.stencilFail!==void 0&&(c.stencilFail=h.stencilFail),h.stencilZFail!==void 0&&(c.stencilZFail=h.stencilZFail),h.stencilZPass!==void 0&&(c.stencilZPass=h.stencilZPass),h.wireframe!==void 0&&(c.wireframe=h.wireframe),h.wireframeLinewidth!==void 0&&(c.wireframeLinewidth=h.wireframeLinewidth),h.wireframeLinecap!==void 0&&(c.wireframeLinecap=h.wireframeLinecap),h.wireframeLinejoin!==void 0&&(c.wireframeLinejoin=h.wireframeLinejoin),h.rotation!==void 0&&(c.rotation=h.rotation),h.linewidth!==void 0&&(c.linewidth=h.linewidth),h.worldUnits!==void 0&&(c.worldUnits=h.worldUnits),h.dashed!==void 0&&(c.dashed=h.dashed),h.dashSize!==void 0&&(c.dashSize=h.dashSize),h.dashScale!==void 0&&(c.dashScale=h.dashScale),h.dashOffset!==void 0&&(c.dashOffset=h.dashOffset),h.gapSize!==void 0&&(c.gapSize=h.gapSize),h.resolution!==void 0&&c.resolution&&c.resolution.fromArray&&c.resolution.fromArray(h.resolution),h.polygonOffset!==void 0&&(c.polygonOffset=h.polygonOffset),h.polygonOffsetFactor!==void 0&&(c.polygonOffsetFactor=h.polygonOffsetFactor),h.polygonOffsetUnits!==void 0&&(c.polygonOffsetUnits=h.polygonOffsetUnits),h.dithering!==void 0&&(c.dithering=h.dithering),h.alphaToCoverage!==void 0&&(c.alphaToCoverage=h.alphaToCoverage),h.premultipliedAlpha!==void 0&&(c.premultipliedAlpha=h.premultipliedAlpha),h.toneMapped!==void 0&&(c.toneMapped=h.toneMapped),h.normalScale!==void 0&&c.normalScale!==void 0&&(Array.isArray(h.normalScale)?c.normalScale.fromArray(h.normalScale):typeof h.normalScale=="number"?c.normalScale.set(h.normalScale,h.normalScale):console.warn("normalScale is not an array or number",h.normalScale)),h.reflectivity!==void 0&&(c.reflectivity=h.reflectivity),Object.entries(h).forEach(([d,p])=>{d.startsWith("_")||p&&p.resource&&typeof p.resource=="string"&&(c[d]=We.Deserialize(p,c[d],o))}),delete c.userData.gltfExtensions[cs.WebGiMaterialExtrasExtension];const u=t.json?.asset?.version?parseFloat(t.json?.asset?.version):null;(c.userData.legacyBumpScale||u&&u<=2)&&c?.bumpScale!==void 0&&c?.bumpMap&&c.defines&&(console.warn("MaterialManager: Old format material loaded, bump map might be incorrect.",c,c.bumpScale),c.defines.BUMP_MAP_SCALE_LEGACY="1",c.userData.legacyBumpScale=!0,c.needsUpdate=!0)}),a&&delete s.userData.gltfExtensions[cs.WebGiMaterialExtrasExtension]}}}),cs.Export=e=>({writeMaterial(t,i){if(!t?.isMaterial)return;i.extensions||(i.extensions={});const n={};t.fog!==void 0&&t.fog!==si.MaterialProperties.fog&&(n.fog=t.fog),t.flatShading!==void 0&&t.flatShading!==si.MaterialProperties.flatShading&&(n.flatShading=t.flatShading),t.blending!==void 0&&t.blending!==It.blending&&(n.blending=t.blending),t.side!==void 0&&t.side!==Zi&&(n.side=t.side),t.shadowSide!==void 0&&t.shadowSide!==It.shadowSide&&(n.shadowSide=t.shadowSide),t.depthFunc!==void 0&&t.depthFunc!==It.depthFunc&&(n.depthFunc=t.depthFunc),t.depthTest!==void 0&&t.depthTest!==It.depthTest&&(n.depthTest=t.depthTest),t.depthWrite!==void 0&&t.depthWrite!==It.depthWrite&&(n.depthWrite=t.depthWrite),t.colorWrite!==void 0&&t.colorWrite!==It.colorWrite&&(n.colorWrite=t.colorWrite),t.vertexColors!==void 0&&t.vertexColors!==It.vertexColors&&(n.vertexColors=t.vertexColors),t.alphaTest!==void 0&&t.alphaTest!==It.alphaTest&&(n.alphaTest=t.alphaTest),t.alphaHash!==void 0&&t.alphaHash!==It.alphaHash&&(n.alphaHash=t.alphaHash),t.envMapIntensity!==void 0&&t.envMapIntensity!==si.MaterialProperties.envMapIntensity&&(n.envMapIntensity=t.envMapIntensity),t.envMapRotation!==void 0&&!t.envMapRotation.equals(si.MaterialProperties.envMapRotation)&&(n.envMapRotation=t.envMapRotation.toArray()),t.blendSrc!==void 0&&t.blendSrc!==It.blendSrc&&(n.blendSrc=t.blendSrc),t.blendDst!==void 0&&t.blendDst!==It.blendDst&&(n.blendDst=t.blendDst),t.blendEquation!==void 0&&t.blendEquation!==It.blendEquation&&(n.blendEquation=t.blendEquation),t.blendSrcAlpha!==void 0&&t.blendSrcAlpha!==It.blendSrcAlpha&&(n.blendSrcAlpha=t.blendSrcAlpha),t.blendDstAlpha!==void 0&&t.blendDstAlpha!==It.blendDstAlpha&&(n.blendDstAlpha=t.blendDstAlpha),t.blendEquationAlpha!==void 0&&t.blendEquationAlpha!==It.blendEquationAlpha&&(n.blendEquationAlpha=t.blendEquationAlpha),t.blendColor!==void 0&&t.blendColor!==It.blendColor&&(n.blendColor=t.blendColor.getHex()),t.blendAlpha!==void 0&&t.blendAlpha!==It.blendAlpha&&(n.blendAlpha=t.blendAlpha),t.stencilWrite!==void 0&&t.stencilWrite!==It.stencilWrite&&(n.stencilWrite=t.stencilWrite),t.stencilWriteMask!==void 0&&t.stencilWriteMask!==It.stencilWriteMask&&(n.stencilWriteMask=t.stencilWriteMask),t.stencilFunc!==void 0&&t.stencilFunc!==It.stencilFunc&&(n.stencilFunc=t.stencilFunc),t.stencilRef!==void 0&&t.stencilRef!==It.stencilRef&&(n.stencilRef=t.stencilRef),t.stencilFuncMask!==void 0&&t.stencilFuncMask!==It.stencilFuncMask&&(n.stencilFuncMask=t.stencilFuncMask),t.stencilFail!==void 0&&t.stencilFail!==It.stencilFail&&(n.stencilFail=t.stencilFail),t.stencilZFail!==void 0&&t.stencilZFail!==It.stencilZFail&&(n.stencilZFail=t.stencilZFail),t.stencilZPass!==void 0&&t.stencilZPass!==It.stencilZPass&&(n.stencilZPass=t.stencilZPass),t.wireframe!==void 0&&t.wireframe!==si.MaterialProperties.wireframe&&(n.wireframe=t.wireframe),t.wireframeLinewidth!==void 0&&t.wireframeLinewidth!==si.MaterialProperties.wireframeLinewidth&&(n.wireframeLinewidth=t.wireframeLinewidth),t.wireframeLinecap!==void 0&&t.wireframeLinecap!==si.MaterialProperties.wireframeLinecap&&(n.wireframeLinecap=t.wireframeLinecap),t.wireframeLinejoin!==void 0&&t.wireframeLinejoin!==si.MaterialProperties.wireframeLinejoin&&(n.wireframeLinejoin=t.wireframeLinejoin),t.rotation!==void 0&&(n.rotation=t.rotation),t.linewidth!==void 0&&t.linewidth!==ji.MaterialProperties.linewidth&&(n.linewidth=t.linewidth),t.worldUnits!==void 0&&t.worldUnits!==ji.MaterialProperties.worldUnits&&(n.worldUnits=t.worldUnits),t.dashed!==void 0&&t.dashed!==ji.MaterialProperties.dashed&&(n.dashed=t.dashed),t.dashSize!==void 0&&t.dashSize!==ji.MaterialProperties.dashSize&&(n.dashSize=t.dashSize),t.dashScale!==void 0&&t.dashScale!==ji.MaterialProperties.dashScale&&(n.dashScale=t.dashScale),t.dashOffset!==void 0&&t.dashOffset!==ji.MaterialProperties.dashOffset&&(n.dashOffset=t.dashOffset),t.gapSize!==void 0&&t.gapSize!==ji.MaterialProperties.gapSize&&(n.gapSize=t.gapSize),t.polygonOffset!==void 0&&t.polygonOffset!==It.polygonOffset&&(n.polygonOffset=t.polygonOffset),t.polygonOffsetFactor!==void 0&&t.polygonOffsetFactor!==It.polygonOffsetFactor&&(n.polygonOffsetFactor=t.polygonOffsetFactor),t.polygonOffsetUnits!==void 0&&t.polygonOffsetUnits!==It.polygonOffsetUnits&&(n.polygonOffsetUnits=t.polygonOffsetUnits),t.dithering!==void 0&&t.dithering!==It.dithering&&(n.dithering=t.dithering),t.alphaToCoverage!==void 0&&t.alphaToCoverage!==It.alphaToCoverage&&(n.alphaToCoverage=t.alphaToCoverage),t.premultipliedAlpha!==void 0&&t.premultipliedAlpha!==It.premultipliedAlpha&&(n.premultipliedAlpha=t.premultipliedAlpha),t.toneMapped!==void 0&&t.toneMapped!==It.toneMapped&&(n.toneMapped=t.toneMapped),t.normalScale!==void 0&&t.normalScale.isVector2&&(t.normalScale.x!==si.MaterialProperties.normalScale.x||t.normalScale.y!==si.MaterialProperties.normalScale.y)&&(n.normalScale=[t.normalScale.x,t.normalScale.y]);const s=this.materialExternalResources[t.uuid];s&&Object.entries(s).forEach(([a,o])=>{if(a.startsWith("_"))return;let l=!1;o?.userData&&o.userData.embedUrlImagePreviews===void 0&&(o.userData.embedUrlImagePreviews=e.options.exporterOptions?.embedUrlImagePreviews,l=!0),n[a]=We.Serialize(o,this.serializedMeta),o?.userData&&l&&delete o.userData.embedUrlImagePreviews}),Object.keys(n).length>0&&(i.extensions[cs.WebGiMaterialExtrasExtension]=n,e.extensionsUsed[cs.WebGiMaterialExtrasExtension]=!0)},materialExternalResources:{},serializedMeta:{images:{},textures:{}},beforeParse(t){if(this.materialExternalResources={},!e.options.externalImagesInExtras)return;const i=[];(Array.isArray(t)?t:[t]).forEach(n=>{n?.traverse(s=>{s&&s.material?.isMaterial&&i.push(s.material)})}),i.forEach(n=>{n&&(this.materialExternalResources[n.uuid]||(this.materialExternalResources[n.uuid]={}),this.materialExternalResources[n.uuid].__materialRef=n,Object.entries(n).forEach(([s,a])=>{s.startsWith("_")||a&&a.isTexture&&a.userData.rootPath&&Hc(a.userData.rootPath)&&(n[s]=null,this.materialExternalResources[n.uuid][s]=a)}))})},afterParse(t){const i=Object.values(this.materialExternalResources);if(i.length<1)return;i.forEach(s=>{const a=s.__materialRef;a&&(Object.entries(s).forEach(([o,l])=>{o.startsWith("_")||l&&(a[o]=l)}),delete this.materialExternalResources[a.uuid])});const n=e.json.scenes[e.json.scene||0];n.extensions||(n.extensions={}),n.extensions[cs.WebGiMaterialExtrasExtension]={resources:this.serializedMeta},e.extensionsUsed[cs.WebGiMaterialExtrasExtension]=!0}}),cs.Textures=void 0;let Ld=cs;const Nh=class Nh{};Nh.WebGiMaterialsAlphaMapExtension="WEBGI_materials_alphamap",Nh.Import=e=>new GG(e),Nh.Export=e=>new zG(e),Nh.Textures={alphaTexture:"G"};let xl=Nh;class GG{constructor(e){this.parser=e,this.name=xl.WebGiMaterialsAlphaMapExtension}async extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.alphaTexture!==void 0&&s.push(i.assignTexture(t,"alphaMap",a.alphaTexture)),Promise.all(s)}}class zG{constructor(e){this.writer=e,this.name=xl.WebGiMaterialsAlphaMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||!e.alphaMap)return;const i=this.writer,n=i.extensionsUsed,s={};if(e.alphaMap&&i.checkEmptyMap(e.alphaMap)){const a={index:i.processTexture(e.alphaMap)};i.applyTextureTransform(a,e.alphaMap),s.alphaTexture=a}Object.keys(s)&&(t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0)}}const kh=class kh{};kh.WebGiMaterialsBumpMapExtension="WEBGI_materials_bumpmap",kh.Import=e=>new VG(e),kh.Export=e=>new HG(e),kh.Textures={bumpTexture:"R"};let rh=kh;class VG{constructor(e){this.parser=e,this.name=rh.WebGiMaterialsBumpMapExtension}async extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.bumpScale!==void 0&&(t.bumpScale=a.bumpScale),a.bumpTexture!==void 0&&s.push(i.assignTexture(t,"bumpMap",a.bumpTexture)),Promise.all(s)}}class HG{constructor(e){this.writer=e,this.name=rh.WebGiMaterialsBumpMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||e.bumpScale===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(e.bumpScale!==si.MaterialProperties.bumpScale&&(s.bumpScale=e.bumpScale),e.bumpMap&&i.checkEmptyMap(e.bumpMap)){const a={index:i.processTexture(e.bumpMap)};i.applyTextureTransform(a,e.bumpMap),s.bumpTexture=a}Object.keys(s)&&(t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0)}}const Gh=class Gh{};Gh.WebGiMaterialsDisplacementMapExtension="WEBGI_materials_displacementmap",Gh.Import=e=>new QG(e),Gh.Export=e=>new jG(e),Gh.Textures={displacementTexture:"R"};let Sl=Gh;class QG{constructor(e){this.parser=e,this.name=Sl.WebGiMaterialsDisplacementMapExtension}async extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.displacementScale!==void 0&&(t.displacementScale=a.displacementScale),a.displacementBias!==void 0&&(t.displacementBias=a.displacementBias),a.displacementTexture!==void 0&&s.push(i.assignTexture(t,"displacementMap",a.displacementTexture)),Promise.all(s)}}class jG{constructor(e){this.writer=e,this.name=Sl.WebGiMaterialsDisplacementMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||e.displacementScale===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(e.displacementScale!==si.MaterialProperties.displacementScale&&(s.displacementScale=e.displacementScale),e.displacementBias!==si.MaterialProperties.displacementBias&&(s.displacementBias=e.displacementBias),e.displacementMap&&i.checkEmptyMap(e.displacementMap)){const a={index:i.processTexture(e.displacementMap)};i.applyTextureTransform(a,e.displacementMap),s.displacementTexture=a}Object.keys(s)&&(t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0)}}const zh=class zh{};zh.WebGiMaterialsLightMapExtension="WEBGI_materials_lightmap",zh.Import=e=>new WG(e),zh.Export=e=>new qG(e),zh.Textures={lightMapTexture:"RGB"};let El=zh;class WG{constructor(e){this.parser=e,this.name=El.WebGiMaterialsLightMapExtension}async extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.lightMapIntensity!==void 0&&(t.lightMapIntensity=a.lightMapIntensity),a.lightMapTexture!==void 0&&s.push(i.assignTexture(t,"lightMap",a.lightMapTexture)),Promise.all(s)}}class qG{constructor(e){this.writer=e,this.name=El.WebGiMaterialsLightMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||e.lightMapIntensity===0)return;const i=this.writer,n=i.extensionsUsed,s={};if(e.lightMapIntensity!==si.MaterialProperties.lightMapIntensity&&(s.lightMapIntensity=e.lightMapIntensity),e.lightMap&&i.checkEmptyMap(e.lightMap)){const a={index:i.processTexture(e.lightMap)};i.applyTextureTransform(a,e.lightMap),s.lightMapTexture=a}Object.keys(s)&&(t.extensions=t.extensions||{},t.extensions[this.name]=s,n[this.name]=!0)}}const wr=class wr{};wr.WebGiObject3DExtrasExtension="WEBGI_object3d_extras",wr.Import=e=>({name:"__"+wr.WebGiObject3DExtrasExtension,afterRoot:async t=>{(t.scenes||(t.scene?[t.scene]:[])).forEach(n=>{n.traverse(s=>{if(!s||!s.isObject3D)return;const a=s.userData?.gltfExtensions?.[wr.WebGiObject3DExtrasExtension];if(!a){s.isLight&&!s.isAmbientLight&&(s.castShadow=!0);return}s.castShadow=a.castShadow??!1,s.receiveShadow=a.receiveShadow??!1,a.visible!==void 0&&(s.visible=a.visible),a.frustumCulled!==void 0&&(s.frustumCulled=a.frustumCulled),a.renderOrder!==void 0&&(s.renderOrder=a.renderOrder),a.layers!==void 0&&(s.layers.mask=a.layers),s.userData.__keepShadowDef=!0,delete s.userData.gltfExtensions[wr.WebGiObject3DExtrasExtension]})})}}),wr.Export=e=>({writeNode:(t,i)=>{if(!t?.isObject3D)return;i.extensions||(i.extensions={});const n={};t.castShadow!==void 0&&t.castShadow&&(n.castShadow=t.castShadow),t.receiveShadow!==void 0&&t.receiveShadow&&(n.receiveShadow=t.receiveShadow),t.visible===!1&&(n.visible=!1),t.frustumCulled===!1&&(n.frustumCulled=!1),t.renderOrder!==0&&(n.renderOrder=t.renderOrder),t.layers.mask!==1&&(n.layers=t.layers.mask),t.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),Object.keys(n).length>0&&(i.extensions[wr.WebGiObject3DExtrasExtension]=n,e.extensionsUsed[wr.WebGiObject3DExtrasExtension]=!0)}}),wr.Textures=void 0;let Od=wr;class RT extends ti{constructor(e){super(e),this.type=Yt}async loadAsync(e,t){const i=await this.parseAsync(e,t,!1),n=new Vn(i.data,i.width,i.height,qt,this.type);return n.needsUpdate=!0,n.flipY=!0,n.colorSpace=Ct,n.minFilter=at,n.magFilter=at,n.source.data.complete=!0,n}async parseAsync(e,t,i=!1){let n=!1;if(!e.startsWith("data:")&&!e.startsWith("blob:")){this.responseType="blob";const l=await super.loadAsync(e,t);e=URL.createObjectURL(l),n=!0}const s=await DS(e);n&&URL.revokeObjectURL(e);let a=Uint8Array;return this.type===Yt?a=Uint16Array:this.type===Ut&&(a=Float32Array),{data:XG(s.data,4,a,i),width:s.width,height:s.height}}setDataType(e){return this.type=e,this}}function XG(r,e=3,t=Uint16Array,i=!1){let n;const s=r.byteLength>>2,a=new t(s*e);for(let o=0;o<s;o++)n=Math.pow(2,r[o*4+3]-136),i?(a[o*e]=Math.min(r[o*4]*n,65504),a[o*e+1]=Math.min(r[o*4+1]*n,65504),a[o*e+2]=Math.min(r[o*4+2]*n,65504)):(a[o*e]=zn.toHalfFloat(Math.min(r[o*4]*n,65504)),a[o*e+1]=zn.toHalfFloat(Math.min(r[o*4+1]*n,65504)),a[o*e+2]=zn.toHalfFloat(Math.min(r[o*4+2]*n,65504))),e===4&&(a[o*e+3]=zn.toHalfFloat(1));return a}const of=class of{static async ImportViewerConfig(e,t,i,n){if(!n){const l=e.json.scenes||[];if(l.length!==1){for(const c of l){const h=l.indexOf(c);await this.ImportViewerConfig(e,t,h>=0?[i[h]]:i,c)}return{}}n=l[0]}const s=i.length>0?i[0]:void 0,a=n.extensions?.[this.ViewerConfigGLTFExtension];if(!a)return{};const o={type:"ThreeViewer",version:"0",plugins:[],assetType:"config",...a};return o.resources&&(o.resources=await this.ImportResources(o.resources,e,t)),s&&(s.importedViewerConfig=o),o}static async ImportResources(e,t,i){if(e.__isLoadedResources)return e;await this._parseArrayBuffers(e,t);const n=await this._parseExtraResources(e,t,i);return await i.loadConfigResources(e||{},n)}static async _parseExtraResources(e,t,i){const n={textures:{},materials:{}};if(e.textures&&t.json.textures)for(const[s,a]of[...Object.entries(e.textures)]){if(a.uuid||!s)continue;delete e.textures[s];const o=t.json.textures.findIndex(l=>l.extras?.uuid===s||t.json.samplers?.[l.sampler]?.extras?.uuid===s||t.json.images?.[l.source]?.extras?.t_uuid===s);o>=0&&(n.textures[s]=await t.getDependency("texture",o))}if(e.materials&&t.json.materials)for(const[s,a]of[...Object.entries(e.materials)]){if(a.uuid||!s)continue;delete e.materials[s];const o=t.json.materials.findIndex(l=>l.extras?.uuid===s);if(o>=0){const l=await t.getDependency("material",o);n.materials[s]=i.assetManager.materials.convertToIMaterial(l)}}return n}static async _parseArrayBuffers(e,t){const i=[];Object.values(e).forEach(n=>{Object.values(n).forEach(s=>{s.url&&(s.url.type==="Uint16Array"&&s.url.data&&i.push(s.url),s.url.type==="Uint8Array"&&s.url.data&&i.push(s.url))})});for(const n of i){const s=n.data.image,a=t.json.images[s],o=await t.getDependency("bufferView",a.bufferView);if(a.mimeType.startsWith("image/")&&n.type==="Uint16Array"&&n.encoding==="rgbe"){const l=new Blob([o]);let c=URL.createObjectURL(l);const h=n.encodingVersion||1;h<2&&(c="data:image/png;base64,"+btoa(await l.text())),n.data=(await new RT().parseAsync(c,void 0,h<3)).data,URL.revokeObjectURL(c),delete n.encoding,delete n.encodingVersion}else n.data=o}}static ExportViewerConfig(e,t){const n=Object.entries(t.serializationMeta).reduce((l,c)=>l+(c[0].startsWith("_")?0:Object.keys(c[1]).length),0)?t.serializationMeta:void 0,s=e.toJSON(!0,void 0,n),a=t.json.scenes[t.json.scene||0];a.extensions||(a.extensions={}),t.extensionsUsed[this.ViewerConfigGLTFExtension]=!0,a.extensions[this.ViewerConfigGLTFExtension]=s;const o=s.resources;if(o&&(of.BundleExtraResources(t.json,o),of.BundleArrayBuffers(o,t),n))return delete s.resources,o}static BundleArrayBuffers(e,t){const i=[];Object.entries(e).forEach(([n,s])=>{n.startsWith("_")||s&&Object.values(s).forEach(a=>{a.url&&(a.url.type==="Uint16Array"&&a.url.data&&(a.url.data instanceof Uint16Array||(a.url.data=new Uint16Array(a.url.data)),i.push(a.url)),a.url.type==="Uint8Array"&&a.url.data&&(a.url.data instanceof Uint8Array||(a.url.data=new Uint8Array(a.url.data)),i.push(a.url)))})});for(const n of i){let s="application/octet-stream";if(n.mimeType&&(s=n.mimeType),t.options.exporterOptions.encodeUint16Rgbe&&n.type==="Uint16Array"&&n.width>0&&n.height>0){const u=AE(n.data,4),d=new ImageData(u,n.width,n.height),p=fy.getDataURL(d,!0).split(",")[1];s="image/png",n.data=Uint8Array.from(atob(p),m=>m.charCodeAt(0)),n.encoding="rgbe",n.encodingVersion=3}t.json.images||(t.json.images=[]);const o={mimeType:s},l=t.json.images.push(o)-1,c=n.data;o.bufferView=t.processBufferViewImageBuffer(c),n.data={image:l}}}static BundleExtraResources(e,t){const{textures:i,materials:n}=t;e.textures&&e.samplers&&e.images&&i&&[...Object.entries(i)].forEach(([s,a])=>{e.textures.find(l=>l.extras?.uuid===s||e.samplers[l.sampler]?.extras?.uuid===s||e.images[l.source]?.extras?.t_uuid===s)&&(a.image&&t.images&&t.images[a.image]&&delete t.images[a.image],i[s]={})}),e.materials&&n&&[...Object.entries(n)].forEach(([s,a])=>{e.materials.find(l=>l.extras?.uuid===s)&&(n[s]={})})}};of.ViewerConfigGLTFExtension="WEBGI_viewer";let ho=of;class Mt extends oi{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new ZG(t)}),this.register(function(t){return new ez(t)}),this.register(function(t){return new cz(t)}),this.register(function(t){return new hz(t)}),this.register(function(t){return new uz(t)}),this.register(function(t){return new iz(t)}),this.register(function(t){return new nz(t)}),this.register(function(t){return new sz(t)}),this.register(function(t){return new rz(t)}),this.register(function(t){return new JG(t)}),this.register(function(t){return new az(t)}),this.register(function(t){return new tz(t)}),this.register(function(t){return new lz(t)}),this.register(function(t){return new oz(t)}),this.register(function(t){return new $G(t)}),this.register(function(t){return new dz(t)}),this.register(function(t){return new fz(t)})}load(e,t,i,n){const s=this;let a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){const c=Ps.extractUrlBase(e);a=Ps.resolveURL(c,this.path)}else a=Ps.extractUrlBase(e);this.manager.itemStart(e);const o=function(c){n?n(c):console.error(c),s.manager.itemError(e),s.manager.itemEnd(e)},l=new ti(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{s.parse(c,a,function(h){t(h),s.manager.itemEnd(e)},o,e)}catch(h){o(h)}},i,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setDDSLoader(){throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".')}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,n,s){let a;const o={},l={},c=new TextDecoder;if(typeof e=="string")a=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===BT){try{o[zt.KHR_BINARY_GLTF]=new c0(e)}catch(d){n&&n(d);return}a=JSON.parse(o[zt.KHR_BINARY_GLTF].content)}else a=JSON.parse(c.decode(e));else a=e;if(a.asset===void 0||a.asset.version[0]<2){n&&n(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const h=new NT(a,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});h.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u<this.pluginCallbacks.length;u++){const d=this.pluginCallbacks[u](h);d.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),l[d.name]=d,o[d.name]=!0}if(a.extensionsUsed)for(let u=0;u<a.extensionsUsed.length;++u){const d=a.extensionsUsed[u],p=a.extensionsRequired||[];switch(d){case zt.KHR_MATERIALS_UNLIT:o[d]=new KG;break;case zt.KHR_DRACO_MESH_COMPRESSION:o[d]=new pz(a,this.dracoLoader);break;case zt.KHR_TEXTURE_TRANSFORM:o[d]=new mz;break;case zt.KHR_MESH_QUANTIZATION:o[d]=new gz;break;default:p.indexOf(d)>=0&&l[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}h.setExtensions(o),h.setPlugins(l),h.parse(i,n)}parseAsync(e,t){const i=this;return new Promise(function(n,s){i.parse(e,t,n,s)})}}Mt.ObjectConstructors={DirectionalLight:sl,PointLight:nl,SpotLight:zc,MeshStandardMaterial:Ya,MeshBasicMaterial:is,MeshPhysicalMaterial:Jo,LineBasicMaterial:Mi,PointsMaterial:Tr,PerspectiveCamera:zi,OrthographicCamera:Mr};function YG(){let r={};return{get:function(e){return r[e]},add:function(e,t){r[e]=t},remove:function(e){delete r[e]},removeAll:function(){r={}}}}const zt={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class $G{constructor(e){this.parser=e,this.name=zt.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let i=0,n=t.length;i<n;i++){const s=t[i];s.extensions&&s.extensions[this.name]&&s.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,s.extensions[this.name].light)}}_loadLight(e){const t=this.parser,i="light:"+e;let n=t.cache.get(i);if(n)return n;const s=t.json,l=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e];let c;const h=new ee(16777215);l.color!==void 0&&h.setRGB(l.color[0],l.color[1],l.color[2],Bt);const u=l.range!==void 0?l.range:0;switch(l.type){case"directional":c=new Mt.ObjectConstructors.DirectionalLight(h),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new Mt.ObjectConstructors.PointLight(h),c.distance=u;break;case"spot":c=new Mt.ObjectConstructors.SpotLight(h),c.distance=u,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,c.angle=l.spot.outerConeAngle,c.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return c.position.set(0,0,0),c.decay=2,hr(c,l),l.intensity!==void 0&&(c.intensity=l.intensity),c.name=t.createUniqueName(l.name||"light_"+e),n=Promise.resolve(c),t.cache.add(i,n),n}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,i=this.parser,s=i.json.nodes[e],o=(s.extensions&&s.extensions[this.name]||{}).light;return o===void 0?null:this._loadLight(o).then(function(l){return i._getNodeRef(t.cache,o,l)})}}class KG{constructor(){this.name=zt.KHR_MATERIALS_UNLIT}getMaterialType(){return Mt.ObjectConstructors.MeshBasicMaterial}extendParams(e,t,i){const n=[];e.color=new ee(1,1,1),e.opacity=1;const s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){const a=s.baseColorFactor;e.color.setRGB(a[0],a[1],a[2],Bt),e.opacity=a[3]}s.baseColorTexture!==void 0&&n.push(i.assignTexture(e,"map",s.baseColorTexture,Ct))}return Promise.all(n)}}class JG{constructor(e){this.parser=e,this.name=zt.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=n.extensions[this.name].emissiveStrength;return s!==void 0&&(t.emissiveIntensity=s),Promise.resolve()}}class ZG{constructor(e){this.parser=e,this.name=zt.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:Mt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];if(a.clearcoatFactor!==void 0&&(t.clearcoat=a.clearcoatFactor),a.clearcoatTexture!==void 0&&s.push(i.assignTexture(t,"clearcoatMap",a.clearcoatTexture)),a.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=a.clearcoatRoughnessFactor),a.clearcoatRoughnessTexture!==void 0&&s.push(i.assignTexture(t,"clearcoatRoughnessMap",a.clearcoatRoughnessTexture)),a.clearcoatNormalTexture!==void 0&&(s.push(i.assignTexture(t,"clearcoatNormalMap",a.clearcoatNormalTexture)),a.clearcoatNormalTexture.scale!==void 0)){const o=a.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new K(o,o)}return Promise.all(s)}}class ez{constructor(e){this.parser=e,this.name=zt.KHR_MATERIALS_DISPERSION}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:Jo}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=n.extensions[this.name];return t.dispersion=s.dispersion!==void 0?s.dispersion:0,Promise.resolve()}}class tz{constructor(e){this.parser=e,this.name=zt.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:Mt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.iridescenceFactor!==void 0&&(t.iridescence=a.iridescenceFactor),a.iridescenceTexture!==void 0&&s.push(i.assignTexture(t,"iridescenceMap",a.iridescenceTexture)),a.iridescenceIor!==void 0&&(t.iridescenceIOR=a.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),a.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=a.iridescenceThicknessMinimum),a.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=a.iridescenceThicknessMaximum),a.iridescenceThicknessTexture!==void 0&&s.push(i.assignTexture(t,"iridescenceThicknessMap",a.iridescenceThicknessTexture)),Promise.all(s)}}class iz{constructor(e){this.parser=e,this.name=zt.KHR_MATERIALS_SHEEN}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:Mt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[];t.sheenColor=new ee(0,0,0),t.sheenRoughness=0,t.sheen=1;const a=n.extensions[this.name];if(a.sheenColorFactor!==void 0){const o=a.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],Bt)}return a.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=a.sheenRoughnessFactor),a.sheenColorTexture!==void 0&&s.push(i.assignTexture(t,"sheenColorMap",a.sheenColorTexture,Ct)),a.sheenRoughnessTexture!==void 0&&s.push(i.assignTexture(t,"sheenRoughnessMap",a.sheenRoughnessTexture)),n.extras&&n.extras.sheenFactor!==void 0&&(t.sheen=n.extras.sheenFactor,delete n.extras.sheenFactor),Promise.all(s)}}class nz{constructor(e){this.parser=e,this.name=zt.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:Mt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.transmissionFactor!==void 0&&(t.transmission=a.transmissionFactor),a.transmissionTexture!==void 0&&s.push(i.assignTexture(t,"transmissionMap",a.transmissionTexture)),Promise.all(s)}}class sz{constructor(e){this.parser=e,this.name=zt.KHR_MATERIALS_VOLUME}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:Mt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];t.thickness=a.thicknessFactor!==void 0?a.thicknessFactor:0,a.thicknessTexture!==void 0&&s.push(i.assignTexture(t,"thicknessMap",a.thicknessTexture)),t.attenuationDistance=a.attenuationDistance||1/0;const o=a.attenuationColor||[1,1,1];return t.attenuationColor=new ee().setRGB(o[0],o[1],o[2],Bt),Promise.all(s)}}class rz{constructor(e){this.parser=e,this.name=zt.KHR_MATERIALS_IOR}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:Mt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=n.extensions[this.name];return t.ior=s.ior!==void 0?s.ior:1.5,Promise.resolve()}}class az{constructor(e){this.parser=e,this.name=zt.KHR_MATERIALS_SPECULAR}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:Mt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];t.specularIntensity=a.specularFactor!==void 0?a.specularFactor:1,a.specularTexture!==void 0&&s.push(i.assignTexture(t,"specularIntensityMap",a.specularTexture));const o=a.specularColorFactor||[1,1,1];return t.specularColor=new ee().setRGB(o[0],o[1],o[2],Bt),a.specularColorTexture!==void 0&&s.push(i.assignTexture(t,"specularColorMap",a.specularColorTexture,Ct)),Promise.all(s)}}class oz{constructor(e){this.parser=e,this.name=zt.EXT_MATERIALS_BUMP}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:Mt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return t.bumpScale=a.bumpFactor!==void 0?a.bumpFactor:1,a.bumpTexture!==void 0&&s.push(i.assignTexture(t,"bumpMap",a.bumpTexture)),Promise.all(s)}}class lz{constructor(e){this.parser=e,this.name=zt.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const i=this.parser.json.materials[e];return!i.extensions||!i.extensions[this.name]?null:Mt.ObjectConstructors.MeshPhysicalMaterial}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const s=[],a=n.extensions[this.name];return a.anisotropyStrength!==void 0&&(t.anisotropy=a.anisotropyStrength),a.anisotropyRotation!==void 0&&(t.anisotropyRotation=a.anisotropyRotation),a.anisotropyTexture!==void 0&&s.push(i.assignTexture(t,"anisotropyMap",a.anisotropyTexture)),Promise.all(s)}}class cz{constructor(e){this.parser=e,this.name=zt.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,i=t.json,n=i.textures[e];if(!n.extensions||!n.extensions[this.name])return null;const s=n.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(i.extensionsRequired&&i.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,a)}}class hz{constructor(e){this.parser=e,this.name=zt.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,i=this.parser,n=i.json,s=n.textures[e];if(!s.extensions||!s.extensions[t])return null;const a=s.extensions[t],o=n.images[a.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return this.detectSupport().then(function(c){if(c)return i.loadTextureImage(e,a.source,l);if(n.extensionsRequired&&n.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return i.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class uz{constructor(e){this.parser=e,this.name=zt.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,i=this.parser,n=i.json,s=n.textures[e];if(!s.extensions||!s.extensions[t])return null;const a=s.extensions[t],o=n.images[a.source];let l=i.textureLoader;if(o.uri){const c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return this.detectSupport().then(function(c){if(c)return i.loadTextureImage(e,a.source,l);if(n.extensionsRequired&&n.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return i.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class dz{constructor(e){this.name=zt.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){const n=i.extensions[this.name],s=this.parser.getDependency("buffer",n.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(o){const l=n.byteOffset||0,c=n.byteLength||0,h=n.count,u=n.byteStride,d=new Uint8Array(o,l,c);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(h,u,d,n.mode,n.filter).then(function(p){return p.buffer}):a.ready.then(function(){const p=new ArrayBuffer(h*u);return a.decodeGltfBuffer(new Uint8Array(p),h,u,d,n.mode,n.filter),p})})}else return null}}class fz{constructor(e){this.name=zt.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;const n=t.meshes[i.mesh];for(const c of n.primitives)if(c.mode!==Hs.TRIANGLES&&c.mode!==Hs.TRIANGLE_STRIP&&c.mode!==Hs.TRIANGLE_FAN&&c.mode!==void 0)return null;const a=i.extensions[this.name].attributes,o=[],l={};for(const c in a)o.push(this.parser.getDependency("accessor",a[c]).then(h=>(l[c]=h,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{const h=c.pop(),u=h.isGroup?h.children:[h],d=c[0].count,p=[];for(const m of u){const A=new fe,g=new S,y=new $e,v=new S(1,1,1),_=new Oc(m.geometry,m.material,d);for(let b=0;b<d;b++)l.TRANSLATION&&g.fromBufferAttribute(l.TRANSLATION,b),l.ROTATION&&y.fromBufferAttribute(l.ROTATION,b),l.SCALE&&v.fromBufferAttribute(l.SCALE,b),_.setMatrixAt(b,A.compose(g,y,v));_.sourceTrs=l;for(const b in l)if(b==="_COLOR_0"){const T=l[b];_.instanceColor=new ha(T.array,T.itemSize,T.normalized)}else b!=="TRANSLATION"&&b!=="ROTATION"&&b!=="SCALE"&&m.geometry.setAttribute(b,l[b]);ft.prototype.copy.call(_,m),this.parser.assignFinalMaterial(_),p.push(_)}return h.isGroup?(h.clear(),h.add(...p),h):p[0]}))}}const BT="glTF",Ud=12,LT={JSON:1313821514,BIN:5130562};class c0{constructor(e){this.name=zt.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Ud),i=new TextDecoder;if(this.header={magic:i.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==BT)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const n=this.header.length-Ud,s=new DataView(e,Ud);let a=0;for(;a<n;){const o=s.getUint32(a,!0);a+=4;const l=s.getUint32(a,!0);if(a+=4,l===LT.JSON){const c=new Uint8Array(e,Ud+a,o);this.content=i.decode(c)}else if(l===LT.BIN){const c=Ud+a;this.body=e.slice(c,c+o)}a+=o}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class pz{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=zt.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const i=this.json,n=this.dracoLoader,s=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},l={},c={};for(const h in a){const u=u0[h]||h.toLowerCase();o[u]=a[h]}for(const h in e.attributes){const u=u0[h]||h.toLowerCase();if(a[h]!==void 0){const d=i.accessors[e.attributes[h]],p=ah[d.componentType];c[u]=p.name,l[u]=d.normalized===!0}}return t.getDependency("bufferView",s).then(function(h){return new Promise(function(u,d){n.decodeDracoFile(h,function(p){for(const m in p.attributes){const A=p.attributes[m],g=l[m];g!==void 0&&(A.normalized=g)}u(p)},o,c,Bt,d)})})}}class mz{constructor(){this.name=zt.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e.__hasGLTFUuid||(e=e.clone()),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class gz{constructor(){this.name=zt.KHR_MESH_QUANTIZATION}}class OT extends kc{constructor(e,t,i,n){super(e,t,i,n)}copySampleValue_(e){const t=this.resultBuffer,i=this.sampleValues,n=this.valueSize,s=e*n*3+n;for(let a=0;a!==n;a++)t[a]=i[s+a];return t}interpolate_(e,t,i,n){const s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=o*2,c=o*3,h=n-t,u=(i-t)/h,d=u*u,p=d*u,m=e*c,A=m-c,g=-2*p+3*d,y=p-d,v=1-g,_=y-d+u;for(let b=0;b!==o;b++){const T=a[A+b+o],E=a[A+b+l]*h,M=a[m+b+o],I=a[m+b]*h;s[b]=v*T+_*E+g*M+y*I}return s}}const Az=new $e;class yz extends OT{interpolate_(e,t,i,n){const s=super.interpolate_(e,t,i,n);return Az.fromArray(s).normalize().toArray(s),s}}const Hs={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},ah={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},UT={9728:mi,9729:at,9984:Jh,9985:Io,9986:Na,9987:Dn},FT={33071:di,33648:Kr,10497:Pn},h0={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},u0={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},uo={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},_z={CUBICSPLINE:void 0,LINEAR:tc,STEP:ec},d0={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function vz(r){return r.DefaultMaterial===void 0&&(r.DefaultMaterial=new Mt.ObjectConstructors.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:us})),r.DefaultMaterial}function xa(r,e,t){for(const i in t.extensions)r[i]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[i]=t.extensions[i])}function hr(r,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(r.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function bz(r,e,t){let i=!1,n=!1,s=!1;for(let c=0,h=e.length;c<h;c++){const u=e[c];if(u.POSITION!==void 0&&(i=!0),u.NORMAL!==void 0&&(n=!0),u.COLOR_0!==void 0&&(s=!0),i&&n&&s)break}if(!i&&!n&&!s)return Promise.resolve(r);const a=[],o=[],l=[];for(let c=0,h=e.length;c<h;c++){const u=e[c];if(i){const d=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):r.attributes.position;a.push(d)}if(n){const d=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):r.attributes.normal;o.push(d)}if(s){const d=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):r.attributes.color;l.push(d)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then(function(c){const h=c[0],u=c[1],d=c[2];return i&&(r.morphAttributes.position=h),n&&(r.morphAttributes.normal=u),s&&(r.morphAttributes.color=d),r.morphTargetsRelative=!0,r})}function wz(r,e){if(r.updateMorphTargets(),e.weights!==void 0)for(let t=0,i=e.weights.length;t<i;t++)r.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(r.morphTargetInfluences.length===t.length){r.morphTargetDictionary={};for(let i=0,n=t.length;i<n;i++)r.morphTargetDictionary[t[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Cz(r){let e;const t=r.extensions&&r.extensions[zt.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+f0(t.attributes):e=r.indices+":"+f0(r.attributes)+":"+r.mode,r.targets!==void 0)for(let i=0,n=r.targets.length;i<n;i++)e+=":"+f0(r.targets[i]);return e}function f0(r){let e="";const t=Object.keys(r).sort();for(let i=0,n=t.length;i<n;i++)e+=t[i]+":"+r[t[i]]+";";return e}function p0(r){switch(r){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function xz(r){return r.search(/\.jpe?g($|\?)/i)>0||r.search(/^data\:image\/jpeg/)===0?"image/jpeg":r.search(/\.webp($|\?)/i)>0||r.search(/^data\:image\/webp/)===0?"image/webp":"image/png"}const Sz=new fe;class NT{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new YG,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,n=-1,s=!1,a=-1;if(typeof navigator<"u"){const o=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(o)===!0;const l=o.match(/Version\/(\d+)/);n=i&&l?parseInt(l[1],10):-1,s=o.indexOf("Firefox")>-1,a=s?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&n<17||s&&a<98?this.textureLoader=new Za(this.options.manager):this.textureLoader=new Vx(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new ti(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,n=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(a){const o={scene:a[0][n.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:n.asset,parser:i,userData:{}};return xa(s,o,n),hr(o,n),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(const l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let n=0,s=t.length;n<s;n++){const a=t[n].joints;for(let o=0,l=a.length;o<l;o++)e[a[o]].isBone=!0}for(let n=0,s=e.length;n<s;n++){const a=e[n];a.mesh!==void 0&&(this._addNodeRef(this.meshCache,a.mesh),a.skin!==void 0&&(i[a.mesh].isSkinnedMesh=!0)),a.camera!==void 0&&this._addNodeRef(this.cameraCache,a.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,i){if(e.refs[t]<=1)return i;const n=i.clone(),s=(a,o)=>{const l=this.associations.get(a);l!=null&&this.associations.set(o,l);for(const[c,h]of a.children.entries())s(h,o.children[c])};return s(i,n),n.name+="_instance_"+e.uses[t]++,n}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let i=0;i<t.length;i++){const n=e(t[i]);if(n)return n}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const i=[];for(let n=0;n<t.length;n++){const s=e(t[n]);s&&i.push(s)}return i}getDependency(e,t){const i=e+":"+t;let n=this.cache.get(i);if(!n){switch(e){case"scene":n=this.loadScene(t);break;case"node":n=this._invokeOne(function(s){return s.loadNode&&s.loadNode(t)});break;case"mesh":n=this._invokeOne(function(s){return s.loadMesh&&s.loadMesh(t)});break;case"accessor":n=this.loadAccessor(t);break;case"bufferView":n=this._invokeOne(function(s){return s.loadBufferView&&s.loadBufferView(t)});break;case"buffer":n=this.loadBuffer(t);break;case"material":n=this._invokeOne(function(s){return s.loadMaterial&&s.loadMaterial(t)});break;case"texture":n=this._invokeOne(function(s){return s.loadTexture&&s.loadTexture(t)});break;case"skin":n=this.loadSkin(t);break;case"animation":n=this._invokeOne(function(s){return s.loadAnimation&&s.loadAnimation(t)});break;case"camera":n=this.loadCamera(t);break;default:if(n=this._invokeOne(function(s){return s!=this&&s.getDependency&&s.getDependency(e,t)}),!n)throw new Error("Unknown type: "+e);break}this.cache.add(i,n)}return n}getDependencies(e){let t=this.cache.get(e);if(!t){const i=this,n=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(n.map(function(s,a){return i.getDependency(e,a)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],i=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[zt.KHR_BINARY_GLTF].body);const n=this.options;return new Promise(function(s,a){i.load(Ps.resolveURL(t.uri,n.path),s,void 0,function(){a(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(i){const n=t.byteLength||0,s=t.byteOffset||0;return i.slice(s,s+n)})}loadAccessor(e){const t=this,i=this.json,n=this.json.accessors[e];if(n.bufferView===void 0&&n.sparse===void 0){const a=h0[n.type],o=ah[n.componentType],l=n.normalized===!0,c=new o(n.count*a);return Promise.resolve(new Ze(c,a,l))}const s=[];return n.bufferView!==void 0?s.push(this.getDependency("bufferView",n.bufferView)):s.push(null),n.sparse!==void 0&&(s.push(this.getDependency("bufferView",n.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",n.sparse.values.bufferView))),Promise.all(s).then(function(a){const o=a[0],l=h0[n.type],c=ah[n.componentType],h=c.BYTES_PER_ELEMENT,u=h*l,d=n.byteOffset||0,p=n.bufferView!==void 0?i.bufferViews[n.bufferView].byteStride:void 0,m=n.normalized===!0;let A,g;if(p&&p!==u){const y=Math.floor(d/p),v="InterleavedBuffer:"+n.bufferView+":"+n.componentType+":"+y+":"+n.count;let _=t.cache.get(v);_||(A=new c(o,y*p,n.count*p/h),_=new Mc(A,p/h),t.cache.add(v,_)),g=new Rn(_,l,d%p/h,m)}else o===null?A=new c(n.count*l):A=new c(o,d,n.count*l),g=new Ze(A,l,m);if(n.sparse!==void 0){const y=h0.SCALAR,v=ah[n.sparse.indices.componentType],_=n.sparse.indices.byteOffset||0,b=n.sparse.values.byteOffset||0,T=new v(a[1],_,n.sparse.count*y),E=new c(a[2],b,n.sparse.count*l);o!==null&&(g=new Ze(g.array.slice(),g.itemSize,g.normalized));for(let M=0,I=T.length;M<I;M++){const C=T[M];if(g.setX(C,E[M*l]),l>=2&&g.setY(C,E[M*l+1]),l>=3&&g.setZ(C,E[M*l+2]),l>=4&&g.setW(C,E[M*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return g})}loadTexture(e){const t=this.json,i=this.options;if(e<0||e>=t.textures.length)return console.warn("THREE.GLTFLoader: Invalid texture index:",e),null;const s=t.textures[e].source;if(s<0||s>=t.images.length)return console.warn("THREE.GLTFLoader: Invalid source index:",s),null;const a=t.images[s];let o=this.textureLoader;if(a.uri){const l=i.manager.getHandler(a.uri);l!==null&&(o=l)}return this.loadTextureImage(e,s,o)}loadTextureImage(e,t,i){const n=this,s=this.json,a=s.textures[e],o=s.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];const c=this.loadImageSource(t,i).then(function(h){h.name=a.name||o.name||"",h.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(h.name=o.uri);const d=(s.samplers||{})[a.sampler]||{};return h.magFilter=UT[d.magFilter]||at,h.minFilter=UT[d.minFilter]||Dn,h.wrapS=FT[d.wrapS]||Pn,h.wrapT=FT[d.wrapT]||Pn,d.extras&&(d.extras.uuid!==void 0&&(h.uuid=d.extras.uuid,h.__hasGLTFUuid=!0),d.extras.colorSpace!==void 0&&(h.colorSpace=d.extras.colorSpace,h.userData._forcedColorSpace=!0,delete d.extras.colorSpace)),n.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t,i=!1,n=!1){const s=this,a=this.json,o=this.options;if(!n&&this.sourceCache[e]!==void 0)return this.sourceCache[e].then(m=>m.clone());const l=a.images[e],c=self.URL||self.webkitURL;l.uri===void 0&&l.extras&&l.extras.uri&&(l.uri=l.extras.uri);let h=l.uri||"",u=!1,d=null;if(l.bufferView!==void 0&&(!i||!h))h=s.getDependency("bufferView",l.bufferView).then(function(m){u=!0;const A=new Blob([m],{type:l.mimeType});return h=c.createObjectURL(A),d=A,h});else if(l.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const p=Promise.resolve(h).then(function(m){return new Promise(function(A,g){let y=A;t.isImageBitmapLoader===!0&&(y=function(v){const _=new kt(v);_.needsUpdate=!0,A(_)}),t.load(Ps.resolveURL(m,o.path),y,void 0,function(v){t.isImageBitmapLoader===!0?(t=new Za(s.options.manager),y=A,t.setCrossOrigin(s.options.crossOrigin),t.setRequestHeader(s.options.requestHeader),t.load(Ps.resolveURL(m,o.path),y,void 0,g)):g(v)})})}).then(function(m){if(u===!0&&c.revokeObjectURL(h),hr(m,l),m.userData.mimeType=l.mimeType||xz(l.uri),m.flipY=!1,l.extras){if(l.extras.flipY!==void 0){if(t.isImageBitmapLoader===!0&&typeof createImageBitmap!==void 0){let A=m;const g=l.extras.flipY&&!A.flipY;createImageBitmap(A.source.data,{imageOrientation:g?"flipY":"none"}).then(function(y){A._newTex&&(A=A._newTex),A.source.data.close&&A.source.data.close(),A.source.data=y,A.source.needsUpdate=!0,A.needsUpdate=!0})}m.flipY=l.extras.flipY,m.needsUpdate=!0,delete l.extras.flipY}l.extras.uuid!==void 0&&(m.source.uuid=l.extras.uuid),l.extras.t_uuid!==void 0&&(m.uuid=l.extras.t_uuid,m.__hasGLTFUuid=!0),l.extras.t_colorSpace!==void 0&&(m.colorSpace=l.extras.t_colorSpace,m.userData._forcedColorSpace=!0,delete l.extras.t_colorSpace)}return l.uri&&typeof l.uri=="string"&&u===!1&&(m.userData.rootPath=o.path&&o.path.startsWith("/")?l.uri:Ps.resolveURL(l.uri,o.path)),d&&(m.userData.__sourceBlob=d),!i&&l.uri&&l.uri!==h&&s.loadImageSource(e,t,!0,!0).then(function(A){m.source.data&&m.source.data.close&&m.source.data.close(),m.dispose(),m.source=A.source,m.source.needsUpdate=!0,m.needsUpdate=!0,m.uuid=A.uuid,A.__hasGLTFUuid&&(m.__hasGLTFUuid=!0),m.flipY=A.flipY,m.colorSpace=A.colorSpace,m.userData=A.userData,m.setDirty&&m.setDirty(),A._newTex=m}),m}).catch(function(m){throw console.error("THREE.GLTFLoader: Couldn't load texture",h),m});return this.sourceCache[e]=p,p}assignTexture(e,t,i,n){const s=this;return this.getDependency("texture",i.index).then(function(a){if(!a)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(a=a.clone(),a.channel=i.texCoord),s.extensions[zt.KHR_TEXTURE_TRANSFORM]){const o=i.extensions!==void 0?i.extensions[zt.KHR_TEXTURE_TRANSFORM]:void 0;if(o){const l=s.associations.get(a);a=s.extensions[zt.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),s.associations.set(a,l)}}return n!==void 0&&!a.userData._forcedColorSpace&&(a.colorSpace=n),e[t]=a,a})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const n=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){const l="PointsMaterial:"+i.uuid;let c=this.cache.get(l);c||(c=new Mt.ObjectConstructors.PointsMaterial,tn.prototype.copy.call(c,i),c.color.copy(i.color),c.map=i.map,c.sizeAttenuation=!1,this.cache.add(l,c)),i=c}else if(e.isLine){const l="LineBasicMaterial:"+i.uuid;let c=this.cache.get(l);c||(c=new Mt.ObjectConstructors.LineBasicMaterial,tn.prototype.copy.call(c,i),c.color.copy(i.color),c.map=i.map,this.cache.add(l,c)),i=c}const o=i.userData&&i.userData.gltfExtensions?!!i.userData.gltfExtensions.WEBGI_material_extras:!1;if((n||s||a)&&!o){let l="ClonedMaterial:"+i.uuid+":";n&&(l+="derivative-tangents:"),s&&(l+="vertex-colors:"),a&&(l+="flat-shading:");let c=this.cache.get(l);c||(c=i.clone(),s&&(c.vertexColors=!0),a&&(c.flatShading=!0),n&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(l,c),this.associations.set(c,this.associations.get(i))),i=c}e.material=i}getMaterialType(){return Mt.ObjectConstructors.MeshStandardMaterial}loadMaterial(e){const t=this,i=this.json,n=this.extensions,s=i.materials[e];let a;const o={},l=s.extensions||{},c=[];if(l[zt.KHR_MATERIALS_UNLIT]){const u=n[zt.KHR_MATERIALS_UNLIT];a=u.getMaterialType(),c.push(u.extendParams(o,s,t))}else{const u=s.pbrMetallicRoughness||{};if(o.color=new ee(1,1,1),o.opacity=1,Array.isArray(u.baseColorFactor)){const d=u.baseColorFactor;o.color.setRGB(d[0],d[1],d[2],Bt),o.opacity=d[3]}u.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",u.baseColorTexture,Ct)),o.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,o.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",u.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",u.metallicRoughnessTexture))),a=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,o)})))}s.doubleSided===!0&&(o.side=Zi);const h=s.alphaMode||d0.OPAQUE;if(h===d0.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,h===d0.MASK&&(o.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&a!==Mt.ObjectConstructors.MeshBasicMaterial&&(c.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new K(1,1),s.normalTexture.scale!==void 0)){const u=s.normalTexture.scale;o.normalScale.set(u,u)}if(s.occlusionTexture!==void 0&&a!==Mt.ObjectConstructors.MeshBasicMaterial&&(c.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&a!==Mt.ObjectConstructors.MeshBasicMaterial){const u=s.emissiveFactor;o.emissive=new ee().setRGB(u[0],u[1],u[2],Bt)}return s.emissiveTexture!==void 0&&a!==Mt.ObjectConstructors.MeshBasicMaterial&&c.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,Ct)),Promise.all(c).then(function(){const u=new a(o);return s.extras&&s.extras.uuid&&(u.uuid=s.extras.uuid),s.name&&(u.name=s.name),hr(u,s),t.associations.set(u,{materials:e}),s.extensions&&xa(n,u,s),u})}createUniqueName(e){const t=Et.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,i=this.extensions,n=this.primitiveCache;function s(o){return i[zt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return kT(l,o,t)})}const a=[];for(let o=0,l=e.length;o<l;o++){const c=e[o],h=Cz(c),u=n[h];if(u)a.push(u.promise);else{let d;c.extensions&&c.extensions[zt.KHR_DRACO_MESH_COMPRESSION]?d=s(c):d=kT(new Je,c,t),n[h]={primitive:c,promise:d},a.push(d)}}return Promise.all(a)}loadMesh(e){const t=this,i=this.json,n=this.extensions,s=i.meshes[e],a=s.primitives,o=[];for(let l=0,c=a.length;l<c;l++){const h=a[l].material===void 0?vz(this.cache):this.getDependency("material",a[l].material);o.push(h)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(l){const c=l.slice(0,l.length-1),h=l[l.length-1],u=[];for(let p=0,m=h.length;p<m;p++){const A=h[p],g=a[p];let y;const v=c[p];if(g.mode===Hs.TRIANGLES||g.mode===Hs.TRIANGLE_STRIP||g.mode===Hs.TRIANGLE_FAN||g.mode===void 0)y=s.isSkinnedMesh===!0?new _p(A,v):new _e(A,v),y.isSkinnedMesh===!0&&y.normalizeSkinWeights(),g.mode===Hs.TRIANGLE_STRIP?y.geometry=ov(y.geometry,Uw):g.mode===Hs.TRIANGLE_FAN&&(y.geometry=ov(y.geometry,oy));else if(g.mode===Hs.LINES)y=new Ms(A,v);else if(g.mode===Hs.LINE_STRIP)y=new fn(A,v);else if(g.mode===Hs.LINE_LOOP)y=new $y(A,v);else if(g.mode===Hs.POINTS)y=new Wo(A,v);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(y.geometry.morphAttributes).length>0&&wz(y,s),y.name=t.createUniqueName(s.name||"mesh_"+e),y.geometry&&s.extras&&s.extras.isGeometryUserData?(hr(y.geometry,s),g.extensions&&xa(n,y.geometry,g)):(hr(y,s),g.extensions&&xa(n,y,g)),t.assignFinalMaterial(y),u.push(y)}s.extensions&&u.forEach(p=>xa(n,p,s));for(let p=0,m=u.length;p<m;p++)t.associations.set(u[p],{meshes:e,primitives:p});if(u.length===1)return s.extensions&&xa(n,u[0],s),u[0];const d=new Vi;s.extensions&&xa(n,d,s),t.associations.set(d,{meshes:e});for(let p=0,m=u.length;p<m;p++)d.add(u[p]);return d})}loadCamera(e){let t;const i=this.json.cameras[e],n=i[i.type];if(!n){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return i.type==="perspective"?t=new Mt.ObjectConstructors.PerspectiveCamera(Ft.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):i.type==="orthographic"&&(t=new Mt.ObjectConstructors.OrthographicCamera(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),hr(t,i),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],i=[];for(let n=0,s=t.joints.length;n<s;n++)i.push(this._loadNodeShallow(t.joints[n]));return t.inverseBindMatrices!==void 0?i.push(this.getDependency("accessor",t.inverseBindMatrices)):i.push(null),Promise.all(i).then(function(n){const s=n.pop(),a=n,o=[],l=[];for(let c=0,h=a.length;c<h;c++){const u=a[c];if(u){o.push(u);const d=new fe;s!==null&&d.fromArray(s.array,c*16),l.push(d)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new Bc(o,l)})}loadAnimation(e){const t=this.json,i=this,n=t.animations[e],s=n.name?n.name:"animation_"+e,a=[],o=[],l=[],c=[],h=[];for(let u=0,d=n.channels.length;u<d;u++){const p=n.channels[u],m=n.samplers[p.sampler],A=p.target,g=A.node,y=n.parameters!==void 0?n.parameters[m.input]:m.input,v=n.parameters!==void 0?n.parameters[m.output]:m.output;A.node!==void 0&&(a.push(this.getDependency("node",g)),o.push(this.getDependency("accessor",y)),l.push(this.getDependency("accessor",v)),c.push(m),h.push(A))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(h)]).then(function(u){const d=u[0],p=u[1],m=u[2],A=u[3],g=u[4],y=[];for(let _=0,b=d.length;_<b;_++){const T=d[_],E=p[_],M=m[_],I=A[_],C=g[_];if(T===void 0)continue;T.updateMatrix&&T.updateMatrix();const x=i._createAnimationTracks(T,E,M,I,C);if(x)for(let D=0;D<x.length;D++)y.push(x[D])}const v=new Ja(s,void 0,y);return hr(v,n),v})}createNodeMesh(e){const t=this.json,i=this,n=t.nodes[e];return n.mesh===void 0?null:i.getDependency("mesh",n.mesh).then(function(s){const a=i._getNodeRef(i.meshCache,n.mesh,s);return n.weights!==void 0&&a.traverse(function(o){if(o.isMesh)for(let l=0,c=n.weights.length;l<c;l++)o.morphTargetInfluences[l]=n.weights[l]}),a})}loadNode(e){const t=this.json,i=this,n=t.nodes[e],s=i._loadNodeShallow(e),a=[],o=n.children||[];for(let c=0,h=o.length;c<h;c++)a.push(i.getDependency("node",o[c]));const l=n.skin===void 0?Promise.resolve(null):i.getDependency("skin",n.skin);return Promise.all([s,Promise.all(a),l]).then(function(c){const h=c[0],u=c[1],d=c[2];d!==null&&h.traverse(function(p){p.isSkinnedMesh&&p.bind(d,Sz)});for(let p=0,m=u.length;p<m;p++)h.add(u[p]);return h})}_loadNodeShallow(e){const t=this.json,i=this.extensions,n=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const s=t.nodes[e],a=s.name?n.createUniqueName(s.name):"",o=[],l=n._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&o.push(l),s.camera!==void 0&&o.push(n.getDependency("camera",s.camera).then(function(c){return n._getNodeRef(n.cameraCache,s.camera,c)})),n._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){o.push(c)}),this.nodeCache[e]=Promise.all(o).then(function(c){let h;if(s.isBone===!0?h=new Rc:c.length>1?h=new Vi:c.length===1?h=c[0]:h=new ft,h!==c[0])for(let u=0,d=c.length;u<d;u++)h.add(c[u]);if(s.name&&(h.userData.name=s.name,h.name=a),hr(h,s),s.extensions&&xa(i,h,s),s.matrix!==void 0){const u=new fe;u.fromArray(s.matrix),h.applyMatrix4(u)}else s.translation!==void 0&&h.position.fromArray(s.translation),s.rotation!==void 0&&h.quaternion.fromArray(s.rotation),s.scale!==void 0&&h.scale.fromArray(s.scale);return n.associations.has(h)||n.associations.set(h,{}),n.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],n=this,s=new Vi;i.name&&(s.name=n.createUniqueName(i.name)),hr(s,i),i.extensions&&xa(t,s,i);const a=i.nodes||[],o=[];for(let l=0,c=a.length;l<c;l++)o.push(n.getDependency("node",a[l]));return Promise.all(o).then(function(l){for(let h=0,u=l.length;h<u;h++)s.add(l[h]);const c=h=>{const u=new Map;for(const[d,p]of n.associations)(d instanceof tn||d instanceof kt)&&u.set(d,p);return h.traverse(d=>{const p=n.associations.get(d);p!=null&&u.set(d,p)}),u};return n.associations=c(s),s})}_createAnimationTracks(e,t,i,n,s){const a=[],o=e.name?e.name:e.uuid,l=[];uo[s.path]===uo.weights?e.traverse(function(d){d.morphTargetInfluences&&l.push(d.name?d.name:d.uuid)}):l.push(o);let c;switch(uo[s.path]){case uo.weights:c=$a;break;case uo.rotation:c=fa;break;case uo.position:case uo.scale:c=Ka;break;default:i.itemSize===1?c=$a:c=Ka;break}const h=n.interpolation!==void 0?_z[n.interpolation]:tc,u=this._getArrayFromAccessor(i);for(let d=0,p=l.length;d<p;d++){const m=new c(l[d]+"."+uo[s.path],t.array,u,h);n.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(m),a.push(m)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const i=p0(t.constructor),n=new Float32Array(t.length);for(let s=0,a=t.length;s<a;s++)n[s]=t[s]*i;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(i){const n=this instanceof fa?yz:OT;return new n(this.times,this.values,this.getValueSize()/3,i)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Ez(r,e,t){const i=e.attributes,n=new en;if(i.POSITION!==void 0){const o=t.json.accessors[i.POSITION],l=o.min,c=o.max;if(l!==void 0&&c!==void 0){if(n.set(new S(l[0],l[1],l[2]),new S(c[0],c[1],c[2])),o.normalized){const h=p0(ah[o.componentType]);n.min.multiplyScalar(h),n.max.multiplyScalar(h)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const s=e.targets;if(s!==void 0){const o=new S,l=new S;for(let c=0,h=s.length;c<h;c++){const u=s[c];if(u.POSITION!==void 0){const d=t.json.accessors[u.POSITION],p=d.min,m=d.max;if(p!==void 0&&m!==void 0){if(l.setX(Math.max(Math.abs(p[0]),Math.abs(m[0]))),l.setY(Math.max(Math.abs(p[1]),Math.abs(m[1]))),l.setZ(Math.max(Math.abs(p[2]),Math.abs(m[2]))),d.normalized){const A=p0(ah[d.componentType]);l.multiplyScalar(A)}o.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}n.expandByVector(o)}r.boundingBox=n;const a=new un;n.getCenter(a.center),a.radius=n.min.distanceTo(n.max)/2,r.boundingSphere=a}function kT(r,e,t){const i=e.attributes,n=[];function s(a,o){return t.getDependency("accessor",a).then(function(l){r.setAttribute(o,l)})}for(const a in i){const o=u0[a]||a.toLowerCase();o in r.attributes||n.push(s(i[a],o))}if(e.indices!==void 0&&!r.index){const a=t.getDependency("accessor",e.indices).then(function(o){r.setIndex(o)});n.push(a)}return Nt.workingColorSpace!==Bt&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Nt.workingColorSpace}" not supported.`),hr(r,e),Ez(r,e,t),Promise.all(n).then(function(){return e.targets!==void 0?bz(r,e.targets,t):r})}const GT=async(r,e)=>{if(!r||!(r instanceof ArrayBuffer)||!r.byteLength||!e.encrypt)return r;if(!e.encryptKey&&window&&window.prompt&&(e.encryptKey=window.prompt("GLTFEncryption: Enter encryption key/password")||""),!e.encryptKey)return console.warn("GLTF Export: encryption key not provided, skipping encryption"),r;const t=await TS(new Uint8Array(r),e.encryptKey);return $E(t,{asset:{version:"2.0",generator:"ThreePipeGLBWrapper",encryption:{type:"aesgcm",version:1}}})},zT={key:(r,e,t)=>r.key||window&&window.prompt&&window.prompt("GLTFEncryption: Please enter the password/key for the model: "+t)||"",async process(r,e){if(typeof r=="string"||r.byteLength<100)return r;const t=100;if(!new TextDecoder().decode(new Uint8Array(r,0,t)).includes("GLBWrapper"))return r;const n=new c0(r),s=JSON.parse(n.content||"{}");let a=n.body||r;const o=s.asset?.encryption;if(!o)return a;const l=o.type,c=o.version;if(l==="aesgcm"&&c===1){const h=await tt(this.key,o,s,e)||"";try{a=(await IS(new Uint8Array(a),h)).buffer}catch{throw new ErrorEvent("decryption error")}}return a}},cA=class cA extends ti{async parseAsync(e){return e}load(e,t,i,n){return super.load(e,s=>{try{if(typeof s=="string")this.parseAsync(JSON.parse(s)).then(t);else throw new Error("Invalid JSON")}catch(a){n?.(a)}},i,n)}};cA.SupportedJSONTypes=[],cA.SupportedJSONExtensions=[];let Fd=cA;const Gl=class Gl extends Fd{async parseAsync(e){if(!this.viewer)throw"Viewer not set in JSONMaterialLoader.";let t;return Gl.FindExistingMaterial&&e.uuid&&this.viewer&&(t=this.viewer.materialManager.findMaterial(e.uuid)),await Gl.DeserializeMaterialJSON(e,this.viewer,void 0,t)}static async DeserializeMaterialJSON(e,t,i,n){i=i||Fr();const s={...e};e.images&&(Array.isArray(e.images)?i.images=Object.fromEntries(e.images.map(o=>[o.uuid,o])):i.images=e.images,delete s.images),e.textures&&(Array.isArray(e.textures)?i.textures=Object.fromEntries(e.textures.map(o=>[o.uuid,o])):i.textures=e.textures,delete s.textures),e.materials&&(Array.isArray(e.materials)?i.materials=Object.fromEntries(e.materials.map(o=>[o.uuid,o])):i.materials=e.materials,delete s.materials);const a=await t.loadConfigResources(i);return We.Deserialize(s,n||void 0,a)}};Gl.SupportedJSONTypes=()=>["Material",...[...We.SerializableMaterials.values()].flatMap(e=>[e.TYPE,...e.TypeAlias||[]])],Gl.SupportedJSONExtensions=()=>["mat",...[...We.SerializableMaterials.values()].map(e=>e.TypeSlug)],Gl.FindExistingMaterial=!1;let oh=Gl;class m0 extends oi{constructor(e){super(e)}load(e,t,i,n){const s=this,a=this.path===""?Ps.extractUrlBase(e):this.path,o=new ti(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(l){try{t(s.parse(l,a))}catch(c){n?n(c):console.error(c),s.manager.itemError(e)}},i,n)}setMaterialOptions(e){return this.materialOptions=e,this}parse(e,t){const i=e.split(`
`);let n={};const s=/\s+/,a={};for(let l=0;l<i.length;l++){let c=i[l];if(c=c.trim(),c.length===0||c.charAt(0)==="#")continue;const h=c.indexOf(" ");let u=h>=0?c.substring(0,h):c;u=u.toLowerCase();let d=h>=0?c.substring(h+1):"";if(d=d.trim(),u==="newmtl")n={name:d},a[d]=n;else if(u==="ka"||u==="kd"||u==="ks"||u==="ke"){const p=d.split(s,3);n[u]=[parseFloat(p[0]),parseFloat(p[1]),parseFloat(p[2])]}else n[u]=d}const o=new Mz(this.resourcePath||t,this.materialOptions);return o.setCrossOrigin(this.crossOrigin),o.setManager(this.manager),o.setMaterials(a),o}}class Mz{constructor(e="",t={}){this.baseUrl=e,this.options=t,this.materialsInfo={},this.materials={},this.materialsPending=new Map,this.materialsArray=[],this.nameLookup={},this.crossOrigin="anonymous",this.side=this.options.side!==void 0?this.options.side:us,this.wrap=this.options.wrap!==void 0?this.options.wrap:Pn}setCrossOrigin(e){return this.crossOrigin=e,this}setManager(e){this.manager=e}setMaterials(e){this.materialsInfo=this.convert(e),this.materials={},this.materialsPending=new Map,this.materialsArray=[],this.nameLookup={}}convert(e){if(!this.options)return e;const t={};for(const i in e){const n=e[i],s={};t[i]=s;for(const a in n){let o=!0,l=n[a];const c=a.toLowerCase();switch(c){case"kd":case"ka":case"ks":this.options&&this.options.normalizeRGB&&(l=[l[0]/255,l[1]/255,l[2]/255]),this.options&&this.options.ignoreZeroRGBs&&l[0]===0&&l[1]===0&&l[2]===0&&(o=!1);break}o&&(s[c]=l)}}return t}async preload(){await Promise.all(Object.keys(this.materialsInfo).map(e=>this.create(e)))}getIndex(e){return this.nameLookup[e]}async getAsArray(){const e=this.materialsArray,t=this.nameLookup,i=Object.keys(this.materialsInfo),n=await Promise.all(i.map(s=>this.create(s)));return i.forEach((s,a)=>{e[a]=n[a],t[s]=a}),e}async create(e){if(this.materials[e]===void 0){const t=this.materialsPending;return t.has(e)||t.set(e,this.createMaterial_(e).finally(()=>t.delete(e))),t.get(e)}return this.materials[e]}async createMaterial_(e){const t=this,i=this.materials,n=this.materialsInfo[e],s={name:e,side:this.side};function a(d,p){return typeof p!="string"||p===""?"":/^https?:\/\//i.test(p)?p:d+p}const o=new Map;function l(d,p){const m=()=>s[d]?void 0:c(d,p);o.set(d,o.has(d)?o.get(d).then(m):m())}async function c(d,p){const m=t.getTextureParams(p,s),A=a(t.baseUrl,m.url),g=await new Promise(y=>{t.loadTexture(A,void 0,y,void 0,v=>{console.warn("MTLLoader2: Unable to load texture",A,v),y(void 0)})});g&&(g.repeat.copy(m.scale),g.offset.copy(m.offset),g.wrapS=t.wrap,g.wrapT=t.wrap,(d==="map"||d==="emissiveMap")&&(g.colorSpace=Ct),s[d]=g)}const h=Array.from(Object.keys(n||{}));let u=h.includes("d")||h.includes("D");for(const d of h){const p=n[d];let m;if(p!=="")switch(d.toLowerCase()){case"kd":s.color=new ee().fromArray(p).convertSRGBToLinear();break;case"ks":s.specular=new ee().fromArray(p).convertSRGBToLinear();break;case"ke":s.emissive=new ee().fromArray(p).convertSRGBToLinear();break;case"map_kd":l("map",p);break;case"map_ks":l("specularMap",p);break;case"map_ke":l("emissiveMap",p);break;case"norm":l("normalMap",p);break;case"map_bump":case"bump":l("bumpMap",p);break;case"map_d":l("alphaMap",p),s.transparent=!0;break;case"ns":s.shininess=parseFloat(p);break;case"d":m=parseFloat(p),m<1&&(s.opacity=m,s.transparent=!0);break;case"tr":if(u)break;m=parseFloat(p),this.options&&this.options.invertTrProperty&&(m=1-m),m>0&&(s.opacity=1-m,s.transparent=!0);break}}return await Promise.all(o.values()),i[e]=new Zo(s),i[e]}getTextureParams(e,t){const i={scale:new K(1,1),offset:new K(0,0)},n=e.split(/\s+/);let s;return s=n.indexOf("-bm"),s>=0&&(t.bumpScale=parseFloat(n[s+1]),n.splice(s,2)),s=n.indexOf("-s"),s>=0&&(i.scale.set(parseFloat(n[s+1]),parseFloat(n[s+2])),n.splice(s,4)),s=n.indexOf("-o"),s>=0&&(i.offset.set(parseFloat(n[s+1]),parseFloat(n[s+2])),n.splice(s,4)),i.url=n.join(" ").trim(),i}loadTexture(e,t,i,n,s){const a=this.manager!==void 0?this.manager:d_;let o=a.getHandler(e);o===null&&(o=new Za(a)),o.setCrossOrigin&&o.setCrossOrigin(this.crossOrigin);const l=o.load(e,i,n,s);return t!==void 0&&(l.mapping=t),l}}const Tz=/^[og]\s*(.+)?/,Iz=/^mtllib /,Pz=/^usemtl /,Dz=/^usemap /,VT=/\s+/,HT=new S,g0=new S,QT=new S,jT=new S,Qs=new S,pg=new ee;function Rz(){const r={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}const i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(n,s){const a=this._finalize(!1);a&&(a.inherited||a.groupCount<=0)&&this.materials.splice(a.index,1);const o={index:this.materials.length,name:n||"",mtllib:Array.isArray(s)&&s.length>0?s[s.length-1]:"",smooth:a!==void 0?a.smooth:this.smooth,groupStart:a!==void 0?a.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){const c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(n){const s=this.currentMaterial();if(s&&s.groupEnd===-1&&(s.groupEnd=this.geometry.vertices.length/3,s.groupCount=s.groupEnd-s.groupStart,s.inherited=!1),n&&this.materials.length>1)for(let a=this.materials.length-1;a>=0;a--)this.materials[a].groupCount<=0&&this.materials.splice(a,1);return n&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),s}},i&&i.name&&typeof i.clone=="function"){const n=i.clone(0);n.inherited=!0,this.object.materials.push(n)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(e,t){const i=parseInt(e,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(e,t,i){const n=this.vertices,s=this.object.geometry.vertices;s.push(n[e+0],n[e+1],n[e+2]),s.push(n[t+0],n[t+1],n[t+2]),s.push(n[i+0],n[i+1],n[i+2])},addVertexPoint:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){const t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,i){const n=this.normals,s=this.object.geometry.normals;s.push(n[e+0],n[e+1],n[e+2]),s.push(n[t+0],n[t+1],n[t+2]),s.push(n[i+0],n[i+1],n[i+2])},addFaceNormal:function(e,t,i){const n=this.vertices,s=this.object.geometry.normals;HT.fromArray(n,e),g0.fromArray(n,t),QT.fromArray(n,i),Qs.subVectors(QT,g0),jT.subVectors(HT,g0),Qs.cross(jT),Qs.normalize(),s.push(Qs.x,Qs.y,Qs.z),s.push(Qs.x,Qs.y,Qs.z),s.push(Qs.x,Qs.y,Qs.z)},addColor:function(e,t,i){const n=this.colors,s=this.object.geometry.colors;n[e]!==void 0&&s.push(n[e+0],n[e+1],n[e+2]),n[t]!==void 0&&s.push(n[t+0],n[t+1],n[t+2]),n[i]!==void 0&&s.push(n[i+0],n[i+1],n[i+2])},addUV:function(e,t,i){const n=this.uvs,s=this.object.geometry.uvs;s.push(n[e+0],n[e+1]),s.push(n[t+0],n[t+1]),s.push(n[i+0],n[i+1])},addDefaultUV:function(){const e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){const t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,i,n,s,a,o,l,c){const h=this.vertices.length;let u=this.parseVertexIndex(e,h),d=this.parseVertexIndex(t,h),p=this.parseVertexIndex(i,h);if(this.addVertex(u,d,p),this.addColor(u,d,p),o!==void 0&&o!==""){const m=this.normals.length;u=this.parseNormalIndex(o,m),d=this.parseNormalIndex(l,m),p=this.parseNormalIndex(c,m),this.addNormal(u,d,p)}else this.addFaceNormal(u,d,p);if(n!==void 0&&n!==""){const m=this.uvs.length;u=this.parseUVIndex(n,m),d=this.parseUVIndex(s,m),p=this.parseUVIndex(a,m),this.addUV(u,d,p),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";const t=this.vertices.length;for(let i=0,n=e.length;i<n;i++){const s=this.parseVertexIndex(e[i],t);this.addVertexPoint(s),this.addColor(s)}},addLineGeometry:function(e,t){this.object.geometry.type="Line";const i=this.vertices.length,n=this.uvs.length;for(let s=0,a=e.length;s<a;s++)this.addVertexLine(this.parseVertexIndex(e[s],i));for(let s=0,a=t.length;s<a;s++)this.addUVLine(this.parseUVIndex(t[s],n))}};return r.startObject("",!1),r}class WT extends oi{constructor(e){super(e),this.materials=null}load(e,t,i,n){const s=this,a=new ti(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),s.currentUrl=e,a.load(e,async function(o){try{t(await s.parse(o))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}s.currentUrl=void 0},i,n)}setMaterials(e){return this.materials=e,this}async parse(e){const t=new Rz;e.indexOf(`\r
`)!==-1&&(e=e.replace(/\r\n/g,`
`)),e.indexOf(`\\
`)!==-1&&(e=e.replace(/\\\n/g,""));const i=e.split(`
`);let n=[];for(let o=0,l=i.length;o<l;o++){const c=i[o].trimStart();if(c.length===0)continue;const h=c.charAt(0);if(h!=="#")if(h==="v"){const u=c.split(VT);switch(u[0]){case"v":t.vertices.push(parseFloat(u[1]),parseFloat(u[2]),parseFloat(u[3])),u.length>=7?(pg.setRGB(parseFloat(u[4]),parseFloat(u[5]),parseFloat(u[6])).convertSRGBToLinear(),t.colors.push(pg.r,pg.g,pg.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(u[1]),parseFloat(u[2]),parseFloat(u[3]));break;case"vt":t.uvs.push(parseFloat(u[1]),parseFloat(u[2]));break}}else if(h==="f"){const d=c.slice(1).trim().split(VT),p=[];for(let A=0,g=d.length;A<g;A++){const y=d[A];if(y.length>0){const v=y.split("/");p.push(v)}}const m=p[0];for(let A=1,g=p.length-1;A<g;A++){const y=p[A],v=p[A+1];t.addFace(m[0],y[0],v[0],m[1],y[1],v[1],m[2],y[2],v[2])}}else if(h==="l"){const u=c.substring(1).trim().split(" ");let d=[];const p=[];if(c.indexOf("/")===-1)d=u;else for(let m=0,A=u.length;m<A;m++){const g=u[m].split("/");g[0]!==""&&d.push(g[0]),g[1]!==""&&p.push(g[1])}t.addLineGeometry(d,p)}else if(h==="p"){const d=c.slice(1).trim().split(" ");t.addPointGeometry(d)}else if((n=Tz.exec(c))!==null){const u=(" "+n[0].slice(1).trim()).slice(1);t.startObject(u)}else if(Pz.test(c))t.object.startMaterial(c.substring(7).trim(),t.materialLibraries);else if(Iz.test(c)){t.materialLibraries.push(c.substring(7).trim());let u=c.substring(7).trim(),d=this.manager.getHandler(u);if(!d&&u.trim().split("?")[0].endsWith(".mtl")&&(d=new m0(this.manager),d.setPath(this.path),d.setWithCredentials(this.withCredentials),d.setRequestHeader(this.requestHeader),d.setResourcePath(this.resourcePath),d.setCrossOrigin(this.crossOrigin)),this.currentUrl.startsWith("http")&&!u.startsWith("http")&&(u=this.currentUrl.substring(0,this.currentUrl.lastIndexOf("/")+1)+u),!d)console.warn("OBJLoader2: Register MTLLoader2 or any other material loader to loading manager to load the material file:",u);else{const p=await d.loadAsync(u).catch(m=>{console.warn(m)});p&&this.setMaterials(p)}}else if(Dz.test(c))console.warn('OBJLoader2: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.');else if(h==="s"){if(n=c.split(" "),n.length>1){const d=n[1].trim().toLowerCase();t.object.smooth=d!=="0"&&d!=="off"}else t.object.smooth=!0;const u=t.object.currentMaterial();u&&(u.smooth=t.object.smooth)}else{if(c==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+c+'"')}}t.finalize();const s=new Vi;if(s.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0){const o=this.materials===null?[]:await Promise.all(t.objects.map(l=>l.geometry.vertices.length===0?[]:Promise.all(l.materials.map(c=>this.materials.create(c.name)))));for(let l=0,c=t.objects.length;l<c;l++){const h=t.objects[l],u=h.geometry,d=h.materials,p=u.type==="Line",m=u.type==="Points";let A=!1;if(u.vertices.length===0)continue;const g=new Je;g.setAttribute("position",new Ee(u.vertices,3)),u.normals.length>0&&g.setAttribute("normal",new Ee(u.normals,3)),u.colors.length>0&&(A=!0,g.setAttribute("color",new Ee(u.colors,3))),u.hasUVIndices===!0&&g.setAttribute("uv",new Ee(u.uvs,2));const y=[];for(let _=0,b=d.length;_<b;_++){const T=d[_],E=T.name+"_"+T.smooth+"_"+A;let M=t.materials[E];if(this.materials!==null){if(M=o[l][_],p&&M&&!(M instanceof Mi)){const I=new Mi;tn.prototype.copy.call(I,M),I.color.copy(M.color),M=I}else if(m&&M&&!(M instanceof Tr)){const I=new Tr({size:10,sizeAttenuation:!1});tn.prototype.copy.call(I,M),I.color.copy(M.color),I.map=M.map,M=I}}M===void 0&&(p?M=new Mi:m?M=new Tr({size:1,sizeAttenuation:!1}):M=new Ya,M.name=T.name,M.flatShading=!T.smooth,M.vertexColors=A,t.materials[E]=M),y.push(M)}let v;if(y.length>1){for(let _=0,b=d.length;_<b;_++){const T=d[_];g.addGroup(T.groupStart,T.groupCount,_)}p?v=new Ms(g,y):m?v=new Wo(g,y):v=new _e(g,y)}else p?v=new Ms(g,y[0]):m?v=new Wo(g,y[0]):v=new _e(g,y[0]);v.name=h.name,s.add(v)}}else if(t.vertices.length>0){const o=new Tr({size:1,sizeAttenuation:!1}),l=new Je;l.setAttribute("position",new Ee(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(l.setAttribute("color",new Ee(t.colors,3)),o.vertexColors=!0);const c=new Wo(l,o);s.add(c)}return s}}var qT={},Bz=(function(r,e,t,i,n){var s=new Worker(qT[e]||(qT[e]=URL.createObjectURL(new Blob([r+';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'],{type:"text/javascript"}))));return s.onmessage=function(a){var o=a.data,l=o.$e$;if(l){var c=new Error(l[0]);c.code=l[1],c.stack=l[2],n(c,null)}else n(null,o)},s.postMessage(t,i),s}),Tt=Uint8Array,rs=Uint16Array,Nd=Int32Array,lh=new Tt([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ch=new Tt([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),kd=new Tt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),XT=function(r,e){for(var t=new rs(31),i=0;i<31;++i)t[i]=e+=1<<r[i-1];for(var n=new Nd(t[30]),i=1;i<30;++i)for(var s=t[i];s<t[i+1];++s)n[s]=s-t[i]<<5|i;return{b:t,r:n}},YT=XT(lh,2),A0=YT.b,mg=YT.r;A0[28]=258,mg[258]=28;for(var $T=XT(ch,0),KT=$T.b,y0=$T.r,Gd=new rs(32768),Ei=0;Ei<32768;++Ei){var fo=(Ei&43690)>>1|(Ei&21845)<<1;fo=(fo&52428)>>2|(fo&13107)<<2,fo=(fo&61680)>>4|(fo&3855)<<4,Gd[Ei]=((fo&65280)>>8|(fo&255)<<8)>>1}for(var js=(function(r,e,t){for(var i=r.length,n=0,s=new rs(e);n<i;++n)r[n]&&++s[r[n]-1];var a=new rs(e);for(n=1;n<e;++n)a[n]=a[n-1]+s[n-1]<<1;var o;if(t){o=new rs(1<<e);var l=15-e;for(n=0;n<i;++n)if(r[n])for(var c=n<<4|r[n],h=e-r[n],u=a[r[n]-1]++<<h,d=u|(1<<h)-1;u<=d;++u)o[Gd[u]>>l]=c}else for(o=new rs(i),n=0;n<i;++n)r[n]&&(o[n]=Gd[a[r[n]-1]++]>>15-r[n]);return o}),Sa=new Tt(288),Ei=0;Ei<144;++Ei)Sa[Ei]=8;for(var Ei=144;Ei<256;++Ei)Sa[Ei]=9;for(var Ei=256;Ei<280;++Ei)Sa[Ei]=7;for(var Ei=280;Ei<288;++Ei)Sa[Ei]=8;for(var hh=new Tt(32),Ei=0;Ei<32;++Ei)hh[Ei]=5;var JT=js(Sa,9,0),ZT=js(Sa,9,1),e1=js(hh,5,0),t1=js(hh,5,1),gg=function(r){for(var e=r[0],t=1;t<r.length;++t)r[t]>e&&(e=r[t]);return e},Ws=function(r,e,t){var i=e/8|0;return(r[i]|r[i+1]<<8)>>(e&7)&t},Ag=function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},uh=function(r){return(r+7)/8|0},qs=function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new Tt(r.subarray(e,t))},Lz={UnexpectedEOF:0,InvalidBlockType:1,InvalidLengthLiteral:2,InvalidDistance:3,StreamFinished:4,NoStreamHandler:5,InvalidHeader:6,NoCallback:7,InvalidUTF8:8,ExtraFieldTooLong:9,InvalidDate:10,FilenameTooLong:11,StreamFinishing:12,InvalidZipData:13,UnknownCompressionMethod:14},i1=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],it=function(r,e,t){var i=new Error(e||i1[r]);if(i.code=r,Error.captureStackTrace&&Error.captureStackTrace(i,it),!t)throw i;return i},zd=function(r,e,t,i){var n=r.length,s=i?i.length:0;if(!n||e.f&&!e.l)return t||new Tt(0);var a=!t,o=a||e.i!=2,l=e.i;a&&(t=new Tt(n*3));var c=function(gt){var F=t.length;if(gt>F){var xe=new Tt(Math.max(F*2,gt));xe.set(t),t=xe}},h=e.f||0,u=e.p||0,d=e.b||0,p=e.l,m=e.d,A=e.m,g=e.n,y=n*8;do{if(!p){h=Ws(r,u,1);var v=Ws(r,u+1,3);if(u+=3,v)if(v==1)p=ZT,m=t1,A=9,g=5;else if(v==2){var E=Ws(r,u,31)+257,M=Ws(r,u+10,15)+4,I=E+Ws(r,u+5,31)+1;u+=14;for(var C=new Tt(I),x=new Tt(19),D=0;D<M;++D)x[kd[D]]=Ws(r,u+D*3,7);u+=M*3;for(var U=gg(x),O=(1<<U)-1,N=js(x,U,1),D=0;D<I;){var H=N[Ws(r,u,O)];u+=H&15;var _=H>>4;if(_<16)C[D++]=_;else{var V=0,X=0;for(_==16?(X=3+Ws(r,u,3),u+=2,V=C[D-1]):_==17?(X=3+Ws(r,u,7),u+=3):_==18&&(X=11+Ws(r,u,127),u+=7);X--;)C[D++]=V}}var W=C.subarray(0,E),ce=C.subarray(E);A=gg(W),g=gg(ce),p=js(W,A,1),m=js(ce,g,1)}else it(1);else{var _=uh(u)+4,b=r[_-4]|r[_-3]<<8,T=_+b;if(T>n){l&&it(0);break}o&&c(d+b),t.set(r.subarray(_,T),d),e.b=d+=b,e.p=u=T*8,e.f=h;continue}if(u>y){l&&it(0);break}}o&&c(d+131072);for(var ue=(1<<A)-1,we=(1<<g)-1,Pe=u;;Pe=u){var V=p[Ag(r,u)&ue],Qe=V>>4;if(u+=V&15,u>y){l&&it(0);break}if(V||it(2),Qe<256)t[d++]=Qe;else if(Qe==256){Pe=u,p=null;break}else{var ie=Qe-254;if(Qe>264){var D=Qe-257,oe=lh[D];ie=Ws(r,u,(1<<oe)-1)+A0[D],u+=oe}var me=m[Ag(r,u)&we],Ce=me>>4;me||it(3),u+=me&15;var ce=KT[Ce];if(Ce>3){var oe=ch[Ce];ce+=Ag(r,u)&(1<<oe)-1,u+=oe}if(u>y){l&&it(0);break}o&&c(d+131072);var Xe=d+ie;if(d<ce){var dt=s-ce,Ke=Math.min(ce,Xe);for(dt+d<0&&it(3);d<Ke;++d)t[d]=i[dt+d]}for(;d<Xe;++d)t[d]=t[d-ce]}}e.l=p,e.p=Pe,e.b=d,e.f=h,p&&(h=1,e.m=A,e.d=m,e.n=g)}while(!h);return d!=t.length&&a?qs(t,0,d):t.subarray(0,d)},kr=function(r,e,t){t<<=e&7;var i=e/8|0;r[i]|=t,r[i+1]|=t>>8},dh=function(r,e,t){t<<=e&7;var i=e/8|0;r[i]|=t,r[i+1]|=t>>8,r[i+2]|=t>>16},yg=function(r,e){for(var t=[],i=0;i<r.length;++i)r[i]&&t.push({s:i,f:r[i]});var n=t.length,s=t.slice();if(!n)return{t:po,l:0};if(n==1){var a=new Tt(t[0].s+1);return a[t[0].s]=1,{t:a,l:1}}t.sort(function(T,E){return T.f-E.f}),t.push({s:-1,f:25001});var o=t[0],l=t[1],c=0,h=1,u=2;for(t[0]={s:-1,f:o.f+l.f,l:o,r:l};h!=n-1;)o=t[t[c].f<t[u].f?c++:u++],l=t[c!=h&&t[c].f<t[u].f?c++:u++],t[h++]={s:-1,f:o.f+l.f,l:o,r:l};for(var d=s[0].s,i=1;i<n;++i)s[i].s>d&&(d=s[i].s);var p=new rs(d+1),m=_g(t[h-1],p,0);if(m>e){var i=0,A=0,g=m-e,y=1<<g;for(s.sort(function(E,M){return p[M.s]-p[E.s]||E.f-M.f});i<n;++i){var v=s[i].s;if(p[v]>e)A+=y-(1<<m-p[v]),p[v]=e;else break}for(A>>=g;A>0;){var _=s[i].s;p[_]<e?A-=1<<e-p[_]++-1:++i}for(;i>=0&&A;--i){var b=s[i].s;p[b]==e&&(--p[b],++A)}m=e}return{t:new Tt(p),l:m}},_g=function(r,e,t){return r.s==-1?Math.max(_g(r.l,e,t+1),_g(r.r,e,t+1)):e[r.s]=t},_0=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new rs(++e),i=0,n=r[0],s=1,a=function(l){t[i++]=l},o=1;o<=e;++o)if(r[o]==n&&o!=e)++s;else{if(!n&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(n),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(n);s=1,n=r[o]}return{c:t.subarray(0,i),n:e}},fh=function(r,e){for(var t=0,i=0;i<e.length;++i)t+=r[i]*e[i];return t},v0=function(r,e,t){var i=t.length,n=uh(e+2);r[n]=i&255,r[n+1]=i>>8,r[n+2]=r[n]^255,r[n+3]=r[n+1]^255;for(var s=0;s<i;++s)r[n+s+4]=t[s];return(n+4+i)*8},b0=function(r,e,t,i,n,s,a,o,l,c,h){kr(e,h++,t),++n[256];for(var u=yg(n,15),d=u.t,p=u.l,m=yg(s,15),A=m.t,g=m.l,y=_0(d),v=y.c,_=y.n,b=_0(A),T=b.c,E=b.n,M=new rs(19),I=0;I<v.length;++I)++M[v[I]&31];for(var I=0;I<T.length;++I)++M[T[I]&31];for(var C=yg(M,7),x=C.t,D=C.l,U=19;U>4&&!x[kd[U-1]];--U);var O=c+5<<3,N=fh(n,Sa)+fh(s,hh)+a,H=fh(n,d)+fh(s,A)+a+14+3*U+fh(M,x)+2*M[16]+3*M[17]+7*M[18];if(l>=0&&O<=N&&O<=H)return v0(e,h,r.subarray(l,l+c));var V,X,W,ce;if(kr(e,h,1+(H<N)),h+=2,H<N){V=js(d,p,0),X=d,W=js(A,g,0),ce=A;var ue=js(x,D,0);kr(e,h,_-257),kr(e,h+5,E-1),kr(e,h+10,U-4),h+=14;for(var I=0;I<U;++I)kr(e,h+3*I,x[kd[I]]);h+=3*U;for(var we=[v,T],Pe=0;Pe<2;++Pe)for(var Qe=we[Pe],I=0;I<Qe.length;++I){var ie=Qe[I]&31;kr(e,h,ue[ie]),h+=x[ie],ie>15&&(kr(e,h,Qe[I]>>5&127),h+=Qe[I]>>12)}}else V=JT,X=Sa,W=e1,ce=hh;for(var I=0;I<o;++I){var oe=i[I];if(oe>255){var ie=oe>>18&31;dh(e,h,V[ie+257]),h+=X[ie+257],ie>7&&(kr(e,h,oe>>23&31),h+=lh[ie]);var me=oe&31;dh(e,h,W[me]),h+=ce[me],me>3&&(dh(e,h,oe>>5&8191),h+=ch[me])}else dh(e,h,V[oe]),h+=X[oe]}return dh(e,h,V[256]),h+X[256]},n1=new Nd([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),po=new Tt(0),s1=function(r,e,t,i,n,s){var a=s.z||r.length,o=new Tt(i+a+5*(1+Math.ceil(a/7e3))+n),l=o.subarray(i,o.length-n),c=s.l,h=(s.r||0)&7;if(e){h&&(l[0]=s.r>>3);for(var u=n1[e-1],d=u>>13,p=u&8191,m=(1<<t)-1,A=s.p||new rs(32768),g=s.h||new rs(m+1),y=Math.ceil(t/3),v=2*y,_=function(be){return(r[be]^r[be+1]<<y^r[be+2]<<v)&m},b=new Nd(25e3),T=new rs(288),E=new rs(32),M=0,I=0,C=s.i||0,x=0,D=s.w||0,U=0;C+2<a;++C){var O=_(C),N=C&32767,H=g[O];if(A[N]=H,g[O]=N,D<=C){var V=a-C;if((M>7e3||x>24576)&&(V>423||!c)){h=b0(r,l,0,b,T,E,I,x,U,C-U,h),x=M=I=0,U=C;for(var X=0;X<286;++X)T[X]=0;for(var X=0;X<30;++X)E[X]=0}var W=2,ce=0,ue=p,we=N-H&32767;if(V>2&&O==_(C-we))for(var Pe=Math.min(d,V)-1,Qe=Math.min(32767,C),ie=Math.min(258,V);we<=Qe&&--ue&&N!=H;){if(r[C+W]==r[C+W-we]){for(var oe=0;oe<ie&&r[C+oe]==r[C+oe-we];++oe);if(oe>W){if(W=oe,ce=we,oe>Pe)break;for(var me=Math.min(we,oe-2),Ce=0,X=0;X<me;++X){var Xe=C-we+X&32767,dt=A[Xe],Ke=Xe-dt&32767;Ke>Ce&&(Ce=Ke,H=Xe)}}}N=H,H=A[N],we+=N-H&32767}if(ce){b[x++]=268435456|mg[W]<<18|y0[ce];var gt=mg[W]&31,F=y0[ce]&31;I+=lh[gt]+ch[F],++T[257+gt],++E[F],D=C+W,++M}else b[x++]=r[C],++T[r[C]]}}for(C=Math.max(C,D);C<a;++C)b[x++]=r[C],++T[r[C]];h=b0(r,l,c,b,T,E,I,x,U,C-U,h),c||(s.r=h&7|l[h/8|0]<<3,h-=7,s.h=g,s.p=A,s.i=C,s.w=D)}else{for(var C=s.w||0;C<a+c;C+=65535){var xe=C+65535;xe>=a&&(l[h/8|0]=c,xe=a),h=v0(l,h+1,r.subarray(C,xe))}s.i=a}return qs(o,0,i+uh(h)+n)},r1=(function(){for(var r=new Int32Array(256),e=0;e<256;++e){for(var t=e,i=9;--i;)t=(t&1&&-306674912)^t>>>1;r[e]=t}return r})(),ph=function(){var r=-1;return{p:function(e){for(var t=r,i=0;i<e.length;++i)t=r1[t&255^e[i]]^t>>>8;r=t},d:function(){return~r}}},vg=function(){var r=1,e=0;return{p:function(t){for(var i=r,n=e,s=t.length|0,a=0;a!=s;){for(var o=Math.min(a+2655,s);a<o;++a)n+=i+=t[a];i=(i&65535)+15*(i>>16),n=(n&65535)+15*(n>>16)}r=i,e=n},d:function(){return r%=65521,e%=65521,(r&255)<<24|(r&65280)<<8|(e&255)<<8|e>>8}}},Ml=function(r,e,t,i,n){if(!n&&(n={l:1},e.dictionary)){var s=e.dictionary.subarray(-32768),a=new Tt(s.length+r.length);a.set(s),a.set(r,s.length),r=a,n.w=s.length}return s1(r,e.level==null?6:e.level,e.mem==null?n.l?Math.ceil(Math.max(8,Math.min(13,Math.log(r.length)))*1.5):20:12+e.mem,t,i,n)},Vd=function(r,e){var t={};for(var i in r)t[i]=r[i];for(var i in e)t[i]=e[i];return t},a1=function(r,e,t){for(var i=r(),n=r.toString(),s=n.slice(n.indexOf("[")+1,n.lastIndexOf("]")).replace(/\s+/g,"").split(","),a=0;a<i.length;++a){var o=i[a],l=s[a];if(typeof o=="function"){e+=";"+l+"=";var c=o.toString();if(o.prototype)if(c.indexOf("[native code]")!=-1){var h=c.indexOf(" ",8)+1;e+=c.slice(h,c.indexOf("(",h))}else{e+=c;for(var u in o.prototype)e+=";"+l+".prototype."+u+"="+o.prototype[u].toString()}else e+=c}else t[l]=o}return e},bg=[],Oz=function(r){var e=[];for(var t in r)r[t].buffer&&e.push((r[t]=new r[t].constructor(r[t])).buffer);return e},o1=function(r,e,t,i){if(!bg[t]){for(var n="",s={},a=r.length-1,o=0;o<a;++o)n=a1(r[o],n,s);bg[t]={c:a1(r[a],n,s),e:s}}var l=Vd({},bg[t].e);return Bz(bg[t].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+e.toString()+"}",t,l,Oz(l),i)},mh=function(){return[Tt,rs,Nd,lh,ch,kd,A0,KT,ZT,t1,Gd,i1,js,gg,Ws,Ag,uh,qs,it,zd,_h,mo,w0]},gh=function(){return[Tt,rs,Nd,lh,ch,kd,mg,y0,JT,Sa,e1,hh,Gd,n1,po,js,kr,dh,yg,_g,_0,fh,v0,b0,uh,qs,s1,Ml,Hd,mo]},l1=function(){return[x0,E0,ri,ph,r1]},c1=function(){return[S0,d1]},h1=function(){return[M0,ri,vg]},u1=function(){return[T0]},mo=function(r){return postMessage(r,[r.buffer])},w0=function(r){return r&&{out:r.size&&new Tt(r.size),dictionary:r.dictionary}},Ah=function(r,e,t,i,n,s){var a=o1(t,i,n,function(o,l){a.terminate(),s(o,l)});return a.postMessage([r,e],e.consume?[r.buffer]:[]),function(){a.terminate()}},Xs=function(r){return r.ondata=function(e,t){return postMessage([e,t],[e.buffer])},function(e){e.data.length?(r.push(e.data[0],e.data[1]),postMessage([e.data[0].length])):r.flush()}},yh=function(r,e,t,i,n,s,a){var o,l=o1(r,i,n,function(c,h){c?(l.terminate(),e.ondata.call(e,c)):Array.isArray(h)?h.length==1?(e.queuedSize-=h[0],e.ondrain&&e.ondrain(h[0])):(h[1]&&l.terminate(),e.ondata.call(e,c,h[0],h[1])):a(h)});l.postMessage(t),e.queuedSize=0,e.push=function(c,h){e.ondata||it(5),o&&e.ondata(it(4,0,1),null,!!h),e.queuedSize+=c.length,l.postMessage([c,o=h],[c.buffer])},e.terminate=function(){l.terminate()},s&&(e.flush=function(){l.postMessage([])})},as=function(r,e){return r[e]|r[e+1]<<8},ln=function(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0},C0=function(r,e){return ln(r,e)+ln(r,e+4)*4294967296},ri=function(r,e,t){for(;t;++e)r[e]=t,t>>>=8},x0=function(r,e){var t=e.filename;if(r[0]=31,r[1]=139,r[2]=8,r[8]=e.level<2?4:e.level==9?2:0,r[9]=3,e.mtime!=0&&ri(r,4,Math.floor(new Date(e.mtime||Date.now())/1e3)),t){r[3]=8;for(var i=0;i<=t.length;++i)r[i+10]=t.charCodeAt(i)}},S0=function(r){(r[0]!=31||r[1]!=139||r[2]!=8)&&it(6,"invalid gzip data");var e=r[3],t=10;e&4&&(t+=(r[10]|r[11]<<8)+2);for(var i=(e>>3&1)+(e>>4&1);i>0;i-=!r[t++]);return t+(e&2)},d1=function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0},E0=function(r){return 10+(r.filename?r.filename.length+1:0)},M0=function(r,e){var t=e.level,i=t==0?0:t<6?1:t==9?3:2;if(r[0]=120,r[1]=i<<6|(e.dictionary&&32),r[1]|=31-(r[0]<<8|r[1])%31,e.dictionary){var n=vg();n.p(e.dictionary),ri(r,2,n.d())}},T0=function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&it(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&it(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2};function Tl(r,e){return typeof r=="function"&&(e=r,r={}),this.ondata=e,r}var Ys=(function(){function r(e,t){if(typeof e=="function"&&(t=e,e={}),this.ondata=t,this.o=e||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new Tt(98304),this.o.dictionary){var i=this.o.dictionary.subarray(-32768);this.b.set(i,32768-i.length),this.s.i=32768-i.length}}return r.prototype.p=function(e,t){this.ondata(Ml(e,this.o,0,0,this.s),t)},r.prototype.push=function(e,t){this.ondata||it(5),this.s.l&&it(4);var i=e.length+this.s.z;if(i>this.b.length){if(i>2*this.b.length-32768){var n=new Tt(i&-32768);n.set(this.b.subarray(0,this.s.z)),this.b=n}var s=this.b.length-this.s.z;this.b.set(e.subarray(0,s),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(e.subarray(s),32768),this.s.z=e.length-s+32768,this.s.i=32766,this.s.w=32768}else this.b.set(e,this.s.z),this.s.z+=e.length;this.s.l=t&1,(this.s.z>this.s.w+8191||t)&&(this.p(this.b,t||!1),this.s.w=this.s.i,this.s.i-=2)},r.prototype.flush=function(){this.ondata||it(5),this.s.l&&it(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},r})(),f1=(function(){function r(e,t){yh([gh,function(){return[Xs,Ys]}],this,Tl.call(this,e,t),function(i){var n=new Ys(i.data);onmessage=Xs(n)},6,1)}return r})();function p1(r,e,t){return t||(t=e,e={}),typeof t!="function"&&it(7),Ah(r,e,[gh],function(i){return mo(Hd(i.data[0],i.data[1]))},0,t)}function Hd(r,e){return Ml(r,e||{},0,0)}var ys=(function(){function r(e,t){typeof e=="function"&&(t=e,e={}),this.ondata=t;var i=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:i?i.length:0},this.o=new Tt(32768),this.p=new Tt(0),i&&this.o.set(i)}return r.prototype.e=function(e){if(this.ondata||it(5),this.d&&it(4),!this.p.length)this.p=e;else if(e.length){var t=new Tt(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},r.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,i=zd(this.p,this.s,this.o);this.ondata(qs(i,t,this.s.b),this.d),this.o=qs(i,this.s.b-32768),this.s.b=this.o.length,this.p=qs(this.p,this.s.p/8|0),this.s.p&=7},r.prototype.push=function(e,t){this.e(e),this.c(t)},r})(),I0=(function(){function r(e,t){yh([mh,function(){return[Xs,ys]}],this,Tl.call(this,e,t),function(i){var n=new ys(i.data);onmessage=Xs(n)},7,0)}return r})();function P0(r,e,t){return t||(t=e,e={}),typeof t!="function"&&it(7),Ah(r,e,[mh],function(i){return mo(_h(i.data[0],w0(i.data[1])))},1,t)}function _h(r,e){return zd(r,{i:2},e&&e.out,e&&e.dictionary)}var wg=(function(){function r(e,t){this.c=ph(),this.l=0,this.v=1,Ys.call(this,e,t)}return r.prototype.push=function(e,t){this.c.p(e),this.l+=e.length,Ys.prototype.push.call(this,e,t)},r.prototype.p=function(e,t){var i=Ml(e,this.o,this.v&&E0(this.o),t&&8,this.s);this.v&&(x0(i,this.o),this.v=0),t&&(ri(i,i.length-8,this.c.d()),ri(i,i.length-4,this.l)),this.ondata(i,t)},r.prototype.flush=function(){Ys.prototype.flush.call(this)},r})(),m1=(function(){function r(e,t){yh([gh,l1,function(){return[Xs,Ys,wg]}],this,Tl.call(this,e,t),function(i){var n=new wg(i.data);onmessage=Xs(n)},8,1)}return r})();function g1(r,e,t){return t||(t=e,e={}),typeof t!="function"&&it(7),Ah(r,e,[gh,l1,function(){return[Cg]}],function(i){return mo(Cg(i.data[0],i.data[1]))},2,t)}function Cg(r,e){e||(e={});var t=ph(),i=r.length;t.p(r);var n=Ml(r,e,E0(e),8),s=n.length;return x0(n,e),ri(n,s-8,t.d()),ri(n,s-4,i),n}var xg=(function(){function r(e,t){this.v=1,this.r=0,ys.call(this,e,t)}return r.prototype.push=function(e,t){if(ys.prototype.e.call(this,e),this.r+=e.length,this.v){var i=this.p.subarray(this.v-1),n=i.length>3?S0(i):4;if(n>i.length){if(!t)return}else this.v>1&&this.onmember&&this.onmember(this.r-i.length);this.p=i.subarray(n),this.v=0}ys.prototype.c.call(this,t),this.s.f&&!this.s.l&&!t&&(this.v=uh(this.s.p)+9,this.s={i:0},this.o=new Tt(0),this.push(new Tt(0),t))},r})(),A1=(function(){function r(e,t){var i=this;yh([mh,c1,function(){return[Xs,ys,xg]}],this,Tl.call(this,e,t),function(n){var s=new xg(n.data);s.onmember=function(a){return postMessage(a)},onmessage=Xs(s)},9,0,function(n){return i.onmember&&i.onmember(n)})}return r})();function y1(r,e,t){return t||(t=e,e={}),typeof t!="function"&&it(7),Ah(r,e,[mh,c1,function(){return[Sg]}],function(i){return mo(Sg(i.data[0],i.data[1]))},3,t)}function Sg(r,e){var t=S0(r);return t+8>r.length&&it(6,"invalid gzip data"),zd(r.subarray(t,-8),{i:2},e&&e.out||new Tt(d1(r)),e&&e.dictionary)}var D0=(function(){function r(e,t){this.c=vg(),this.v=1,Ys.call(this,e,t)}return r.prototype.push=function(e,t){this.c.p(e),Ys.prototype.push.call(this,e,t)},r.prototype.p=function(e,t){var i=Ml(e,this.o,this.v&&(this.o.dictionary?6:2),t&&4,this.s);this.v&&(M0(i,this.o),this.v=0),t&&ri(i,i.length-4,this.c.d()),this.ondata(i,t)},r.prototype.flush=function(){Ys.prototype.flush.call(this)},r})(),Uz=(function(){function r(e,t){yh([gh,h1,function(){return[Xs,Ys,D0]}],this,Tl.call(this,e,t),function(i){var n=new D0(i.data);onmessage=Xs(n)},10,1)}return r})();function Fz(r,e,t){return t||(t=e,e={}),typeof t!="function"&&it(7),Ah(r,e,[gh,h1,function(){return[Eg]}],function(i){return mo(Eg(i.data[0],i.data[1]))},4,t)}function Eg(r,e){e||(e={});var t=vg();t.p(r);var i=Ml(r,e,e.dictionary?6:2,4);return M0(i,e),ri(i,i.length-4,t.d()),i}var Mg=(function(){function r(e,t){ys.call(this,e,t),this.v=e&&e.dictionary?2:1}return r.prototype.push=function(e,t){if(ys.prototype.e.call(this,e),this.v){if(this.p.length<6&&!t)return;this.p=this.p.subarray(T0(this.p,this.v-1)),this.v=0}t&&(this.p.length<4&&it(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),ys.prototype.c.call(this,t)},r})(),_1=(function(){function r(e,t){yh([mh,u1,function(){return[Xs,ys,Mg]}],this,Tl.call(this,e,t),function(i){var n=new Mg(i.data);onmessage=Xs(n)},11,0)}return r})();function v1(r,e,t){return t||(t=e,e={}),typeof t!="function"&&it(7),Ah(r,e,[mh,u1,function(){return[Ea]}],function(i){return mo(Ea(i.data[0],w0(i.data[1])))},5,t)}function Ea(r,e){return zd(r.subarray(T0(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}var R0=(function(){function r(e,t){this.o=Tl.call(this,e,t)||{},this.G=xg,this.I=ys,this.Z=Mg}return r.prototype.i=function(){var e=this;this.s.ondata=function(t,i){e.ondata(t,i)}},r.prototype.push=function(e,t){if(this.ondata||it(5),this.s)this.s.push(e,t);else{if(this.p&&this.p.length){var i=new Tt(this.p.length+e.length);i.set(this.p),i.set(e,this.p.length)}else this.p=e;this.p.length>2&&(this.s=this.p[0]==31&&this.p[1]==139&&this.p[2]==8?new this.G(this.o):(this.p[0]&15)!=8||this.p[0]>>4>7||(this.p[0]<<8|this.p[1])%31?new this.I(this.o):new this.Z(this.o),this.i(),this.s.push(this.p,t),this.p=null)}},r})(),Nz=(function(){function r(e,t){R0.call(this,e,t),this.queuedSize=0,this.G=A1,this.I=I0,this.Z=_1}return r.prototype.i=function(){var e=this;this.s.ondata=function(t,i,n){e.ondata(t,i,n)},this.s.ondrain=function(t){e.queuedSize-=t,e.ondrain&&e.ondrain(t)}},r.prototype.push=function(e,t){this.queuedSize+=e.length,R0.prototype.push.call(this,e,t)},r})();function kz(r,e,t){return t||(t=e,e={}),typeof t!="function"&&it(7),r[0]==31&&r[1]==139&&r[2]==8?y1(r,e,t):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?P0(r,e,t):v1(r,e,t)}function Gz(r,e){return r[0]==31&&r[1]==139&&r[2]==8?Sg(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?_h(r,e):Ea(r,e)}var B0=function(r,e,t,i){for(var n in r){var s=r[n],a=e+n,o=i;Array.isArray(s)&&(o=Vd(i,s[1]),s=s[0]),s instanceof Tt?t[a]=[s,o]:(t[a+="/"]=[new Tt(0),o],B0(s,a,t,i))}},b1=typeof TextEncoder<"u"&&new TextEncoder,L0=typeof TextDecoder<"u"&&new TextDecoder,w1=0;try{L0.decode(po,{stream:!0}),w1=1}catch{}var C1=function(r){for(var e="",t=0;;){var i=r[t++],n=(i>127)+(i>223)+(i>239);if(t+n>r.length)return{s:e,r:qs(r,t-1)};n?n==3?(i=((i&15)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,e+=String.fromCharCode(55296|i>>10,56320|i&1023)):n&1?e+=String.fromCharCode((i&31)<<6|r[t++]&63):e+=String.fromCharCode((i&15)<<12|(r[t++]&63)<<6|r[t++]&63):e+=String.fromCharCode(i)}},zz=(function(){function r(e){this.ondata=e,w1?this.t=new TextDecoder:this.p=po}return r.prototype.push=function(e,t){if(this.ondata||it(5),t=!!t,this.t){this.ondata(this.t.decode(e,{stream:!0}),t),t&&(this.t.decode().length&&it(8),this.t=null);return}this.p||it(4);var i=new Tt(this.p.length+e.length);i.set(this.p),i.set(e,this.p.length);var n=C1(i),s=n.s,a=n.r;t?(a.length&&it(8),this.p=null):this.p=a,this.ondata(s,t)},r})(),Vz=(function(){function r(e){this.ondata=e}return r.prototype.push=function(e,t){this.ondata||it(5),this.d&&it(4),this.ondata(go(e),this.d=t||!1)},r})();function go(r,e){if(e){for(var t=new Tt(r.length),i=0;i<r.length;++i)t[i]=r.charCodeAt(i);return t}if(b1)return b1.encode(r);for(var n=r.length,s=new Tt(r.length+(r.length>>1)),a=0,o=function(h){s[a++]=h},i=0;i<n;++i){if(a+5>s.length){var l=new Tt(a+8+(n-i<<1));l.set(s),s=l}var c=r.charCodeAt(i);c<128||e?o(c):c<2048?(o(192|c>>6),o(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|r.charCodeAt(++i)&1023,o(240|c>>18),o(128|c>>12&63),o(128|c>>6&63),o(128|c&63)):(o(224|c>>12),o(128|c>>6&63),o(128|c&63))}return qs(s,0,a)}function Qd(r,e){if(e){for(var t="",i=0;i<r.length;i+=16384)t+=String.fromCharCode.apply(null,r.subarray(i,i+16384));return t}else{if(L0)return L0.decode(r);var n=C1(r),s=n.s,t=n.r;return t.length&&it(8),s}}var x1=function(r){return r==1?3:r<6?2:r==9?1:0},S1=function(r,e){return e+30+as(r,e+26)+as(r,e+28)},E1=function(r,e,t){var i=as(r,e+28),n=Qd(r.subarray(e+46,e+46+i),!(as(r,e+8)&2048)),s=e+46+i,a=ln(r,e+20),o=t&&a==4294967295?M1(r,s):[a,ln(r,e+24),ln(r,e+42)],l=o[0],c=o[1],h=o[2];return[as(r,e+10),l,c,n,s+as(r,e+30)+as(r,e+32),h]},M1=function(r,e){for(;as(r,e)!=1;e+=4+as(r,e+2));return[C0(r,e+12),C0(r,e+4),C0(r,e+20)]},Ao=function(r){var e=0;if(r)for(var t in r){var i=r[t].length;i>65535&&it(9),e+=i+4}return e},vh=function(r,e,t,i,n,s,a,o){var l=i.length,c=t.extra,h=o&&o.length,u=Ao(c);ri(r,e,a!=null?33639248:67324752),e+=4,a!=null&&(r[e++]=20,r[e++]=t.os),r[e]=20,e+=2,r[e++]=t.flag<<1|(s<0&&8),r[e++]=n&&8,r[e++]=t.compression&255,r[e++]=t.compression>>8;var d=new Date(t.mtime==null?Date.now():t.mtime),p=d.getFullYear()-1980;if((p<0||p>119)&&it(10),ri(r,e,p<<25|d.getMonth()+1<<21|d.getDate()<<16|d.getHours()<<11|d.getMinutes()<<5|d.getSeconds()>>1),e+=4,s!=-1&&(ri(r,e,t.crc),ri(r,e+4,s<0?-s-2:s),ri(r,e+8,t.size)),ri(r,e+12,l),ri(r,e+14,u),e+=16,a!=null&&(ri(r,e,h),ri(r,e+6,t.attrs),ri(r,e+10,a),e+=14),r.set(i,e),e+=l,u)for(var m in c){var A=c[m],g=A.length;ri(r,e,+m),ri(r,e+2,g),r.set(A,e+4),e+=4+g}return h&&(r.set(o,e),e+=h),e},O0=function(r,e,t,i,n){ri(r,e,101010256),ri(r,e+8,t),ri(r,e+10,t),ri(r,e+12,i),ri(r,e+16,n)},jd=(function(){function r(e){this.filename=e,this.c=ph(),this.size=0,this.compression=0}return r.prototype.process=function(e,t){this.ondata(null,e,t)},r.prototype.push=function(e,t){this.ondata||it(5),this.c.p(e),this.size+=e.length,t&&(this.crc=this.c.d()),this.process(e,t||!1)},r})(),Hz=(function(){function r(e,t){var i=this;t||(t={}),jd.call(this,e),this.d=new Ys(t,function(n,s){i.ondata(null,n,s)}),this.compression=8,this.flag=x1(t.level)}return r.prototype.process=function(e,t){try{this.d.push(e,t)}catch(i){this.ondata(i,null,t)}},r.prototype.push=function(e,t){jd.prototype.push.call(this,e,t)},r})(),Qz=(function(){function r(e,t){var i=this;t||(t={}),jd.call(this,e),this.d=new f1(t,function(n,s,a){i.ondata(n,s,a)}),this.compression=8,this.flag=x1(t.level),this.terminate=this.d.terminate}return r.prototype.process=function(e,t){this.d.push(e,t)},r.prototype.push=function(e,t){jd.prototype.push.call(this,e,t)},r})(),jz=(function(){function r(e){this.ondata=e,this.u=[],this.d=1}return r.prototype.add=function(e){var t=this;if(this.ondata||it(5),this.d&2)this.ondata(it(4+(this.d&1)*8,0,1),null,!1);else{var i=go(e.filename),n=i.length,s=e.comment,a=s&&go(s),o=n!=e.filename.length||a&&s.length!=a.length,l=n+Ao(e.extra)+30;n>65535&&this.ondata(it(11,0,1),null,!1);var c=new Tt(l);vh(c,0,e,i,o,-1);var h=[c],u=function(){for(var g=0,y=h;g<y.length;g++){var v=y[g];t.ondata(null,v,!1)}h=[]},d=this.d;this.d=0;var p=this.u.length,m=Vd(e,{f:i,u:o,o:a,t:function(){e.terminate&&e.terminate()},r:function(){if(u(),d){var g=t.u[p+1];g?g.r():t.d=1}d=1}}),A=0;e.ondata=function(g,y,v){if(g)t.ondata(g,y,v),t.terminate();else if(A+=y.length,h.push(y),v){var _=new Tt(16);ri(_,0,134695760),ri(_,4,e.crc),ri(_,8,A),ri(_,12,e.size),h.push(_),m.c=A,m.b=l+A+16,m.crc=e.crc,m.size=e.size,d&&m.r(),d=1}else d&&u()},this.u.push(m)}},r.prototype.end=function(){var e=this;if(this.d&2){this.ondata(it(4+(this.d&1)*8,0,1),null,!0);return}this.d?this.e():this.u.push({r:function(){e.d&1&&(e.u.splice(-1,1),e.e())},t:function(){}}),this.d=3},r.prototype.e=function(){for(var e=0,t=0,i=0,n=0,s=this.u;n<s.length;n++){var a=s[n];i+=46+a.f.length+Ao(a.extra)+(a.o?a.o.length:0)}for(var o=new Tt(i+22),l=0,c=this.u;l<c.length;l++){var a=c[l];vh(o,e,a,a.f,a.u,-a.c-2,t,a.o),e+=46+a.f.length+Ao(a.extra)+(a.o?a.o.length:0),t+=a.b}O0(o,e,this.u.length,i,t),this.ondata(null,o,!0),this.d=2},r.prototype.terminate=function(){for(var e=0,t=this.u;e<t.length;e++){var i=t[e];i.t()}this.d=2},r})();function Wz(r,e,t){t||(t=e,e={}),typeof t!="function"&&it(7);var i={};B0(r,"",i,e);var n=Object.keys(i),s=n.length,a=0,o=0,l=s,c=new Array(s),h=[],u=function(){for(var g=0;g<h.length;++g)h[g]()},d=function(g,y){Ig(function(){t(g,y)})};Ig(function(){d=t});var p=function(){var g=new Tt(o+22),y=a,v=o-a;o=0;for(var _=0;_<l;++_){var b=c[_];try{var T=b.c.length;vh(g,o,b,b.f,b.u,T);var E=30+b.f.length+Ao(b.extra),M=o+E;g.set(b.c,M),vh(g,a,b,b.f,b.u,T,o,b.m),a+=16+E+(b.m?b.m.length:0),o=M+T}catch(I){return d(I,null)}}O0(g,a,c.length,v,y),d(null,g)};s||p();for(var m=function(g){var y=n[g],v=i[y],_=v[0],b=v[1],T=ph(),E=_.length;T.p(_);var M=go(y),I=M.length,C=b.comment,x=C&&go(C),D=x&&x.length,U=Ao(b.extra),O=b.level==0?0:8,N=function(H,V){if(H)u(),d(H,null);else{var X=V.length;c[g]=Vd(b,{size:E,crc:T.d(),c:V,f:M,m:x,u:I!=y.length||x&&C.length!=D,compression:O}),a+=30+I+U+X,o+=76+2*(I+U)+(D||0)+X,--s||p()}};if(I>65535&&N(it(11,0,1),null),!O)N(null,_);else if(E<16e4)try{N(null,Hd(_,b))}catch(H){N(H,null)}else h.push(p1(_,b,N))},A=0;A<l;++A)m(A);return u}function Tg(r,e){e||(e={});var t={},i=[];B0(r,"",t,e);var n=0,s=0;for(var a in t){var o=t[a],l=o[0],c=o[1],h=c.level==0?0:8,u=go(a),d=u.length,p=c.comment,m=p&&go(p),A=m&&m.length,g=Ao(c.extra);d>65535&&it(11);var y=h?Hd(l,c):l,v=y.length,_=ph();_.p(l),i.push(Vd(c,{size:l.length,crc:_.d(),c:y,f:u,m,u:d!=a.length||m&&p.length!=A,o:n,compression:h})),n+=30+d+g+v,s+=76+2*(d+g)+(A||0)+v}for(var b=new Tt(s+22),T=n,E=s-n,M=0;M<i.length;++M){var u=i[M];vh(b,u.o,u,u.f,u.u,u.c.length);var I=30+u.f.length+Ao(u.extra);b.set(u.c,u.o+I),vh(b,n,u,u.f,u.u,u.c.length,u.o,u.m),n+=16+I+(u.m?u.m.length:0)}return O0(b,n,i.length,E,T),b}var T1=(function(){function r(){}return r.prototype.push=function(e,t){this.ondata(null,e,t)},r.compression=0,r})(),qz=(function(){function r(){var e=this;this.i=new ys(function(t,i){e.ondata(null,t,i)})}return r.prototype.push=function(e,t){try{this.i.push(e,t)}catch(i){this.ondata(i,null,t)}},r.compression=8,r})(),Xz=(function(){function r(e,t){var i=this;t<32e4?this.i=new ys(function(n,s){i.ondata(null,n,s)}):(this.i=new I0(function(n,s,a){i.ondata(n,s,a)}),this.terminate=this.i.terminate)}return r.prototype.push=function(e,t){this.i.terminate&&(e=qs(e,0)),this.i.push(e,t)},r.compression=8,r})(),Yz=(function(){function r(e){this.onfile=e,this.k=[],this.o={0:T1},this.p=po}return r.prototype.push=function(e,t){var i=this;if(this.onfile||it(5),this.p||it(4),this.c>0){var n=Math.min(this.c,e.length),s=e.subarray(0,n);if(this.c-=n,this.d?this.d.push(s,!this.c):this.k[0].push(s),e=e.subarray(n),e.length)return this.push(e,t)}else{var a=0,o=0,l=void 0,c=void 0;this.p.length?e.length?(c=new Tt(this.p.length+e.length),c.set(this.p),c.set(e,this.p.length)):c=this.p:c=e;for(var h=c.length,u=this.c,d=u&&this.d,p=function(){var y,v=ln(c,o);if(v==67324752){a=1,l=o,m.d=null,m.c=0;var _=as(c,o+6),b=as(c,o+8),T=_&2048,E=_&8,M=as(c,o+26),I=as(c,o+28);if(h>o+30+M+I){var C=[];m.k.unshift(C),a=2;var x=ln(c,o+18),D=ln(c,o+22),U=Qd(c.subarray(o+30,o+=30+M),!T);x==4294967295?(y=E?[-2]:M1(c,o),x=y[0],D=y[1]):E&&(x=-1),o+=I,m.c=x;var O,N={name:U,compression:b,start:function(){if(N.ondata||it(5),!x)N.ondata(null,po,!0);else{var H=i.o[b];H||N.ondata(it(14,"unknown compression type "+b,1),null,!1),O=x<0?new H(U):new H(U,x,D),O.ondata=function(ce,ue,we){N.ondata(ce,ue,we)};for(var V=0,X=C;V<X.length;V++){var W=X[V];O.push(W,!1)}i.k[0]==C&&i.c?i.d=O:O.push(po,!0)}},terminate:function(){O&&O.terminate&&O.terminate()}};x>=0&&(N.size=x,N.originalSize=D),m.onfile(N)}return"break"}else if(u){if(v==134695760)return l=o+=12+(u==-2&&8),a=3,m.c=0,"break";if(v==33639248)return l=o-=4,a=3,m.c=0,"break"}},m=this;o<h-4;++o){var A=p();if(A==="break")break}if(this.p=po,u<0){var g=a?c.subarray(0,l-12-(u==-2&&8)-(ln(c,l-16)==134695760&&4)):c.subarray(0,o);d?d.push(g,!!a):this.k[+(a==2)].push(g)}if(a&2)return this.push(c.subarray(o),t);this.p=c.subarray(o)}t&&(this.c&&it(13),this.p=null)},r.prototype.register=function(e){this.o[e.compression]=e},r})(),Ig=typeof queueMicrotask=="function"?queueMicrotask:typeof setTimeout=="function"?setTimeout:function(r){r()};function $z(r,e,t){t||(t=e,e={}),typeof t!="function"&&it(7);var i=[],n=function(){for(var g=0;g<i.length;++g)i[g]()},s={},a=function(g,y){Ig(function(){t(g,y)})};Ig(function(){a=t});for(var o=r.length-22;ln(r,o)!=101010256;--o)if(!o||r.length-o>65558)return a(it(13,0,1),null),n;var l=as(r,o+8);if(l){var c=l,h=ln(r,o+16),u=h==4294967295||c==65535;if(u){var d=ln(r,o-12);u=ln(r,d)==101075792,u&&(c=l=ln(r,d+32),h=ln(r,d+48))}for(var p=e&&e.filter,m=function(g){var y=E1(r,h,u),v=y[0],_=y[1],b=y[2],T=y[3],E=y[4],M=y[5],I=S1(r,M);h=E;var C=function(D,U){D?(n(),a(D,null)):(U&&(s[T]=U),--l||a(null,s))};if(!p||p({name:T,size:_,originalSize:b,compression:v}))if(!v)C(null,qs(r,I,I+_));else if(v==8){var x=r.subarray(I,I+_);if(b<524288||_>.8*b)try{C(null,_h(x,{out:new Tt(b)}))}catch(D){C(D,null)}else i.push(P0(x,{size:b},C))}else C(it(14,"unknown compression type "+v,1),null);else C(null,null)},A=0;A<c;++A)m(A)}else a(null,{});return n}function U0(r,e){for(var t={},i=r.length-22;ln(r,i)!=101010256;--i)(!i||r.length-i>65558)&&it(13);var n=as(r,i+8);if(!n)return{};var s=ln(r,i+16),a=s==4294967295||n==65535;if(a){var o=ln(r,i-12);a=ln(r,o)==101075792,a&&(n=ln(r,o+32),s=ln(r,o+48))}for(var l=e&&e.filter,c=0;c<n;++c){var h=E1(r,s,a),u=h[0],d=h[1],p=h[2],m=h[3],A=h[4],g=h[5],y=S1(r,g);s=A,(!l||l({name:m,size:d,originalSize:p,compression:u}))&&(u?u==8?t[m]=_h(r.subarray(y,y+d),{out:new Tt(p)}):it(14,"unknown compression type "+u):t[m]=qs(r,y,y+d))}return t}function I1(r,e,t){const i=t.length-r-1;if(e>=t[i])return i-1;if(e<=t[r])return r;let n=r,s=i,a=Math.floor((n+s)/2);for(;e<t[a]||e>=t[a+1];)e<t[a]?s=a:n=a,a=Math.floor((n+s)/2);return a}function Kz(r,e,t,i){const n=[],s=[],a=[];n[0]=1;for(let o=1;o<=t;++o){s[o]=e-i[r+1-o],a[o]=i[r+o]-e;let l=0;for(let c=0;c<o;++c){const h=a[c+1],u=s[o-c],d=n[c]/(h+u);n[c]=l+h*d,l=u*d}n[o]=l}return n}function Jz(r,e,t,i){const n=I1(r,i,e),s=Kz(n,i,r,e),a=new et(0,0,0,0);for(let o=0;o<=r;++o){const l=t[n-r+o],c=s[o],h=l.w*c;a.x+=l.x*h,a.y+=l.y*h,a.z+=l.z*h,a.w+=l.w*c}return a}function Zz(r,e,t,i,n){const s=[];for(let u=0;u<=t;++u)s[u]=0;const a=[];for(let u=0;u<=i;++u)a[u]=s.slice(0);const o=[];for(let u=0;u<=t;++u)o[u]=s.slice(0);o[0][0]=1;const l=s.slice(0),c=s.slice(0);for(let u=1;u<=t;++u){l[u]=e-n[r+1-u],c[u]=n[r+u]-e;let d=0;for(let p=0;p<u;++p){const m=c[p+1],A=l[u-p];o[u][p]=m+A;const g=o[p][u-1]/o[u][p];o[p][u]=d+m*g,d=A*g}o[u][u]=d}for(let u=0;u<=t;++u)a[0][u]=o[u][t];for(let u=0;u<=t;++u){let d=0,p=1;const m=[];for(let A=0;A<=t;++A)m[A]=s.slice(0);m[0][0]=1;for(let A=1;A<=i;++A){let g=0;const y=u-A,v=t-A;u>=A&&(m[p][0]=m[d][0]/o[v+1][y],g=m[p][0]*o[y][v]);const _=y>=-1?1:-y,b=u-1<=v?A-1:t-u;for(let E=_;E<=b;++E)m[p][E]=(m[d][E]-m[d][E-1])/o[v+1][y+E],g+=m[p][E]*o[y+E][v];u<=v&&(m[p][A]=-m[d][A-1]/o[v+1][u],g+=m[p][A]*o[u][v]),a[A][u]=g;const T=d;d=p,p=T}}let h=t;for(let u=1;u<=i;++u){for(let d=0;d<=t;++d)a[u][d]*=h;h*=t-u}return a}function eV(r,e,t,i,n){const s=n<r?n:r,a=[],o=I1(r,i,e),l=Zz(o,i,r,s,e),c=[];for(let h=0;h<t.length;++h){const u=t[h].clone(),d=u.w;u.x*=d,u.y*=d,u.z*=d,c[h]=u}for(let h=0;h<=s;++h){const u=c[o-r].clone().multiplyScalar(l[h][0]);for(let d=1;d<=r;++d)u.add(c[o-r+d].clone().multiplyScalar(l[h][d]));a[h]=u}for(let h=s+1;h<=n+1;++h)a[h]=new et(0,0,0);return a}function tV(r,e){let t=1;for(let n=2;n<=r;++n)t*=n;let i=1;for(let n=2;n<=e;++n)i*=n;for(let n=2;n<=r-e;++n)i*=n;return t/i}function iV(r){const e=r.length,t=[],i=[];for(let s=0;s<e;++s){const a=r[s];t[s]=new S(a.x,a.y,a.z),i[s]=a.w}const n=[];for(let s=0;s<e;++s){const a=t[s].clone();for(let o=1;o<=s;++o)a.sub(n[s-o].clone().multiplyScalar(tV(s,o)*i[o]));n[s]=a.divideScalar(i[0])}return n}function nV(r,e,t,i,n){const s=eV(r,e,t,i,n);return iV(s)}class sV extends Ts{constructor(e,t,i,n,s){super(),this.degree=e,this.knots=t,this.controlPoints=[],this.startKnot=n||0,this.endKnot=s||this.knots.length-1;for(let a=0;a<i.length;++a){const o=i[a];this.controlPoints[a]=new et(o.x,o.y,o.z,o.w)}}getPoint(e,t=new S){const i=t,n=this.knots[this.startKnot]+e*(this.knots[this.endKnot]-this.knots[this.startKnot]),s=Jz(this.degree,this.knots,this.controlPoints,n);return s.w!==1&&s.divideScalar(s.w),i.set(s.x,s.y,s.z)}getTangent(e,t=new S){const i=t,n=this.knots[0]+e*(this.knots[this.knots.length-1]-this.knots[0]),s=nV(this.degree,this.knots,this.controlPoints,n,1);return i.copy(s[1]).normalize(),i}}let Dt,Xi,Kn;class P1 extends oi{constructor(e){super(e)}load(e,t,i,n){const s=this,a=s.path===""?Ps.extractUrlBase(e):s.path,o=new ti(this.manager);o.setPath(s.path),o.setResponseType("arraybuffer"),o.setRequestHeader(s.requestHeader),o.setWithCredentials(s.withCredentials),o.load(e,function(l){try{t(s.parse(l,a))}catch(c){n?n(c):console.error(c),s.manager.itemError(e)}},i,n)}parse(e,t){if(hV(e))Dt=new cV().parse(e);else{const s=U1(e);if(!uV(s))throw new Error("THREE.FBXLoader: Unknown format.");if(B1(s)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+B1(s));Dt=new lV().parse(s)}const i=new Za(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin),n=new rV(i,this.manager).parse(Dt);return Dt=null,Xi=null,Kn=null,n}}class rV{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){Xi=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),i=this.parseMaterials(t),n=this.parseDeformers(),s=new aV().parse(n);return this.parseScene(n,s,i),Kn}parseConnections(){const e=new Map;return"Connections"in Dt&&Dt.Connections.connections.forEach(function(i){const n=i[0],s=i[1],a=i[2];e.has(n)||e.set(n,{parents:[],children:[]});const o={ID:s,relationship:a};e.get(n).parents.push(o),e.has(s)||e.set(s,{parents:[],children:[]});const l={ID:n,relationship:a};e.get(s).children.push(l)}),e}parseImages(){const e={},t={};if("Video"in Dt.Objects){const i=Dt.Objects.Video;for(const n in i){const s=i[n],a=parseInt(n);if(e[a]=s.RelativeFilename||s.Filename,"Content"in s){const o=s.Content instanceof ArrayBuffer&&s.Content.byteLength>0,l=typeof s.Content=="string"&&s.Content!=="";if(o||l){const c=this.parseImage(i[n]);t[s.RelativeFilename||s.Filename]=c}}}}for(const i in e){const n=e[i];t[n]!==void 0?e[i]=t[n]:e[i]=e[i].split("\\").pop()}return e}parseImage(e){const t=e.Content,i=e.RelativeFilename||e.Filename,n=i.slice(i.lastIndexOf(".")+1).toLowerCase();let s;switch(n){case"bmp":s="image/bmp";break;case"jpg":case"jpeg":s="image/jpeg";break;case"png":s="image/png";break;case"tif":s="image/tiff";break;case"tga":this.manager.getHandler(".tga")===null&&console.warn("FBXLoader: TGA loader not found, skipping ",i),s="image/tga";break;default:console.warn('FBXLoader: Image type "'+n+'" is not supported.');return}if(typeof t=="string")return"data:"+s+";base64,"+t;{const a=new Uint8Array(t);return window.URL.createObjectURL(new Blob([a],{type:s}))}}parseTextures(e){const t=new Map;if("Texture"in Dt.Objects){const i=Dt.Objects.Texture;for(const n in i){const s=this.parseTexture(i[n],e);t.set(parseInt(n),s)}}return t}parseTexture(e,t){const i=this.loadTexture(e,t);i.ID=e.id,i.name=e.attrName;const n=e.WrapModeU,s=e.WrapModeV,a=n!==void 0?n.value:0,o=s!==void 0?s.value:0;if(i.wrapS=a===0?Pn:di,i.wrapT=o===0?Pn:di,"Scaling"in e){const l=e.Scaling.value;i.repeat.x=l[0],i.repeat.y=l[1]}if("Translation"in e){const l=e.Translation.value;i.offset.x=l[0],i.offset.y=l[1]}return i}loadTexture(e,t){const i=new Set(["tga","tif","tiff","exr","dds","hdr","ktx2"]),n=e.FileName.split(".").pop().toLowerCase(),s=i.has(n)?this.manager.getHandler(`.${n}`):this.textureLoader;if(!s)return console.warn(`FBXLoader: ${n.toUpperCase()} loader not found, creating placeholder texture for`,e.RelativeFilename),new kt;const a=s.path;a||s.setPath(this.textureLoader.path);const o=Xi.get(e.id).children;let l;o!==void 0&&o.length>0&&t[o[0].ID]!==void 0&&(l=t[o[0].ID],(l.indexOf("blob:")===0||l.indexOf("data:")===0)&&s.setPath(void 0));const c=s.load(l);return s.setPath(a),c}parseMaterials(e){const t=new Map;if("Material"in Dt.Objects){const i=Dt.Objects.Material;for(const n in i){const s=this.parseMaterial(i[n],e);s!==null&&t.set(parseInt(n),s)}}return t}parseMaterial(e,t){const i=e.id,n=e.attrName;let s=e.ShadingModel;if(typeof s=="object"&&(s=s.value),!Xi.has(i))return null;const a=this.parseParameters(e,t,i);let o;switch(s.toLowerCase()){case"phong":o=new Zo;break;case"lambert":o=new o_;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',s),o=new Zo;break}return o.setValues(a),o.name=n,o}parseParameters(e,t,i){const n={};e.BumpFactor&&(n.bumpScale=e.BumpFactor.value),e.Diffuse?n.color=new ee().fromArray(e.Diffuse.value).convertSRGBToLinear():e.DiffuseColor&&(e.DiffuseColor.type==="Color"||e.DiffuseColor.type==="ColorRGB")&&(n.color=new ee().fromArray(e.DiffuseColor.value).convertSRGBToLinear()),e.DisplacementFactor&&(n.displacementScale=e.DisplacementFactor.value),e.Emissive?n.emissive=new ee().fromArray(e.Emissive.value).convertSRGBToLinear():e.EmissiveColor&&(e.EmissiveColor.type==="Color"||e.EmissiveColor.type==="ColorRGB")&&(n.emissive=new ee().fromArray(e.EmissiveColor.value).convertSRGBToLinear()),e.EmissiveFactor&&(n.emissiveIntensity=parseFloat(e.EmissiveFactor.value)),e.Opacity&&(n.opacity=parseFloat(e.Opacity.value)),n.opacity<1&&(n.transparent=!0),e.ReflectionFactor&&(n.reflectivity=e.ReflectionFactor.value),e.Shininess&&(n.shininess=e.Shininess.value),e.Specular?n.specular=new ee().fromArray(e.Specular.value).convertSRGBToLinear():e.SpecularColor&&e.SpecularColor.type==="Color"&&(n.specular=new ee().fromArray(e.SpecularColor.value).convertSRGBToLinear());const s=this;return Xi.get(i).children.forEach(function(a){const o=a.relationship;switch(o){case"Bump":n.bumpMap=s.getTexture(t,a.ID);break;case"Maya|TEX_ao_map":n.aoMap=s.getTexture(t,a.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":n.map=s.getTexture(t,a.ID),n.map!==void 0&&(n.map.colorSpace=Ct);break;case"DisplacementColor":n.displacementMap=s.getTexture(t,a.ID);break;case"EmissiveColor":n.emissiveMap=s.getTexture(t,a.ID),n.emissiveMap!==void 0&&(n.emissiveMap.colorSpace=Ct);break;case"NormalMap":case"Maya|TEX_normal_map":n.normalMap=s.getTexture(t,a.ID);break;case"ReflectionColor":n.envMap=s.getTexture(t,a.ID),n.envMap!==void 0&&(n.envMap.mapping=$r,n.envMap.colorSpace=Ct);break;case"SpecularColor":n.specularMap=s.getTexture(t,a.ID),n.specularMap!==void 0&&(n.specularMap.colorSpace=Ct);break;case"TransparentColor":case"TransparencyFactor":n.alphaMap=s.getTexture(t,a.ID),n.transparent=!0;break;default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",o);break}}),n}getTexture(e,t){return"LayeredTexture"in Dt.Objects&&t in Dt.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=Xi.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in Dt.Objects){const i=Dt.Objects.Deformer;for(const n in i){const s=i[n],a=Xi.get(parseInt(n));if(s.attrType==="Skin"){const o=this.parseSkeleton(a,i);o.ID=n,a.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),o.geometryID=a.parents[0].ID,e[n]=o}else if(s.attrType==="BlendShape"){const o={id:n};o.rawTargets=this.parseMorphTargets(a,i),o.id=n,a.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[n]=o}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const i=[];return e.children.forEach(function(n){const s=t[n.ID];if(s.attrType!=="Cluster")return;const a={ID:n.ID,indices:[],weights:[],transformLink:new fe().fromArray(s.TransformLink.a)};"Indexes"in s&&(a.indices=s.Indexes.a,a.weights=s.Weights.a),i.push(a)}),{rawBones:i,bones:[]}}parseMorphTargets(e,t){const i=[];for(let n=0;n<e.children.length;n++){const s=e.children[n],a=t[s.ID],o={name:a.attrName,initialWeight:a.DeformPercent,id:a.id,fullWeights:a.FullWeights.a};if(a.attrType!=="BlendShapeChannel")return;o.geoID=Xi.get(parseInt(s.ID)).children.filter(function(l){return l.relationship===void 0})[0].ID,i.push(o)}return i}parseScene(e,t,i){Kn=new Vi;const n=this.parseModels(e.skeletons,t,i),s=Dt.Objects.Model,a=this;n.forEach(function(l){const c=s[l.ID];a.setLookAtProperties(l,c),Xi.get(l.ID).parents.forEach(function(u){const d=n.get(u.ID);d!==void 0&&d.add(l)}),l.parent===null&&Kn.add(l)}),this.bindSkeleton(e.skeletons,t,n),this.addGlobalSceneSettings(),Kn.traverse(function(l){if(l.userData.transformData){l.parent&&(l.userData.transformData.parentMatrix=l.parent.matrix,l.userData.transformData.parentMatrixWorld=l.parent.matrixWorld);const c=L1(l.userData.transformData);l.applyMatrix4(c),l.updateWorldMatrix()}});const o=new oV().parse();Kn.children.length===1&&Kn.children[0].isGroup&&(Kn.children[0].animations=o,Kn=Kn.children[0]),Kn.animations=o}parseModels(e,t,i){const n=new Map,s=Dt.Objects.Model;for(const a in s){const o=parseInt(a),l=s[a],c=Xi.get(o);let h=this.buildSkeleton(c,e,o,l.attrName);if(!h){switch(l.attrType){case"Camera":h=this.createCamera(c);break;case"Light":h=this.createLight(c);break;case"Mesh":h=this.createMesh(c,t,i);break;case"NurbsCurve":h=this.createCurve(c,t);break;case"LimbNode":case"Root":h=new Rc;break;default:h=new Vi;break}h.name=l.attrName?Et.sanitizeNodeName(l.attrName):"",h.userData.originalName=l.attrName,h.ID=o}this.getTransformData(h,l),n.set(o,h)}return n}buildSkeleton(e,t,i,n){let s=null;return e.parents.forEach(function(a){for(const o in t){const l=t[o];l.rawBones.forEach(function(c,h){if(c.ID===a.ID){const u=s;s=new Rc,s.matrixWorld.copy(c.transformLink),s.name=n?Et.sanitizeNodeName(n):"",s.userData.originalName=n,s.ID=i,l.bones[h]=s,u!==null&&s.add(u)}})}}),s}createCamera(e){let t,i;if(e.children.forEach(function(n){const s=Dt.Objects.NodeAttribute[n.ID];s!==void 0&&(i=s)}),i===void 0)t=new ft;else{let n=0;i.CameraProjectionType!==void 0&&i.CameraProjectionType.value===1&&(n=1);let s=1;i.NearPlane!==void 0&&(s=i.NearPlane.value/1e3);let a=1e3;i.FarPlane!==void 0&&(a=i.FarPlane.value/1e3);let o=window.innerWidth,l=window.innerHeight;i.AspectWidth!==void 0&&i.AspectHeight!==void 0&&(o=i.AspectWidth.value,l=i.AspectHeight.value);const c=o/l;let h=45;i.FieldOfView!==void 0&&(h=i.FieldOfView.value);const u=i.FocalLength?i.FocalLength.value:null;switch(n){case 0:t=new zi(h,c,s,a),u!==null&&t.setFocalLength(u);break;case 1:t=new Mr(-o/2,o/2,l/2,-l/2,s,a);break;default:console.warn("THREE.FBXLoader: Unknown camera type "+n+"."),t=new ft;break}}return t}createLight(e){let t,i;if(e.children.forEach(function(n){const s=Dt.Objects.NodeAttribute[n.ID];s!==void 0&&(i=s)}),i===void 0)t=new ft;else{let n;i.LightType===void 0?n=0:n=i.LightType.value;let s=16777215;i.Color!==void 0&&(s=new ee().fromArray(i.Color.value).convertSRGBToLinear());let a=i.Intensity===void 0?1:i.Intensity.value/100;i.CastLightOnObject!==void 0&&i.CastLightOnObject.value===0&&(a=0);let o=0;i.FarAttenuationEnd!==void 0&&(i.EnableFarAttenuation!==void 0&&i.EnableFarAttenuation.value===0?o=0:o=i.FarAttenuationEnd.value);const l=1;switch(n){case 0:t=new nl(s,a,o,l);break;case 1:t=new sl(s,a);break;case 2:let c=Math.PI/3;i.InnerAngle!==void 0&&(c=Ft.degToRad(i.InnerAngle.value));let h=0;i.OuterAngle!==void 0&&(h=Ft.degToRad(i.OuterAngle.value),h=Math.max(h,1)),t=new zc(s,a,o,c,h,l);break;default:console.warn("THREE.FBXLoader: Unknown light type "+i.LightType.value+", defaulting to a PointLight."),t=new nl(s,a);break}i.CastShadows!==void 0&&i.CastShadows.value===1&&(t.castShadow=!0)}return t}createMesh(e,t,i){let n,s=null,a=null;const o=[];return e.children.forEach(function(l){t.has(l.ID)&&(s=t.get(l.ID)),i.has(l.ID)&&o.push(i.get(l.ID))}),o.length>1?a=o:o.length>0?a=o[0]:(a=new Zo({name:oi.DEFAULT_MATERIAL_NAME,color:13421772}),o.push(a)),"color"in s.attributes&&o.forEach(function(l){l.vertexColors=!0}),s.FBX_Deformer?(n=new _p(s,a),n.normalizeSkinWeights()):n=new _e(s,a),n}createCurve(e,t){const i=e.children.reduce(function(s,a){return t.has(a.ID)&&(s=t.get(a.ID)),s},null),n=new Mi({name:oi.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new fn(i,n)}getTransformData(e,t){const i={};"InheritType"in t&&(i.inheritType=parseInt(t.InheritType.value)),"RotationOrder"in t?i.eulerOrder=O1(t.RotationOrder.value):i.eulerOrder="ZYX","Lcl_Translation"in t&&(i.translation=t.Lcl_Translation.value),"PreRotation"in t&&(i.preRotation=t.PreRotation.value),"Lcl_Rotation"in t&&(i.rotation=t.Lcl_Rotation.value),"PostRotation"in t&&(i.postRotation=t.PostRotation.value),"Lcl_Scaling"in t&&(i.scale=t.Lcl_Scaling.value),"ScalingOffset"in t&&(i.scalingOffset=t.ScalingOffset.value),"ScalingPivot"in t&&(i.scalingPivot=t.ScalingPivot.value),"RotationOffset"in t&&(i.rotationOffset=t.RotationOffset.value),"RotationPivot"in t&&(i.rotationPivot=t.RotationPivot.value),e.userData.transformData=i}setLookAtProperties(e,t){"LookAtProperty"in t&&Xi.get(e.ID).children.forEach(function(n){if(n.relationship==="LookAtProperty"){const s=Dt.Objects.Model[n.ID];if("Lcl_Translation"in s){const a=s.Lcl_Translation.value;e.target!==void 0?(e.target.position.fromArray(a),Kn.add(e.target)):e.lookAt(new S().fromArray(a))}}})}bindSkeleton(e,t,i){const n=this.parsePoseNodes();for(const s in e){const a=e[s];Xi.get(parseInt(a.ID)).parents.forEach(function(l){if(t.has(l.ID)){const c=l.ID;Xi.get(c).parents.forEach(function(u){i.has(u.ID)&&i.get(u.ID).bind(new Bc(a.bones),n[u.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in Dt.Objects){const t=Dt.Objects.Pose;for(const i in t)if(t[i].attrType==="BindPose"&&t[i].NbPoseNodes>0){const n=t[i].PoseNode;Array.isArray(n)?n.forEach(function(s){e[s.Node]=new fe().fromArray(s.Matrix.a)}):e[n.Node]=new fe().fromArray(n.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in Dt){if("AmbientColor"in Dt.GlobalSettings){const e=Dt.GlobalSettings.AmbientColor.value,t=e[0],i=e[1],n=e[2];if(t!==0||i!==0||n!==0){const s=new ee(t,i,n).convertSRGBToLinear();Kn.add(new Kp(s,1))}}"UnitScaleFactor"in Dt.GlobalSettings&&(Kn.userData.unitScaleFactor=Dt.GlobalSettings.UnitScaleFactor.value)}}}class aV{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in Dt.Objects){const i=Dt.Objects.Geometry;for(const n in i){const s=Xi.get(parseInt(n)),a=this.parseGeometry(s,i[n],e);t.set(parseInt(n),a)}}return this.negativeMaterialIndices===!0&&console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."),t}parseGeometry(e,t,i){switch(t.attrType){case"Mesh":return this.parseMeshGeometry(e,t,i);case"NurbsCurve":return this.parseNurbsGeometry(t)}}parseMeshGeometry(e,t,i){const n=i.skeletons,s=[],a=e.parents.map(function(u){return Dt.Objects.Model[u.ID]});if(a.length===0)return;const o=e.children.reduce(function(u,d){return n[d.ID]!==void 0&&(u=n[d.ID]),u},null);e.children.forEach(function(u){i.morphTargets[u.ID]!==void 0&&s.push(i.morphTargets[u.ID])});const l=a[0],c={};"RotationOrder"in l&&(c.eulerOrder=O1(l.RotationOrder.value)),"InheritType"in l&&(c.inheritType=parseInt(l.InheritType.value)),"GeometricTranslation"in l&&(c.translation=l.GeometricTranslation.value),"GeometricRotation"in l&&(c.rotation=l.GeometricRotation.value),"GeometricScaling"in l&&(c.scale=l.GeometricScaling.value);const h=L1(c);return this.genGeometry(t,o,s,h)}genGeometry(e,t,i,n){const s=new Je;e.attrName&&(s.name=e.attrName);const a=this.parseGeoNode(e,t),o=this.genBuffers(a),l=new Ee(o.vertex,3);if(l.applyMatrix4(n),s.setAttribute("position",l),o.colors.length>0&&s.setAttribute("color",new Ee(o.colors,3)),t&&(s.setAttribute("skinIndex",new Xf(o.weightsIndices,4)),s.setAttribute("skinWeight",new Ee(o.vertexWeights,4)),s.FBX_Deformer=t),o.normal.length>0){const c=new At().getNormalMatrix(n),h=new Ee(o.normal,3);h.applyNormalMatrix(c),s.setAttribute("normal",h)}if(o.uvs.forEach(function(c,h){const u=h===0?"uv":`uv${h}`;s.setAttribute(u,new Ee(o.uvs[h],2))}),a.material&&a.material.mappingType!=="AllSame"){let c=o.materialIndex[0],h=0;if(o.materialIndex.forEach(function(u,d){u!==c&&(s.addGroup(h,d-h,c),c=u,h=d)}),s.groups.length>0){const u=s.groups[s.groups.length-1],d=u.start+u.count;d!==o.materialIndex.length&&s.addGroup(d,o.materialIndex.length-d,c)}s.groups.length===0&&s.addGroup(0,o.materialIndex.length,o.materialIndex[0])}return this.addMorphTargets(s,e,i,n),s}parseGeoNode(e,t){const i={};if(i.vertexPositions=e.Vertices!==void 0?e.Vertices.a:[],i.vertexIndices=e.PolygonVertexIndex!==void 0?e.PolygonVertexIndex.a:[],e.LayerElementColor&&(i.color=this.parseVertexColors(e.LayerElementColor[0])),e.LayerElementMaterial&&(i.material=this.parseMaterialIndices(e.LayerElementMaterial[0])),e.LayerElementNormal&&(i.normal=this.parseNormals(e.LayerElementNormal[0])),e.LayerElementUV){i.uv=[];let n=0;for(;e.LayerElementUV[n];)e.LayerElementUV[n].UV&&i.uv.push(this.parseUVs(e.LayerElementUV[n])),n++}return i.weightTable={},t!==null&&(i.skeleton=t,t.rawBones.forEach(function(n,s){n.indices.forEach(function(a,o){i.weightTable[a]===void 0&&(i.weightTable[a]=[]),i.weightTable[a].push({id:s,weight:n.weights[o]})})})),i}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,n=0,s=!1,a=[],o=[],l=[],c=[],h=[],u=[];const d=this;return e.vertexIndices.forEach(function(p,m){let A,g=!1;p<0&&(p=p^-1,g=!0);let y=[],v=[];if(a.push(p*3,p*3+1,p*3+2),e.color){const _=Pg(m,i,p,e.color);l.push(_[0],_[1],_[2])}if(e.skeleton){if(e.weightTable[p]!==void 0&&e.weightTable[p].forEach(function(_){v.push(_.weight),y.push(_.id)}),v.length>4){s||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),s=!0);const _=[0,0,0,0],b=[0,0,0,0];v.forEach(function(T,E){let M=T,I=y[E];b.forEach(function(C,x,D){if(M>C){D[x]=M,M=C;const U=_[x];_[x]=I,I=U}})}),y=_,v=b}for(;v.length<4;)v.push(0),y.push(0);for(let _=0;_<4;++_)h.push(v[_]),u.push(y[_])}if(e.normal){const _=Pg(m,i,p,e.normal);o.push(_[0],_[1],_[2])}e.material&&e.material.mappingType!=="AllSame"&&(A=Pg(m,i,p,e.material)[0],A<0&&(d.negativeMaterialIndices=!0,A=0)),e.uv&&e.uv.forEach(function(_,b){const T=Pg(m,i,p,_);c[b]===void 0&&(c[b]=[]),c[b].push(T[0]),c[b].push(T[1])}),n++,g&&(d.genFace(t,e,a,A,o,l,c,h,u,n),i++,n=0,a=[],o=[],l=[],c=[],h=[],u=[])}),t}getNormalNewell(e){const t=new S(0,0,0);for(let i=0;i<e.length;i++){const n=e[i],s=e[(i+1)%e.length];t.x+=(n.y-s.y)*(n.z+s.z),t.y+=(n.z-s.z)*(n.x+s.x),t.z+=(n.x-s.x)*(n.y+s.y)}return t.normalize(),t}getNormalTangentAndBitangent(e){const t=this.getNormalNewell(e),n=(Math.abs(t.z)>.5?new S(0,1,0):new S(0,0,1)).cross(t).normalize(),s=t.clone().cross(n).normalize();return{normal:t,tangent:n,bitangent:s}}flattenVertex(e,t,i){return new K(e.dot(t),e.dot(i))}genFace(e,t,i,n,s,a,o,l,c,h){let u;if(h>3){const d=[],p=t.baseVertexPositions||t.vertexPositions;for(let y=0;y<i.length;y+=3)d.push(new S(p[i[y]],p[i[y+1]],p[i[y+2]]));const{tangent:m,bitangent:A}=this.getNormalTangentAndBitangent(d),g=[];for(const y of d)g.push(this.flattenVertex(y,m,A));u=ar.triangulateShape(g,[])}else u=[[0,1,2]];for(const[d,p,m]of u)e.vertex.push(t.vertexPositions[i[d*3]]),e.vertex.push(t.vertexPositions[i[d*3+1]]),e.vertex.push(t.vertexPositions[i[d*3+2]]),e.vertex.push(t.vertexPositions[i[p*3]]),e.vertex.push(t.vertexPositions[i[p*3+1]]),e.vertex.push(t.vertexPositions[i[p*3+2]]),e.vertex.push(t.vertexPositions[i[m*3]]),e.vertex.push(t.vertexPositions[i[m*3+1]]),e.vertex.push(t.vertexPositions[i[m*3+2]]),t.skeleton&&(e.vertexWeights.push(l[d*4]),e.vertexWeights.push(l[d*4+1]),e.vertexWeights.push(l[d*4+2]),e.vertexWeights.push(l[d*4+3]),e.vertexWeights.push(l[p*4]),e.vertexWeights.push(l[p*4+1]),e.vertexWeights.push(l[p*4+2]),e.vertexWeights.push(l[p*4+3]),e.vertexWeights.push(l[m*4]),e.vertexWeights.push(l[m*4+1]),e.vertexWeights.push(l[m*4+2]),e.vertexWeights.push(l[m*4+3]),e.weightsIndices.push(c[d*4]),e.weightsIndices.push(c[d*4+1]),e.weightsIndices.push(c[d*4+2]),e.weightsIndices.push(c[d*4+3]),e.weightsIndices.push(c[p*4]),e.weightsIndices.push(c[p*4+1]),e.weightsIndices.push(c[p*4+2]),e.weightsIndices.push(c[p*4+3]),e.weightsIndices.push(c[m*4]),e.weightsIndices.push(c[m*4+1]),e.weightsIndices.push(c[m*4+2]),e.weightsIndices.push(c[m*4+3])),t.color&&(e.colors.push(a[d*3]),e.colors.push(a[d*3+1]),e.colors.push(a[d*3+2]),e.colors.push(a[p*3]),e.colors.push(a[p*3+1]),e.colors.push(a[p*3+2]),e.colors.push(a[m*3]),e.colors.push(a[m*3+1]),e.colors.push(a[m*3+2])),t.material&&t.material.mappingType!=="AllSame"&&(e.materialIndex.push(n),e.materialIndex.push(n),e.materialIndex.push(n)),t.normal&&(e.normal.push(s[d*3]),e.normal.push(s[d*3+1]),e.normal.push(s[d*3+2]),e.normal.push(s[p*3]),e.normal.push(s[p*3+1]),e.normal.push(s[p*3+2]),e.normal.push(s[m*3]),e.normal.push(s[m*3+1]),e.normal.push(s[m*3+2])),t.uv&&t.uv.forEach(function(A,g){e.uvs[g]===void 0&&(e.uvs[g]=[]),e.uvs[g].push(o[g][d*2]),e.uvs[g].push(o[g][d*2+1]),e.uvs[g].push(o[g][p*2]),e.uvs[g].push(o[g][p*2+1]),e.uvs[g].push(o[g][m*2]),e.uvs[g].push(o[g][m*2+1])})}addMorphTargets(e,t,i,n){if(i.length===0)return;e.morphTargetsRelative=!0,e.morphAttributes.position=[];const s=this;i.forEach(function(a){a.rawTargets.forEach(function(o){const l=Dt.Objects.Geometry[o.geoID];l!==void 0&&s.genMorphGeometry(e,t,l,n,o.name)})})}genMorphGeometry(e,t,i,n,s){const a=t.Vertices!==void 0?t.Vertices.a:[],o=t.PolygonVertexIndex!==void 0?t.PolygonVertexIndex.a:[],l=i.Vertices!==void 0?i.Vertices.a:[],c=i.Indexes!==void 0?i.Indexes.a:[],h=e.attributes.position.count*3,u=new Float32Array(h);for(let A=0;A<c.length;A++){const g=c[A]*3;u[g]=l[A*3],u[g+1]=l[A*3+1],u[g+2]=l[A*3+2]}const d={vertexIndices:o,vertexPositions:u,baseVertexPositions:a},p=this.genBuffers(d),m=new Ee(p.vertex,3);m.name=s||i.attrName,m.applyMatrix4(n),e.morphAttributes.position.push(m)}parseNormals(e){const t=e.MappingInformationType,i=e.ReferenceInformationType,n=e.Normals.a;let s=[];return i==="IndexToDirect"&&("NormalIndex"in e?s=e.NormalIndex.a:"NormalsIndex"in e&&(s=e.NormalsIndex.a)),{dataSize:3,buffer:n,indices:s,mappingType:t,referenceType:i}}parseUVs(e){const t=e.MappingInformationType,i=e.ReferenceInformationType,n=e.UV.a;let s=[];return i==="IndexToDirect"&&(s=e.UVIndex.a),{dataSize:2,buffer:n,indices:s,mappingType:t,referenceType:i}}parseVertexColors(e){const t=e.MappingInformationType,i=e.ReferenceInformationType,n=e.Colors.a;let s=[];i==="IndexToDirect"&&(s=e.ColorIndex.a);for(let a=0,o=new ee;a<n.length;a+=4)o.fromArray(n,a).convertSRGBToLinear().toArray(n,a);return{dataSize:4,buffer:n,indices:s,mappingType:t,referenceType:i}}parseMaterialIndices(e){const t=e.MappingInformationType,i=e.ReferenceInformationType;if(t==="NoMappingInformation")return{dataSize:1,buffer:[0],indices:[0],mappingType:"AllSame",referenceType:i};const n=e.Materials.a,s=[];for(let a=0;a<n.length;++a)s.push(a);return{dataSize:1,buffer:n,indices:s,mappingType:t,referenceType:i}}parseNurbsGeometry(e){const t=parseInt(e.Order);if(isNaN(t))return console.error("THREE.FBXLoader: Invalid Order %s given for geometry ID: %s",e.Order,e.id),new Je;const i=t-1,n=e.KnotVector.a,s=[],a=e.Points.a;for(let u=0,d=a.length;u<d;u+=4)s.push(new et().fromArray(a,u));let o,l;if(e.Form==="Closed")s.push(s[0]);else if(e.Form==="Periodic"){o=i,l=n.length-1-o;for(let u=0;u<i;++u)s.push(s[u])}const h=new sV(i,n,s,o,l).getPoints(s.length*12);return new Je().setFromPoints(h)}}class oV{parse(){const e=[],t=this.parseClips();if(t!==void 0)for(const i in t){const n=t[i],s=this.addClip(n);e.push(s)}return e}parseClips(){if(Dt.Objects.AnimationCurve===void 0)return;const e=this.parseAnimationCurveNodes();this.parseAnimationCurves(e);const t=this.parseAnimationLayers(e);return this.parseAnimStacks(t)}parseAnimationCurveNodes(){const e=Dt.Objects.AnimationCurveNode,t=new Map;for(const i in e){const n=e[i];if(n.attrName.match(/S|R|T|DeformPercent/)!==null){const s={id:n.id,attr:n.attrName,curves:{}};t.set(s.id,s)}}return t}parseAnimationCurves(e){const t=Dt.Objects.AnimationCurve;for(const i in t){const n={id:t[i].id,times:t[i].KeyTime.a.map(dV),values:t[i].KeyValueFloat.a},s=Xi.get(n.id);if(s!==void 0){const a=s.parents[0].ID,o=s.parents[0].relationship;o.match(/X/)?e.get(a).curves.x=n:o.match(/Y/)?e.get(a).curves.y=n:o.match(/Z/)?e.get(a).curves.z=n:o.match(/DeformPercent/)&&e.has(a)&&(e.get(a).curves.morph=n)}}}parseAnimationLayers(e){const t=Dt.Objects.AnimationLayer,i=new Map;for(const n in t){const s=[],a=Xi.get(parseInt(n));a!==void 0&&(a.children.forEach(function(l,c){if(e.has(l.ID)){const h=e.get(l.ID);if(h.curves.x!==void 0||h.curves.y!==void 0||h.curves.z!==void 0){if(s[c]===void 0){const u=Xi.get(l.ID).parents.filter(function(d){return d.relationship!==void 0})[0].ID;if(u!==void 0){const d=Dt.Objects.Model[u.toString()];if(d===void 0){console.warn("THREE.FBXLoader: Encountered a unused curve.",l);return}const p={modelName:d.attrName?Et.sanitizeNodeName(d.attrName):"",ID:d.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};Kn.traverse(function(m){m.ID===d.id&&(p.transform=m.matrix,m.userData.transformData&&(p.eulerOrder=m.userData.transformData.eulerOrder))}),p.transform||(p.transform=new fe),"PreRotation"in d&&(p.preRotation=d.PreRotation.value),"PostRotation"in d&&(p.postRotation=d.PostRotation.value),s[c]=p}}s[c]&&(s[c][h.attr]=h)}else if(h.curves.morph!==void 0){if(s[c]===void 0){const u=Xi.get(l.ID).parents.filter(function(y){return y.relationship!==void 0})[0].ID,d=Xi.get(u).parents[0].ID,p=Xi.get(d).parents[0].ID,m=Xi.get(p).parents[0].ID,A=Dt.Objects.Model[m],g={modelName:A.attrName?Et.sanitizeNodeName(A.attrName):"",morphName:Dt.Objects.Deformer[u].attrName};s[c]=g}s[c][h.attr]=h}}}),i.set(parseInt(n),s))}return i}parseAnimStacks(e){const t=Dt.Objects.AnimationStack,i={};for(const n in t){const s=Xi.get(parseInt(n)).children;s.length>1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const a=e.get(s[0].ID);i[n]={name:t[n].attrName,layer:a}}return i}addClip(e){let t=[];const i=this;return e.layer.forEach(function(n){t=t.concat(i.generateTracks(n))}),new Ja(e.name,-1,t)}generateTracks(e){const t=[];let i=new S,n=new S;if(e.transform&&e.transform.decompose(i,new $e,n),i=i.toArray(),n=n.toArray(),e.T!==void 0&&Object.keys(e.T.curves).length>0){const s=this.generateVectorTrack(e.modelName,e.T.curves,i,"position");s!==void 0&&t.push(s)}if(e.R!==void 0&&Object.keys(e.R.curves).length>0){const s=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder);s!==void 0&&t.push(s)}if(e.S!==void 0&&Object.keys(e.S.curves).length>0){const s=this.generateVectorTrack(e.modelName,e.S.curves,n,"scale");s!==void 0&&t.push(s)}if(e.DeformPercent!==void 0){const s=this.generateMorphTrack(e);s!==void 0&&t.push(s)}return t}generateVectorTrack(e,t,i,n){const s=this.getTimesForAllAxes(t),a=this.getKeyframeTrackValues(s,t,i);return new Ka(e+"."+n,s,a)}generateRotationTrack(e,t,i,n,s){let a,o;if(t.x!==void 0&&t.y!==void 0&&t.z!==void 0){const u=this.interpolateRotations(t.x,t.y,t.z,s);a=u[0],o=u[1]}i!==void 0&&(i=i.map(Ft.degToRad),i.push(s),i=new Pt().fromArray(i),i=new $e().setFromEuler(i)),n!==void 0&&(n=n.map(Ft.degToRad),n.push(s),n=new Pt().fromArray(n),n=new $e().setFromEuler(n).invert());const l=new $e,c=new Pt,h=[];if(!o||!a)return new fa(e+".quaternion",[0],[0]);for(let u=0;u<o.length;u+=3)c.set(o[u],o[u+1],o[u+2],s),l.setFromEuler(c),i!==void 0&&l.premultiply(i),n!==void 0&&l.multiply(n),u>2&&new $e().fromArray(h,(u-3)/3*4).dot(l)<0&&l.set(-l.x,-l.y,-l.z,-l.w),l.toArray(h,u/3*4);return new fa(e+".quaternion",a,h)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,i=t.values.map(function(s){return s/100}),n=Kn.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new $a(e.modelName+".morphTargetInfluences["+n+"]",t.times,i)}getTimesForAllAxes(e){let t=[];if(e.x!==void 0&&(t=t.concat(e.x.times)),e.y!==void 0&&(t=t.concat(e.y.times)),e.z!==void 0&&(t=t.concat(e.z.times)),t=t.sort(function(i,n){return i-n}),t.length>1){let i=1,n=t[0];for(let s=1;s<t.length;s++){const a=t[s];a!==n&&(t[i]=a,n=a,i++)}t=t.slice(0,i)}return t}getKeyframeTrackValues(e,t,i){const n=i,s=[];let a=-1,o=-1,l=-1;return e.forEach(function(c){if(t.x&&(a=t.x.times.indexOf(c)),t.y&&(o=t.y.times.indexOf(c)),t.z&&(l=t.z.times.indexOf(c)),a!==-1){const h=t.x.values[a];s.push(h),n[0]=h}else s.push(n[0]);if(o!==-1){const h=t.y.values[o];s.push(h),n[1]=h}else s.push(n[1]);if(l!==-1){const h=t.z.values[l];s.push(h),n[2]=h}else s.push(n[2])}),s}interpolateRotations(e,t,i,n){const s=[],a=[];s.push(e.times[0]),a.push(Ft.degToRad(e.values[0])),a.push(Ft.degToRad(t.values[0])),a.push(Ft.degToRad(i.values[0]));for(let o=1;o<e.values.length;o++){const l=[e.values[o-1],t.values[o-1],i.values[o-1]];if(isNaN(l[0])||isNaN(l[1])||isNaN(l[2]))continue;const c=l.map(Ft.degToRad),h=[e.values[o],t.values[o],i.values[o]];if(isNaN(h[0])||isNaN(h[1])||isNaN(h[2]))continue;const u=h.map(Ft.degToRad),d=[h[0]-l[0],h[1]-l[1],h[2]-l[2]],p=[Math.abs(d[0]),Math.abs(d[1]),Math.abs(d[2])];if(p[0]>=180||p[1]>=180||p[2]>=180){const A=Math.max(...p)/180,g=new Pt(...c,n),y=new Pt(...u,n),v=new $e().setFromEuler(g),_=new $e().setFromEuler(y);v.dot(_)&&_.set(-_.x,-_.y,-_.z,-_.w);const b=e.times[o-1],T=e.times[o]-b,E=new $e,M=new Pt;for(let I=0;I<1;I+=1/A)E.copy(v.clone().slerp(_.clone(),I)),s.push(b+I*T),M.setFromQuaternion(E,n),a.push(M.x),a.push(M.y),a.push(M.z)}else s.push(e.times[o]),a.push(Ft.degToRad(e.values[o])),a.push(Ft.degToRad(t.values[o])),a.push(Ft.degToRad(i.values[o]))}return[s,a]}}class lV{getPrevNode(){return this.nodeStack[this.currentIndent-2]}getCurrentNode(){return this.nodeStack[this.currentIndent-1]}getCurrentProp(){return this.currentProp}pushStack(e){this.nodeStack.push(e),this.currentIndent+=1}popStack(){this.nodeStack.pop(),this.currentIndent-=1}setCurrentProp(e,t){this.currentProp=e,this.currentPropName=t}parse(e){this.currentIndent=0,this.allNodes=new R1,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,i=e.split(/[\r\n]+/);return i.forEach(function(n,s){const a=n.match(/^[\s\t]*;/),o=n.match(/^[\s\t]*$/);if(a||o)return;const l=n.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),c=n.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),h=n.match("^\\t{"+(t.currentIndent-1)+"}}");l?t.parseNodeBegin(n,l):c?t.parseNodeProperty(n,c,i[++s]):h?t.popStack():n.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(n)}),this.allNodes}parseNodeBegin(e,t){const i=t[1].trim().replace(/^"/,"").replace(/"$/,""),n=t[2].split(",").map(function(l){return l.trim().replace(/^"/,"").replace(/"$/,"")}),s={name:i},a=this.parseNodeAttr(n),o=this.getCurrentNode();this.currentIndent===0?this.allNodes.add(i,s):i in o?(i==="PoseNode"?o.PoseNode.push(s):o[i].id!==void 0&&(o[i]={},o[i][o[i].id]=o[i]),a.id!==""&&(o[i][a.id]=s)):typeof a.id=="number"?(o[i]={},o[i][a.id]=s):i!=="Properties70"&&(i==="PoseNode"?o[i]=[s]:o[i]=s),typeof a.id=="number"&&(s.id=a.id),a.name!==""&&(s.attrName=a.name),a.type!==""&&(s.attrType=a.type),this.pushStack(s)}parseNodeAttr(e){let t=e[0];e[0]!==""&&(t=parseInt(e[0]),isNaN(t)&&(t=e[0]));let i="",n="";return e.length>1&&(i=e[1].replace(/^(\w+)::/,""),n=e[2]),{id:t,name:i,type:n}}parseNodeProperty(e,t,i){let n=t[1].replace(/^"/,"").replace(/"$/,"").trim(),s=t[2].replace(/^"/,"").replace(/"$/,"").trim();n==="Content"&&s===","&&(s=i.replace(/"/g,"").replace(/,$/,"").trim());const a=this.getCurrentNode();if(a.name==="Properties70"){this.parseNodeSpecialProperty(e,n,s);return}if(n==="C"){const l=s.split(",").slice(1),c=parseInt(l[0]),h=parseInt(l[1]);let u=s.split(",").slice(3);u=u.map(function(d){return d.trim().replace(/^"/,"")}),n="connections",s=[c,h],pV(s,u),a[n]===void 0&&(a[n]=[])}n==="Node"&&(a.id=s),n in a&&Array.isArray(a[n])?a[n].push(s):n!=="a"?a[n]=s:a.a=s,this.setCurrentProp(a,n),n==="a"&&s.slice(-1)!==","&&(a.a=N0(s))}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,e.slice(-1)!==","&&(t.a=N0(t.a))}parseNodeSpecialProperty(e,t,i){const n=i.split('",').map(function(h){return h.trim().replace(/^\"/,"").replace(/\s/,"_")}),s=n[0],a=n[1],o=n[2],l=n[3];let c=n[4];switch(a){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":c=parseFloat(c);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":c=N0(c);break}this.getPrevNode()[s]={type:a,type2:o,flag:l,value:c},this.setCurrentProp(this.getPrevNode(),s)}}class cV{parse(e){const t=new D1(e);t.skip(23);const i=t.getUint32();if(i<6400)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+i);const n=new R1;for(;!this.endOfContent(t);){const s=this.parseNode(t,i);s!==null&&n.add(s.name,s)}return n}endOfContent(e){return e.size()%16===0?(e.getOffset()+160+16&-16)>=e.size():e.getOffset()+160+16>=e.size()}parseNode(e,t){const i={},n=t>=7500?e.getUint64():e.getUint32(),s=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const a=e.getUint8(),o=e.getString(a);if(n===0)return null;const l=[];for(let d=0;d<s;d++)l.push(this.parseProperty(e));const c=l.length>0?l[0]:"",h=l.length>1?l[1]:"",u=l.length>2?l[2]:"";for(i.singleProperty=s===1&&e.getOffset()===n;n>e.getOffset();){const d=this.parseNode(e,t);d!==null&&this.parseSubNode(o,i,d)}return i.propertyList=l,typeof c=="number"&&(i.id=c),h!==""&&(i.attrName=h),u!==""&&(i.attrType=u),o!==""&&(i.name=o),i}parseSubNode(e,t,i){if(i.singleProperty===!0){const n=i.propertyList[0];Array.isArray(n)?(t[i.name]=i,i.a=n):t[i.name]=n}else if(e==="Connections"&&i.name==="C"){const n=[];i.propertyList.forEach(function(s,a){a!==0&&n.push(s)}),t.connections===void 0&&(t.connections=[]),t.connections.push(n)}else if(i.name==="Properties70")Object.keys(i).forEach(function(s){t[s]=i[s]});else if(e==="Properties70"&&i.name==="P"){let n=i.propertyList[0],s=i.propertyList[1];const a=i.propertyList[2],o=i.propertyList[3];let l;n.indexOf("Lcl ")===0&&(n=n.replace("Lcl ","Lcl_")),s.indexOf("Lcl ")===0&&(s=s.replace("Lcl ","Lcl_")),s==="Color"||s==="ColorRGB"||s==="Vector"||s==="Vector3D"||s.indexOf("Lcl_")===0?l=[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:l=i.propertyList[4],t[n]={type:s,type2:a,flag:o,value:l}}else t[i.name]===void 0?typeof i.id=="number"?(t[i.name]={},t[i.name][i.id]=i):t[i.name]=i:i.name==="PoseNode"?(Array.isArray(t[i.name])||(t[i.name]=[t[i.name]]),t[i.name].push(i)):t[i.name][i.id]===void 0&&(t[i.name][i.id]=i)}parseProperty(e){const t=e.getString(1);let i;switch(t){case"C":return e.getBoolean();case"D":return e.getFloat64();case"F":return e.getFloat32();case"I":return e.getInt32();case"L":return e.getInt64();case"R":return i=e.getUint32(),e.getArrayBuffer(i);case"S":return i=e.getUint32(),e.getString(i);case"Y":return e.getInt16();case"b":case"c":case"d":case"f":case"i":case"l":const n=e.getUint32(),s=e.getUint32(),a=e.getUint32();if(s===0)switch(t){case"b":case"c":return e.getBooleanArray(n);case"d":return e.getFloat64Array(n);case"f":return e.getFloat32Array(n);case"i":return e.getInt32Array(n);case"l":return e.getInt64Array(n)}const o=Ea(new Uint8Array(e.getArrayBuffer(a))),l=new D1(o.buffer);switch(t){case"b":case"c":return l.getBooleanArray(n);case"d":return l.getFloat64Array(n);case"f":return l.getFloat32Array(n);case"i":return l.getInt32Array(n);case"l":return l.getInt64Array(n)}break;default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class D1{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=t!==void 0?t:!0,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return(this.getUint8()&1)===1}getBooleanArray(e){const t=[];for(let i=0;i<e;i++)t.push(this.getBoolean());return t}getUint8(){const e=this.dv.getUint8(this.offset);return this.offset+=1,e}getInt16(){const e=this.dv.getInt16(this.offset,this.littleEndian);return this.offset+=2,e}getInt32(){const e=this.dv.getInt32(this.offset,this.littleEndian);return this.offset+=4,e}getInt32Array(e){const t=[];for(let i=0;i<e;i++)t.push(this.getInt32());return t}getUint32(){const e=this.dv.getUint32(this.offset,this.littleEndian);return this.offset+=4,e}getInt64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t&2147483648?(t=~t&4294967295,e=~e&4294967295,e===4294967295&&(t=t+1&4294967295),e=e+1&4294967295,-(t*4294967296+e)):t*4294967296+e}getInt64Array(e){const t=[];for(let i=0;i<e;i++)t.push(this.getInt64());return t}getUint64(){let e,t;return this.littleEndian?(e=this.getUint32(),t=this.getUint32()):(t=this.getUint32(),e=this.getUint32()),t*4294967296+e}getFloat32(){const e=this.dv.getFloat32(this.offset,this.littleEndian);return this.offset+=4,e}getFloat32Array(e){const t=[];for(let i=0;i<e;i++)t.push(this.getFloat32());return t}getFloat64(){const e=this.dv.getFloat64(this.offset,this.littleEndian);return this.offset+=8,e}getFloat64Array(e){const t=[];for(let i=0;i<e;i++)t.push(this.getFloat64());return t}getArrayBuffer(e){const t=this.dv.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}getString(e){const t=this.offset;let i=new Uint8Array(this.dv.buffer,t,e);this.skip(e);const n=i.indexOf(0);return n>=0&&(i=new Uint8Array(this.dv.buffer,t,n)),this._textDecoder.decode(i)}}class R1{add(e,t){this[e]=t}}function hV(r){const e="Kaydara FBX Binary  \0";return r.byteLength>=e.length&&e===U1(r,0,e.length)}function uV(r){const e=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let t=0;function i(n){const s=r[n-1];return r=r.slice(t+n),t++,s}for(let n=0;n<e.length;++n)if(i(1)===e[n])return!1;return!0}function B1(r){const e=/FBXVersion: (\d+)/,t=r.match(e);if(t)return parseInt(t[1]);throw new Error("THREE.FBXLoader: Cannot find the version number for the file given.")}function dV(r){return r/46186158e3}const fV=[];function Pg(r,e,t,i){let n;switch(i.mappingType){case"ByPolygonVertex":n=r;break;case"ByPolygon":n=e;break;case"ByVertice":n=t;break;case"AllSame":n=i.indices[0];break;default:console.warn("THREE.FBXLoader: unknown attribute mapping type "+i.mappingType)}i.referenceType==="IndexToDirect"&&(n=i.indices[n]);const s=n*i.dataSize,a=s+i.dataSize;return mV(fV,i.buffer,s,a)}const F0=new Pt,bh=new S;function L1(r){const e=new fe,t=new fe,i=new fe,n=new fe,s=new fe,a=new fe,o=new fe,l=new fe,c=new fe,h=new fe,u=new fe,d=new fe,p=r.inheritType?r.inheritType:0;if(r.translation&&e.setPosition(bh.fromArray(r.translation)),r.preRotation){const x=r.preRotation.map(Ft.degToRad);x.push(r.eulerOrder||Pt.DEFAULT_ORDER),t.makeRotationFromEuler(F0.fromArray(x))}if(r.rotation){const x=r.rotation.map(Ft.degToRad);x.push(r.eulerOrder||Pt.DEFAULT_ORDER),i.makeRotationFromEuler(F0.fromArray(x))}if(r.postRotation){const x=r.postRotation.map(Ft.degToRad);x.push(r.eulerOrder||Pt.DEFAULT_ORDER),n.makeRotationFromEuler(F0.fromArray(x)),n.invert()}r.scale&&s.scale(bh.fromArray(r.scale)),r.scalingOffset&&o.setPosition(bh.fromArray(r.scalingOffset)),r.scalingPivot&&a.setPosition(bh.fromArray(r.scalingPivot)),r.rotationOffset&&l.setPosition(bh.fromArray(r.rotationOffset)),r.rotationPivot&&c.setPosition(bh.fromArray(r.rotationPivot)),r.parentMatrixWorld&&(u.copy(r.parentMatrix),h.copy(r.parentMatrixWorld));const m=t.clone().multiply(i).multiply(n),A=new fe;A.extractRotation(h);const g=new fe;g.copyPosition(h);const y=g.clone().invert().multiply(h),v=A.clone().invert().multiply(y),_=s,b=new fe;if(p===0)b.copy(A).multiply(m).multiply(v).multiply(_);else if(p===1)b.copy(A).multiply(v).multiply(m).multiply(_);else{const D=new fe().scale(new S().setFromMatrixScale(u)).clone().invert(),U=v.clone().multiply(D);b.copy(A).multiply(m).multiply(U).multiply(_)}const T=c.clone().invert(),E=a.clone().invert();let M=e.clone().multiply(l).multiply(c).multiply(t).multiply(i).multiply(n).multiply(T).multiply(o).multiply(a).multiply(s).multiply(E);const I=new fe().copyPosition(M),C=h.clone().multiply(I);return d.copyPosition(C),M=d.clone().multiply(b),M.premultiply(h.invert()),M}function O1(r){r=r||0;const e=["ZYX","YZX","XZY","ZXY","YXZ","XYZ"];return r===6?(console.warn("THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect."),e[0]):e[r]}function N0(r){return r.split(",").map(function(t){return parseFloat(t)})}function U1(r,e,t){return e===void 0&&(e=0),t===void 0&&(t=r.byteLength),new TextDecoder().decode(new Uint8Array(r,e,t))}function pV(r,e){for(let t=0,i=r.length,n=e.length;t<n;t++,i++)r[i]=e[t]}function mV(r,e,t,i){for(let n=t,s=0;n<i;n++,s++)r[s]=e[n];return r}class F1 extends P1{async loadAsync(e,t){const i=kt.DEFAULT_IMAGE;kt.DEFAULT_IMAGE||(kt.DEFAULT_IMAGE=Bm);const n=await super.loadAsync(e,t);return kt.DEFAULT_IMAGE=i,n}}class N1 extends ti{load(e,t,i,n){return this.setResponseType("arraybuffer"),super.load(e,s=>{const a=U0(new Uint8Array(s)),o=new Map(Object.entries(a).map(([l,c])=>[l,new File([c],l)]));t?.(o)},i,n)}}const gV=["hdr","exr","webp","avif","ktx","hdrpng","svg","cube","ico","bmp","gif","tiff"],Tn=class Tn extends Mt{constructor(e){super(e),this.isGLTFLoader2=!0,this._resPathUrlModifier={oldResourcePath:"",newResourcePath:"",modify:t=>{if(!Tn._UseResourcePath||!this._resPathUrlModifier.oldResourcePath||!this._resPathUrlModifier.newResourcePath)return t;let i=this._resPathUrlModifier.oldResourcePath;const n=this._resPathUrlModifier.newResourcePath;return i?.startsWith("/")&&/^https?:\/\//i.test(n)&&(i=n.replace(/(^https?:\/\/[^/]+).*/i,"$1")+i),t.startsWith(i)?t.replace(i,n):t}},this.preparsers=[],this.gltfViewerParser=t=>i=>{this._resPathUrlModifier.newResourcePath=i.options.path,this._resPathUrlModifier.oldResourcePath=i.json?.extras?.resourcePath,t.assetManager.importer.addURLModifier(this._resPathUrlModifier.modify),i.importOptions=this.importOptions||void 0;const n=i.getDependency;i.getDependency=async(d,p)=>{const m=await n.call(i,d,p);return k1(m,i.bundledResources),m};const s=i.createUniqueName;i.createUniqueName=d=>{const p=(i.importOptions?.createUniqueNames??Tn.CreateUniqueNames)==="auto";let m=!1;return p?m=!i.json?.scenes[i.json.scene??0]?.extras?.rootSceneModelRoot:m=i.importOptions?.createUniqueNames===!0||Tn.CreateUniqueNames===!0&&i.importOptions?.createUniqueNames!==!1,m?s.call(i,d):d};const a=Oi()+".drc",o=Oi()+".ktx2",l=i.json?.extensionsRequired?.includes?.("KHR_draco_mesh_compression");if(l){const d=t.assetManager.importer.registerFile(a);d&&this.setDRACOLoader(d)}i.json?.extensionsUsed?.includes?.("EXT_meshopt_compression")&&(window.MeshoptDecoder?(this.setMeshoptDecoder(window.MeshoptDecoder),i.options.meshoptDecoder=window.MeshoptDecoder):console.error("Add GLTFMeshOptDecodePlugin(and initialize it) to viewer to enable EXT_meshopt_compression decode"));const h=t.assetManager.importer.registerFile(o);h&&(this.setKTX2Loader(h),i.options.ktx2Loader=h);const u=gV.map(d=>Oi()+"."+d);return u.forEach(d=>t.assetManager.importer.registerFile(d)),{name:"GLTF2_HELPER_PLUGIN",beforeRoot:async()=>{const d=i.json.extras?.[Tn.BundledResourcesKey];!d||d.__isLoadedResources||(i.bundledResources=await ho.ImportResources(d,i,t))},afterRoot:async d=>{d._bundledResources=i.bundledResources,await ho.ImportViewerConfig(i,t,d.scenes||[d.scene]),l&&t.assetManager.importer.unregisterFile(a),h&&t.assetManager.importer.unregisterFile(o),u.forEach(p=>t.assetManager.importer.unregisterFile(p)),t.assetManager.importer.removeURLModifier(this._resPathUrlModifier.modify)}}},this.preparsers.push(zT),Mt.ObjectConstructors.DirectionalLight=lg,Mt.ObjectConstructors.PointLight=cg,Mt.ObjectConstructors.SpotLight=hg,Mt.ObjectConstructors.MeshStandardMaterial=si,Mt.ObjectConstructors.MeshBasicMaterial=gs,Mt.ObjectConstructors.MeshPhysicalMaterial=si,Mt.ObjectConstructors.LineBasicMaterial=Yn,Mt.ObjectConstructors.PerspectiveCamera=rT,Mt.ObjectConstructors.OrthographicCamera=aT}async preparse(e,t){for(const i of this.preparsers)e=await i.process(e,t);return e}parse(e,t,i,n,s){this.preparse.call(this,e,s||t).then(a=>{if(!a||!a.byteLength&&typeof a!="string"){Tn.AllowEmptyFiles?i&&i({scene:new Vi,scenes:[],animations:[],cameras:[]}):n&&n(new ErrorEvent("GLTFLoader2: empty file"));return}const o=kt.DEFAULT_IMAGE;kt.DEFAULT_IMAGE||(kt.DEFAULT_IMAGE=Bm);const l=this.importOptions?.useMeshLines??Tn.UseMeshLines;return Mt.ObjectConstructors.LineBasicMaterial=l?ji:Yn,a?super.parse(a,t,c=>{kt.DEFAULT_IMAGE=o,Mt.ObjectConstructors.LineBasicMaterial=l?ji:Yn;for(const h of c.scenes)h.updateMatrixWorld();i&&i(c)},n):n&&n(new ErrorEvent("no data"))}).catch(a=>{console.error(a),n&&n(a??new ErrorEvent("unknown error"))})}transform(e,t){let i=e?e.scene||!!e.scenes&&e.scenes.length>0&&e.scenes[0]:void 0;if(!i)return;i&&i.children.length===1&&!i.userData?.rootSceneModelRoot&&!i.importedViewerConfig&&i.name==="AuxScene"&&!e.cameras?.length&&(i=i.children[0],i.removeFromParent()),i.userData||(i.userData={}),e.userData&&(i.userData.gltfExtras=e.userData),e.cameras&&e.cameras.forEach(l=>!l.parent&&i?.add(l)),e.asset&&(i.userData.gltfAsset=e.asset),t.importAsModelRoot?i.userData.rootSceneModelRoot=!0:t.importAsModelRoot===!1&&i.userData.rootSceneModelRoot&&delete i.userData.rootSceneModelRoot;const n=[],s=new Map,a=new Set;if(i.traverse(l=>{l.userData.gltfUUID&&(an(l,"uuid",l.userData.gltfUUID,!0,!0),delete l.userData.gltfUUID),l.isLine&&n.push(l),l.uuid&&(s.has(l.uuid)||s.set(l.uuid,[]),s.get(l.uuid).push(l)),l.name&&(s.has(l.name)||s.set(l.name,[]),s.get(l.name).push(l));const c=l;c.geometry&&c.geometry.isBufferGeometry&&(c.geometry.userData.isPlaceholder?c.geometry=Ds.DummyGeometry:a.add(c.geometry));const h=Array.isArray(c.material)?c.material:c.material?[c.material]:[];for(let u=0;u<h.length;u++){const d=h[u];d?.userData.isPlaceholder&&(d.isLineBasicMaterial?h[u]=Ds.DummyLineBasicMaterial:d.isLineMaterial?h[u]=Ds.DummyLineMaterial:h[u]=Ds.DummyMaterial)}Array.isArray(c.material)&&c.material.length?c.material=h:h.length===1&&(c.material=h[0])}),a.forEach(l=>{k1(l,e._bundledResources)}),e.animations.length>0){i.animations=[];for(const l of e.animations){let c=!1;if(l.userData.rootRefs){for(const h of l.userData.rootRefs){const u=s.get(h)||[];for(const d of u)d.animations||(d.animations=[]),d.animations.includes(l)||d.animations.push(l),c=!0}c&&delete l.userData.rootRefs}c||i.animations.push(l)}}if(this.importOptions?.useMeshLines??Tn.UseMeshLines)for(const l of n)AV(l);return i.importedBundledResources=e._bundledResources,i}register(e){return super.register(e)}setup(e,t){this.register(Ld.Import(e.loadConfigResources));for(const i of t)this.register(i);for(const i of Tn.ImportExtensions)this.register(i);return this.register(this.gltfViewerParser(e)),this}};Tn._EmbedResourcePath=!1,Tn._UseResourcePath=!0,Tn.ImportExtensions=[Od.Import,Bd.Import,rh.Import,Sl.Import,El.Import,xl.Import,e=>({name:"_EMBED_RESOURCE_PATH",afterRoot:async t=>{!Tn._EmbedResourcePath||!t.scene||(t.userData.resourcePath=e.options.path)}})],Tn.UseMeshLines=!0,Tn.CreateUniqueNames="auto",Tn.BundledResourcesKey="BundledResources",Tn.AllowEmptyFiles=!0;let Il=Tn;function AV(r){const e=r.parent;if(!e){console.warn("GLTFLoader2: Line has no parent",r);return}r.geometry.index&&(r.geometry=r.geometry.toNonIndexed());const t=r.isLineSegments?new cT(new uT,r.material):new Kv(new Jv,r.material);let i=r.geometry.attributes.position.array;if(r.isLineLoop){const h=new Float32Array(i.length+3);h.set(i),h.set(i.subarray(0,3),i.length),i=h}t.geometry.setPositions(i);const n=r.geometry.attributes.color?.array;n&&t.geometry.setColors&&t.geometry.setColors(n),t.geometry.name=r.geometry.name,an(t.geometry,"uuid",r.geometry.uuid,!0,!0),t.geometry.userData={...r.geometry.userData};const s=e.children.indexOf(r);e.add(t);const{geometry:a,material:o}=t,l=r.userData;r.userData={},r.userData.__keepShadowDef||(r.castShadow=t.castShadow,r.receiveShadow=t.receiveShadow),t.copy(r,!1),t.geometry=a,t.material=o,[...r.children].map(h=>{t.add(h)}),t.userData={...t.userData,...l},an(t,"uuid",r.uuid,!0,!0),r.removeFromParent(),t.computeLineDistances();const c=e.children.indexOf(t);c>=0&&c!==s&&(e.children.splice(c,1),e.children.splice(s,0,t))}function k1(r,e){if(r&&r.userData){const t=r.userData.gltfExtensions;delete r.userData.gltfExtensions,r.userData=We.Deserialize(r.userData,{},e),r.userData.gltfExtensions=t}}const k0=new WeakMap;class G1 extends oi{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,i,n){const s=new ti(this.manager);s.setPath(this.path),s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,a=>{this.parse(a,t,n)},i,n)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,Ct,i).catch(i)}decodeDracoFile(e,t,i,n,s=Bt,a=()=>{}){const o={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:n||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:s};return this.decodeGeometry(e,o).then(t).catch(a)}decodeGeometry(e,t){const i=JSON.stringify(t);if(k0.has(e)){const l=k0.get(e);if(l.key===i)return l.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let n;const s=this.workerNextTaskID++,a=e.byteLength,o=this._getWorker(s,a).then(l=>(n=l,new Promise((c,h)=>{n._callbacks[s]={resolve:c,reject:h},n.postMessage({type:"decode",id:s,taskConfig:t,buffer:e},[e])}))).then(l=>this._createGeometry(l.geometry));return o.catch(()=>!0).then(()=>{n&&s&&this._releaseTask(n,s)}),k0.set(e,{key:i,promise:o}),o}_createGeometry(e){const t=new Je;e.index&&t.setIndex(new Ze(e.index.array,1));for(let i=0;i<e.attributes.length;i++){const n=e.attributes[i],s=n.name,a=n.array,o=n.itemSize,l=new Ze(a,o);s==="color"&&(this._assignVertexColorSpace(l,n.vertexColorSpace),l.normalized=!(a instanceof Float32Array)),t.setAttribute(s,l)}return t}_assignVertexColorSpace(e,t){if(t!==Ct)return;const i=new ee;for(let n=0,s=e.count;n<s;n++)i.fromBufferAttribute(e,n).convertSRGBToLinear(),e.setXYZ(n,i.r,i.g,i.b)}_loadLibrary(e,t){const i=new ti(this.manager);return i.setPath(this.decoderPath),i.setResponseType(t),i.setWithCredentials(this.withCredentials),new Promise((n,s)=>{i.load(e,n,void 0,s)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(i=>{const n=i[0];e||(this.decoderConfig.wasmBinary=i[1]);const s=yV,a=["/* draco decoder */",n,"","/* worker */",s.substring(s.indexOf("{")+1,s.lastIndexOf("}"))].join(`
`);this.workerSourceURL=URL.createObjectURL(new Blob([a]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const n=new Worker(this.workerSourceURL);n._callbacks={},n._taskCosts={},n._taskLoad=0,n.postMessage({type:"init",decoderConfig:this.decoderConfig}),n.onmessage=function(s){const a=s.data;switch(a.type){case"decode":n._callbacks[a.id].resolve(a);break;case"error":n._callbacks[a.id].reject(a);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+a.type+'"')}},this.workerPool.push(n)}else this.workerPool.sort(function(n,s){return n._taskLoad>s._taskLoad?-1:1});const i=this.workerPool[this.workerPool.length-1];return i._taskCosts[e]=t,i._taskLoad+=t,i})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}const yV=`
function DRACOWorker() {

	let decoderConfig;
	let decoderPending;

	onmessage = function ( e ) {

		const message = e.data;

		switch ( message.type ) {

			case 'init':
				decoderConfig = message.decoderConfig;
				decoderPending = new Promise( function ( resolve/*, reject*/ ) {

					decoderConfig.onModuleLoaded = function ( draco ) {

						// Module is Promise-like. Wrap before resolving to avoid loop.
						resolve( { draco: draco } );

					};

					DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef

				} );
				break;

			case 'decode':
				const buffer = message.buffer;
				const taskConfig = message.taskConfig;
				decoderPending.then( ( module ) => {

					const draco = module.draco;
					const decoder = new draco.Decoder();

					try {

						const geometry = decodeGeometry( draco, decoder, new Int8Array( buffer ), taskConfig );

						const buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );

						if ( geometry.index ) buffers.push( geometry.index.array.buffer );

						self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );

					} catch ( error ) {

						console.error( error );

						self.postMessage( { type: 'error', id: message.id, error: error.message } );

					} finally {

						draco.destroy( decoder );

					}

				} );
				break;

		}

	};

	function decodeGeometry( draco, decoder, array, taskConfig ) {

		const attributeIDs = taskConfig.attributeIDs;
		const attributeTypes = taskConfig.attributeTypes;

		let dracoGeometry;
		let decodingStatus;

		const geometryType = decoder.GetEncodedGeometryType( array );

		if ( geometryType === draco.TRIANGULAR_MESH ) {

			dracoGeometry = new draco.Mesh();
			decodingStatus = decoder.DecodeArrayToMesh( array, array.byteLength, dracoGeometry );

		} else if ( geometryType === draco.POINT_CLOUD ) {

			dracoGeometry = new draco.PointCloud();
			decodingStatus = decoder.DecodeArrayToPointCloud( array, array.byteLength, dracoGeometry );

		} else {

			throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );

		}

		if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {

			throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );

		}

		const geometry = { index: null, attributes: [] };

		// Gather all vertex attributes.
		for ( const attributeName in attributeIDs ) {

			const attributeType = self[ attributeTypes[ attributeName ] ];

			let attribute;
			let attributeID;

			// A Draco file may be created with default vertex attributes, whose attribute IDs
			// are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
			// a Draco file may contain a custom set of attributes, identified by known unique
			// IDs. glTF files always do the latter, and .drc files typically do the former.
			if ( taskConfig.useUniqueIDs ) {

				attributeID = attributeIDs[ attributeName ];
				attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );

			} else {

				attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );

				if ( attributeID === - 1 ) continue;

				attribute = decoder.GetAttribute( dracoGeometry, attributeID );

			}

			const attributeResult = decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute );

			if ( attributeName === 'color' ) {

				attributeResult.vertexColorSpace = taskConfig.vertexColorSpace;

			}

			geometry.attributes.push( attributeResult );

		}

		// Add index.
		if ( geometryType === draco.TRIANGULAR_MESH ) {

			geometry.index = decodeIndex( draco, decoder, dracoGeometry );

		}

		draco.destroy( dracoGeometry );

		return geometry;

	}

	function decodeIndex( draco, decoder, dracoGeometry ) {

		const numFaces = dracoGeometry.num_faces();
		const numIndices = numFaces * 3;
		const byteLength = numIndices * 4;

		const ptr = draco._malloc( byteLength );
		decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
		const index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
		draco._free( ptr );

		return { array: index, itemSize: 1 };

	}

	function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {

		const numComponents = attribute.num_components();
		const numPoints = dracoGeometry.num_points();
		const numValues = numPoints * numComponents;
		const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
		const dataType = getDracoDataType( draco, attributeType );

		const ptr = draco._malloc( byteLength );
		decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
		const array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
		draco._free( ptr );

		return {
			name: attributeName,
			array: array,
			itemSize: numComponents
		};

	}

	function getDracoDataType( draco, attributeType ) {

		switch ( attributeType ) {

			case Float32Array: return draco.DT_FLOAT32;
			case Int8Array: return draco.DT_INT8;
			case Int16Array: return draco.DT_INT16;
			case Int32Array: return draco.DT_INT32;
			case Uint8Array: return draco.DT_UINT8;
			case Uint16Array: return draco.DT_UINT16;
			case Uint32Array: return draco.DT_UINT32;

		}

	}

}
`,Co=class Co extends G1{constructor(e){super(e),this.encoderPending=null,this.decoderModulePending=null,this.encoderConfig={type:"js"},this.isDRACOLoader2=!0,this.setDecoderPath(Co.DRACO_LIBRARY_PATH)}transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new _e(e,new si({color:new ee(1,1,1)})):void 0}preload(e=!0,t=!1){return e&&super.preload(),t&&this.initEncoder(),this}async initEncoder(){if(this.encoderPending)return this.encoderPending;const e=typeof WebAssembly!="object"||this.encoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_encoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_encoder.wasm","arraybuffer"))),this.encoderPending=Promise.all(t).then(async i=>{const n=i[0];e||(this.encoderConfig.wasmBinary=i[1]);const a=(0,eval)(n+`
DracoEncoderModule;`);if(typeof a!="function")throw new Error("DRACOLoader2: unable to find DracoEncoderModule");return new Promise(o=>{a({...this.encoderConfig,onModuleLoaded:o})})}),this.encoderPending}async initDecoder(){return this.decoderModulePending?this.decoderModulePending:(this.decoderModulePending=(async()=>{await this._initDecoder();const e=await fetch(this.workerSourceURL).then(async n=>n.text()).then(n=>{const s=n.indexOf("/* worker */");if(s<1)throw new Error("unable to load decoder module");return n.substring(0,s-1)}),i=(0,eval)(e+`
DracoDecoderModule;`);if(typeof i!="function")throw new Error("DRACOLoader2: unable to find DracoDecoderModule");return new Promise(n=>{i({...this.decoderConfig,onModuleLoaded:n})})})(),this.decoderModulePending)}async _loadLibrary(e,t){return Co.LibraryValueMap[e]?Co.LibraryValueMap[e]:Co.LibraryValueMap[e]=await super._loadLibrary(e,t)}static SetDecoderJsString(e){this.LibraryValueMap["draco_decoder.js"]=e}static SetDecoderWasmBinary(e,t){this.LibraryValueMap["draco_wasm_wrapper.js"]=e,this.LibraryValueMap["draco_decoder.wasm"]=t}};Co.DRACO_LIBRARY_PATH="https://cdn.jsdelivr.net/gh/google/draco@1.5.6/javascript/",Co.LibraryValueMap={};let Dg=Co;class G0 extends f_{constructor(e){super(e),this.type=Yt}parse(e){const C=Math.pow(2.7182818,2.2);function x(w,P){let R=0;for(let Y=0;Y<65536;++Y)(Y==0||w[Y>>3]&1<<(Y&7))&&(P[R++]=Y);const k=R-1;for(;R<65536;)P[R++]=0;return k}function D(w){for(let P=0;P<16384;P++)w[P]={},w[P].len=0,w[P].lit=0,w[P].p=null}const U={l:0,c:0,lc:0};function O(w,P,R,k,Y){for(;R<w;)P=P<<8|wt(k,Y),R+=8;R-=w,U.l=P>>R&(1<<w)-1,U.c=P,U.lc=R}const N=new Array(59);function H(w){for(let R=0;R<=58;++R)N[R]=0;for(let R=0;R<65537;++R)N[w[R]]+=1;let P=0;for(let R=58;R>0;--R){const k=P+N[R]>>1;N[R]=P,P=k}for(let R=0;R<65537;++R){const k=w[R];k>0&&(w[R]=k|N[k]++<<6)}}function V(w,P,R,k,Y,Q){const Z=P;let ae=0,te=0;for(;k<=Y;k++){if(Z.value-P.value>R)return!1;O(6,ae,te,w,Z);const J=U.l;if(ae=U.c,te=U.lc,Q[k]=J,J==63){if(Z.value-P.value>R)throw new Error("Something wrong with hufUnpackEncTable");O(8,ae,te,w,Z);let re=U.l+6;if(ae=U.c,te=U.lc,k+re>Y+1)throw new Error("Something wrong with hufUnpackEncTable");for(;re--;)Q[k++]=0;k--}else if(J>=59){let re=J-59+2;if(k+re>Y+1)throw new Error("Something wrong with hufUnpackEncTable");for(;re--;)Q[k++]=0;k--}}H(Q)}function X(w){return w&63}function W(w){return w>>6}function ce(w,P,R,k){for(;P<=R;P++){const Y=W(w[P]),Q=X(w[P]);if(Y>>Q)throw new Error("Invalid table entry");if(Q>14){const Z=k[Y>>Q-14];if(Z.len)throw new Error("Invalid table entry");if(Z.lit++,Z.p){const ae=Z.p;Z.p=new Array(Z.lit);for(let te=0;te<Z.lit-1;++te)Z.p[te]=ae[te]}else Z.p=new Array(1);Z.p[Z.lit-1]=P}else if(Q){let Z=0;for(let ae=1<<14-Q;ae>0;ae--){const te=k[(Y<<14-Q)+Z];if(te.len||te.p)throw new Error("Invalid table entry");te.len=Q,te.lit=P,Z++}}}return!0}const ue={c:0,lc:0};function we(w,P,R,k){w=w<<8|wt(R,k),P+=8,ue.c=w,ue.lc=P}const Pe={c:0,lc:0};function Qe(w,P,R,k,Y,Q,Z,ae,te){if(w==P){k<8&&(we(R,k,Y,Q),R=ue.c,k=ue.lc),k-=8;let J=R>>k;if(J=new Uint8Array([J])[0],ae.value+J>te)return!1;const re=Z[ae.value-1];for(;J-- >0;)Z[ae.value++]=re}else if(ae.value<te)Z[ae.value++]=w;else return!1;Pe.c=R,Pe.lc=k}function ie(w){return w&65535}function oe(w){const P=ie(w);return P>32767?P-65536:P}const me={a:0,b:0};function Ce(w,P){const R=oe(w),Y=oe(P),Q=R+(Y&1)+(Y>>1),Z=Q,ae=Q-Y;me.a=Z,me.b=ae}function Xe(w,P){const R=ie(w),k=ie(P),Y=R-(k>>1)&65535,Q=k+Y-32768&65535;me.a=Q,me.b=Y}function dt(w,P,R,k,Y,Q,Z){const ae=Z<16384,te=R>Y?Y:R;let J=1,re,Se;for(;J<=te;)J<<=1;for(J>>=1,re=J,J>>=1;J>=1;){Se=0;const Te=Se+Q*(Y-re),Oe=Q*J,Re=Q*re,le=k*J,Ue=k*re;let ze,Rt,ci,vi;for(;Se<=Te;Se+=Re){let hi=Se;const ot=Se+k*(R-re);for(;hi<=ot;hi+=Ue){const ui=hi+le,Zn=hi+Oe,hn=Zn+le;ae?(Ce(w[hi+P],w[Zn+P]),ze=me.a,ci=me.b,Ce(w[ui+P],w[hn+P]),Rt=me.a,vi=me.b,Ce(ze,Rt),w[hi+P]=me.a,w[ui+P]=me.b,Ce(ci,vi),w[Zn+P]=me.a,w[hn+P]=me.b):(Xe(w[hi+P],w[Zn+P]),ze=me.a,ci=me.b,Xe(w[ui+P],w[hn+P]),Rt=me.a,vi=me.b,Xe(ze,Rt),w[hi+P]=me.a,w[ui+P]=me.b,Xe(ci,vi),w[Zn+P]=me.a,w[hn+P]=me.b)}if(R&J){const ui=hi+Oe;ae?Ce(w[hi+P],w[ui+P]):Xe(w[hi+P],w[ui+P]),ze=me.a,w[ui+P]=me.b,w[hi+P]=ze}}if(Y&J){let hi=Se;const ot=Se+k*(R-re);for(;hi<=ot;hi+=Ue){const ui=hi+le;ae?Ce(w[hi+P],w[ui+P]):Xe(w[hi+P],w[ui+P]),ze=me.a,w[ui+P]=me.b,w[hi+P]=ze}}re=J,J>>=1}return Se}function Ke(w,P,R,k,Y,Q,Z,ae,te){let J=0,re=0;const Se=Z,Te=Math.trunc(k.value+(Y+7)/8);for(;k.value<Te;)for(we(J,re,R,k),J=ue.c,re=ue.lc;re>=14;){const Re=J>>re-14&16383,le=P[Re];if(le.len)re-=le.len,Qe(le.lit,Q,J,re,R,k,ae,te,Se),J=Pe.c,re=Pe.lc;else{if(!le.p)throw new Error("hufDecode issues");let Ue;for(Ue=0;Ue<le.lit;Ue++){const ze=X(w[le.p[Ue]]);for(;re<ze&&k.value<Te;)we(J,re,R,k),J=ue.c,re=ue.lc;if(re>=ze&&W(w[le.p[Ue]])==(J>>re-ze&(1<<ze)-1)){re-=ze,Qe(le.p[Ue],Q,J,re,R,k,ae,te,Se),J=Pe.c,re=Pe.lc;break}}if(Ue==le.lit)throw new Error("hufDecode issues")}}const Oe=8-Y&7;for(J>>=Oe,re-=Oe;re>0;){const Re=P[J<<14-re&16383];if(Re.len)re-=Re.len,Qe(Re.lit,Q,J,re,R,k,ae,te,Se),J=Pe.c,re=Pe.lc;else throw new Error("hufDecode issues")}return!0}function gt(w,P,R,k,Y,Q){const Z={value:0},ae=R.value,te=Ge(P,R),J=Ge(P,R);R.value+=4;const re=Ge(P,R);if(R.value+=4,te<0||te>=65537||J<0||J>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const Se=new Array(65537),Te=new Array(16384);D(Te);const Oe=k-(R.value-ae);if(V(w,R,Oe,te,J,Se),re>8*(k-(R.value-ae)))throw new Error("Something wrong with hufUncompress");ce(Se,te,J,Te),Ke(Se,Te,w,R,re,J,Q,Y,Z)}function F(w,P,R){for(let k=0;k<R;++k)P[k]=w[P[k]]}function xe(w){for(let P=1;P<w.length;P++){const R=w[P-1]+w[P]-128;w[P]=R}}function be(w,P){let R=0,k=Math.floor((w.length+1)/2),Y=0;const Q=w.length-1;for(;!(Y>Q||(P[Y++]=w[R++],Y>Q));)P[Y++]=w[k++]}function Ne(w){let P=w.byteLength;const R=new Array;let k=0;const Y=new DataView(w);for(;P>0;){const Q=Y.getInt8(k++);if(Q<0){const Z=-Q;P-=Z+1;for(let ae=0;ae<Z;ae++)R.push(Y.getUint8(k++))}else{const Z=Q;P-=2;const ae=Y.getUint8(k++);for(let te=0;te<Z+1;te++)R.push(ae)}}return R}function ge(w,P,R,k,Y,Q){let Z=new DataView(Q.buffer);const ae=R[w.idx[0]].width,te=R[w.idx[0]].height,J=3,re=Math.floor(ae/8),Se=Math.ceil(ae/8),Te=Math.ceil(te/8),Oe=ae-(Se-1)*8,Re=te-(Te-1)*8,le={value:0},Ue=new Array(J),ze=new Array(J),Rt=new Array(J),ci=new Array(J),vi=new Array(J);for(let ot=0;ot<J;++ot)vi[ot]=P[w.idx[ot]],Ue[ot]=ot<1?0:Ue[ot-1]+Se*Te,ze[ot]=new Float32Array(64),Rt[ot]=new Uint16Array(64),ci[ot]=new Uint16Array(Se*64);for(let ot=0;ot<Te;++ot){let ui=8;ot==Te-1&&(ui=Re);let Zn=8;for(let xt=0;xt<Se;++xt){xt==Se-1&&(Zn=Oe);for(let ei=0;ei<J;++ei)Rt[ei].fill(0),Rt[ei][0]=Y[Ue[ei]++],ut(le,k,Rt[ei]),ke(Rt[ei],ze[ei]),Ve(ze[ei]);z(ze);for(let ei=0;ei<J;++ei)B(ze[ei],ci[ei],xt*64)}let hn=0;for(let xt=0;xt<J;++xt){const ei=R[w.idx[xt]].type;for(let xr=8*ot;xr<8*ot+ui;++xr){hn=vi[xt][xr];for(let Mo=0;Mo<re;++Mo){const Wr=Mo*64+(xr&7)*8;Z.setUint16(hn+0*ei,ci[xt][Wr+0],!0),Z.setUint16(hn+2*ei,ci[xt][Wr+1],!0),Z.setUint16(hn+4*ei,ci[xt][Wr+2],!0),Z.setUint16(hn+6*ei,ci[xt][Wr+3],!0),Z.setUint16(hn+8*ei,ci[xt][Wr+4],!0),Z.setUint16(hn+10*ei,ci[xt][Wr+5],!0),Z.setUint16(hn+12*ei,ci[xt][Wr+6],!0),Z.setUint16(hn+14*ei,ci[xt][Wr+7],!0),hn+=16*ei}}if(re!=Se)for(let xr=8*ot;xr<8*ot+ui;++xr){const Mo=vi[xt][xr]+8*re*2*ei,Wr=re*64+(xr&7)*8;for(let wA=0;wA<Zn;++wA)Z.setUint16(Mo+wA*2*ei,ci[xt][Wr+wA],!0)}}}const hi=new Uint16Array(ae);Z=new DataView(Q.buffer);for(let ot=0;ot<J;++ot){R[w.idx[ot]].decoded=!0;const ui=R[w.idx[ot]].type;if(R[ot].type==2)for(let Zn=0;Zn<te;++Zn){const hn=vi[ot][Zn];for(let xt=0;xt<ae;++xt)hi[xt]=Z.getUint16(hn+xt*2*ui,!0);for(let xt=0;xt<ae;++xt)Z.setFloat32(hn+xt*2*ui,$(hi[xt]),!0)}}}function ut(w,P,R){let k,Y=1;for(;Y<64;)k=P[w.value],k==65280?Y=64:k>>8==255?Y+=k&255:(R[Y]=k,Y++),w.value++}function ke(w,P){P[0]=$(w[0]),P[1]=$(w[1]),P[2]=$(w[5]),P[3]=$(w[6]),P[4]=$(w[14]),P[5]=$(w[15]),P[6]=$(w[27]),P[7]=$(w[28]),P[8]=$(w[2]),P[9]=$(w[4]),P[10]=$(w[7]),P[11]=$(w[13]),P[12]=$(w[16]),P[13]=$(w[26]),P[14]=$(w[29]),P[15]=$(w[42]),P[16]=$(w[3]),P[17]=$(w[8]),P[18]=$(w[12]),P[19]=$(w[17]),P[20]=$(w[25]),P[21]=$(w[30]),P[22]=$(w[41]),P[23]=$(w[43]),P[24]=$(w[9]),P[25]=$(w[11]),P[26]=$(w[18]),P[27]=$(w[24]),P[28]=$(w[31]),P[29]=$(w[40]),P[30]=$(w[44]),P[31]=$(w[53]),P[32]=$(w[10]),P[33]=$(w[19]),P[34]=$(w[23]),P[35]=$(w[32]),P[36]=$(w[39]),P[37]=$(w[45]),P[38]=$(w[52]),P[39]=$(w[54]),P[40]=$(w[20]),P[41]=$(w[22]),P[42]=$(w[33]),P[43]=$(w[38]),P[44]=$(w[46]),P[45]=$(w[51]),P[46]=$(w[55]),P[47]=$(w[60]),P[48]=$(w[21]),P[49]=$(w[34]),P[50]=$(w[37]),P[51]=$(w[47]),P[52]=$(w[50]),P[53]=$(w[56]),P[54]=$(w[59]),P[55]=$(w[61]),P[56]=$(w[35]),P[57]=$(w[36]),P[58]=$(w[48]),P[59]=$(w[49]),P[60]=$(w[57]),P[61]=$(w[58]),P[62]=$(w[62]),P[63]=$(w[63])}function Ve(w){const P=.5*Math.cos(.7853975),R=.5*Math.cos(3.14159/16),k=.5*Math.cos(3.14159/8),Y=.5*Math.cos(3*3.14159/16),Q=.5*Math.cos(5*3.14159/16),Z=.5*Math.cos(3*3.14159/8),ae=.5*Math.cos(7*3.14159/16),te=new Array(4),J=new Array(4),re=new Array(4),Se=new Array(4);for(let Te=0;Te<8;++Te){const Oe=Te*8;te[0]=k*w[Oe+2],te[1]=Z*w[Oe+2],te[2]=k*w[Oe+6],te[3]=Z*w[Oe+6],J[0]=R*w[Oe+1]+Y*w[Oe+3]+Q*w[Oe+5]+ae*w[Oe+7],J[1]=Y*w[Oe+1]-ae*w[Oe+3]-R*w[Oe+5]-Q*w[Oe+7],J[2]=Q*w[Oe+1]-R*w[Oe+3]+ae*w[Oe+5]+Y*w[Oe+7],J[3]=ae*w[Oe+1]-Q*w[Oe+3]+Y*w[Oe+5]-R*w[Oe+7],re[0]=P*(w[Oe+0]+w[Oe+4]),re[3]=P*(w[Oe+0]-w[Oe+4]),re[1]=te[0]+te[3],re[2]=te[1]-te[2],Se[0]=re[0]+re[1],Se[1]=re[3]+re[2],Se[2]=re[3]-re[2],Se[3]=re[0]-re[1],w[Oe+0]=Se[0]+J[0],w[Oe+1]=Se[1]+J[1],w[Oe+2]=Se[2]+J[2],w[Oe+3]=Se[3]+J[3],w[Oe+4]=Se[3]-J[3],w[Oe+5]=Se[2]-J[2],w[Oe+6]=Se[1]-J[1],w[Oe+7]=Se[0]-J[0]}for(let Te=0;Te<8;++Te)te[0]=k*w[16+Te],te[1]=Z*w[16+Te],te[2]=k*w[48+Te],te[3]=Z*w[48+Te],J[0]=R*w[8+Te]+Y*w[24+Te]+Q*w[40+Te]+ae*w[56+Te],J[1]=Y*w[8+Te]-ae*w[24+Te]-R*w[40+Te]-Q*w[56+Te],J[2]=Q*w[8+Te]-R*w[24+Te]+ae*w[40+Te]+Y*w[56+Te],J[3]=ae*w[8+Te]-Q*w[24+Te]+Y*w[40+Te]-R*w[56+Te],re[0]=P*(w[Te]+w[32+Te]),re[3]=P*(w[Te]-w[32+Te]),re[1]=te[0]+te[3],re[2]=te[1]-te[2],Se[0]=re[0]+re[1],Se[1]=re[3]+re[2],Se[2]=re[3]-re[2],Se[3]=re[0]-re[1],w[0+Te]=Se[0]+J[0],w[8+Te]=Se[1]+J[1],w[16+Te]=Se[2]+J[2],w[24+Te]=Se[3]+J[3],w[32+Te]=Se[3]-J[3],w[40+Te]=Se[2]-J[2],w[48+Te]=Se[1]-J[1],w[56+Te]=Se[0]-J[0]}function z(w){for(let P=0;P<64;++P){const R=w[0][P],k=w[1][P],Y=w[2][P];w[0][P]=R+1.5747*Y,w[1][P]=R-.1873*k-.4682*Y,w[2][P]=R+1.8556*k}}function B(w,P,R){for(let k=0;k<64;++k)P[R+k]=zn.toHalfFloat(ne(w[k]))}function ne(w){return w<=1?Math.sign(w)*Math.pow(Math.abs(w),2.2):Math.sign(w)*Math.pow(C,Math.abs(w)-1)}function de(w){return new DataView(w.array.buffer,w.offset.value,w.size)}function ye(w){const P=w.viewer.buffer.slice(w.offset.value,w.offset.value+w.size),R=new Uint8Array(Ne(P)),k=new Uint8Array(R.length);return xe(R),be(R,k),new DataView(k.buffer)}function pe(w){const P=w.array.slice(w.offset.value,w.offset.value+w.size),R=Ea(P),k=new Uint8Array(R.length);return xe(R),be(R,k),new DataView(k.buffer)}function nt(w){const P=w.viewer,R={value:w.offset.value},k=new Uint16Array(w.columns*w.lines*(w.inputChannels.length*w.type)),Y=new Uint8Array(8192);let Q=0;const Z=new Array(w.inputChannels.length);for(let Re=0,le=w.inputChannels.length;Re<le;Re++)Z[Re]={},Z[Re].start=Q,Z[Re].end=Z[Re].start,Z[Re].nx=w.columns,Z[Re].ny=w.lines,Z[Re].size=w.type,Q+=Z[Re].nx*Z[Re].ny*Z[Re].size;const ae=Ae(P,R),te=Ae(P,R);if(te>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(ae<=te)for(let Re=0;Re<te-ae+1;Re++)Y[Re+ae]=_t(P,R);const J=new Uint16Array(65536),re=x(Y,J),Se=Ge(P,R);gt(w.array,P,R,Se,k,Q);for(let Re=0;Re<w.inputChannels.length;++Re){const le=Z[Re];for(let Ue=0;Ue<Z[Re].size;++Ue)dt(k,le.start+Ue,le.nx,le.size,le.ny,le.nx*le.size,re)}F(J,k,Q);let Te=0;const Oe=new Uint8Array(k.buffer.byteLength);for(let Re=0;Re<w.lines;Re++)for(let le=0;le<w.inputChannels.length;le++){const Ue=Z[le],ze=Ue.nx*Ue.size,Rt=new Uint8Array(k.buffer,Ue.end*2,ze*2);Oe.set(Rt,Te),Te+=ze*2,Ue.end+=ze}return new DataView(Oe.buffer)}function Le(w){const P=w.array.slice(w.offset.value,w.offset.value+w.size),R=Ea(P),k=w.inputChannels.length*w.lines*w.columns*w.totalBytes,Y=new ArrayBuffer(k),Q=new DataView(Y);let Z=0,ae=0;const te=new Array(4);for(let J=0;J<w.lines;J++)for(let re=0;re<w.inputChannels.length;re++){let Se=0;switch(w.inputChannels[re].pixelType){case 1:te[0]=Z,te[1]=te[0]+w.columns,Z=te[1]+w.columns;for(let Oe=0;Oe<w.columns;++Oe){const Re=R[te[0]++]<<8|R[te[1]++];Se+=Re,Q.setUint16(ae,Se,!0),ae+=2}break;case 2:te[0]=Z,te[1]=te[0]+w.columns,te[2]=te[1]+w.columns,Z=te[2]+w.columns;for(let Oe=0;Oe<w.columns;++Oe){const Re=R[te[0]++]<<24|R[te[1]++]<<16|R[te[2]++]<<8;Se+=Re,Q.setUint32(ae,Se,!0),ae+=4}break}}return Q}function Ye(w){const P=w.viewer,R={value:w.offset.value},k=new Uint8Array(w.columns*w.lines*(w.inputChannels.length*w.type*2)),Y={version:Ht(P,R),unknownUncompressedSize:Ht(P,R),unknownCompressedSize:Ht(P,R),acCompressedSize:Ht(P,R),dcCompressedSize:Ht(P,R),rleCompressedSize:Ht(P,R),rleUncompressedSize:Ht(P,R),rleRawSize:Ht(P,R),totalAcUncompressedCount:Ht(P,R),totalDcUncompressedCount:Ht(P,R),acCompression:Ht(P,R)};if(Y.version<2)throw new Error("EXRLoader.parse: "+L.compression+" version "+Y.version+" is unsupported");const Q=new Array;let Z=Ae(P,R)-2;for(;Z>0;){const le=yt(P.buffer,R),Ue=_t(P,R),ze=Ue>>2&3,Rt=(Ue>>4)-1,ci=new Int8Array([Rt])[0],vi=_t(P,R);Q.push({name:le,index:ci,type:vi,compression:ze}),Z-=le.length+3}const ae=L.channels,te=new Array(w.inputChannels.length);for(let le=0;le<w.inputChannels.length;++le){const Ue=te[le]={},ze=ae[le];Ue.name=ze.name,Ue.compression=0,Ue.decoded=!1,Ue.type=ze.pixelType,Ue.pLinear=ze.pLinear,Ue.width=w.columns,Ue.height=w.lines}const J={idx:new Array(3)};for(let le=0;le<w.inputChannels.length;++le){const Ue=te[le];for(let ze=0;ze<Q.length;++ze){const Rt=Q[ze];Ue.name==Rt.name&&(Ue.compression=Rt.compression,Rt.index>=0&&(J.idx[Rt.index]=le),Ue.offset=le)}}let re,Se,Te;if(Y.acCompressedSize>0)switch(Y.acCompression){case 0:re=new Uint16Array(Y.totalAcUncompressedCount),gt(w.array,P,R,Y.acCompressedSize,re,Y.totalAcUncompressedCount);break;case 1:const le=w.array.slice(R.value,R.value+Y.totalAcUncompressedCount),Ue=Ea(le);re=new Uint16Array(Ue.buffer),R.value+=Y.totalAcUncompressedCount;break}if(Y.dcCompressedSize>0){const le={array:w.array,offset:R,size:Y.dcCompressedSize};Se=new Uint16Array(pe(le).buffer),R.value+=Y.dcCompressedSize}if(Y.rleRawSize>0){const le=w.array.slice(R.value,R.value+Y.rleCompressedSize),Ue=Ea(le);Te=Ne(Ue.buffer),R.value+=Y.rleCompressedSize}let Oe=0;const Re=new Array(te.length);for(let le=0;le<Re.length;++le)Re[le]=new Array;for(let le=0;le<w.lines;++le)for(let Ue=0;Ue<te.length;++Ue)Re[Ue].push(Oe),Oe+=te[Ue].width*w.type*2;ge(J,Re,te,re,Se,k);for(let le=0;le<te.length;++le){const Ue=te[le];if(!Ue.decoded)switch(Ue.compression){case 2:let ze=0,Rt=0;for(let ci=0;ci<w.lines;++ci){let vi=Re[le][ze];for(let hi=0;hi<Ue.width;++hi){for(let ot=0;ot<2*Ue.type;++ot)k[vi++]=Te[Rt+ot*Ue.width*Ue.height];Rt++}ze++}break;default:throw new Error("EXRLoader.parse: unsupported channel compression")}}return new DataView(k.buffer)}function yt(w,P){const R=new Uint8Array(w);let k=0;for(;R[P.value+k]!=0;)k+=1;const Y=new TextDecoder().decode(R.slice(P.value,P.value+k));return P.value=P.value+k+1,Y}function Me(w,P,R){const k=new TextDecoder().decode(new Uint8Array(w).slice(P.value,P.value+R));return P.value=P.value+R,k}function je(w,P){const R=st(w,P),k=Ge(w,P);return[R,k]}function Wt(w,P){const R=Ge(w,P),k=Ge(w,P);return[R,k]}function st(w,P){const R=w.getInt32(P.value,!0);return P.value=P.value+4,R}function Ge(w,P){const R=w.getUint32(P.value,!0);return P.value=P.value+4,R}function wt(w,P){const R=w[P.value];return P.value=P.value+1,R}function _t(w,P){const R=w.getUint8(P.value);return P.value=P.value+1,R}const Ht=function(w,P){let R;return"getBigInt64"in DataView.prototype?R=Number(w.getBigInt64(P.value,!0)):R=w.getUint32(P.value+4,!0)+Number(w.getUint32(P.value,!0)<<32),P.value+=8,R};function j(w,P){const R=w.getFloat32(P.value,!0);return P.value+=4,R}function Ie(w,P){return zn.toHalfFloat(j(w,P))}function $(w){const P=(w&31744)>>10,R=w&1023;return(w>>15?-1:1)*(P?P===31?R?NaN:1/0:Math.pow(2,P-15)*(1+R/1024):6103515625e-14*(R/1024))}function Ae(w,P){const R=w.getUint16(P.value,!0);return P.value+=2,R}function Be(w,P){return $(Ae(w,P))}function pt(w,P,R,k){const Y=R.value,Q=[];for(;R.value<Y+k-1;){const Z=yt(P,R),ae=st(w,R),te=_t(w,R);R.value+=3;const J=st(w,R),re=st(w,R);Q.push({name:Z,pixelType:ae,pLinear:te,xSampling:J,ySampling:re})}return R.value+=1,Q}function Kt(w,P){const R=j(w,P),k=j(w,P),Y=j(w,P),Q=j(w,P),Z=j(w,P),ae=j(w,P),te=j(w,P),J=j(w,P);return{redX:R,redY:k,greenX:Y,greenY:Q,blueX:Z,blueY:ae,whiteX:te,whiteY:J}}function Ji(w,P){const R=["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"],k=_t(w,P);return R[k]}function Nn(w,P){const R=st(w,P),k=st(w,P),Y=st(w,P),Q=st(w,P);return{xMin:R,yMin:k,xMax:Y,yMax:Q}}function Jt(w,P){const R=["INCREASING_Y","DECREASING_Y","RANDOM_Y"],k=_t(w,P);return R[k]}function bs(w,P){const R=["ENVMAP_LATLONG","ENVMAP_CUBE"],k=_t(w,P);return R[k]}function Zs(w,P){const R=["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"],k=["ROUND_DOWN","ROUND_UP"],Y=Ge(w,P),Q=Ge(w,P),Z=_t(w,P);return{xSize:Y,ySize:Q,levelMode:R[Z&15],roundingMode:k[Z>>4]}}function pA(w,P){const R=j(w,P),k=j(w,P);return[R,k]}function Fa(w,P){const R=j(w,P),k=j(w,P),Y=j(w,P);return[R,k,Y]}function hf(w,P,R,k,Y){if(k==="string"||k==="stringvector"||k==="iccProfile")return Me(P,R,Y);if(k==="chlist")return pt(w,P,R,Y);if(k==="chromaticities")return Kt(w,R);if(k==="compression")return Ji(w,R);if(k==="box2i")return Nn(w,R);if(k==="envmap")return bs(w,R);if(k==="tiledesc")return Zs(w,R);if(k==="lineOrder")return Jt(w,R);if(k==="float")return j(w,R);if(k==="v2f")return pA(w,R);if(k==="v3f")return Fa(w,R);if(k==="int")return st(w,R);if(k==="rational")return je(w,R);if(k==="timecode")return Wt(w,R);if(k==="preview")return R.value+=Y,"skipped";R.value+=Y}function mA(w,P){const R=Math.log2(w);return P=="ROUND_DOWN"?Math.floor(R):Math.ceil(R)}function gA(w,P,R){let k=0;switch(w.levelMode){case"ONE_LEVEL":k=1;break;case"MIPMAP_LEVELS":k=mA(Math.max(P,R),w.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return k}function Eo(w,P,R,k){const Y=new Array(w);for(let Q=0;Q<w;Q++){const Z=1<<Q;let ae=P/Z|0;k=="ROUND_UP"&&ae*Z<P&&(ae+=1);const te=Math.max(ae,1);Y[Q]=(te+R-1)/R|0}return Y}function AA(){const w=this,P=w.offset,R={value:0};for(let k=0;k<w.tileCount;k++){const Y=st(w.viewer,P),Q=st(w.viewer,P);P.value+=8,w.size=Ge(w.viewer,P);const Z=Y*w.blockWidth,ae=Q*w.blockHeight;w.columns=Z+w.blockWidth>w.width?w.width-Z:w.blockWidth,w.lines=ae+w.blockHeight>w.height?w.height-ae:w.blockHeight;const te=w.columns*w.totalBytes,re=w.size<w.lines*te?w.uncompress(w):de(w);P.value+=w.size;for(let Se=0;Se<w.lines;Se++){const Te=Se*w.columns*w.totalBytes;for(let Oe=0;Oe<w.inputChannels.length;Oe++){const Re=L.channels[Oe].name,le=w.channelByteOffsets[Re]*w.columns,Ue=w.decodeChannels[Re];if(Ue===void 0)continue;R.value=Te+le;const ze=(w.height-(1+ae+Se))*w.outLineWidth;for(let Rt=0;Rt<w.columns;Rt++){const ci=ze+(Rt+Z)*w.outputChannels+Ue;w.byteArray[ci]=w.getter(re,R)}}}}}function Xh(){const w=this,P=w.offset,R={value:0};for(let k=0;k<w.height/w.blockHeight;k++){const Y=st(w.viewer,P)-L.dataWindow.yMin;w.size=Ge(w.viewer,P),w.lines=Y+w.blockHeight>w.height?w.height-Y:w.blockHeight;const Q=w.columns*w.totalBytes,ae=w.size<w.lines*Q?w.uncompress(w):de(w);P.value+=w.size;for(let te=0;te<w.blockHeight;te++){const J=k*w.blockHeight,re=te+w.scanOrder(J);if(re>=w.height)continue;const Se=te*Q,Te=(w.height-1-re)*w.outLineWidth;for(let Oe=0;Oe<w.inputChannels.length;Oe++){const Re=L.channels[Oe].name,le=w.channelByteOffsets[Re]*w.columns,Ue=w.decodeChannels[Re];if(Ue!==void 0){R.value=Se+le;for(let ze=0;ze<w.columns;ze++){const Rt=Te+ze*w.outputChannels+Ue;w.byteArray[Rt]=w.getter(ae,R)}}}}}}function yA(w,P,R){const k={};if(w.getUint32(0,!0)!=20000630)throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");k.version=w.getUint8(4);const Y=w.getUint8(5);k.spec={singleTile:!!(Y&2),longName:!!(Y&4),deepFormat:!!(Y&8),multiPart:!!(Y&16)},R.value=8;let Q=!0;for(;Q;){const Z=yt(P,R);if(Z==0)Q=!1;else{const ae=yt(P,R),te=Ge(w,R),J=hf(w,P,R,ae,te);J===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${ae}'.`):k[Z]=J}}if((Y&-7)!=0)throw console.error("THREE.EXRHeader:",k),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return k}function _A(w,P,R,k,Y){const Q={size:0,viewer:P,array:R,offset:k,width:w.dataWindow.xMax-w.dataWindow.xMin+1,height:w.dataWindow.yMax-w.dataWindow.yMin+1,inputChannels:w.channels,channelByteOffsets:{},scanOrder:null,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:Bt};switch(w.compression){case"NO_COMPRESSION":Q.blockHeight=1,Q.uncompress=de;break;case"RLE_COMPRESSION":Q.blockHeight=1,Q.uncompress=ye;break;case"ZIPS_COMPRESSION":Q.blockHeight=1,Q.uncompress=pe;break;case"ZIP_COMPRESSION":Q.blockHeight=16,Q.uncompress=pe;break;case"PIZ_COMPRESSION":Q.blockHeight=32,Q.uncompress=nt;break;case"PXR24_COMPRESSION":Q.blockHeight=16,Q.uncompress=Le;break;case"DWAA_COMPRESSION":Q.blockHeight=32,Q.uncompress=Ye;break;case"DWAB_COMPRESSION":Q.blockHeight=256,Q.uncompress=Ye;break;default:throw new Error("EXRLoader.parse: "+w.compression+" is unsupported")}const Z={};for(const re of w.channels)switch(re.name){case"Y":case"R":case"G":case"B":case"A":Z[re.name]=!0,Q.type=re.pixelType}let ae=!1;if(Z.R&&Z.G&&Z.B)ae=!Z.A,Q.outputChannels=4,Q.decodeChannels={R:0,G:1,B:2,A:3};else if(Z.Y)Q.outputChannels=1,Q.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(Q.type==1)switch(Y){case Ut:Q.getter=Be;break;case Yt:Q.getter=Ae;break}else if(Q.type==2)switch(Y){case Ut:Q.getter=j;break;case Yt:Q.getter=Ie}else throw new Error("EXRLoader.parse: unsupported pixelType "+Q.type+" for "+w.compression+".");Q.columns=Q.width;const te=Q.width*Q.height*Q.outputChannels;switch(Y){case Ut:Q.byteArray=new Float32Array(te),ae&&Q.byteArray.fill(1,0,te);break;case Yt:Q.byteArray=new Uint16Array(te),ae&&Q.byteArray.fill(15360,0,te);break;default:console.error("THREE.EXRLoader: unsupported type: ",Y);break}let J=0;for(const re of w.channels)Q.decodeChannels[re.name]!==void 0&&(Q.channelByteOffsets[re.name]=J),J+=re.pixelType*2;if(Q.totalBytes=J,Q.outLineWidth=Q.width*Q.outputChannels,w.lineOrder==="INCREASING_Y"?Q.scanOrder=re=>re:Q.scanOrder=re=>Q.height-1-re,Q.outputChannels==4?(Q.format=qt,Q.colorSpace=Bt):(Q.format=Jr,Q.colorSpace=ai),w.spec.singleTile){Q.blockHeight=w.tiles.ySize,Q.blockWidth=w.tiles.xSize;const re=gA(w.tiles,Q.width,Q.height),Se=Eo(re,Q.width,w.tiles.xSize,w.tiles.roundingMode),Te=Eo(re,Q.height,w.tiles.ySize,w.tiles.roundingMode);Q.tileCount=Se[0]*Te[0];for(let Oe=0;Oe<re;Oe++)for(let Re=0;Re<Te[Oe];Re++)for(let le=0;le<Se[Oe];le++)Ht(P,k);Q.decode=AA.bind(Q)}else{Q.blockWidth=Q.width;const re=Math.ceil(Q.height/Q.blockHeight);for(let Se=0;Se<re;Se++)Ht(P,k);Q.decode=Xh.bind(Q)}return Q}const vA={value:0},bA=new DataView(e),ow=new Uint8Array(e),L=yA(bA,e,vA),q=_A(L,bA,ow,vA,this.type);return q.decode(),{header:L,width:q.width,height:q.height,data:q.byteArray,format:q.format,colorSpace:q.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,i,n){function s(a,o){a.colorSpace=o.colorSpace,a.minFilter=at,a.magFilter=at,a.generateMipmaps=!1,a.flipY=!1,t&&t(a,o)}return super.load(e,s,i,n)}}const z0=new WeakMap;class z1 extends oi{constructor(e){super(e),this.libraryPath="",this.libraryPending=null,this.libraryBinary=null,this.libraryConfig={},this.url="",this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.workerConfig={},this.materials=[],this.warnings=[]}setLibraryPath(e){return this.libraryPath=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,i,n){const s=new ti(this.manager);s.setPath(this.path),s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),this.url=e,s.load(e,a=>{if(z0.has(a))return z0.get(a).promise.then(t).catch(n);this.decodeObjects(a,e).then(o=>{o.userData.warnings=this.warnings,this.warnings=[],t(o)}).catch(o=>n(o))},i,n)}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}decodeObjects(e,t){let i,n;const s=e.byteLength,a=this._getWorker(s).then(o=>(i=o,n=this.workerNextTaskID++,new Promise((l,c)=>{i._callbacks[n]={resolve:l,reject:c},i.postMessage({type:"decode",id:n,buffer:e},[e])}))).then(o=>this._createGeometry(o.data)).catch(o=>{throw o});return a.catch(()=>!0).then(()=>{i&&n&&this._releaseTask(i,n)}),z0.set(e,{url:t,promise:a}),a}parse(e,t,i){this.decodeObjects(e,"").then(n=>{n.userData.warnings=this.warnings,t(n)}).catch(n=>i(n))}_compareMaterials(e){if(this.materials.includes(e))return e;const t={};t.name=e.name,t.color={},t.color.r=e.color.r,t.color.g=e.color.g,t.color.b=e.color.b,t.type=e.type,t.vertexColors=e.vertexColors;const i=JSON.stringify(t);for(let n=0;n<this.materials.length;n++){const s=this.materials[n],a={};if(a.name=s.name,a.color={},a.color.r=s.color.r,a.color.g=s.color.g,a.color.b=s.color.b,a.type=s.type,a.vertexColors=s.vertexColors,JSON.stringify(a)===i)return s}return this.materials.push(e),e}_createMaterial(e,t){if(e===void 0)return new Ya({color:new ee(1,1,1),metalness:.8,name:oi.DEFAULT_MATERIAL_NAME,side:Zi});const i=new Jo({color:new ee(e.diffuseColor.r/255,e.diffuseColor.g/255,e.diffuseColor.b/255),emissive:new ee(e.emissionColor.r,e.emissionColor.g,e.emissionColor.b),flatShading:e.disableLighting,ior:e.indexOfRefraction,name:e.name,reflectivity:e.reflectivity,opacity:1-e.transparency,side:Zi,specularColor:e.specularColor,transparent:e.transparency>0});if(i.userData.id=e.id,e.pbrSupported){const s=e.pbr;i.anisotropy=s.anisotropic,i.anisotropyRotation=s.anisotropicRotation,i.color=new ee(s.baseColor.r,s.baseColor.g,s.baseColor.b),i.clearcoat=s.clearcoat,i.clearcoatRoughness=s.clearcoatRoughness,i.metalness=s.metallic,i.transmission=1-s.opacity,i.roughness=s.roughness,i.sheen=s.sheen,i.specularIntensity=s.specular,i.thickness=s.subsurface}e.pbrSupported&&e.pbr.opacity===0&&e.transparency===1&&(i.opacity=.2,i.transmission=1);const n=new Za;for(let s=0;s<e.textures.length;s++){const a=e.textures[s];if(a.image!==null){const o=n.load(a.image);switch(a.type){case"Bump":i.bumpMap=o;break;case"Diffuse":i.map=o;break;case"Emap":i.envMap=o;break;case"Opacity":i.transmissionMap=o;break;case"Transparency":i.alphaMap=o,i.transparent=!0;break;case"PBR_Alpha":i.alphaMap=o,i.transparent=!0;break;case"PBR_AmbientOcclusion":i.aoMap=o;break;case"PBR_Anisotropic":i.anisotropyMap=o;break;case"PBR_BaseColor":i.map=o;break;case"PBR_Clearcoat":i.clearcoatMap=o;break;case"PBR_ClearcoatBump":i.clearcoatNormalMap=o;break;case"PBR_ClearcoatRoughness":i.clearcoatRoughnessMap=o;break;case"PBR_Displacement":i.displacementMap=o;break;case"PBR_Emission":i.emissiveMap=o;break;case"PBR_Metallic":i.metalnessMap=o;break;case"PBR_Roughness":i.roughnessMap=o;break;case"PBR_Sheen":i.sheenColorMap=o;break;case"PBR_Specular":i.specularColorMap=o;break;case"PBR_Subsurface":i.thicknessMap=o;break;default:this.warnings.push({message:`THREE.3DMLoader: No conversion exists for 3dm ${a.type}.`,type:"no conversion"});break}o.wrapS=a.wrapU===0?Pn:di,o.wrapT=a.wrapV===0?Pn:di,a.repeat&&o.repeat.set(a.repeat[0],a.repeat[1])}}return t&&new G0().load(t.image,function(s){s.mapping=THREE.EquirectangularReflectionMapping,i.envMap=s}),i}_createGeometry(e){const t=new ft,i=[],n=[],s=[];t.userData.layers=e.layers,t.userData.groups=e.groups,t.userData.settings=e.settings,t.userData.settings.renderSettings=e.renderSettings,t.userData.strings=e.strings,t.userData.objectType="File3dm",t.userData.materials=null,t.name=this.url;let a=e.objects;const o=e.materials;for(let l=0;l<a.length;l++){const c=a[l],h=c.attributes;switch(c.objectType){case"InstanceDefinition":n.push(c);break;case"InstanceReference":s.push(c);break;default:let u=null;switch(h.materialSource.name){case"ObjectMaterialSource_MaterialFromLayer":h.layerIndex>=0&&(u=e.layers[h.layerIndex].renderMaterialIndex);break;case"ObjectMaterialSource_MaterialFromObject":h.materialIndex>=0&&(u=h.materialIndex);break}let d=null;if(u>=0){const A=o[u];d=this._createMaterial(A,e.renderEnvironment)}const p=this._createObject(c,d);if(p===void 0)continue;const m=e.layers[h.layerIndex];p.visible=m?m.visible:!0,h.isInstanceDefinitionObject?i.push(p):t.add(p);break}}for(let l=0;l<n.length;l++){const c=n[l];a=[];for(let h=0;h<c.attributes.objectIds.length;h++){const u=c.attributes.objectIds[h];for(let d=0;d<i.length;d++){const p=i[d].userData.attributes.id;u===p&&a.push(i[d])}}for(let h=0;h<s.length;h++){const u=s[h];if(u.geometry.parentIdefId===c.attributes.id){const d=u.geometry.xform.array,p=new fe;if(p.set(...d),a.length===1){const m=a[0].clone(!0);if(m.name=u.attributes.name||m.name,m.applyMatrix4(p),u.attributes.materialIndex>=0&&u.attributes.materialIndex!==a[0].userData.attributes.materialIndex){const A=o[u.attributes.materialIndex],g=this._createMaterial(A);m.material=this._compareMaterials(g)}if(m.userData.defAttributes=m.userData.attributes,m.userData.defObjectType=m.userData.objectType,m.userData.attributes={...m.userData.attributes,...u.attributes},m.userData.objectType=u.objectType,u.attributes.layerIndex!==void 0){const A=e.layers[u.attributes.layerIndex];m.visible=A?A.visible:m.visible}t.add(m)}else{console.warn("THREE.Rhino3dmLoader: InstanceReference with multiple/no objects, not all properties will be copied.");const m=new ft;m.applyMatrix4(p);for(let A=0;A<a.length;A++)m.add(a[A].clone(!0));t.add(m)}}}}return t.userData.materials=this.materials,t.name="",t}_createObject(e,t){const i=new y_,n=e.attributes;let s,a,o,l;switch(e.objectType){case"Point":case"PointSet":s=i.parse(e.geometry),s.attributes.hasOwnProperty("color")?a=new Tr({vertexColors:!0,sizeAttenuation:!1,size:2}):(o=n.drawColor,l=new ee(o.r/255,o.g/255,o.b/255),a=new Tr({color:l,sizeAttenuation:!1,size:2})),a=this._compareMaterials(a);const c=new Wo(s,a);return c.userData.attributes=n,c.userData.objectType=e.objectType,n.name&&(c.name=n.name),c;case"Mesh":case"Extrusion":case"SubD":case"Brep":if(e.geometry===null)return;s=i.parse(e.geometry),t===null&&(t=this._createMaterial()),s.attributes.hasOwnProperty("color")&&(t.vertexColors=!0),t=this._compareMaterials(t);const h=new _e(s,t);return h.castShadow=n.castsShadows,h.receiveShadow=n.receivesShadows,h.userData.attributes=n,h.userData.objectType=e.objectType,n.name&&(h.name=n.name,s.name=n.name),h;case"Curve":s=i.parse(e.geometry),o=n.drawColor,l=new ee(o.r/255,o.g/255,o.b/255),a=new Mi({color:l}),a=this._compareMaterials(a);const u=new fn(s,a);return u.userData.attributes=n,u.userData.objectType=e.objectType,n.name&&(u.name=n.name),u;case"TextDot":s=e.geometry;const d=document.createElement("canvas").getContext("2d"),p=`${s.fontHeight}px ${s.fontFace}`;d.font=p;const m=d.measureText(s.text).width+10,A=s.fontHeight+10,g=window.devicePixelRatio;d.canvas.width=m*g,d.canvas.height=A*g,d.canvas.style.width=m+"px",d.canvas.style.height=A+"px",d.setTransform(g,0,0,g,0,0),d.font=p,d.textBaseline="middle",d.textAlign="center",l=n.drawColor,d.fillStyle=`rgba(${l.r},${l.g},${l.b},${l.a})`,d.fillRect(0,0,m,A),d.fillStyle="white",d.fillText(s.text,m/2,A/2);const y=new qo(d.canvas);y.minFilter=at,y.generateMipmaps=!1,y.wrapS=di,y.wrapT=di,a=new gu({map:y,depthTest:!1});const v=new mp(a);return v.position.set(s.point[0],s.point[1],s.point[2]),v.scale.set(m/10,A/10,1),v.userData.attributes=n,v.userData.objectType=e.objectType,n.name&&(v.name=n.name),v;case"Light":s=e.geometry;let _;switch(s.lightStyle.name){case"LightStyle_WorldPoint":_=new nl,_.castShadow=n.castsShadows,_.position.set(s.location[0],s.location[1],s.location[2]),_.shadow.normalBias=.1;break;case"LightStyle_WorldSpot":_=new zc,_.castShadow=n.castsShadows,_.position.set(s.location[0],s.location[1],s.location[2]),_.target.position.set(s.direction[0],s.direction[1],s.direction[2]),_.angle=s.spotAngleRadians,_.shadow.normalBias=.1;break;case"LightStyle_WorldRectangular":_=new Jp;const b=Math.abs(s.width[2]),T=Math.abs(s.length[0]);_.position.set(s.location[0]-T/2,s.location[1],s.location[2]-b/2),_.height=T,_.width=b,_.lookAt(s.direction[0],s.direction[1],s.direction[2]);break;case"LightStyle_WorldDirectional":_=new sl,_.castShadow=n.castsShadows,_.position.set(s.location[0],s.location[1],s.location[2]),_.target.position.set(s.direction[0],s.direction[1],s.direction[2]),_.shadow.normalBias=.1;break}return _&&(_.intensity=s.intensity,o=s.diffuse,l=new ee(o.r/255,o.g/255,o.b/255),_.color=l,_.userData.attributes=n,_.userData.objectType=e.objectType),_}}_initLibrary(){if(!this.libraryPending){const e=new ti(this.manager);e.setPath(this.libraryPath);const t=new Promise((s,a)=>{e.load("rhino3dm.js",s,void 0,a)}),i=new ti(this.manager);i.setPath(this.libraryPath),i.setResponseType("arraybuffer");const n=new Promise((s,a)=>{i.load("rhino3dm.wasm",s,void 0,a)});this.libraryPending=Promise.all([t,n]).then(([s,a])=>{this.libraryConfig.wasmBinary=a;const o=_V,l=["/* rhino3dm.js */",s,"/* worker */",o.substring(o.indexOf("{")+1,o.lastIndexOf("}"))].join(`
`);this.workerSourceURL=URL.createObjectURL(new Blob([l]))})}return this.libraryPending}_getWorker(e){return this._initLibrary().then(()=>{if(this.workerPool.length<this.workerLimit){const i=new Worker(this.workerSourceURL);i._callbacks={},i._taskCosts={},i._taskLoad=0,i.postMessage({type:"init",libraryConfig:this.libraryConfig}),i.onmessage=n=>{const s=n.data;switch(s.type){case"warning":this.warnings.push(s.data),console.warn(s.data);break;case"decode":i._callbacks[s.id].resolve(s);break;case"error":i._callbacks[s.id].reject(s);break;default:console.error('THREE.Rhino3dmLoader: Unexpected message, "'+s.type+'"')}},this.workerPool.push(i)}else this.workerPool.sort(function(i,n){return i._taskLoad>n._taskLoad?-1:1});const t=this.workerPool[this.workerPool.length-1];return t._taskLoad+=e,t})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this}}const _V=`
function Rhino3dmWorker() {

	let libraryPending;
	let libraryConfig;
	let rhino;
	let taskID;

	onmessage = function ( e ) {

		const message = e.data;

		switch ( message.type ) {

			case 'init':

				libraryConfig = message.libraryConfig;
				const wasmBinary = libraryConfig.wasmBinary;
				let RhinoModule;
				libraryPending = new Promise( function ( resolve ) {

					/* Like Basis Loader */
					RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };

					rhino3dm( RhinoModule ); // eslint-disable-line no-undef

				 } ).then( () => {

					rhino = RhinoModule;

				 } );

				break;

			case 'decode':

				taskID = message.id;
				const buffer = message.buffer;
				libraryPending.then( () => {

					try {

						const data = decodeObjects( rhino, buffer );
						self.postMessage( { type: 'decode', id: message.id, data } );

					} catch ( error ) {

						self.postMessage( { type: 'error', id: message.id, error } );

					}

				} );

				break;

		}

	};

	function decodeObjects( rhino, buffer ) {

		const arr = new Uint8Array( buffer );
		const doc = rhino.File3dm.fromByteArray( arr );

		const objects = [];
		const materials = [];
		const layers = [];
		const views = [];
		const namedViews = [];
		const groups = [];
		const strings = [];

		//Handle objects

		const objs = doc.objects();
		const cnt = objs.count;

		for ( let i = 0; i < cnt; i ++ ) {

			const _object = objs.get( i );

			const object = extractObjectData( _object, doc );

			_object.delete();

			if ( object ) {

				objects.push( object );

			}

		}

		// Handle instance definitions
		// console.log( \`Instance Definitions Count: \${doc.instanceDefinitions().count()}\` );

		for ( let i = 0; i < doc.instanceDefinitions().count; i ++ ) {

			const idef = doc.instanceDefinitions().get( i );
			const idefAttributes = extractProperties( idef );
			idefAttributes.objectIds = idef.getObjectIds();

			objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );

		}

		// Handle materials

		const textureTypes = [
			// rhino.TextureType.Bitmap,
			rhino.TextureType.Diffuse,
			rhino.TextureType.Bump,
			rhino.TextureType.Transparency,
			rhino.TextureType.Opacity,
			rhino.TextureType.Emap
		];

		const pbrTextureTypes = [
			rhino.TextureType.PBR_BaseColor,
			rhino.TextureType.PBR_Subsurface,
			rhino.TextureType.PBR_SubsurfaceScattering,
			rhino.TextureType.PBR_SubsurfaceScatteringRadius,
			rhino.TextureType.PBR_Metallic,
			rhino.TextureType.PBR_Specular,
			rhino.TextureType.PBR_SpecularTint,
			rhino.TextureType.PBR_Roughness,
			rhino.TextureType.PBR_Anisotropic,
			rhino.TextureType.PBR_Anisotropic_Rotation,
			rhino.TextureType.PBR_Sheen,
			rhino.TextureType.PBR_SheenTint,
			rhino.TextureType.PBR_Clearcoat,
			rhino.TextureType.PBR_ClearcoatBump,
			rhino.TextureType.PBR_ClearcoatRoughness,
			rhino.TextureType.PBR_OpacityIor,
			rhino.TextureType.PBR_OpacityRoughness,
			rhino.TextureType.PBR_Emission,
			rhino.TextureType.PBR_AmbientOcclusion,
			rhino.TextureType.PBR_Displacement
		];

		for ( let i = 0; i < doc.materials().count; i ++ ) {

			const _material = doc.materials().get( i );

			const material = extractProperties( _material );

			const textures = [];

			textures.push( ...extractTextures( _material, textureTypes, doc ) );

			material.pbrSupported = _material.physicallyBased().supported;

			if ( material.pbrSupported ) {

				textures.push( ...extractTextures( _material, pbrTextureTypes, doc ) );
				material.pbr = extractProperties( _material.physicallyBased() );

			}

			material.textures = textures;

			materials.push( material );

			_material.delete();

		}

		// Handle layers

		for ( let i = 0; i < doc.layers().count; i ++ ) {

			const _layer = doc.layers().get( i );
			const layer = extractProperties( _layer );

			layers.push( layer );

			_layer.delete();

		}

		// Handle views

		for ( let i = 0; i < doc.views().count; i ++ ) {

			const _view = doc.views().get( i );
			const view = extractProperties( _view );

			views.push( view );

			_view.delete();

		}

		// Handle named views

		for ( let i = 0; i < doc.namedViews().count; i ++ ) {

			const _namedView = doc.namedViews().get( i );
			const namedView = extractProperties( _namedView );

			namedViews.push( namedView );

			_namedView.delete();

		}

		// Handle groups

		for ( let i = 0; i < doc.groups().count; i ++ ) {

			const _group = doc.groups().get( i );
			const group = extractProperties( _group );

			groups.push( group );

			_group.delete();

		}

		// Handle settings

		const settings = extractProperties( doc.settings() );

		//TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.

		// Handle dimstyles
		// console.log( \`Dimstyle Count: \${doc.dimstyles().count()}\` );

		// Handle bitmaps
		// console.log( \`Bitmap Count: \${doc.bitmaps().count()}\` );

		// Handle strings
		// console.log( \`Document Strings Count: \${doc.strings().count()}\` );
		// Note: doc.strings().documentUserTextCount() counts any doc.strings defined in a section
		// console.log( \`Document User Text Count: \${doc.strings().documentUserTextCount()}\` );

		const strings_count = doc.strings().count;

		for ( let i = 0; i < strings_count; i ++ ) {

			strings.push( doc.strings().get( i ) );

		}

		// Handle Render Environments for Material Environment

		// get the id of the active render environment skylight, which we'll use for environment texture
		const reflectionId = doc.settings().renderSettings().renderEnvironments.reflectionId;

		const rc = doc.renderContent();

		let renderEnvironment = null;

		for ( let i = 0; i < rc.count; i ++ ) {

			const content = rc.get(i);

			switch ( content.kind ) {

				case 'environment':

					const id = content.id;

					// there could be multiple render environments in a 3dm file
					if ( id !== reflectionId ) break;

					const renderTexture = content.findChild( 'texture' );
					const fileName = renderTexture.fileName;

					for ( let j = 0; j < doc.embeddedFiles().count; j ++ ) {

						const _fileName = doc.embeddedFiles().get( j ).fileName;

						if ( fileName === _fileName ) {

							const background = doc.getEmbeddedFileAsBase64( fileName );
							const backgroundImage = 'data:image/png;base64,' + background;
							renderEnvironment = { type: 'renderEnvironment', image: backgroundImage, name: fileName };

						}

					}

					break;

			}

		}

		// Handle Render Settings

		const renderSettings = {
			ambientLight: doc.settings().renderSettings().ambientLight,
			backgroundColorTop: doc.settings().renderSettings().backgroundColorTop,
			backgroundColorBottom: doc.settings().renderSettings().backgroundColorBottom,
			useHiddenLights: doc.settings().renderSettings().useHiddenLights,
			depthCue: doc.settings().renderSettings().depthCue,
			flatShade: doc.settings().renderSettings().flatShade,
			renderBackFaces: doc.settings().renderSettings().renderBackFaces,
			renderPoints: doc.settings().renderSettings().renderPoints,
			renderCurves: doc.settings().renderSettings().renderCurves,
			renderIsoParams: doc.settings().renderSettings().renderIsoParams,
			renderMeshEdges: doc.settings().renderSettings().renderMeshEdges,
			renderAnnotations: doc.settings().renderSettings().renderAnnotations,
			useViewportSize: doc.settings().renderSettings().useViewportSize,
			scaleBackgroundToFit: doc.settings().renderSettings().scaleBackgroundToFit,
			transparentBackground: doc.settings().renderSettings().transparentBackground,
			imageDpi: doc.settings().renderSettings().imageDpi,
			shadowMapLevel: doc.settings().renderSettings().shadowMapLevel,
			namedView: doc.settings().renderSettings().namedView,
			snapShot: doc.settings().renderSettings().snapShot,
			specificViewport: doc.settings().renderSettings().specificViewport,
			groundPlane: extractProperties( doc.settings().renderSettings().groundPlane ),
			safeFrame: extractProperties( doc.settings().renderSettings().safeFrame ),
			dithering: extractProperties( doc.settings().renderSettings().dithering ),
			skylight: extractProperties( doc.settings().renderSettings().skylight ),
			linearWorkflow: extractProperties( doc.settings().renderSettings().linearWorkflow ),
			renderChannels: extractProperties( doc.settings().renderSettings().renderChannels ),
			sun: extractProperties( doc.settings().renderSettings().sun ),
			renderEnvironments: extractProperties( doc.settings().renderSettings().renderEnvironments ),
			postEffects: extractProperties( doc.settings().renderSettings().postEffects ),

		};

		doc.delete();

		return { objects, materials, layers, views, namedViews, groups, strings, settings, renderSettings, renderEnvironment };

	}

	function extractTextures( m, tTypes, d ) {

		const textures = [];

		for ( let i = 0; i < tTypes.length; i ++ ) {

			const _texture = m.getTexture( tTypes[ i ] );
			if ( _texture ) {

				let textureType = tTypes[ i ].constructor.name;
				textureType = textureType.substring( 12, textureType.length );
				const texture = extractTextureData( _texture, textureType, d );
				textures.push( texture );
				_texture.delete();

			}

		}

		return textures;

	}

	function extractTextureData( t, tType, d ) {

		const texture = { type: tType };

		const image = d.getEmbeddedFileAsBase64( t.fileName );

		texture.wrapU = t.wrapU;
		texture.wrapV = t.wrapV;
		texture.wrapW = t.wrapW;
		const uvw = t.uvwTransform.toFloatArray( true );

		texture.repeat = [ uvw[ 0 ], uvw[ 5 ] ];

		if ( image ) {

			texture.image = 'data:image/png;base64,' + image;

		} else {

			self.postMessage( { type: 'warning', id: taskID, data: {
				message: \`THREE.3DMLoader: Image for \${tType} texture not embedded in file.\`,
				type: 'missing resource'
			}

			} );

			texture.image = null;

		}

		return texture;

	}

	function extractObjectData( object, doc ) {

		const _geometry = object.geometry();
		const _attributes = object.attributes();
		let objectType = _geometry.objectType;
		let geometry, attributes, position, data, mesh;

		// skip instance definition objects
		//if( _attributes.isInstanceDefinitionObject ) { continue; }

		// TODO: handle other geometry types
		switch ( objectType ) {

			case rhino.ObjectType.Curve:

				const pts = curveToPoints( _geometry, 100 );

				position = {};
				attributes = {};
				data = {};

				position.itemSize = 3;
				position.type = 'Float32Array';
				position.array = [];

				for ( let j = 0; j < pts.length; j ++ ) {

					position.array.push( pts[ j ][ 0 ] );
					position.array.push( pts[ j ][ 1 ] );
					position.array.push( pts[ j ][ 2 ] );

				}

				attributes.position = position;
				data.attributes = attributes;

				geometry = { data };

				break;

			case rhino.ObjectType.Point:

				const pt = _geometry.location;

				position = {};
				const color = {};
				attributes = {};
				data = {};

				position.itemSize = 3;
				position.type = 'Float32Array';
				position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];

				const _color = _attributes.drawColor( doc );

				color.itemSize = 3;
				color.type = 'Float32Array';
				color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];

				attributes.position = position;
				attributes.color = color;
				data.attributes = attributes;

				geometry = { data };

				break;

			case rhino.ObjectType.PointSet:
			case rhino.ObjectType.Mesh:

				geometry = _geometry.toThreejsJSON();

				break;

			case rhino.ObjectType.Brep:

				const faces = _geometry.faces();
				mesh = new rhino.Mesh();

				for ( let faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {

					const face = faces.get( faceIndex );
					const _mesh = face.getMesh( rhino.MeshType.Any );

					if ( _mesh ) {

						mesh.append( _mesh );
						_mesh.delete();

					}

					face.delete();

				}

				if ( mesh.faces().count > 0 ) {

					mesh.compact();
					geometry = mesh.toThreejsJSON();
					faces.delete();

				}

				mesh.delete();

				break;

			case rhino.ObjectType.Extrusion:

				mesh = _geometry.getMesh( rhino.MeshType.Any );

				if ( mesh ) {

					geometry = mesh.toThreejsJSON();
					mesh.delete();

				}

				break;

			case rhino.ObjectType.TextDot:

				geometry = extractProperties( _geometry );

				break;

			case rhino.ObjectType.Light:

				geometry = extractProperties( _geometry );

				if ( geometry.lightStyle.name === 'LightStyle_WorldLinear' ) {

					self.postMessage( { type: 'warning', id: taskID, data: {
						message: \`THREE.3DMLoader: No conversion exists for \${objectType.constructor.name} \${geometry.lightStyle.name}\`,
						type: 'no conversion',
						guid: _attributes.id
					}

					} );

				}

				break;

			case rhino.ObjectType.InstanceReference:

				geometry = extractProperties( _geometry );
				geometry.xform = extractProperties( _geometry.xform );
				geometry.xform.array = _geometry.xform.toFloatArray( true );

				break;

			case rhino.ObjectType.SubD:

				// TODO: precalculate resulting vertices and faces and warn on excessive results
				_geometry.subdivide( 3 );
				mesh = rhino.Mesh.createFromSubDControlNet( _geometry, false );
				if ( mesh ) {

					geometry = mesh.toThreejsJSON();
					mesh.delete();

				}

				break;

				/*
				case rhino.ObjectType.Annotation:
				case rhino.ObjectType.Hatch:
				case rhino.ObjectType.ClipPlane:
				*/

			default:

				self.postMessage( { type: 'warning', id: taskID, data: {
					message: \`THREE.3DMLoader: Conversion not implemented for \${objectType.constructor.name}\`,
					type: 'not implemented',
					guid: _attributes.id
				}

				} );

				break;

		}

		if ( geometry ) {

			attributes = extractProperties( _attributes );
			attributes.geometry = extractProperties( _geometry );

			if ( _attributes.groupCount > 0 ) {

				attributes.groupIds = _attributes.getGroupList();

			}

			if ( _attributes.userStringCount > 0 ) {

				attributes.userStrings = _attributes.getUserStrings();

			}

			if ( _geometry.userStringCount > 0 ) {

				attributes.geometry.userStrings = _geometry.getUserStrings();

			}

			if ( _attributes.decals().count > 0 ) {

				self.postMessage( { type: 'warning', id: taskID, data: {
					message: \`THREE.3DMLoader: No conversion exists for the decals associated with this object.\`,
					type: 'no conversion',
					guid: _attributes.id
				}

				} );

			}

			attributes.drawColor = _attributes.drawColor( doc );

			objectType = objectType.constructor.name;
			objectType = objectType.substring( 11, objectType.length );

			return { geometry, attributes, objectType };

		} else {

			self.postMessage( { type: 'warning', id: taskID, data: {
				message: \`THREE.3DMLoader: \${objectType.constructor.name} has no associated mesh geometry.\`,
				type: 'missing mesh',
				guid: _attributes.id
			}

			} );

		}

	}

	function extractProperties( object ) {

		const result = {};

		for ( const property in object ) {

			const value = object[ property ];

			if ( typeof value !== 'function' ) {

				if ( typeof value === 'object' && value !== null && value.hasOwnProperty( 'constructor' ) ) {

					result[ property ] = { name: value.constructor.name, value: value.value };

				} else if ( typeof value === 'object' && value !== null ) {

					result[ property ] = extractProperties( value );

				} else {

					result[ property ] = value;

				}

			} else {

				// these are functions that could be called to extract more data.
				//console.log( \`\${property}: \${object[ property ].constructor.name}\` );

			}

		}

		return result;

	}

	function curveToPoints( curve, pointLimit ) {

		let pointCount = pointLimit;
		let rc = [];
		const ts = [];

		if ( curve instanceof rhino.LineCurve ) {

			return [ curve.pointAtStart, curve.pointAtEnd ];

		}

		if ( curve instanceof rhino.PolylineCurve ) {

			pointCount = curve.pointCount;
			for ( let i = 0; i < pointCount; i ++ ) {

				rc.push( curve.point( i ) );

			}

			return rc;

		}

		if ( curve instanceof rhino.PolyCurve ) {

			const segmentCount = curve.segmentCount;

			for ( let i = 0; i < segmentCount; i ++ ) {

				const segment = curve.segmentCurve( i );
				const segmentArray = curveToPoints( segment, pointCount );
				rc = rc.concat( segmentArray );
				segment.delete();

			}

			return rc;

		}

		if ( curve instanceof rhino.ArcCurve ) {

			pointCount = Math.floor( curve.angleDegrees / 5 );
			pointCount = pointCount < 2 ? 2 : pointCount;
			// alternative to this hardcoded version: https://stackoverflow.com/a/18499923/2179399

		}

		if ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) {

			const pLine = curve.tryGetPolyline();

			for ( let i = 0; i < pLine.count; i ++ ) {

				rc.push( pLine.get( i ) );

			}

			pLine.delete();

			return rc;

		}

		const domain = curve.domain;
		const divisions = pointCount - 1.0;

		for ( let j = 0; j < pointCount; j ++ ) {

			const t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] );

			if ( t === domain[ 0 ] || t === domain[ 1 ] ) {

				ts.push( t );
				continue;

			}

			const tan = curve.tangentAt( t );
			const prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] );

			// Duplicated from THREE.Vector3
			// How to pass imports to worker?

			const tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ];
			const ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ];

			const denominator = Math.sqrt( tS * ptS );

			let angle;

			if ( denominator === 0 ) {

				angle = Math.PI / 2;

			} else {

				const theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator;
				angle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) );

			}

			if ( angle < 0.1 ) continue;

			ts.push( t );

		}

		rc = ts.map( t => curve.pointAt( t ) );
		return rc;

	}

}
`,ki=class ki extends z1{constructor(e){super(e),this.materials=[],this.setLibraryPath(ki.LIBRARY_PATH)}_createMaterial(e){return ki.ImportMaterials?super._createMaterial(e):this.materials[0]||new Ya({color:new ee(1,1,1),metalness:.8,name:"default",side:Zi})}async loadAsync(e,t){const i=await super.loadAsync(e,t);i.rotateX(-Math.PI/2),i.userData.materials&&delete i.userData.materials;const n=i.userData.layers;return i.traverse(s=>{const a=s.userData.attributes?.castsShadows,o=s.userData.attributes?.receivesShadows;s.castShadow=a,s.receiveShadow=o;const l=s.userData.attributes?.layerIndex??s.userData.defAttributes?.layerIndex,c=n[l];c&&(s.userData.rhinoLayer=c),s.userData.rhino3dmRoot=i.uuid,ki.LoadUserDataStrings||(s.userData.strings=[]),ki.LoadUserDataWarnings||delete s.userData.warnings,this._hideLineMesh(s),this._useInstancedMesh(s),this._useMaterialSource(s,c)}),this.materials=[],i}_useMaterialSource(e,t){if(!ki.ImportMaterials)return;const i=e;if(i.material?.name==="default"||ki.ForceLayerMaterials){const n=i.userData.attributes?.materialSource||i.userData.defAttributes?.materialSource,s=i.userData.attributes?.colorSource||i.userData.defAttributes?.colorSource;if(!ki.ForceLayerMaterials&&!n&&!s)return;ki.ForceLayerMaterials||n?.value===0||n?.value===1&&s?.value===0?t&&(i.material=this._compareMaterials(this._createMaterial({diffuseColor:t.color,name:t.name,transparency:0,textures:[]}))):n?.value===3||n?.value===1&&s?.value===3?i.traverseAncestors(a=>{a?.material&&(i.material=a.material)}):n&&n.value!==1&&console.warn("Unknown material source",n,i,i.userData.attributes)}}_useInstancedMesh(e){if(!ki.ReplaceWithInstancedMesh||e.children.length<=0)return;const t=e.children,i=t.map(s=>s.geometry);i.filter((s,a)=>i.indexOf(s)===a).forEach(s=>{const a=t.filter(l=>l.geometry===s),o=a.length>0?a.filter(l=>l.material===a[0].material):[];if(o.length>1){const l=new Oc(s,o[0].material,o.length);l.userData={...o[0].userData},l.userData.instanceUserData=[],l.userData.attributes=l.userData.defAttributes||l.userData.attributes,l.userData.defAttributes&&delete l.userData.defAttributes,l.name=l.userData.attributes?.name||o[0].name,o.forEach((c,h)=>{l.setMatrixAt(h,c.matrix),e.remove(c),l.userData.instanceUserData.push(c.userData)}),e.add(l)}})}_hideLineMesh(e){if(!ki.HideLineMesh&&!ki.HidePointMesh||e.children.length<=0)return;const t=[];e.traverse(i=>{(i&&ki.HideLineMesh&&(i.isLine||i.isLineSegments)||ki.HidePointMesh&&i.isPoints)&&t.push(i)}),t.forEach(i=>{i.userData.visible_3dm=i.visible,i.visible=!1})}};ki.LIBRARY_PATH=`https://cdn.jsdelivr.net/npm/rhino3dm@${qu("rhino3dm","8.0.1")}/`,ki.ImportMaterials=!0,ki.ForceLayerMaterials=!1,ki.ReplaceWithInstancedMesh=!1,ki.HideLineMesh=!1,ki.HidePointMesh=!1,ki.LoadUserDataStrings=!0,ki.LoadUserDataWarnings=!0;let ur=ki;const Vh=class Vh extends oi{constructor(e){super(e)}load(e,t,i,n){const s=Vh.USE_CANVAS_TEXTURE?document.createElement("canvas"):void 0,a=Vh.USE_CANVAS_TEXTURE?new qo(s):new kt,o=new Gc(this.manager);return o.setCrossOrigin(this.crossOrigin),o.setPath(this.path),o.load(e,function(l){s?Vh.CopyImageToCanvas(s,l):a.image=l,a.needsUpdate=!0,t!==void 0&&t(a)},i,n),a}static CopyImageToCanvas(e,t){e.width=t.naturalWidth||t.width||512,e.height=t.naturalHeight||t.height||512;const i=e.getContext("2d");i?(i.clearRect(0,0,e.width,e.height),i.drawImage(t,0,0,e.width,e.height)):console.error("SVGTextureLoader: Failed to get canvas context.")}};Vh.USE_CANVAS_TEXTURE=qu("svg-load-disable-canvas")!=="true";let Rg=Vh;class V1 extends oi{constructor(e){super(e)}load(e,t,i,n){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const s=this,a=Ai.get(e);if(a!==void 0)return s.manager.itemStart(e),setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0),a;const o=document.createElementNS("http://www.w3.org/1999/xhtml","video");function l(){o.removeEventListener("loadedmetadata",l,!1),o.removeEventListener("error",c,!1),Ai.add(e,o),t&&t(o),s.manager.itemEnd(e)}function c(h){o.removeEventListener("loadedmetadata",l,!1),o.removeEventListener("error",c,!1),n&&n(h),s.manager.itemError(e),s.manager.itemEnd(e)}return o.addEventListener("loadedmetadata",l,!1),o.addEventListener("error",c,!1),e.substr(0,5)!=="data:"&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),s.manager.itemStart(e),o.src=e,o.preload="auto",o.autoplay=!0,o.setAttribute("webkit-playsinline","webkit-playsinline"),o.setAttribute("playsinline",""),o}}class H1 extends oi{constructor(e){super(e)}load(e,t,i,n){const s=new V1(this.manager);s.setCrossOrigin(this.crossOrigin),s.setPath(this.path);let a;const o=s.load(e,function(l){a||(a=new Jy(l)),a.format=qt,a.minFilter=at,a.magFilter=at,a.colorSpace=Ct,a.needsUpdate=!0,t!==void 0&&t(a)},i,n);return!a&&o&&(a=new Jy(o)),a}}const hA=class hA extends Dd{constructor(){super(),this.processors=[],this.processors.push(GT)}register(e){return super.register(e)}async parseAsync(e,t){if(!e)throw new Error("No object to export");let i=!e.__isGLTFOutput&&(Array.isArray(e)||e.isObject3D)?await new Promise((n,s)=>this.parse(e,n,s,t)):e;for(const n of this.processors)i=await n(i,t);if(i&&i instanceof Blob)return i;if(i&&typeof i=="object"&&!i.byteLength)return new Blob([JSON.stringify(i,(n,s)=>n.startsWith("__")?void 0:s,t.jsonSpaces??2)],{type:"model/gltf+json"});if(i)return new Blob([i],{type:"model/gltf+binary"});throw new Error("GLTFExporter2.parse() failed")}parse(e,t,i,n={}){const s={binary:!1,trs:n.trs??!1,onlyVisible:n.onlyVisible??!1,truncateDrawRange:n.truncateDrawRange??!0,externalImagesInExtras:!n.embedUrlImages&&n.externalImagesInExtras||!1,maxTextureSize:n.maxTextureSize??1/0,animations:n.animations??[],includeCustomExtensions:n.includeCustomExtensions??!0,forceIndices:n.forceIndices??!1,exporterOptions:n,ignoreInvalidMorphTargetTracks:n.ignoreInvalidMorphTargetTracks,ignoreEmptyTextures:n.ignoreEmptyTextures};n.exportExt==="glb"&&(s.binary=!0);const a=o=>{t(Object.assign(o,{__isGLTFOutput:!0}))};return super.parse(e,a,i,s,new DT)}setup(e,t){for(const i of hA.ExportExtensions)this.register(i);if(t)for(const i of t)this.register(i);return this.register(this.gltfViewerWriter(e)),this}gltfViewerWriter(e){return t=>({afterParse:i=>{i=Array.isArray(i)?i[0]:i;let n;if(!i?.userData?.rootSceneModelRoot||t.options?.exporterOptions?.viewerConfig===!1||i?.userData?.__exportViewerConfig===!1?(n=pd(t.serializationMeta),ho.BundleExtraResources(t.json,n),ho.BundleArrayBuffers(n,t)):n=ho.ExportViewerConfig(e,t),!n||Object.values(n).reduce((o,l)=>o+Object.keys(l).length,0)===0)return;const a=t.json.extras||{};a[Il.BundledResourcesKey]=n,t.json.extras=a}})}};hA.ExportExtensions=[Ld.Export,Od.Export,Bd.Export,Sl.Export,El.Export,xl.Export,e=>({name:"_AssetPropsWriter",beforeParse:t=>{const i=Array.isArray(t)?t:[t];for(const n of i)n.userData.gltfExtras&&(n.__gltfExtras=n.userData.gltfExtras,delete n.userData.gltfExtras),n.userData.gltfAsset&&(n.__gltfAsset=n.userData.gltfAsset,delete n.userData.gltfAsset)},afterParse:t=>{const i=e.json.extras||{},n=Array.isArray(t)?t:[t];for(const s of n)s.__gltfAsset&&(s.userData.gltfAsset=s.__gltfAsset,delete s.__gltfAsset),s.__gltfExtras&&(s.userData.gltfExtras=s.__gltfExtras,Object.assign(i,s.userData.gltfExtras),delete s.__gltfExtras);Object.keys(i).length>0&&(e.json.extras=i)}})];let Bg=hA;class Q1{async parseAsync(e,{jsonSpaces:t=2}){return new Blob([JSON.stringify(e,null,t)],{type:"application/json"})}}class j1{async parseAsync(e,t){return new Blob([e],{type:"text/plain"})}}const vV=new TextEncoder,W1=3;class q1{parse(e,t,i){if(!e||!(e.isWebGLRenderer||e.isDataTexture))throw Error("EXRExporter.parse: Unsupported first parameter, expected instance of WebGLRenderer or DataTexture.");if(e.isWebGLRenderer){const n=e,s=t,a=i;bV(s);const o=CV(s,a),l=SV(n,s,o),c=X1(l,o),h=Y1(c,o);return $1(h,o)}else if(e.isDataTexture){const n=e,s=t;wV(n);const a=xV(n,s),o=n.image.data,l=X1(o,a),c=Y1(l,a);return $1(c,a)}}}function bV(r){if(!r||!r.isWebGLRenderTarget)throw Error("EXRExporter.parse: Unsupported second parameter, expected instance of WebGLRenderTarget.");if(r.isWebGLCubeRenderTarget||r.isWebGL3DRenderTarget||r.isWebGLArrayRenderTarget)throw Error("EXRExporter.parse: Unsupported render target type, expected instance of WebGLRenderTarget.");if(r.texture.type!==Ut&&r.texture.type!==Yt)throw Error("EXRExporter.parse: Unsupported WebGLRenderTarget texture type.");if(r.texture.format!==qt)throw Error("EXRExporter.parse: Unsupported WebGLRenderTarget texture format, expected RGBAFormat.")}function wV(r){if(r.type!==Ut&&r.type!==Yt)throw Error("EXRExporter.parse: Unsupported DataTexture texture type.");if(r.format!==qt)throw Error("EXRExporter.parse: Unsupported DataTexture texture format, expected RGBAFormat.");if(!r.image.data)throw Error("EXRExporter.parse: Invalid DataTexture image data.");if(r.type===Ut&&r.image.data.constructor.name!=="Float32Array")throw Error("EXRExporter.parse: DataTexture image data doesn't match type, expected 'Float32Array'.");if(r.type===Yt&&r.image.data.constructor.name!=="Uint16Array")throw Error("EXRExporter.parse: DataTexture image data doesn't match type, expected 'Uint16Array'.")}function CV(r,e={}){const t={0:1,2:1,3:16},i=e.textureIndex||0,n=Array.isArray(r.textures)?r.textures[i]:r.texture,s=r.width,a=r.height,o=n.type,l=n.format,c=n.colorSpace,h=e.compression!==void 0?e.compression:W1,u=e.type!==void 0?e.type:Yt,d=u===Ut?2:1,p=t[h];return{width:s,height:a,type:o,format:l,colorSpace:c,compression:h,blockLines:p,dataType:d,dataSize:2*d,numBlocks:Math.ceil(a/p),numInputChannels:4,numOutputChannels:4,flipY:!1,textureIndex:e.textureIndex||0}}function xV(r,e={}){const t={0:1,2:1,3:16},i=r.image.width,n=r.image.height,s=r.type,a=r.format,o=r.colorSpace,l=e.compression!==void 0?e.compression:W1,c=e.type!==void 0?e.type:Yt,h=c===Ut?2:1,u=t[l];return{width:i,height:n,type:s,format:a,colorSpace:o,compression:l,blockLines:u,dataType:h,dataSize:2*h,numBlocks:Math.ceil(n/u),numInputChannels:4,numOutputChannels:4,flipY:r.isDataTexture&&r.flipY,textureIndex:e.textureIndex||0}}function SV(r,e,t){let i;return t.type===Ut?i=new Float32Array(t.width*t.height*t.numInputChannels):i=new Uint16Array(t.width*t.height*t.numInputChannels),r.readRenderTargetPixels(e,0,0,t.width,t.height,i,void 0,t.textureIndex),i}function X1(r,e){const t=e.width,i=e.height,n={r:0,g:0,b:0,a:0},s={value:0},a=e.numOutputChannels==4?1:0,o=e.type==Ut?LV:BV,l=e.dataType==1?PV:V0,c=new Uint8Array(e.width*e.height*e.numOutputChannels*e.dataSize),h=new DataView(c.buffer);for(let u=0;u<i;++u)for(let d=0;d<t;++d){const p=u*t*4+d*4,m=o(r,p),A=o(r,p+1),g=o(r,p+2),y=o(r,p+3),v=(e.flipY?u:i-u-1)*t*(3+a)*e.dataSize;IV(n,m,A,g,y),s.value=v+d*e.dataSize,l(h,n.a,s),s.value=v+a*t*e.dataSize+d*e.dataSize,l(h,n.b,s),s.value=v+(1+a)*t*e.dataSize+d*e.dataSize,l(h,n.g,s),s.value=v+(2+a)*t*e.dataSize+d*e.dataSize,l(h,n.r,s)}return c}function Y1(r,e){let t,i,n=0;const s={data:new Array,totalSize:0},a=e.width*e.numOutputChannels*e.blockLines*e.dataSize;switch(e.compression){case 0:t=EV;break;case 2:case 3:t=MV;break}e.compression!==0&&(i=new Uint8Array(a));for(let o=0;o<e.numBlocks;++o){const l=r.subarray(a*o,a*(o+1));let c=t(l,i);c.length>=l.length&&(c=l),n+=c.length,s.data.push({dataChunk:c,size:c.length})}return s.totalSize=n,s}function EV(r){return r}function MV(r,e){e=e.subarray(0,r.length);let t=0,i=Math.floor((r.length+1)/2),n=0;const s=r.length-1;for(;!(n>s||(e[t++]=r[n++],n>s));)e[i++]=r[n++];let a=e[0];for(let l=1;l<e.length;l++){const c=e[l]-a+384;a=e[l],e[l]=c}return Eg(e)}function TV(r,e,t){const i={value:0},n=new DataView(r.buffer);$t(n,20000630,i),$t(n,2,i),mn(n,"compression",i),mn(n,"compression",i),$t(n,1,i),Wd(n,t.compression,i),mn(n,"screenWindowCenter",i),mn(n,"v2f",i),$t(n,8,i),$t(n,0,i),$t(n,0,i),mn(n,"screenWindowWidth",i),mn(n,"float",i),$t(n,4,i),V0(n,1,i),mn(n,"pixelAspectRatio",i),mn(n,"float",i),$t(n,4,i),V0(n,1,i),mn(n,"lineOrder",i),mn(n,"lineOrder",i),$t(n,1,i),Wd(n,0,i),mn(n,"dataWindow",i),mn(n,"box2i",i),$t(n,16,i),$t(n,0,i),$t(n,0,i),$t(n,t.width-1,i),$t(n,t.height-1,i),mn(n,"displayWindow",i),mn(n,"box2i",i),$t(n,16,i),$t(n,0,i),$t(n,0,i),$t(n,t.width-1,i),$t(n,t.height-1,i),mn(n,"channels",i),mn(n,"chlist",i),$t(n,t.numOutputChannels*18+1,i),mn(n,"A",i),$t(n,t.dataType,i),i.value+=4,$t(n,1,i),$t(n,1,i),mn(n,"B",i),$t(n,t.dataType,i),i.value+=4,$t(n,1,i),$t(n,1,i),mn(n,"G",i),$t(n,t.dataType,i),i.value+=4,$t(n,1,i),$t(n,1,i),mn(n,"R",i),$t(n,t.dataType,i),i.value+=4,$t(n,1,i),$t(n,1,i),Wd(n,0,i),Wd(n,0,i);let s=i.value+t.numBlocks*8;for(let a=0;a<e.data.length;++a)DV(n,s,i),s+=e.data[a].size+8}function $1(r,e){const t=e.numBlocks*8,i=259+18*e.numOutputChannels,n={value:i+t},s=new Uint8Array(i+t+r.totalSize+e.numBlocks*8),a=new DataView(s.buffer);TV(s,r,e);for(let o=0;o<r.data.length;++o){const l=r.data[o].dataChunk,c=r.data[o].size;$t(a,o*e.blockLines,n),$t(a,c,n),s.set(l,n.value),n.value+=c}return s}function IV(r,e,t,i,n){r.r=e,r.g=t,r.b=i,r.a=n}function Wd(r,e,t){r.setUint8(t.value,e),t.value+=1}function $t(r,e,t){r.setUint32(t.value,e,!0),t.value+=4}function PV(r,e,t){r.setUint16(t.value,zn.toHalfFloat(e),!0),t.value+=2}function V0(r,e,t){r.setFloat32(t.value,e,!0),t.value+=4}function DV(r,e,t){r.setBigUint64(t.value,BigInt(e),!0),t.value+=8}function mn(r,e,t){const i=vV.encode(e+"\0");for(let n=0;n<i.length;++n)Wd(r,i[n],t)}function RV(r){const e=(r&31744)>>10,t=r&1023;return(r>>15?-1:1)*(e?e===31?t?NaN:1/0:Math.pow(2,e-15)*(1+t/1024):6103515625e-14*(t/1024))}function BV(r,e){return RV(r[e])}function LV(r,e){return r[e]}class H0 extends q1{async parseAsync(e,t){const i=e;if(i.isWebGLRenderTarget&&!i.renderManager)throw new Error("No renderManager on renderTarget");if(!i.isWebGLRenderTarget&&!e.isDataTexture)throw new Error("Invalid object type");i.isWebGLRenderTarget&&i.textures.length>1&&t.textureIndex===void 0&&console.warn("RenderTarget has multiple textures, but no textureIndex specified. Using texture 0.");const n=i.isWebGLRenderTarget?this.parse(i.renderManager.webglRenderer,i,t):this.parse(e,t);return new Blob([n],{type:"image/x-exr"})}}const K1=(r,e)=>{const t=r.exportOptions||{},i=r.obj.isMaterial?r.obj:null,n=r.obj.isObject3D?r.obj:null;if(r.state==="processing"){if(i){const s=e.replaceTexture?ve.getMapsForMaterial.call(i):null,a=s&&e.replaceTexture?J1(s,i,i,e.replaceTexture):null;i.__exportState={savedMaps:a}}if(n){const{objectList:s,meshLines:a,fomMap:o,geomMap:l,matCloneMap:c,savedTextures:h}=n.__exportState={objectList:new Set,meshLines:new Map,fomMap:new Map,geomMap:new Map,matCloneMap:new Map,savedTextures:new Map};n.traverse(d=>{d?.isObject3D&&(s.add(d),d.children&&d._sChildren&&(d._tChildren=d.children,d.children=d._sChildren))});const u=new Map;s.forEach(d=>{t.preserveUUIDs!==!1&&d.uuid&&(d.userData.gltfUUID=d.uuid),e.object&&e.object(d,n),UV(d,t);const p=OV(d,n,e.objectGeometry);p&&(e.objectGeometryReplace&&e.objectGeometryReplace(d,p),l.set(d,d.forcedOverrideGeometry),d.forcedOverrideGeometry=p);const m=a.has(d)?null:FV(d);m&&a.set(d,m),e.objectMaterials&&e.objectMaterials(d,n.material);const A=NV(d,c,u,n,e.objectMaterial);A!==void 0&&(e.objectMaterialsReplace&&e.objectMaterialsReplace(d,A),o.set(d,d.forcedOverrideMaterial),d.forcedOverrideMaterial=A);const g=qe.getMapsForObject3D.call(d);u.set(d,g)}),e.replaceTexture&&u.forEach((d,p)=>{const m=J1(d,p,n,e.replaceTexture);h.set(p,m)}),u.clear()}}if((r.state==="done"||r.state==="error")&&(i&&i.__exportState&&(e.revertTextures&&e.revertTextures(i),Z1(i.__exportState.savedMaps,i),delete i.__exportState),n&&n.__exportState)){const{objectList:s,meshLines:a,fomMap:o,geomMap:l,matCloneMap:c,savedTextures:h}=n.__exportState;delete n.__exportState,s.forEach(u=>{t.preserveUUIDs!==!1&&u.userData.gltfUUID&&delete u.userData.gltfUUID,kV(u,a.get(u)),e.revertObject&&e.revertObject(u),u._tChildren&&(u.children=u._tChildren,delete u._tChildren)}),a.clear(),s.clear(),new Set([...c.values()]).forEach(u=>{u.dispose&&u.dispose()}),c.clear(),o.forEach((u,d)=>{u!==void 0?d.forcedOverrideMaterial=u:delete d.forcedOverrideMaterial}),o.clear(),l.forEach((u,d)=>{u!==void 0?d.forcedOverrideGeometry=u:delete d.forcedOverrideGeometry}),l.clear(),e.revertTextures&&h.forEach((u,d)=>{e.revertTextures&&e.revertTextures(d),Z1(u,d)}),h.clear()}};function J1(r,e,t,i){const n={},s={};return r.forEach((a,o)=>{if(!i)return;const l=i(e,a,o,t);l!==a&&(n[o]=l,s[o]=a)}),jm(n,e),s}function Z1(r,e){r&&jm(r,e)}function OV(r,e,t){const i=r.geometry;if(!i)return;let n=null;if(i.userData.isPlaceholder)n=Ds.DummyGeometry;else if(t){const s=t(r,i,e);s&&(n=s)}if(n&&n!==i)return n}function UV(r,e){if(r.animations){e.animations||(e.animations=[]);for(const t of r.animations){if(t.__gltfExport===!1)continue;const i=t.userData.rootRefs||[];e.preserveUUIDs!==!1&&r.uuid?i.includes(r.uuid)||i.push(r.uuid):r.name&&(i.includes(r.name)||i.push(r.name)),t.userData.rootRefs=i,e.animations.includes(t)||e.animations.push(t)}}}function FV(r){const e=r,t=e.geometry;if(typeof t?.getPositions=="function"&&r.isLine===void 0&&r.isLineSegments===void 0&&(r.isLine2||r.isLineSegments2)){const i=t.getPositions();if(i){const n=t.getColors&&e.geometry.getColors(),s=new Je;s.attributes.position=new Ze(i,3),n&&(s.attributes.color=new Ze(n,3)),s.name=t.name,s.userData=t.userData,s.uuid=t.uuid;const a=r.geometry;return r.assetType?r._currentGeometry=s:r.geometry=s,e.isLine2?r.isLine=!0:e.isLineSegments2&&(r.isLine=!0,r.isLineSegments=!0),a}}}function NV(r,e,t,i,n){if(!r.material)return;const s=r.material,a=Array.isArray(s),o=a?s:[s];let l=a?[...s]:s;const c=(h,u,d)=>{let p=e.get(u);p||(p=d(),e.set(u,p)),a?l[h]=p:l=p};if(o.forEach((h,u)=>{if(h.userData.isPlaceholder)c(u,h,()=>Ds.DummyMaterial);else{const d=n?n(r,h,i,u):null;if(d)c(u,h,d);else{const p=ve.getMapsForMaterial.call(h);t.set(h,p),h.userData.sProperties!==void 0&&c(u,h,()=>{const m=new h.constructor;m.name=h.name;const A=jE(h,h.userData.sProperties);return jm(A,m),m.userData.uuid=h.uuid,m.userData.sProperties=h.userData.sProperties,m.userData.rootPath=h.userData.rootPath,m.userData.rootPathOptions=h.userData.rootPathOptions,m})}}}),a?l.some((h,u)=>h!==s[u]):l!==s)return l}function kV(r,e){if(e&&r.geometry){const t=r.geometry;r.assetType?r._currentGeometry=e:r.geometry=e,t.dispose(!0),r.isLine&&delete r.isLine,r.isLineSegments&&delete r.isLineSegments}}class eI extends xi{constructor(){super(),this.exporters=[{ctor:()=>new Q1,ext:["json"]},{ctor:()=>new j1,ext:["txt","text"]},{ctor:()=>new H0,ext:["exr"]}],this.exportHooks={},this._cachedWriters=[],this.addEventListener("exportFile",e=>K1(e,this.exportHooks))}addExporter(...e){for(const t of e){if(this.exporters.includes(t)){console.warn("Exporter already added",t);return}this.exporters.push(t)}}removeExporter(...e){for(const t of e){const i=this.exporters.indexOf(t);i>=0&&this.exporters.splice(i,1)}}getExporter(...e){return this.exporters.find(t=>t.ext.some(i=>e.includes(i)))}async exportObject(e,t={}){if(!e?.assetType){console.error("Object has no asset type");return}const i=[];e.assetType==="model"&&e.traverse(s=>{s.userData.excludeFromExport&&s.visible&&(s.visible=!1,i.push(s))});const n=await this._exportFile(e,t);return e.assetType==="model"&&i.forEach(s=>s.visible=!0),e?.userData?.rootSceneModelRoot&&t.viewerConfig===!1&&delete e.userData.__exportViewerConfig,n}async _exportFile(e,t={}){let i;try{this.dispatchEvent({type:"exportFile",obj:e,state:"processing",exportOptions:t});const n=await this.processBeforeExport(e,t),s=n?.typeExt||n?.ext;if(!n||!s)throw console.error(n,t,e),new Error(`AssetExporter - Unable to preprocess before export ${s}`);if(n.blob)i=n.blob;else{const a=this._getWriter(s);this.dispatchEvent({type:"exportFile",obj:e,state:"exporting",exportOptions:t}),i=await a.parseAsync(n.obj,{exportExt:n.ext??s,...t}),i.ext=n.ext}i=await this.processAfterExport(i,e,t),this.dispatchEvent({type:"exportFile",obj:e,state:"done",exportOptions:t})}catch(n){throw console.error("AssetExporter: Unable to Export file",e),this.dispatchEvent({type:"exportFile",obj:e,state:"error",error:n,exportOptions:t}),n}return i}_createParser(e){const t=this.exporters.find(n=>n.ext.includes(e));if(!t)throw new Error(`No exporter found for extension ${e}`);const i=t?.ctor(this,t);if(!i)throw new Error(`Unable to create writer for extension ${e}`);return this._cachedWriters.push({ext:t.ext,parser:i}),this.dispatchEvent({type:"exporterCreate",exporter:t,parser:i}),i}_getWriter(e){return this._cachedWriters.find(t=>t.ext.includes(e))?.parser??this._createParser(e)}async processBeforeExport(e,t={}){switch(e.assetType){case"light":console.error("AssetExporter: light export not implemented");return;case"model":return{obj:e,ext:t.exportExt??"glb"};case"material":return{obj:GV(e),ext:t.exportExt||e.constructor?.TypeSlug,typeExt:"json"};case"texture":return t.exportExt?{obj:e,ext:t.exportExt}:{obj:e.toJSON(),ext:"json"};case"renderTarget":if(e.renderManager){const i=t.exportExt&&t.exportExt!=="auto"?t.exportExt==="exr"?"image/x-exr":"image/"+t.exportExt:"auto";let n;if(e.textures.length>1){const s={};for(let o=0;o<e.textures.length;o++){const l=e.renderManager.exportRenderTarget(e,i,o);s[`texture_${o}.${l.ext}`]=new Uint8Array(l.__buffer||await l.arrayBuffer())}const a=Tg(s);n=new Blob([a],{type:"application/zip"}),n.ext="zip",n.__buffer=a.buffer}else n=e.renderManager.exportRenderTarget(e,i);return{obj:e,ext:n.ext,blob:n}}else return{obj:e,ext:"exr"};default:console.error("AssetExporter: unknown asset type",e.assetType)}}async processAfterExport(e,t,i={}){return e}dispose(){}}function GV(r){return r.toJSON()}class tI extends xi{constructor(){super(),this._materials=[],this._disposeMaterial=e=>{const t=e.target;!t||t.assetType!=="material"||this.unregisterMaterial(t)},this._registerMaterial=e=>{const t=e.target;!t||t.assetType!=="material"||this.registerMaterial(t)},this.unregisterExtensionsOnRemove=!1,this._materialExtensions=[],zV()}findOrCreate(e,t){let i=this.findMaterial(e);return i||(i=this.create(e,t)),i}create(e,t={},i=!0,n){const s=this.findTemplate(e);if(!s){console.error("No material template found for type",e);return}const a=this._create(s,t);return n&&an(a,"uuid",n,!0,!0),a&&i&&this.registerMaterial(a),a}_create(e,t){if(!e){console.error("No material template provided");return}const i=new e;return t&&i&&i.setValues(t,!0),i}registerMaterial(e){if(!e||this._materials.includes(e))return;e.assetType||JM.call(e),this.findMaterial(e.uuid)&&(an(e,"uuid",Oi(),!0,!0),e.userData.uuid&&(e.userData.uuid=e.uuid)),e.addEventListener("__unregister",this._disposeMaterial),e.addEventListener("__register",this._registerMaterial),e.registerMaterialExtensions?.(this._materialExtensions),e.setDirty(),this._materials.push(e)}registerMaterials(e){e.forEach(t=>this.registerMaterial(t))}unregisterMaterial(e){this._materials=this._materials.filter(t=>t.uuid!==e.uuid),this.unregisterExtensionsOnRemove&&e.unregisterMaterialExtensions?.(this._materialExtensions),e.removeEventListener("__unregister",this._disposeMaterial),e.removeEventListener("__register",this._registerMaterial)}clearMaterials(){[...this._materials].forEach(e=>this.unregisterMaterial(e))}dispose(e=!0){const t=this._materials;this._materials=[];for(const i of t){if(!e&&i.userData.runtimeMaterial){this._materials.push(i);continue}i.dispose()}}findMaterial(e){return e?this._materials.find(t=>t.uuid===e):void 0}findMaterialsByName(e,t=!1){return this._materials.filter(i=>typeof e!="string"||t?i.name.match(typeof e=="string"?"^"+e+"$":e)!==null:i.name===e)}getMaterialsOfType(e){return e?this._materials.filter(t=>t.constructor.TypeSlug===e):[]}getAllMaterials(){return[...this._materials]}convertToIMaterial(e,{useSourceMaterial:t=!0,materialTemplate:i,createFromTemplate:n=!0}={}){if(!e)return;if(e.assetType)return e;if(e.iMaterial?.assetType)return e.iMaterial;const s=e.userData?.uuid||e.uuid;let a=this.findMaterial(s);if(!a&&n!==!1){const o=t===!1||!e.isMaterial,l=i||!o&&e.type&&e.type||"physical";a=this.create(l,o?void 0:e)}else a&&(console.warn("Material with the same uuid already exists, copying properties"),e.type!==a.type&&console.error("Material type mismatch, delete previous material first?",e,a),a.setValues(e));return a?(a.uuid=s,a.userData.uuid=s,e.iMaterial=a):(console.warn("Failed to convert material to IMaterial, just upgrading",e,t,i),a=ve.upgradeMaterial.call(e)),a}registerMaterialExtension(e){if(!this._materialExtensions.includes(e)){this._materialExtensions.push(e);for(const t of this._materials)t.registerMaterialExtensions?.([e])}}unregisterMaterialExtension(e){const t=this._materialExtensions.indexOf(e);if(!(t<0)){this._materialExtensions.splice(t,1);for(const i of this._materials)i.unregisterMaterialExtensions?.([e])}}clearExtensions(){[...this._materialExtensions].forEach(e=>this.unregisterMaterialExtension(e))}exportMaterial(e,t,i=!0,n=!1){const s=e.toJSON(),a=JSON.stringify(s,null,i?0:2),o=(t||e.name||"physical_material")+"."+e.constructor.TypeSlug,l=new File([a],o,{type:"application/json"});return n&&AS(l),l}applyMaterial(e,t,i=!0,n){let s=this.findMaterialsByName(t,i);(!s||s.length<1)&&(s=[this.findMaterial(t)]);let a=!1;for(const o of s){if(!o||o===e||o.userData.__isVariation)continue;this.copyMaterialProps(o,e,n)&&(a=!0)}return a}copyMaterialProps(e,t,i){let n=!1;const s=Object.getPrototypeOf(t).constructor.TYPE;if(Object.getPrototypeOf(e).constructor.TYPE===s){const o=e.name;e.setValues(t,void 0,void 0,i),e.name=o,n=!0}else{const o=e["__"+s]||this.create(s);if(o){const l=e.name;o.setValues?o.setValues(t):Object.assign(o,t),o.name=l;const c=e.appliedMeshes;for(const h of[...c??[]])h&&(h.material=o,n=!0);e["__"+s]=o}}return n}registerMaterialTemplate(e){if(!e||We.SerializableMaterials.has(e))return;const t=[...We.SerializableMaterials.values()].find(i=>i.TYPE===e.TYPE);t&&console.warn("Material template with the same type already exists",e,t),We.SerializableMaterials.add(e)}unregisterMaterialTemplate(e){e&&We.SerializableMaterials.delete(e)}findTemplate(e){if(e)return[...We.SerializableMaterials.values()].find(t=>t.TYPE===e)||[...We.SerializableMaterials.values()].find(t=>t.TypeAlias?.includes(e))}}function zV(){const r=`
		vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
		vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
`;lt.bumpmap_pars_fragment=bt(lt.bumpmap_pars_fragment,r,`
    #ifdef BUMP_MAP_SCALE_LEGACY
        ${r.replace(/normalize/g,"")}
    #else
        ${r}
    #endif
    `)}class iI extends f_{constructor(e){super(e),this.type=Yt}parse(e){const a=function(I,C){switch(I){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(C||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(C||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(C||""));default:case 4:throw new Error("THREE.RGBELoader: Memory Error: "+(C||""))}},u=function(I,C,x){C=C||1024;let U=I.pos,O=-1,N=0,H="",V=String.fromCharCode.apply(null,new Uint16Array(I.subarray(U,U+128)));for(;0>(O=V.indexOf(`
`))&&N<C&&U<I.byteLength;)H+=V,N+=V.length,U+=128,V+=String.fromCharCode.apply(null,new Uint16Array(I.subarray(U,U+128)));return-1<O?(I.pos+=N+O+1,H+V.slice(0,O)):!1},d=function(I){const C=/^#\?(\S+)/,x=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,D=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,U=/^\s*FORMAT=(\S+)\s*$/,O=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,N={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let H,V;for((I.pos>=I.byteLength||!(H=u(I)))&&a(1,"no header found"),(V=H.match(C))||a(3,"bad initial token"),N.valid|=1,N.programtype=V[1],N.string+=H+`
`;H=u(I),H!==!1;){if(N.string+=H+`
`,H.charAt(0)==="#"){N.comments+=H+`
`;continue}if((V=H.match(x))&&(N.gamma=parseFloat(V[1])),(V=H.match(D))&&(N.exposure=parseFloat(V[1])),(V=H.match(U))&&(N.valid|=2,N.format=V[1]),(V=H.match(O))&&(N.valid|=4,N.height=parseInt(V[1],10),N.width=parseInt(V[2],10)),N.valid&2&&N.valid&4)break}return N.valid&2||a(3,"missing format specifier"),N.valid&4||a(3,"missing image size specifier"),N},p=function(I,C,x){const D=C;if(D<8||D>32767||I[0]!==2||I[1]!==2||I[2]&128)return new Uint8Array(I);D!==(I[2]<<8|I[3])&&a(3,"wrong scanline width");const U=new Uint8Array(4*C*x);U.length||a(4,"unable to allocate buffer space");let O=0,N=0;const H=4*D,V=new Uint8Array(4),X=new Uint8Array(H);let W=x;for(;W>0&&N<I.byteLength;){N+4>I.byteLength&&a(1),V[0]=I[N++],V[1]=I[N++],V[2]=I[N++],V[3]=I[N++],(V[0]!=2||V[1]!=2||(V[2]<<8|V[3])!=D)&&a(3,"bad rgbe scanline format");let ce=0,ue;for(;ce<H&&N<I.byteLength;){ue=I[N++];const Pe=ue>128;if(Pe&&(ue-=128),(ue===0||ce+ue>H)&&a(3,"bad scanline data"),Pe){const Qe=I[N++];for(let ie=0;ie<ue;ie++)X[ce++]=Qe}else X.set(I.subarray(N,N+ue),ce),ce+=ue,N+=ue}const we=D;for(let Pe=0;Pe<we;Pe++){let Qe=0;U[O]=X[Pe+Qe],Qe+=D,U[O+1]=X[Pe+Qe],Qe+=D,U[O+2]=X[Pe+Qe],Qe+=D,U[O+3]=X[Pe+Qe],O+=4}W--}return U},m=function(I,C,x,D){const U=I[C+3],O=Math.pow(2,U-128)/255;x[D+0]=I[C+0]*O,x[D+1]=I[C+1]*O,x[D+2]=I[C+2]*O,x[D+3]=1},A=function(I,C,x,D){const U=I[C+3],O=Math.pow(2,U-128)/255;x[D+0]=zn.toHalfFloat(Math.min(I[C+0]*O,65504)),x[D+1]=zn.toHalfFloat(Math.min(I[C+1]*O,65504)),x[D+2]=zn.toHalfFloat(Math.min(I[C+2]*O,65504)),x[D+3]=zn.toHalfFloat(1)},g=new Uint8Array(e);g.pos=0;const y=d(g),v=y.width,_=y.height,b=p(g.subarray(g.pos),v,_);let T,E,M;switch(this.type){case Ut:M=b.length/4;const I=new Float32Array(M*4);for(let x=0;x<M;x++)m(b,x*4,I,x*4);T=I,E=Ut;break;case Yt:M=b.length/4;const C=new Uint16Array(M*4);for(let x=0;x<M;x++)A(b,x*4,C,x*4);T=C,E=Yt;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:v,height:_,data:T,header:y.string,gamma:y.gamma,exposure:y.exposure,type:E}}setDataType(e){return this.type=e,this}load(e,t,i,n){function s(a,o){switch(a.type){case Ut:case Yt:a.colorSpace=Bt,a.minFilter=at,a.magFilter=at,a.generateMipmaps=!1,a.flipY=!0;break}t&&t(a,o)}return super.load(e,s,i,n)}}function VV(r,e){const t=(r.version?r.version:"0.0.0").split(".").map(n=>parseInt(n));if(!(r.type==="ViewerApp"&&t[0]===0&&(t[1]<7||t[1]===7&&t[2].toString()[0]<"6")))return;const i=new Set;e.forEach(n=>n.traverse(s=>{s.material&&i.add(s.material)})),i.forEach(n=>{const s=n.map;if(!s)return;const a=s.repeat,o=s.offset,l=s.center,c=s.rotation;["alphaMap","aoMap","bumpMap","displacementMap","emissiveMap","lightMap","metalnessMap","normalMap","roughnessMap","transmissionMap"].forEach(u=>{const d=n[u];d&&(d.repeat.copy(a),d.offset.copy(o),d.center.copy(l),d.rotation=c,d.needsUpdate=!0)}),n.needsUpdate=!0})}class HV extends Mt{constructor(e){super(e),Mt.ObjectConstructors.MeshStandardMaterial=si,Mt.ObjectConstructors.MeshBasicMaterial=gs,Mt.ObjectConstructors.MeshPhysicalMaterial=si,Mt.ObjectConstructors.LineBasicMaterial=Yn}transform(e,t){let i;return e.scene.traverse(n=>{if(i)return;const s=n.material;s&&s.isPhysicalMaterial&&(i=s)}),i}}const Vb=class Vb extends xi{constructor(e,t){super(),this._gltfExporter={ext:["gltf","glb"],extensions:[],ctor:(i,n)=>{const s=new Bg;return s.setup(this.viewer,n.extensions),s}},this.processState=new Map,this.gltfExtensions=[],this._sceneUpdated=this._sceneUpdated.bind(this),this.addAsset=this.addAsset.bind(this),this.addRaw=this.addRaw.bind(this),this._loaderCreate=this._loaderCreate.bind(this),this.addImported=this.addImported.bind(this),this.importer=new Ds(!!e.getPlugin("debug"),t),this.exporter=new eI,this.materials=new tI,this.viewer=e,this.viewer.scene.addEventListener("addSceneObject",this._sceneUpdated),this.viewer.scene.addEventListener("materialChanged",this._sceneUpdated),this.viewer.scene.addEventListener("beforeDeserialize",this._sceneUpdated),this._setupGltfExtensions(),this._setupObjectProcess(),this._setupObjectExport(),this._setupProcessState(),this._addImporters(),this._addExporters()}get storage(){return this.importer.storage}async addAsset(e,t){if(!this.importer||!this.viewer)return[];const i=await this.importer.import(e,t);if(!i){const n=typeof e=="string"?e:e?.path;return n&&!n.split("?")[0].endsWith(".vjson")&&console.warn("Threepipe AssetManager - Unable to import",e,i),[]}return this.loadImported(i,t)}async loadImported(e,{autoSetEnvironment:t=!0,autoSetBackground:i=!1,...n}={}){const s=Array.isArray(e)?e:[e];let a=Array.isArray(e)?[]:void 0;if(n?.importConfig!==!1){const o=s.find(l=>l?.assetType==="config")||s.find(l=>l&&!!l.importedViewerConfig)?.importedViewerConfig;o&&VV(o,s.filter(l=>l?.isObject3D))}for(const o of s){if(!o){Array.isArray(a)&&a.push(void 0);continue}let l=o;const c=o?.__rootBlob?o.__rootBlob.filePath||o.__rootBlob.name:o.__rootPath||o.userData?.rootPath||o.name||"";switch(o.assetType){case"material":this.materials.registerMaterial(o);break;case"texture":t&&(c?.endsWith(".hdr")||c?.endsWith(".exr"))&&(this.viewer.scene.environment=o),i&&(this.viewer.scene.background=o);break;case"model":case"light":case"camera":l=await this.viewer.addSceneObject(o,n);break;case"config":n?.importConfig!==!1&&await this.viewer.importConfig(o);break;default:o.type&&typeof o.type=="string"&&(Array.isArray(o.plugins)||o.type==="ThreeViewer"||this.viewer.getPlugin(o.type))&&await this.viewer.importConfig(o);break}this.dispatchEvent({type:"loadAsset",data:o}),Array.isArray(a)?a.push(l):a=l}return a}async addProcessedAssets(e,t){return this.loadImported(e,t)}async addAssetSingle(e,t){return e?(await this.addAsset(e,t))?.[0]:void 0}async addRaw(e,t={}){const i=await this.importer.processRaw(e,t);return this.loadImported(i,t)}async addRawSingle(e,t={}){return(await this.addRaw(e,t))?.[0]}_sceneUpdated(e){if(e.type==="addSceneObject"){const i=e.object;i.assetType==="material"&&this.materials.registerMaterial(i)}else if(e.type==="materialChanged"){const i=e.material,n=Array.isArray(i)?i:i?[i]:[];for(const s of n)this.materials.registerMaterial(s)}else if(e.type==="beforeDeserialize"){const t=e,i=t.data,n=t.meta;i.metadata||console.warn("Invalid data(no metadata)",i),t.material&&(i.metadata?.type!=="Material"&&console.warn("Invalid material data",i),oh.DeserializeMaterialJSON(i,this.viewer,n,t.material).then(()=>{}))}else console.error("Unexpected")}dispose(){this.importer.dispose(),this.materials.dispose(),this.processState.clear(),this.viewer.scene.removeEventListener("addSceneObject",this._sceneUpdated),this.viewer.scene.removeEventListener("materialChanged",this._sceneUpdated),this.exporter.dispose()}_addImporters(){const e=this.viewer;if(!e)return;const t=this.importer,i=[new qi(class extends Fd{async parseAsync(n){if(n.assetType==="config")return n;const s=n.type||n.metadata?.type,a=t.importers.filter(o=>{const l=o.cls?.SupportedJSONTypes;if(l)return tt(l)?.includes(s)});for(const o of a){if(!o)continue;const l=o.ctor(t),c=await l.parseAsync(n);if(l.dispose&&l.dispose(),c)return c}if(n.serializableClassId){const o=n.resources;n.resources&&delete n.resources;const l=o?await e.loadConfigResources(o):void 0,c=We.Deserialize(n,void 0,l);if(l&&(n.resources=l),c)return c}return super.parseAsync(n)}},["json","vjson"],["application/json"],!1),new qi(Rg,["svg","data:image/svg"],["image/svg+xml"],!1),new qi(Za,["webp","png","jpeg","jpg","ico","data:image","avif","bmp","gif","tiff"],["image/webp","image/png","image/jpeg","image/gif","image/bmp","image/tiff","image/x-icon","image/avif"],!1),new qi(oh,oh.SupportedJSONExtensions,[],!1,n=>(n&&(n.viewer=this.viewer),n)),new qi(class extends iI{constructor(n){super(n),this.setDataType(hv(e.renderManager.renderer))}},["hdr"],["image/vnd.radiance"],!1),new qi(class extends G0{constructor(n){super(n),this.setDataType(hv(e.renderManager.renderer))}},["exr"],["image/x-exr"],!1),new qi(F1,["fbx"],["model/fbx"],!0),new qi(N1,["zip","glbz","gltfz"],["application/zip","model/gltf+zip","model/zip"],!0),new qi(WT,["obj"],["model/obj"],!0),new qi(m0,["mtl"],["model/mtl"],!1),new qi(Il,["gltf","glb","data:model/gltf","data:model/glb"],["model/gltf","model/gltf+json","model/gltf-binary","model/glb"],!0,(n,s,a)=>n?.setup(this.viewer,a.extensions)),new qi(Dg,["drc"],["model/mesh+draco","model/drc"],!0),new qi(H1,["mp4","ogg","mov","webm","data:video"],["video/mp4","video/ogg","video/quicktime","video/webm"],!0),new qi(HV,["phmatgltf"],[],!0)];this.importer.addImporter(...i)}_addExporters(){const e=[this._gltfExporter];this.exporter.addExporter(...e)}_setupObjectProcess(){this.importer.addEventListener("processRaw",e=>{if(e.data&&e.data.isObject3D){const i=e.data;this._loadObjectDependencies(i);return}const t=e.data;t&&t.isMaterial&&t.uuid&&this.materials.registerMaterial(t)}),this.importer.addEventListener("processRawStart",e=>QV(e,this))}_setupObjectExport(){}async _loadObjectDependencies(e){const t=[];if(!e.traverseModels){this.viewer.console.error("AssetManager - Object not upgraded, cannot load dependencies",e);return}e.traverseModels&&e.traverseModels(s=>s.userData.rootPathRefresh&&!s._rootPathRefreshed&&!s._rootPathRefreshing&&s.userData.rootPath?(t.push(s),!1):!0,{visible:!1,widgets:!0});const i=t.map(async s=>{s._rootPathRefreshing=!0;const a=s.userData.rootPath;if(!a)return null;const o=s.userData.rootPathOptions,l=await this.importer.import(a,{...o});if(!l)throw new Error(`Unable to load asset from url - ${a}`);return l}),n=await Promise.allSettled(i);for(let s=0;s<n.length;s++){const a=n[s],o=t[s];if(delete o._rootPathRefreshing,o._rootPathRefreshed=!0,a.status==="rejected"){this.viewer.console.error(`ThreeViewer - Failed to load root path for object ${o.name}`,a.reason);continue}if(a.status!=="fulfilled")continue;const l=a.value;if(!l||!l.length)continue;const c=l.find(m=>m?.isObject3D);if(!c){this.viewer.console.warn("AssetManager - No valid model found in root path",a.value);continue}const h=l.filter(m=>m&&m!==c),u=o.parent,d=u?u.children.indexOf(o):-1;if(u&&o.removeFromParent(),this.viewer.object3dManager.unregisterObject(o),!c.isObject3D){this.viewer.console.warn("Non model dependency loaded. Not fully supported yet.");continue}if(!u){this.viewer.console.error("AssetManager - Unexpected error, no parent found for object when loading dependency",o);continue}c._copyFromEmbedded?c._copyFromEmbedded(o):(o.matrix.decompose(c.position,c.quaternion,c.scale),c.name=o.name,c.userData={...o.userData,...c.userData},c._rootPathRefreshed=!0,c.uuid=o.uuid),u.add(c);const p=u.children.indexOf(c);if(d>=0&&p>=0&&d!==p&&(u.children.splice(p,1),u.children.splice(d,0,c)),h.length)for(const m of h)m?.isObject3D?u.add(m):this.viewer.console.warn("Non model dependency loaded. Not fully supported yet.",m)}}setProcessState(e,t){t===void 0?this.processState.delete(e):this.processState.set(e,t),this.dispatchEvent({type:"processStateUpdate"})}_setupProcessState(){this.importer.addEventListener("importFile",e=>{!e.path||e.path.startsWith("blob:")||e.path.startsWith("data:")||this.setProcessState(e.path,e.state!=="done"?{state:e.state,progress:e.progress?e.progress*100:void 0}:void 0)}),this.importer.addEventListener("processRawStart",e=>{!e.path||e.path.startsWith("blob:")||e.path.startsWith("data:")||this.setProcessState(e.path,{state:"processing",progress:void 0})}),this.importer.addEventListener("processRaw",e=>{!e.path||e.path.startsWith("blob:")||e.path.startsWith("data:")||this.setProcessState(e.path,void 0)}),this.exporter.addEventListener("exportFile",e=>{e.obj.name&&this.setProcessState(e.obj.name,e.state!=="done"?{state:e.state,progress:e.progress?e.progress*100:void 0}:void 0)})}_setupGltfExtensions(){this.importer.addEventListener("loaderCreate",this._loaderCreate),this.viewer.forPlugin("GLTFDracoExportPlugin",e=>{if(e.addExtension)for(const t of this.gltfExtensions)e.addExtension(t.name,t.textures)})}_loaderCreate({loader:e}){if(e.isGLTFLoader2)for(const t of this.gltfExtensions)e.register(t.import)}registerGltfExtension(e){const t=this.gltfExtensions.findIndex(n=>n.name===e.name);t>=0&&this.gltfExtensions.splice(t,1),this.gltfExtensions.push(e),this._gltfExporter.extensions.push(e.export);const i=this.exporter.getExporter("gltf","glb");i&&i!==this._gltfExporter&&i.extensions?.push(e.export)}unregisterGltfExtension(e){const t=this.gltfExtensions.findIndex(s=>s.name===e);if(t<0)return;this.gltfExtensions.splice(t,1);const i=this._gltfExporter.extensions.findIndex(s=>s.name===e);i>=0&&this._gltfExporter.extensions.splice(i,1);const n=this.exporter.getExporter("gltf","glb");if(n?.extensions&&n!==this._gltfExporter){const s=n.extensions.findIndex(a=>a.name===e);s>=0&&n.extensions?.splice(s,1)}}async addImported(e,t={}){return console.error("addImported is deprecated, use addRaw instead"),this.addRaw(e,t)}async addFromPath(e,t={}){return console.error("addFromPath is deprecated, use addAsset instead"),this.addAsset(e,t)}exportViewerConfig(e=!0){return this.viewer?(console.error("exportViewerConfig is deprecated, use viewer.toJSON instead"),this.viewer.toJSON(e,void 0)):{}}exportPluginPresets(e){return console.error("exportPluginPresets is deprecated, use viewer.exportPluginsConfig instead"),this.viewer?.exportPluginsConfig(e)}exportPluginPreset(e){return console.error("exportPluginPreset is deprecated, use viewer.exportPluginConfig instead"),this.viewer?.exportPluginConfig(e)}async importPluginPreset(e,t){return console.error("importPluginPreset is deprecated, use viewer.importPluginConfig instead"),this.viewer?.importPluginConfig(e,t)}async importViewerConfig(e){return this.viewer?.importConfig(e)}applyViewerConfig(e,t){return console.error("applyViewerConfig is deprecated, use viewer.fromJSON instead"),this.viewer?.fromJSON(e,t)}async importConfigResources(e,t){if(!this.importer)throw"Importer not initialized yet.";return e.__isLoadedResources?e:this.viewer?.loadConfigResources(e,t)}};Vb.PluginType="AssetManager";let Lg=Vb;const QV=(r,e)=>{const t=r.data,i=r.options;if(t.isObject3D){const n=[],s=[];t.traverse(a=>{if(a.material){const o=Array.isArray(a.material)?a.material:[a.material],l=[],c=[];for(const h of o){const u=e.materials.convertToIMaterial(h,{createFromTemplate:i.replaceMaterials!==!1})||h;u.uuid=h.uuid,u.userData.uuid=h.uuid,l.push(u);const d=ve.getMapsForMaterial.call(u);c.push(...Array.from(d.values()))}Array.isArray(a.material)?a.material=l:a.material=l[0],new Set(c).forEach(h=>{typeof h.userData.rootPath=="string"&&h.userData.rootPath.startsWith("blob:")&&delete h.userData.rootPath,h.userData.rootPath&&!h.__rootPath?(h.__rootPath=h.userData.rootPath,e.importer.processRawSingle(h,{})):Td.call(h)})}a.isCamera&&n.push(a),a.isLight&&s.push(a)});for(const a of n)if(a.assetType!=="camera")if(!a.parent||i.replaceCameras===!1)ht.upgradeCamera.call(a);else{const o=a.iCamera??!a.isOrthographicCamera?new th("",e.viewer.canvas):new Sd("",e.viewer.canvas);if(a===o)continue;a.parent.children.splice(a.parent.children.indexOf(a),1,o),o.parent=a.parent,o.copy(a),a.parent=null,o.uuid=a.uuid,o.userData.uuid=a.uuid,a.iCamera=o}for(const a of s)if(a.assetType!=="light")if(!a.parent||i.replaceLights===!1)pn.upgradeLight.call(a);else{const o=a.iLight??a.isDirectionalLight?new lg:a.isPointLight?new cg:a.isSpotLight?new hg:a.isAmbientLight?new bl:a.isHemisphereLight?new Ca:a.isRectAreaLight?new Nr:void 0;if(a===o||!o)continue;a.parent.children.splice(a.parent.children.indexOf(a),1,o),o.parent=a.parent,o.copy(a),a.parent=null,o.uuid=a.uuid,o.userData.uuid=a.uuid,a.iLight=o}qe.upgradeObject3D.call(t)}else t.isMaterial?t.assetType||ve.upgradeMaterial.call(t):t.isTexture&&(Td.call(t),r?.options?.generateMipmaps!==void 0&&(t.generateMipmaps=r?.options.generateMipmaps),!t.generateMipmaps&&!t.isRenderTargetTexture&&(t.minFilter=t.minFilter===Dn?at:t.minFilter,t.magFilter=t.magFilter===Dn?at:t.magFilter))},zl=class zl extends xi{constructor(){super(),this._objects=new Map,this._objectExtensions=[],this._materials=new Map,this._geometries=new Map,this._textures=new Map,this._videos=new Map,this._lights=new Map,this.autoDisposeTextures=!0,this.autoDisposeMaterials=!0,this.autoDisposeGeometries=!0,this.autoDisposeObjects=!1,this._rootChanged=e=>{if(!e.target||!this._root)return;const t=e.target.parentRoot;let i=!1;t===this._root?i=!0:e.target.traverseAncestors(n=>{n===this._root&&(i=!0)}),i?this.registerObject(e.target):this.unregisterObject(e.target)},this._materialChanged=e=>{if(!e.target)return;const t=e.target,i=e.oldMaterial;i&&(Array.isArray(i)?this._unregisterMaterials(i,t):this._unregisterMaterial(i,t)),this._registerMaterials(t.materials,t)},this._geometryChanged=e=>{if(!e.target)return;const t=e.target,i=e.oldGeometry;i&&this._unregisterGeometry(i,t),this._registerGeometry(t.geometry,t)},this._texturesChanged=e=>{if(!e.target)return;const t=e.target,i=e.removedTextures;if(i)for(const s of i)this._unregisterTexture(s,t);const n=e.textures;if(n)for(const s of n)this._registerTexture(s,t)},this._textureChanged=e=>{e.target&&(e.oldTexture&&this._unregisterTexture(e.oldTexture,e.target),e.texture&&this._registerTexture(e.texture,e.target))},this._rootChanged=this._rootChanged.bind(this),this._materialChanged=this._materialChanged.bind(this),this._geometryChanged=this._geometryChanged.bind(this),this._texturesChanged=this._texturesChanged.bind(this)}onPostFrame(e){for(const t of this._videos.values()){const i=t.userData.timeline;if(i&&!i.enabled)continue;const n=t.image,s=i?.delay||0,a=i?.scale||1,o=i?.start||0,l=n.duration||1,c=l-(i?.end||0);let h=e.time;if(h-=s,h*=a,h<o&&(h=o),h>c&&(h=c),h<0&&(h=0),h>l&&(h=l),Math.abs(h-n.currentTime)>1/60&&(n.currentTime=h,n.paused)){const d=(t._playid||0)+1;t._playid=d,n.play().then(()=>{t._playid===d&&(n.paused||n.pause(),delete t._playid)})}e.running||!n.paused&&!t._playid&&n.pause()}}setRoot(e){this._root=e}registerObject(e){if(!e||!e.uuid||!e.isObject3D)return;const t=this.getObject(e.uuid);if(t)if(e!==t)console.warn("Object3DManager - Object with the same uuid already registered",e,t),an(e,"uuid",Oi(),!0,!0);else return;e.assetType||qe.upgradeObject3D.call(e),this._objects.set(e.uuid,e),e.addEventListener("parentRootChanged",this._rootChanged),e.addEventListener("materialChanged",this._materialChanged),e.addEventListener("geometryChanged",this._geometryChanged),e.addEventListener("texturesChanged",this._texturesChanged),e.isScene&&(e.addEventListener("backgroundChanged",this._textureChanged),e.addEventListener("environmentChanged",this._textureChanged)),this._registerMaterials(e.materials,e),this._registerGeometry(e.geometry,e);const i=qe.getMapsForObject3D.call(e);if(i)for(const s of i.values())this._registerTexture(s,e);e.objectExtensions||(e.objectExtensions=[]);const n=e.objectExtensions;for(const s of this._objectExtensions){if(n.includes(s))continue;(!s.isCompatible||s.isCompatible(e))&&(n.push(s),s.onRegister&&s.onRegister(e))}this.dispatchEvent({type:"objectAdd",object:e}),e.isLight&&(this._lights.set(e.uuid,e),this.dispatchEvent({type:"lightAdd",light:e})),e.dispatchEvent({type:"__register"})}unregisterObject(e){if(!e||!e.uuid)return!1;const t=this._objects.get(e.uuid);if(!t)return!1;if(e!==t)return console.error("Object3DManager - Object to unregister is not the same as the registered object",e,t),!1;this._objects.delete(e.uuid),e.removeEventListener("materialChanged",this._materialChanged),e.removeEventListener("geometryChanged",this._geometryChanged),e.removeEventListener("texturesChanged",this._texturesChanged),e.isScene&&(e.removeEventListener("backgroundChanged",this._textureChanged),e.removeEventListener("environmentChanged",this._textureChanged)),this._unregisterMaterials(e.materials,e),this._unregisterGeometry(e.geometry,e);const i=qe.getMapsForObject3D.call(e);if(i)for(const n of i.values())this._unregisterTexture(n,e);return this.autoDisposeObjects&&e.userData?.disposeOnIdle!==!1&&e.dispose&&e.dispose(!1),this.dispatchEvent({type:"objectRemove",object:e}),e.isLight&&this._lights.has(e.uuid)&&(this._lights.delete(e.uuid),this.dispatchEvent({type:"lightRemove",light:e})),e.dispatchEvent({type:"__unregister"}),!0}registerObjectExtension(e){if(!(!e||(e.uuid||(e.uuid=Oi()),this._objectExtensions.includes(e)))){this._objectExtensions.push(e);for(const i of this._objects.values())i.objectExtensions&&!i.objectExtensions.includes(e)&&(!e.isCompatible||e.isCompatible(i))&&i.objectExtensions.push(e)}}unregisterObjectExtension(e){if(!e)return;const t=this._objectExtensions.indexOf(e);t<0||this._objectExtensions.splice(t,1)}_registerMaterials(e,t){return e&&e.forEach(i=>this._registerMaterial(i,t))}_unregisterMaterials(e,t){return e&&e.forEach(i=>this._unregisterMaterial(i,t))}_registerMaterial(e,t){if(!e||!e.isMaterial||!t||!e.uuid)return;e.assetType||ve.upgradeMaterial.call(e);let i=e.appliedMeshes;i||(i=new Set,e.appliedMeshes=i);const n=this.getMaterial(e.uuid);n&&e!==n&&(console.warn("Object3DManager - Material with the same uuid already registered",e,n),an(e,"uuid",Oi(),!0,!0));const s=!this._materials.has(e.uuid);i.add(t),this._materials.set(e.uuid,e),s&&e.addEventListener("texturesChanged",this._texturesChanged);const a=ve.getMapsForMaterial.call(e);if(a)for(const o of a.values())this._registerTexture(o,e);s&&(this.dispatchEvent({type:"materialAdd",material:e}),e.dispatchEvent({type:"__register"}))}_unregisterMaterial(e,t){if(!e||!t||!t.uuid)return;const i=e.appliedMeshes;if(!i)return;i.delete(t);const n=this.getMaterial(e.uuid);if(n&&e!==n){console.error("Object3DManager - Material to unregister is not the same as the registered material",e,n);return}if(i.size===0&&n){this._materials.delete(e.uuid),e.removeEventListener("texturesChanged",this._texturesChanged);const s=ve.getMapsForMaterial.call(e);if(s)for(const a of s.values())this._unregisterTexture(a,e);this.dispatchEvent({type:"materialRemove",material:e}),this.autoDisposeMaterials&&e.dispose(!1),e.dispatchEvent({type:"__unregister"})}}_registerGeometry(e,t){if(!e||!e.isBufferGeometry||!t||!t.uuid)return;e.assetType||ni.upgradeGeometry.call(e);let i=e.appliedMeshes;i||(i=new Set,e.appliedMeshes=i);const n=this.getGeometry(e.uuid);n&&e!==n&&(console.warn("Object3DManager - Geometry with the same uuid already registered",e,n),an(e,"uuid",Oi(),!0,!0));const s=!this._geometries.has(e.uuid);i.add(t),this._geometries.set(e.uuid,e),s&&(this.dispatchEvent({type:"geometryAdd",geometry:e}),e.dispatchEvent({type:"__register"}))}_unregisterGeometry(e,t){if(!e||!t||!t.uuid)return;const i=e.appliedMeshes;if(!i)return;i.delete(t);const n=this.getGeometry(e.uuid);n&&e!==n&&console.error("Object3DManager - Geometry to unregister is not the same as the registered geometry",e,n),i.size===0&&this._geometries.has(e.uuid)&&(this._geometries.delete(e.uuid),this.dispatchEvent({type:"geometryRemove",geometry:e}),this.autoDisposeGeometries&&e.dispose(!1),e.dispatchEvent({type:"__unregister"}))}_registerTexture(e,t){if(!e||!e.isTexture||!t||!t.uuid)return;e.assetType||Td.call(e);let i=e.appliedObjects;i||(i=new Set,e.appliedObjects=i);const n=this.getTexture(e.uuid);n&&e!==n&&(console.warn("Object3DManager - Texture with the same uuid already registered",e,n),an(e,"uuid",Oi(),!0,!0));const s=!this._textures.has(e.uuid);i.add(t),this._textures.set(e.uuid,e),e.isVideoTexture&&this._registerVideo(e),s&&(this.dispatchEvent({type:"textureAdd",texture:e}),e.dispatchEvent({type:"__register"}))}_unregisterTexture(e,t){if(!e||!t||!t.uuid)return;const i=e.appliedObjects;if(!i)return;i.delete(t);const n=this.getTexture(e.uuid);if(n&&e!==n){console.error("Object3DManager - Texture to unregister is not the same as the registered texture",e,n);return}i.size===0&&this._textures.has(e.uuid)&&(this._textures.delete(e.uuid),e.isVideoTexture&&this._videos.delete(e.uuid),this.dispatchEvent({type:"textureRemove",texture:e}),e.userData?.disposeOnIdle!==!1&&this.autoDisposeTextures&&!e.isRenderTargetTexture&&e.dispose&&e.dispose(),e.dispatchEvent({type:"__unregister"}),e.isVideoTexture&&(e.image,this.dispatchEvent({type:"videoRemove",video:e})))}_registerVideo(e){this._videos.set(e.uuid,e);const t=e.image;t.preload="auto",t.autoplay=!0,t.loop=!0,t.muted=!0,this.dispatchEvent({type:"videoAdd",video:e})}findObject(e){if(!e)return;const t=this.getObject(e);if(t)return t;const i=this.findObjectsByName(e);if(i.length>1){console.warn("Multiple objects found with name:",e,i);return}return i[0]}findObjectsByName(e){const t=[];return this._objects.forEach(i=>{i.name===e&&t.push(i)}),t}findMaterial(e){if(!e)return;const t=this.getMaterial(e);if(t)return t;const i=this.findMaterialsByName(e);if(i.length>1){console.warn("Multiple materials found with name:",e,i);return}return i[0]}findMaterialsByName(e){const t=[];return this._materials.forEach(i=>{i.name===e&&t.push(i)}),t}dispose(){const e=[...this._objects.values()];for(const t of e)this.unregisterObject(t),t.removeEventListener("parentRootChanged",this._rootChanged);this._objectExtensions=[],this._objects.clear(),this._materials.clear(),this._geometries.clear(),this.dispatchEvent({type:"dispose"})}getObjects(){return[...this._objects.values()]}getObject(e){return this._objects.get(e)}getObjectExtensions(){return[...this._objectExtensions]}getMaterials(){return[...this._materials.values()]}getMaterial(e){return this._materials.get(e)}getGeometries(){return[...this._geometries.values()]}getGeometry(e){return this._geometries.get(e)}getTextures(){return[...this._textures.values()]}getTexture(e){return this._textures.get(e)}getVideos(){return[...this._videos.values()]}getVideo(e){return this._videos.get(e)}getLights(){return[...this._lights.values()]}getLight(e){return this._lights.get(e)}};zl.MaterialTextureProperties=$M,zl.MaterialTexturePropertiesUserData=KM,zl.SceneTextureProperties=tT,zl.Object3DTextureProperties=iT,new Set([...gs.MapProperties,...Yn.MapProperties,...si.MapProperties,...sg.MapProperties]).forEach(e=>zl.MaterialTextureProperties.add(e));let Og=zl;var jV=Object.defineProperty,WV=Object.getOwnPropertyDescriptor,Ma=(r,e,t,i)=>{for(var n=i>1?void 0:i?WV(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&jV(e,t,n),n};f.RenderManager=class extends wT{constructor({canvas:e,alpha:t=!0,renderScale:i=1,powerPreference:n,targetOptions:s}){super(),this._renderSize=new K(512,512),this._renderScale=1,this._passes=[],this._pipeline=[],this._passesNeedsUpdate=!0,this._frameCount=0,this._lastTime=0,this._totalFrameCount=0,this.stableNoise=!1,this.frameWaitTime=0,this._dirty=!0,this.autoBuildPipeline=!0,this.defaultRenderToScreen=!0,this.onPostFrame=()=>{for(const o of this._passes)o.enabled&&o.onPostFrame&&o.onPostFrame?.(this)},this.animationLoop=this.animationLoop.bind(this),this._renderSize=new K(e.clientWidth,e.clientHeight),this._renderScale=i,this._renderer=this._initWebGLRenderer(e,t,s?.stencilBuffer??!1,n),this._context=this._renderer.getContext(),this._isWebGL2=this._renderer.capabilities.isWebGL2,this._isWebGL2||console.error("RenderManager: WebGL 1 is not officially supported anymore. Some features may not work."),this.resetShadows();const a=this.createTarget(s,!1);a.texture.name="EffectComposer.rt1",this._composer=new vT(this._renderer,a)}get renderScale(){return this._renderScale}set renderScale(e){e!==this._renderScale&&(this._renderScale=e,this.setSize(void 0,void 0,!0))}_shadowMapTypeChanged(){this.resetShadows(),this.reset()}get renderer(){return this._renderer}rebuildPipeline(e=!0){this._passesNeedsUpdate=!0,e&&(this._updated({change:"rebuild"}),this.uiConfig?.uiRefresh?.(!0,"postFrame",1))}_refreshPipeline(){if(!this.autoBuildPipeline)return this._pipeline;const e=this._passes;try{this._pipeline=AT(e)}catch(t){console.error("RenderManager: Unable to sort rendering passes",t)}return this._pipeline}animationLoop(e,t){const i=e-this._lastTime;this._lastTime=e,this.frameWaitTime-=i,!(this.frameWaitTime>0)&&(this.frameWaitTime=0,this.dispatchEvent({type:"animationLoop",deltaTime:i,time:e,renderer:this._renderer,xrFrame:t}))}_initWebGLRenderer(e,t,i,n){const s=new hp({canvas:e,antialias:!1,alpha:t,premultipliedAlpha:!1,preserveDrawingBuffer:!0,powerPreference:n??f.RenderManager.POWER_PREFERENCE,stencil:i});return s.setAnimationLoop(this.animationLoop),s.onContextLost=a=>{this.dispatchEvent({type:"contextLost",event:a})},s.onContextRestore=()=>{this.dispatchEvent({type:"contextRestored"})},s.setSize(this._renderSize.width,this._renderSize.height,!1),s.setPixelRatio(this._renderScale),s.toneMapping=Xr,s.toneMappingExposure=1,s.outputColorSpace=ai,s.shadowMap.enabled=!0,s.shadowMap.type=xA,s.shadowMap.autoUpdate=!1,fT.call(s,this)}setSize(e,t,i=!1){!i&&(e?Math.abs(e-this._renderSize.width):0)+(t?Math.abs(t-this._renderSize.height):0)<.1||(e&&(this._renderSize.width=e),t&&(this._renderSize.height=t),this.webglRenderer.xr.enabled&&this.webglRenderer.xr.isPresenting||(this._renderer.setSize(this._renderSize.width,this._renderSize.height,!1),this._renderer.setPixelRatio(this._renderScale)),this._composer.setPixelRatio(this._renderScale,!1),this._composer.setSize(this._renderSize.width,this._renderSize.height),this.resizeTrackedTargets(),this.dispatchEvent({type:"resize"}),this._updated({change:"size",data:this._renderSize.toArray()}),this.reset(),this.uiConfig?.uiRefresh?.(!0,"postFrame",0))}render(e,t){this._passesNeedsUpdate&&(this._refreshPipeline(),this.refreshPasses());for(const i of this._passes)i.enabled&&i.beforeRender&&i.beforeRender(e,e.renderCamera,this);this._composer.renderToScreen=t??this.defaultRenderToScreen,this.dispatchEvent({type:"preRender",scene:e,renderToScreen:this._composer.renderToScreen}),this._composer.render(),this.dispatchEvent({type:"postRender",scene:e,renderToScreen:this._composer.renderToScreen}),this._composer.renderToScreen=!0,t&&this.incRenderToScreen(),this._dirty=!1}incRenderToScreen(){this._frameCount+=1,this._totalFrameCount+=1}get needsRender(){return this.renderSize.x<1||this.renderSize.y<1?!1:(this._dirty=this._dirty||this._passes.findIndex(e=>tt(e.dirty))>=0,this._dirty)}setDirty(e=!1){this._dirty=!0,e&&this.reset()}reset(){this._frameCount=0,this._dirty=!0}resetShadows(){this._renderer.shadowMap.needsUpdate=!0}refreshPasses(){if(!this._passesNeedsUpdate)return;this._passesNeedsUpdate=!1;const e=[];for(const t of this._pipeline){const i=this._passes.find(n=>n.passId===t);if(!i){console.warn("Unable to find pass: ",t);continue}e.push(i)}[...this._composer.passes].forEach(t=>this._composer.removePass(t)),e.forEach(t=>this._composer.addPass(t)),this._updated({change:"passRefresh"}),this.uiConfig?.uiRefresh?.(!0,"postFrame",1)}dispose(e=!0){super.dispose(e),this._renderer.dispose()}updateShaderProperties(e){return e.uniforms.currentFrameCount&&(e.uniforms.currentFrameCount.value=this.frameCount),this.stableNoise?e.uniforms.frameCount?e.uniforms.frameCount.value=this.frameCount:console.warn("RenderManager: no uniform: frameCount"):e.uniforms.frameCount?e.uniforms.frameCount.value=this._totalFrameCount:console.warn("RenderManager: no uniform: frameCount"),this}registerPass(e,t=!0){if(t)for(const i of[...this._passes])e.passId===i.passId&&this.unregisterPass(i);this._passes.push(e),e.onRegister?.(this),this.rebuildPipeline(!1),this._updated({change:"registerPass",pass:e}),this.uiConfig?.uiRefresh?.(!0,"postFrame",1)}unregisterPass(e){const t=this._passes.indexOf(e);t>=0&&(e.onUnregister?.(this),this._passes.splice(t,1),this.rebuildPipeline(!1),this._updated({change:"unregisterPass",pass:e}),this.uiConfig?.uiRefresh?.(!0,"postFrame",1))}get frameCount(){return this._frameCount}get totalFrameCount(){return this._totalFrameCount}resetTotalFrameCount(){this._totalFrameCount=0}set pipeline(e){this._pipeline=e,this.autoBuildPipeline&&console.warn("RenderManager: pipeline changed, but autoBuildPipeline is true. This will not have any effect."),this.rebuildPipeline()}get pipeline(){return this._pipeline}get composer(){return this._composer}get passes(){return this._passes}get isWebGL2(){return this._isWebGL2}get composerTarget(){return this._composer.renderTarget1}get composerTarget2(){return this._composer.renderTarget2}get renderSize(){return this._renderSize}get context(){return this._context}get webglRenderer(){return this._renderer}get clock(){return this._composer.clock}blit(e,{source:t,viewport:i,material:n,clear:s=!0,respectColorSpace:a=!1,blending:o=gn,transparent:l=!0,opacity:c,blendAlpha:h}={}){const u=a?this._composer.copyPass2:this._composer.copyPass,{renderToScreen:d,material:p,uniforms:m,clear:A}=u;n&&(u.material=n);const g=u.material.transparent,y=e?e.viewport.clone():this._renderer.getViewport(new et),v=e?e.scissor.clone():this._renderer.getScissor(new et),_=e?e.scissorTest:this._renderer.getScissorTest(),b=this._renderer.autoClear,T=this._renderer.getRenderTarget(),E=u.material.blending,M=u.material.uniforms.opacity?.value??1,I=u.material.blendAlpha,C=u.material.blendSrc,x=u.material.blendDst,D=u.material.blendEquation;i&&(e?(e.viewport.copy(i),e.scissor.copy(i),e.scissorTest=!0):(this._renderer.setViewport(i),this._renderer.setScissor(i),this._renderer.setScissorTest(!0))),this._renderer.autoClear=!1,u.material.blending=l?o:Sr,u.uniforms=u.material.uniforms,u.renderToScreen=!1,u.clear=s,u.material.transparent=l,u.material.needsUpdate=!0,u.material.uniforms.opacity&&c!==void 0&&(u.material.uniforms.opacity.value=c),h!==void 0&&(u.material.blending=er,u.material.blendSrc=ql,u.material.blendDst=Xl,u.material.blendEquation=Er,u.material.blendAlpha=h),this._renderer.renderWithModes({sceneRender:!0,opaqueRender:!0,shadowMapRender:!1,backgroundRender:!1,transparentRender:!0,transmissionRender:!1},()=>{u.render(this._renderer,e||null,{texture:t},0,!1)}),u.material.uniforms.opacity&&c!==void 0&&(u.material.uniforms.opacity.value=M),u.renderToScreen=d,u.clear=A,u.material.blending=E,u.material.blendSrc=C,u.material.blendDst=x,u.material.blendEquation=D,u.material.blendAlpha=I,u.material.transparent=g,u.material=p,u.uniforms=m,this._renderer.autoClear=b,i&&(e?(e.viewport.copy(y),e.scissor.copy(v),e.scissorTest=_):(this._renderer.setViewport(y),this._renderer.setScissor(v),this._renderer.setScissorTest(_))),this._renderer.setRenderTarget(T)}clearColor({r:e,g:t,b:i,a:n,target:s,depth:a=!0,stencil:o=!0,viewport:l}){const c=this._renderer.getClearColor(new ee),h=this._renderer.getClearAlpha();this._renderer.setClearColor(new ee(e??c.r,t??c.g,i??c.b),n??h);const u=this._renderer.getRenderTarget(),d=this._renderer.getActiveCubeFace(),p=this._renderer.getActiveMipmapLevel(),m=s?s.viewport.clone():this._renderer.getViewport(new et),A=s?s.scissor.clone():this._renderer.getScissor(new et),g=s?s.scissorTest:this._renderer.getScissorTest();l&&(s?(s.viewport.copy(l),s.scissor.copy(l),s.scissorTest=!0):(this._renderer.setViewport(l),this._renderer.setScissor(l),this._renderer.setScissorTest(!0))),this._renderer.setRenderTarget(s??null),this._renderer.clear(!0,a,o),s&&typeof s.clear=="function"?s.clear(this._renderer,!0,a,o):(this._renderer.setRenderTarget(s??null),this._renderer.clear(!0,a,o)),l&&(s?(s.viewport.copy(m),s.scissor.copy(A),s.scissorTest=g):(this._renderer.setViewport(m),this._renderer.setScissor(A),this._renderer.setScissorTest(g))),this._renderer.setRenderTarget(u,d,p),this._renderer.setClearColor(c,h)}_withResolvedTarget(e,t,i){if(e.width&&e.height)return;const n=e.textures?.[t]??e.texture;if(!n)throw new Error("RenderManager: target has no texture");const s=n.image?.width||n.source?.data?.width,a=n.image?.height||n.source?.data?.height,o=this.getTempTarget(s&&a?{size:{width:s,height:a},type:n.type}:{sizeMultiplier:1,type:n.type});this.blit(o,{source:n,clear:!0});const l=i(o);return this.releaseTempTarget(o),l}renderTargetToCanvas(e,t=0,i){const n=this._withResolvedTarget(e,t,l=>this.renderTargetToCanvas(l,0,i));if(n)return n;i=i??document.createElement("canvas");const s=e.textures?.[t]??e.texture;i.width=e.width,i.height=e.height;const a=i.getContext("2d");if(!a)throw new Error("Unable to get 2d context");const o=a.createImageData(i.width,i.height,{colorSpace:["display-p3","srgb"].includes(s.colorSpace)?s.colorSpace:void 0});if(s.type===Yt||s.type===Ut){const l=this.renderTargetToBuffer(e,t);uv({data:l,width:i.width,height:i.height},s.colorSpace,o)}else this._renderer.readRenderTargetPixels(e,0,0,i.width,i.height,o.data,void 0,t);return a.putImageData(o,0,0),i}renderTargetToDataUrl(e,t="image/png",i=90,n=0){const s=e.textures?.[n]??e.texture,a=this.renderTargetToCanvas(e,n),o=(s.flipY?a:B_(a)).toDataURL(t,i);return a.remove(),o}renderTargetToBuffer(e,t=0){const i=e.textures?.[t]??e.texture,n=i.type===Yt?new Uint16Array(e.width*e.height*4):i.type===Ut?new Float32Array(e.width*e.height*4):new Uint8Array(e.width*e.height*4);return this._renderer.readRenderTargetPixels(e,0,0,e.width,e.height,n,void 0,t),n}exportRenderTarget(e,t="auto",i=0){const n=this._withResolvedTarget(e,i,u=>this.exportRenderTarget(u,t,0));if(n)return n;const s=e,a=["image/x-exr"],o=s.textures?.[i]??s.texture;let l=o.type===Yt||o.type===Ut;t==="auto"&&(t=l?"image/x-exr":"image/png"),a.includes(t)||(l=!1);let c;if(l)t!=="image/x-exr"&&(console.warn("RenderManager: mimeType ",t," is not supported for HDR. Using EXR instead"),t="image/x-exr"),c=new H0().parse(this._renderer,s,{textureIndex:i}).buffer;else{const u=this.renderTargetToDataUrl(s,t==="auto"?void 0:t,90,i);c=T_(u.split(",")[1]),t=u.split(";")[0].split(":")[1]}const h=new Blob([c],{type:t});return h.ext=t==="image/x-exr"?"exr":t.split("/")[1],h.__buffer=c,h}_updated(e){this.dispatchEvent({...e,type:"update"})}_createTargetClass(e,t,i){const n=this._processNewTarget,s=this.disposeTarget.bind(this);return new class extends e{constructor(o,...l){super(...l),this.renderManager=o,this.assetType="renderTarget",this.name="RenderTarget",this._ui_isPrimitive=!0,this.uuid=Oi();const h=l[l.length-1]?.colorSpace;this._initTexture(h)}get texture(){return this.textures[0]}set texture(o){this.textures[0]=o}_initTexture(o){const l=c=>{o!==void 0&&(c.colorSpace=o),c.userData||(c.userData={}),c._target=this,c.toJSON=()=>({isRenderTargetTexture:!0})};Array.isArray(this.textures)&&this.textures.length>1?this.textures.forEach(l):l(this.texture)}setSize(o,l,c){return super.setSize(Math.floor(o),Math.floor(l),c),this}clone(o=!0){if(this.isTemporary)throw"Cloning temporary render targets not supported";if(Array.isArray(this.texture))throw"Cloning multiple render targets not supported";const l=new this.constructor(this.renderManager);l.copy(this),l._initTexture((Array.isArray(this.texture)?this.texture[0]:this.texture)?.colorSpace);const c=l.texture;return Array.isArray(c)?c.forEach(h=>h.isRenderTargetTexture=!0):c.isRenderTargetTexture=!0,n(l,this.sizeMultiplier||1,o)}dispose(o=!1){o===!0?s(this,!0):super.dispose()}}(this,...t,i)}get displayCanvasScaling(){return console.error("displayCanvasScaling is deprecated, use renderScale instead"),this.renderScale}set displayCanvasScaling(e){console.error("displayCanvasScaling is deprecated, use renderScale instead"),this.renderScale=e}},f.RenderManager.POWER_PREFERENCE="high-performance",f.RenderManager.ShaderChunk=lt,f.RenderManager.ShaderLib=Di,Ma([dl("Render Size")],f.RenderManager.prototype,"_renderSize",2),Ma([Fe("Render Scale",[.1,8],.05)],f.RenderManager.prototype,"renderScale",1),Ma([G(),Li("Shadow Map Type",["BasicShadowMap","PCFShadowMap","PCFSoftShadowMap","VSMShadowMap"].map((r,e)=>({label:r,value:e})),{tags:["advanced"]}),jt({obj:"shadowMap",key:"type",onChange:f.RenderManager.prototype._shadowMapTypeChanged})],f.RenderManager.prototype,"shadowMapType",2),Ma([jt({obj:"renderer",key:"shadowMap"})],f.RenderManager.prototype,"shadowMap",2),Ma([Bi(void 0,{label:"Passes",tags:["advanced"],order:1e3})],f.RenderManager.prototype,"_passes",2),Ma([se(),G()],f.RenderManager.prototype,"stableNoise",2),Ma([Zt(f.RenderManager.prototype.rebuildPipeline)],f.RenderManager.prototype,"autoBuildPipeline",2),Ma([ct("Rebuild Pipeline",{sendArgs:!1,tags:["advanced"]})],f.RenderManager.prototype,"rebuildPipeline",1),f.RenderManager=Ma([Vc("RenderManager"),vt("Render Manager")],f.RenderManager);var qV=Object.defineProperty,XV=Object.getOwnPropertyDescriptor,nI=(r,e,t,i)=>{for(var n=i>1?void 0:i?XV(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&qV(e,t,n),n};f.ViewerRenderManager=class extends f.RenderManager{constructor({rgbm:e=!0,msaa:t=!1,depthBuffer:i=!0,stencilBuffer:n=!1,...s}){super({...s,targetOptions:{samples:0,colorSpace:e?Fs:ai,type:e?Qt:Yt,depthBuffer:i,stencilBuffer:n,generateMipmaps:!1,minFilter:at}}),this.rgbm=e,this.msaa=t&&this.isWebGL2,this.depthBuffer=i,this.zPrepass=s.zPrepass||!1,this.maxHDRIntensity=s.maxHDRIntensity??(e?16:72);let a=!0;this._renderer.userData||(a=!1,this._renderer.userData={__isIWebGLRenderer:!0}),this._renderer.userData.renderTransmissionPass=!a,this.renderPass=new s0(this),this.screenPass=new f.ScreenPass(s.screenShader||""),this.registerPass(this.renderPass),this.registerPass(this.screenPass)}_gbufferUnpackExtensionChanged(e){this.dispatchEvent({type:"gbufferUnpackExtensionChanged",...e})}render(e,t){const i=this.screenPass.clipBackgroundForce;if(this.rgbm){const n=!e.background&&!e.backgroundColor;n!==i&&(this.screenPass.clipBackgroundForce=n)}super.render(e,t)}},f.ViewerRenderManager.DEFAULT_MSAA_SAMPLES=4,nI([rt(f.ViewerRenderManager.prototype._gbufferUnpackExtensionChanged)],f.ViewerRenderManager.prototype,"gbufferUnpackExtension",2),f.ViewerRenderManager=nI([vt("Render Manager")],f.ViewerRenderManager);const Hb=class Hb extends mt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.fromJSON=void 0,this._lastFrameTime=0,this._lastPreFrameTime=0,this._updaters=[],this._timelineUpdaters=[],this.dependencies=[],this._fadeDisabled=!1,this.disableFrameFade=!0,this.autoIncrementTime=!0,this._postFrame=()=>{if(!this._viewer)return;if(this.isDisabled()||Object.keys(this._updaters).length<1){this._lastFrameTime=0,this._fadeDisabled&&(this._viewer.getPlugin("FrameFade")?.enable(this),this._fadeDisabled=!1);return}let t;if(this.autoIncrementTime){const i=Cn()/1e3;this._lastFrameTime<1&&(this._lastFrameTime=i-1/60),t=i-this._lastFrameTime,this._lastFrameTime=i;const n=this._viewer.getPlugin("Progressive")?.postFrameConvergedRecordingDelta();n&&n>0&&(t=n),n===0&&(t=0)}else{const i=this._viewer.timeline.time;t=i-this._lastFrameTime,this._lastFrameTime=i}if(t*=1e3,!(Math.abs(t)<=1e-4)&&(this._updaters.forEach(i=>{let n=t;i.time+n<0&&(n=-i.time),i.time+=n,Math.abs(n)>.001&&i.u(n)}),!this._fadeDisabled&&this.disableFrameFade)){const i=this._viewer.getPlugin("FrameFade");i&&(i.disable(this),this._fadeDisabled=!0)}},this._preFrame=()=>{if(!this._viewer)return;if(this.isDisabled()||Object.keys(this._timelineUpdaters).length<1){this._lastPreFrameTime=0;return}const t=this._viewer.timeline.time*1e3,i=t-this._lastPreFrameTime;this._lastPreFrameTime=t,!(Math.abs(i)<=1e-4)&&this._timelineUpdaters.forEach(n=>{let s=i;n.time!==t&&(s=t-n.time),n.time+s<0&&(s=-n.time),n.time+=s,Math.abs(s)>.001&&n.u(s)})},this.defaultDriver=t=>({start:()=>this._updaters.push({u:t,time:0}),stop:()=>{const i=this._updaters.findIndex(n=>n.u===t);i>=0&&this._updaters.splice(i,1)}}),this.timelineDriver=t=>({start:()=>this._timelineUpdaters.push({u:t,time:0}),stop:()=>{const i=this._timelineUpdaters.findIndex(n=>n.u===t);i>=0&&this._timelineUpdaters.splice(i,1)}}),this.animations={},this.enabled=e,this._postFrame=this._postFrame.bind(this)}onAdded(e){super.onAdded(e),e.addEventListener("postFrame",this._postFrame),e.addEventListener("preFrame",this._preFrame)}onRemove(e){e.removeEventListener("postFrame",this._postFrame),super.onRemove(e)}animate(e,t){const{target:i,key:n,...s}={...e};let a=s.from,o=s.to;if(i!==void 0){if(n===void 0)throw new Error("PopmotionPlugin - key must be defined when animating in target");n in i||(this._viewer?.console.warn("PopmotionPlugin - key not present in target, creating",n,i),i[n]=a??0);const c=Qv(i,n),h=()=>i[n];s.lastOnUpdate=s.onUpdate,s.onUpdate=u=>{c(u),s.lastOnUpdate&&s.lastOnUpdate(u)},a===void 0&&(!Array.isArray(o)||o.length<2)&&(a=h())}const l=this.createAnimationResult(s);return l.promise=new Promise((c,h)=>{const u=()=>{try{s.onEnd&&s.onEnd()}catch(g){return h(g),!1}return!0},d=a??(Array.isArray(o)?o[0]:a);if(d===void 0){console.warn("from is undefined",s),c();return}const p=typeof d=="boolean";Array.isArray(o)&&o.length<2&&(o=o[0]);const m={...s,driver:s.driver||this.defaultDriver,to:o,from:a,onUpdate:g=>{s.onUpdate&&(p?s.onUpdate(g>=1):s.onUpdate(g))},onComplete:async()=>{try{s.onComplete&&await s.onComplete()}catch(g){if(!u())return;h(g);return}u()&&c()},onStop:async()=>{try{s.onStop&&await s.onStop()}catch(g){if(!u())return;h(g);return}c()}},A=t?t(m):Hv(m);l._stop=A.stop,l.options=m}).then(()=>(delete this.animations[l.id],l.id)),l}async animateAsync(e,t){const i=this.animate(e);return t&&t.push(i),i.promise}animateNumber(e){let t=e.from??0;return this.animate({...e,from:t,to:e.to??1,onUpdate:i=>{const n=i-t;t=i,e.onUpdate&&e.onUpdate(i,n)}})}timeout(e,t){return this.animate({from:0,to:e,duration:e,...t})}async animateTargetAsync(e,t,i,n){const s=this.animate({...i,target:e,key:t});return n&&n.push(s),s.promise}animateTarget(e,t,i){return this.animate({...i,target:e,key:t})}animateCamera(e,t,i=!0,n){const s=i?DM(e,t):RM(e,t);let a=(n?.duration??1e3)*(t.duration??1);if(n?.normalizeDuration&&a>0){const o=e.getWorldPosition(new S),l=o.distanceTo(t.position)+e.target.distanceTo(t.target);if(l<.001){s.onComplete?.();const h=this.createAnimationResult();return h.promise=Promise.resolve(h.id).then(()=>(delete this.animations[h.id],h.id)),h}const c=Math.max(o.distanceTo(e.target),.1);a=Math.max(100,a*Math.min(1,l/c))}return this.animate({ease:Kc.linear,...s,...n,duration:a})}async animateCameraAsync(e,t,i=!0,n,s){const a=this.animateCamera(e,t,i,n);return s&&s.push(a),a.promise}createAnimationResult(e={}){const t=Oi();return this.animations[t]={id:t,options:e,stop:()=>this.stopAnimationResult(t),stopped:!1,_stop:()=>{},anims:[],promise:void 0}}stopAnimationResult(e){const t=this.animations[e];!t||t.stopped||(t._stop?typeof t._stop=="function"&&t._stop():console.warn("Animation not started"),t.anims?.forEach(i=>i.stop()),t.stopped=!0)}animateObject(e,t,i=!0,n,s){const{key:a,tar:o,onChange:l}=Xv(e);let c=a;o&&c&&!(c in o)&&(console.error("PopmotionPlugin invalid key",c,o,e),c=void 0);const h=this.createAnimationResult(e.options);i&&(e.result=h),t=(t||0)+((s??e.delay)||0),h.anims=e.animSet?[...h.anims,this.animateSet(e.animSet,e.animSetParallel??!1,t,i,n)]:h.anims;const u=e.updater??[],d=!c||!o?{to:[0,1]}:{target:o,key:c,to:e.values,offset:e.offsets};return h.anims.push(this.animate({...d,driver:n,ease:typeof e.ease=="string"?Kc[e.ease]:e.ease,duration:e.duration,...e.options,canComplete:i,delay:t,onUpdate:p=>{e.options.onUpdate&&e.options.onUpdate(p),l&&l(),u.forEach(m=>m&&m())}},gk)),h.promise=Promise.all(h.anims.map(async p=>p.promise)).then(()=>(h.anims=[],delete this.animations[h.id],e.result===h&&(e.result=void 0),h.id)),h}animateSet(e,t=!1,i=0,n=!0,s){const a=this.createAnimationResult();if(t)a.anims=e.map(o=>this.animateObject(o,i,n,s));else{let o=i;for(const l of e){a.anims.push(this.animateObject(l,o,n,s));const{delay:c=0,duration:h=0,options:u}=l;o+=c+h+(h+(u.repeatDelay||0))*(u.repeat||0)}}return a.promise=Promise.all(a.anims.map(async o=>o.promise)).then(()=>(a.anims=[],delete this.animations[a.id],a.id)),a}};Hb.PluginType="PopmotionPlugin";let Gr=Hb;var YV=Object.defineProperty,$V=Object.getOwnPropertyDescriptor,Mn=(r,e,t,i)=>{for(var n=i>1?void 0:i?$V(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&YV(e,t,n),n};f.InteractionPromptPlugin=class extends mt{constructor(e=!0){super(),this.animationRunning=!1,this.animationDuration=2e3,this.animationDistance=80,this.animationPauseDuration=6e3,this.rotationDistance=.3,this.yOffset=0,this.autoStart=!0,this.autoStartDelay=3e4,this.autoStop=!0,this.autoStartOnObjectLoad=!0,this.autoStartOnObjectLoadDelay=3e3,this.currentTime=0,this.lastActionTime=1/0,this.pointerIcon=`<svg xmlns="http://www.w3.org/2000/svg" style="transform: translate(-50%, -25%);" xmlns:xlink="http://www.w3.org/1999/xlink" width="25" height="36">
    <defs>
        <path id="A" d="M.001.232h24.997V36H.001z"></path>
    </defs>
    <g transform="translate(-11 -4)" fill="none" fill-rule="evenodd">
        <path fill-opacity="0" fill="#fff" d="M0 0h44v44H0z"></path>
        <g transform="translate(11 3)">
            <path d="M8.733 11.165c.04-1.108.766-2.027 1.743-2.307a2.54 2.54 0 0 1 .628-.089c.16 0 .314.017.463.044 1.088.2 1.9 1.092 1.9 2.16v8.88h1.26c2.943-1.39 5-4.45 5-8.025a9.01 9.01 0 0 0-1.9-5.56l-.43-.5c-.765-.838-1.683-1.522-2.712-2-1.057-.49-2.226-.77-3.46-.77s-2.4.278-3.46.77c-1.03.478-1.947 1.162-2.71 2l-.43.5a9.01 9.01 0 0 0-1.9 5.56 9.04 9.04 0 0 0 .094 1.305c.03.21.088.41.13.617l.136.624c.083.286.196.56.305.832l.124.333a8.78 8.78 0 0 0 .509.953l.065.122a8.69 8.69 0 0 0 3.521 3.191l1.11.537v-9.178z" fill-opacity=".5" fill="#e4e4e4"></path>
            <path d="M22.94 26.218l-2.76 7.74c-.172.485-.676.8-1.253.8H12.24c-1.606 0-3.092-.68-3.98-1.82-1.592-2.048-3.647-3.822-6.11-5.27-.095-.055-.15-.137-.152-.23-.004-.1.046-.196.193-.297.56-.393 1.234-.6 1.926-.6a3.43 3.43 0 0 1 .691.069l4.922.994V10.972c0-.663.615-1.203 1.37-1.203s1.373.54 1.373 1.203v9.882h2.953c.273 0 .533.073.757.21l6.257 3.874c.027.017.045.042.07.06.41.296.586.77.426 1.22M4.1 16.614c-.024-.04-.042-.083-.065-.122a8.69 8.69 0 0 1-.509-.953c-.048-.107-.08-.223-.124-.333l-.305-.832c-.058-.202-.09-.416-.136-.624l-.13-.617a9.03 9.03 0 0 1-.094-1.305c0-2.107.714-4.04 1.9-5.56l.43-.5c.764-.84 1.682-1.523 2.71-2 1.058-.49 2.226-.77 3.46-.77s2.402.28 3.46.77c1.03.477 1.947 1.16 2.712 2l.428.5a9 9 0 0 1 1.901 5.559c0 3.577-2.056 6.636-5 8.026h-1.26v-8.882c0-1.067-.822-1.96-1.9-2.16-.15-.028-.304-.044-.463-.044-.22 0-.427.037-.628.09-.977.28-1.703 1.198-1.743 2.306v9.178l-1.11-.537C6.18 19.098 4.96 18 4.1 16.614M22.97 24.09l-6.256-3.874c-.102-.063-.218-.098-.33-.144 2.683-1.8 4.354-4.855 4.354-8.243 0-.486-.037-.964-.104-1.43a9.97 9.97 0 0 0-1.57-4.128l-.295-.408-.066-.092a10.05 10.05 0 0 0-.949-1.078c-.342-.334-.708-.643-1.094-.922-1.155-.834-2.492-1.412-3.94-1.65l-.732-.088-.748-.03a9.29 9.29 0 0 0-1.482.119c-1.447.238-2.786.816-3.94 1.65a9.33 9.33 0 0 0-.813.686 9.59 9.59 0 0 0-.845.877l-.385.437-.36.5-.288.468-.418.778-.04.09c-.593 1.28-.93 2.71-.93 4.222 0 3.832 2.182 7.342 5.56 8.938l1.437.68v4.946L5 25.64a4.44 4.44 0 0 0-.888-.086c-.017 0-.034.003-.05.003-.252.004-.503.033-.75.08a5.08 5.08 0 0 0-.237.056c-.193.046-.382.107-.568.18-.075.03-.15.057-.225.1-.25.114-.494.244-.723.405a1.31 1.31 0 0 0-.566 1.122 1.28 1.28 0 0 0 .645 1.051C4 29.925 5.96 31.614 7.473 33.563a5.06 5.06 0 0 0 .434.491c1.086 1.082 2.656 1.713 4.326 1.715h6.697c.748-.001 1.43-.333 1.858-.872.142-.18.256-.38.336-.602l2.757-7.74c.094-.26.13-.53.112-.794s-.088-.52-.203-.76a2.19 2.19 0 0 0-.821-.91" fill-opacity=".6" fill="#000"></path>
            <path d="M22.444 24.94l-6.257-3.874a1.45 1.45 0 0 0-.757-.211h-2.953v-9.88c0-.663-.616-1.203-1.373-1.203s-1.37.54-1.37 1.203v16.643l-4.922-.994a3.44 3.44 0 0 0-.692-.069 3.35 3.35 0 0 0-1.925.598c-.147.102-.198.198-.194.298.004.094.058.176.153.23 2.462 1.448 4.517 3.22 6.11 5.27.887 1.14 2.373 1.82 3.98 1.82h6.686c.577 0 1.08-.326 1.253-.8l2.76-7.74c.16-.448-.017-.923-.426-1.22-.025-.02-.043-.043-.07-.06z" fill="#fff"></path>
            <g transform="translate(0 .769)">
                <mask id="B" fill="#fff">
                    <use xlink:href="#A"></use>
                </mask>
                <path d="M23.993 24.992a1.96 1.96 0 0 1-.111.794l-2.758 7.74c-.08.22-.194.423-.336.602-.427.54-1.11.87-1.857.872h-6.698c-1.67-.002-3.24-.633-4.326-1.715-.154-.154-.3-.318-.434-.49C5.96 30.846 4 29.157 1.646 27.773c-.385-.225-.626-.618-.645-1.05a1.31 1.31 0 0 1 .566-1.122 4.56 4.56 0 0 1 .723-.405l.225-.1a4.3 4.3 0 0 1 .568-.18l.237-.056c.248-.046.5-.075.75-.08.018 0 .034-.003.05-.003.303-.001.597.027.89.086l3.722.752V20.68l-1.436-.68c-3.377-1.596-5.56-5.106-5.56-8.938 0-1.51.336-2.94.93-4.222.015-.03.025-.06.04-.09.127-.267.268-.525.418-.778.093-.16.186-.316.288-.468.063-.095.133-.186.2-.277L3.773 5c.118-.155.26-.29.385-.437.266-.3.544-.604.845-.877a9.33 9.33 0 0 1 .813-.686C6.97 2.167 8.31 1.59 9.757 1.35a9.27 9.27 0 0 1 1.481-.119 8.82 8.82 0 0 1 .748.031c.247.02.49.05.733.088 1.448.238 2.786.816 3.94 1.65.387.28.752.588 1.094.922a9.94 9.94 0 0 1 .949 1.078l.066.092c.102.133.203.268.295.408a9.97 9.97 0 0 1 1.571 4.128c.066.467.103.945.103 1.43 0 3.388-1.67 6.453-4.353 8.243.11.046.227.08.33.144l6.256 3.874c.37.23.645.55.82.9.115.24.185.498.203.76m.697-1.195c-.265-.55-.677-1.007-1.194-1.326l-5.323-3.297c2.255-2.037 3.564-4.97 3.564-8.114 0-2.19-.637-4.304-1.84-6.114-.126-.188-.26-.37-.4-.552-.645-.848-1.402-1.6-2.252-2.204C15.472.91 13.393.232 11.238.232A10.21 10.21 0 0 0 5.23 2.19c-.848.614-1.606 1.356-2.253 2.205-.136.18-.272.363-.398.55C1.374 6.756.737 8.87.737 11.06c0 4.218 2.407 8.08 6.133 9.842l.863.41v3.092l-2.525-.51c-.356-.07-.717-.106-1.076-.106a5.45 5.45 0 0 0-3.14.996c-.653.46-1.022 1.202-.99 1.983a2.28 2.28 0 0 0 1.138 1.872c2.24 1.318 4.106 2.923 5.543 4.772 1.26 1.62 3.333 2.59 5.55 2.592h6.698c1.42-.001 2.68-.86 3.134-2.138l2.76-7.74c.272-.757.224-1.584-.134-2.325" fill-opacity=".05" fill="#000" mask="url(#B)"></path>
            </g>
        </g>
    </g>
</svg>`,this._mainCameraUpdate=t=>{this.isDisabled()||(t.change==="deserialize"&&this.animationRunning?(this.stopAnimation({reset:!1}),this.startAnimation()):this._startedOnce&&(this.lastActionTime=Cn()))},this._startedOnce=!1,this._addSceneObject=()=>{this.autoStartOnObjectLoad&&!this._startedOnce&&(this.lastActionTime=Cn()-this.autoStartDelay+this.autoStartOnObjectLoadDelay)},this.onlyOnOrbitControls=!0,this._orbitWarning=!1,this.startAnimation=()=>{if(!(!this._viewer||!this.cursorEl||this.isDisabled())){if(this._viewer.scene.mainCamera.controls?.type!=="OrbitControls"&&this.onlyOnOrbitControls){this._orbitWarning||console.warn("InteractionPromptPlugin requires OrbitControls, to run anyway, set onlyOnOrbitControls to false"),this._orbitWarning=!0;return}this._viewer.scene.modelRoot.children.length!==0&&(this.currentSphericalPosition=new Ir().setFromVector3(new S().subVectors(this._viewer.scene.mainCamera.position,this._viewer.scene.mainCamera.target)),this.cursorEl.style.opacity="1",this.currentTime=0,this.animationRunning=!0,this._startedOnce=!0,this._viewer.scene.mainCamera.setInteractions(!1,f.InteractionPromptPlugin.PluginType))}},this.stopAnimation=async({reset:t=!0}={})=>{if(!(!this._viewer||!this.cursorEl))return this.animationRunning=!1,this.cursorEl.style.opacity="0",this.currentSphericalPosition&&t&&(this._viewer.scene.mainCamera.position.setFromSpherical(this.currentSphericalPosition).add(this._viewer.scene.mainCamera.target),this._viewer.scene.mainCamera.setDirty(),this.currentSphericalPosition=void 0),this._viewer.scene.mainCamera.setInteractions(!0,f.InteractionPromptPlugin.PluginType),this._viewer.doOnce("postFrame")},this._pointerDown=()=>{this.isDisabled()||(this.autoStop&&this.stopAnimation({reset:!1}),this.lastActionTime=Cn())},this._x=0,this._preFrame=async t=>{if(!this._viewer||!this.cursorEl||(this.isDisabled()&&this.animationRunning&&this.stopAnimation(),this.isDisabled())||(!this.animationRunning&&this.autoStart&&this.lastActionTime+this.autoStartDelay<Cn()&&this.startAnimation(),!this.animationRunning))return;if(this.currentTime<=this.animationDuration){this.cursorEl.style.opacity="1";const a=this.currentTime/this.animationDuration;this._x=Math.sin(Math.PI*2*a),(a<.25||a>.75)&&(this._x*=this._x*Math.sign(this._x))}else this.cursorEl.style.opacity="0",this._x=0;if(this.currentTime<=this.animationDuration+50){const a=this.currentSphericalPosition.clone();a.theta+=this._x*this.rotationDistance,this._viewer.scene.mainCamera.position.setFromSpherical(a).add(this._viewer.scene.mainCamera.target),this._viewer.scene.mainCamera.setDirty()}const i=this._viewer.container.getBoundingClientRect(),n=i.width/2+-this._x*Math.min(this.animationDistance,i.width/4),s=i.height/2+this.yOffset*i.height/2;this.cursorEl.style.transform=`translate(${Math.floor(n)}px, ${Math.floor(s)}px)`,this.currentTime+=t.deltaTime,this.currentTime>this.animationDuration+this.animationPauseDuration&&(this.currentTime=0)},this.enabled=e}onAdded(e){super.onAdded(e);{Wn(e.plugins,"InteractionPointerPlugin")&&delete e.plugins.InteractionPointerPlugin;const t=this;Object.defineProperty(e.plugins,"InteractionPointerPlugin",{get(){return console.warn("InteractionPromptPlugin: PluginType renamed from InteractionPointerPlugin to InteractionPromptPlugin. Please update your code/vjson."),t},configurable:!0})}this.lastActionTime=1/0,e.addEventListener("preFrame",this._preFrame),e.container.addEventListener("pointerdown",this._pointerDown,!0),e.container.addEventListener("wheel",this._pointerDown,!0),e.scene.addEventListener("addSceneObject",this._addSceneObject),e.scene.addEventListener("mainCameraUpdate",this._mainCameraUpdate),this._initializeCursor()}onRemove(e){return this.stopAnimation(),e.removeEventListener("preFrame",this._preFrame),e.container.removeEventListener("pointerdown",this._pointerDown,!0),e.container.removeEventListener("wheel",this._pointerDown,!0),e.scene.removeEventListener("addSceneObject",this._addSceneObject),e.scene.removeEventListener("mainCameraUpdate",this._mainCameraUpdate),this.cursorEl&&this.cursorEl.remove(),super.onRemove(e)}_pointerIconChanged(){this.cursorEl&&(this.cursorEl.innerHTML=this.pointerIcon)}_initializeCursor(){this.cursorEl=document.createElement("div"),this.cursorEl.style.position="absolute",this.cursorEl.style.top="0",this.cursorEl.style.left="0",this.cursorEl.style.width="10px",this.cursorEl.style.height="10px",this.cursorEl.style.opacity="0",this._pointerIconChanged(),this._viewer.container.appendChild(this.cursorEl)}},f.InteractionPromptPlugin.PluginType="InteractionPromptPlugin",Mn([G(),se()],f.InteractionPromptPlugin.prototype,"enabled",2),Mn([G(),He()],f.InteractionPromptPlugin.prototype,"animationDuration",2),Mn([G(),He()],f.InteractionPromptPlugin.prototype,"animationDistance",2),Mn([G(),He()],f.InteractionPromptPlugin.prototype,"animationPauseDuration",2),Mn([G(),He()],f.InteractionPromptPlugin.prototype,"rotationDistance",2),Mn([G(),He()],f.InteractionPromptPlugin.prototype,"yOffset",2),Mn([G(),se()],f.InteractionPromptPlugin.prototype,"autoStart",2),Mn([G(),He()],f.InteractionPromptPlugin.prototype,"autoStartDelay",2),Mn([G(),se()],f.InteractionPromptPlugin.prototype,"autoStop",2),Mn([G(),se()],f.InteractionPromptPlugin.prototype,"autoStartOnObjectLoad",2),Mn([G(),se()],f.InteractionPromptPlugin.prototype,"autoStartOnObjectLoadDelay",2),Mn([dl()],f.InteractionPromptPlugin.prototype,"currentTime",2),Mn([dl()],f.InteractionPromptPlugin.prototype,"lastActionTime",2),Mn([he(f.InteractionPromptPlugin.prototype._pointerIconChanged)],f.InteractionPromptPlugin.prototype,"pointerIcon",2),Mn([G()],f.InteractionPromptPlugin.prototype,"onlyOnOrbitControls",2),Mn([ct()],f.InteractionPromptPlugin.prototype,"startAnimation",2),Mn([ct()],f.InteractionPromptPlugin.prototype,"stopAnimation",2),f.InteractionPromptPlugin=Mn([vt("Interaction Prompt")],f.InteractionPromptPlugin);var KV=Object.defineProperty,JV=Object.getOwnPropertyDescriptor,Bs=(r,e,t,i)=>{for(var n=i>1?void 0:i?JV(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&KV(e,t,n),n};const os=(Qr=class extends mt{constructor(e={}){super(),this.enabled=!0,this._cameraViews=[],this.viewLooping=!1,this.viewPauseTime=200,this.animEase="easeInOutSine",this.animDuration=1e3,this.interpolateMode="spherical",this.rotationOffset=.25,this._animating=!1,this.dependencies=[Gr],this.focusNext=(t=!0)=>{if(this._animating||this._cameraViews.length<2)return;let i=this._cameraViews.findIndex(n=>n===this._currentView);i<0&&(i=-1),i=i+1,t?i=i%this._cameraViews.length:i=Math.min(i,this._cameraViews.length-1),this.animateToView(i)},this.focusPrevious=(t=!0)=>{if(this._animating||this._cameraViews.length<2||!this._currentView)return;let i=this._cameraViews.findIndex(n=>n===this._currentView);i<0&&(i=0),i=i-1,t?i=(i+this._cameraViews.length)%this._cameraViews.length:i=Math.max(i,0),this.animateToView(i)},this._popAnimations=[],this.uiConfig={type:"folder",label:"Camera Views",children:[()=>[...this._cameraViews.map(t=>t.uiConfig)],...bi(this)||[]]},this._viewQueue=[],this._animationLooping=!1,this._infiniteLooping=!0,this._viewSetView=({view:t,camera:i})=>{if(!t){this._viewer?.console.warn("Invalid view",t);return}this.setView(t,i)},this._viewUpdateView=({view:t,camera:i})=>{if(!t){this._viewer?.console.warn("Invalid view",t);return}const n=t.name;this.getView(i,t.isWorldSpace??!0,t),t.name=n},this._viewDeleteView=({view:t})=>{if(!t){this._viewer?.console.warn("Invalid view",t);return}this.deleteView(t)},this._viewAnimateView=async({view:t,camera:i,duration:n,easing:s,throwOnStop:a})=>{if(!t){this._viewer?.console.warn("Invalid view",t);return}return this.animateToView(t,n||this.animDuration,s||this.animEase,i,a)},this._viewUpdated=async t=>{this._cameraViews.includes(t.target)&&(this.dispatchEvent({type:"viewUpdate",view:t.target}),this.setDirty({key:"cameraViews",change:"viewUpdate"}))},this._lastAnimTime=-1,this.addCurrentView=this.addCurrentView.bind(this),this.resetToFirstView=this.resetToFirstView.bind(this),this.animateAllViews=this.animateAllViews.bind(this),this._postFrame=this._postFrame.bind(this),this.setDirty=this.setDirty.bind(this),this.animDuration=e.duration??this.animDuration,this.animEase=e.ease??this.animEase,this.interpolateMode=e.interpolateMode??this.interpolateMode}get cameraViews(){return this._cameraViews}get camViews(){return this._cameraViews}get animating(){return this._animating}onAdded(e){super.onAdded(e),e.addEventListener("preFrame",t=>{}),e.addEventListener("postFrame",this._postFrame)}onRemove(e){return e.removeEventListener("postFrame",this._postFrame),super.onRemove(e)}async resetToFirstView(e=100){this.isDisabled()||(this._currentView=void 0,await this.animateToView(0,e),await Qn(2))}async addCurrentView(){if(this.isDisabled())return;const e=this._viewer?.scene.mainCamera;if(!e)return;const t=this.getView(e);return this.addView(t),t.name="View "+this._cameraViews.length,t}addView(e,t=!1){e.addEventListener("setView",this._viewSetView),e.addEventListener("updateView",this._viewUpdateView),e.addEventListener("deleteView",this._viewDeleteView),e.addEventListener("animateView",this._viewAnimateView),e.addEventListener("update",this._viewUpdated);const i=this._cameraViews.includes(e);(!i||t)&&(i||this._cameraViews.push(e),this.setDirty({key:"cameraViews",change:"viewAdd"}),this.dispatchEvent({type:"viewAdd",view:e}))}deleteView(e,t=!1){const i=this._cameraViews.indexOf(e);e.removeEventListener("setView",this._viewSetView),e.removeEventListener("updateView",this._viewUpdateView),e.removeEventListener("deleteView",this._viewDeleteView),e.removeEventListener("animateView",this._viewAnimateView),e.removeEventListener("update",this._viewUpdated),(i>=0||t)&&(i>=0&&this._cameraViews.splice(i,1),this.setDirty({key:"cameraViews",change:"viewDelete"}),this.dispatchEvent({type:"viewDelete",view:e}))}getView(e,t=!0,i){return e=e||this._viewer?.scene.mainCamera,e?e.getView(t,i):i??new f.CameraView}setView(e,t){t=t||this._viewer?.scene.mainCamera,t&&t.setView(e)}async animateToView(e,t,i,n,s=!1,a){if(n=n||this._viewer?.scene.mainCamera,!n)return;if(this._animating){this._popAnimations.forEach(d=>d?.stop&&d.stop()),this._popAnimations=[];let u=0;for(;this._animating&&(await Qn(100),!(u++>20)););if(this._animating){console.warn("Unable to stop all animations, maybe because of viewLooping?");return}}const o=typeof e=="number"?this._cameraViews[e]:typeof e=="string"?this._cameraViews.find(u=>u.name===e):e;if(!o){this._viewer?.console.warn("Invalid view",e);return}a=a??t===void 0;const l=this._viewer?.getPlugin(f.InteractionPromptPlugin);l&&l.animationRunning&&await l.stopAnimation({reset:!0}),this._currentView=o,this._animating=!0,n.setInteractions&&n.setInteractions(!1,Qr.PluginType),n.userData.autoLookAtTarget||console.warn("CameraViewPlugin: camera autoLookAtTarget is disabled, camera look at might not be correct during animation"),this.dispatchEvent({type:"startViewChange",view:o});const c=this._viewer?.getPlugin(Gr);if(!c)throw new Error("PopmotionPlugin not found");const h=typeof i=="function"?i:Kc[i||this.animEase];this._popAnimations=[],await c.animateCameraAsync(n,o,this.interpolateMode==="spherical",{ease:h,duration:t,normalizeDuration:a},this._popAnimations).catch(u=>{if(s)throw u}),this._viewer?.scene.mainCamera.setInteractions(!0,Qr.PluginType),this._animating=!1,this._viewer?.setDirty(),this.dispatchEvent({type:"viewChange",view:o}),await Qn(10)}async animateAllViews(){if(!this.isDisabled()&&!(this.viewLooping||this._cameraViews.length<2)){for(;this._viewQueue.length>0;)this._viewQueue.pop();this._viewQueue.push(...this._cameraViews),this._viewQueue.push(this._viewQueue.shift()),this._infiniteLooping=!1,await this._animationLoop(),this._infiniteLooping=!0}}async stopAllAnimations(){for(this.viewLooping=!1,this._popAnimations.forEach(e=>e?.stop?.()),this._popAnimations=[];this._animating||this._animationLooping;)await Qn(100)}fromJSON(e,t){return this._cameraViews.forEach(i=>this.deleteView(i)),super.fromJSON(e,t)?(this._cameraViews.forEach(i=>this.addView(i,!0)),this.uiConfig?.uiRefresh?.(),this):null}setDirty(e){this.uiConfig?.uiRefresh?.(!1,"postFrame"),this.dispatchEvent({...e,type:"update"})}async animateToObject(e,t=4,i,n,s={min:.5,max:5}){if(!this._viewer)return;const a=new En().expandByObject(e||this._viewer.scene.modelRoot,!1,!0),o=a.getCenter(new S),c=a.getSize(new S).length()/2;await this.animateToTarget(Math.min(s.max,Math.max(s.min,c*t)),o,i,n)}_resolveSelectedObjects(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap(t=>t?.isTexture?[...t.appliedObjects?.values()||[]]:t).flatMap(t=>t?.isMaterial?[...t.appliedMeshes?.values()||[]]:t?.isBufferGeometry?[...t.appliedMeshes?.values()||[]]:t).filter(Boolean)}async animateToFitObject(e,t=1.5,i,n,s={min:.5,max:50}){if(!this._viewer)return;const a=this._resolveSelectedObjects(e),o=a.length?a:[this._viewer.scene.modelRoot];if(i===0){this._viewer.scene.mainCamera.fitObject(o,t,s);return}const l=new En().expandByObject(o[0],!1,!0);for(let d=1;d<o.length;d++)l.expandByObject(o[d],!1,!0);const c=Vm(this._viewer.scene.mainCamera,l),h=l.getCenter(new S);l.getSize(new S).lengthSq()<=0&&o[0].getWorldPosition(h),await this.animateToTarget(Math.min(s.max,Math.max(s.min,c*t)),h,i,n)}async animateToTarget(e,t,i,n){const s=this.getView();s.target.copy(t);const a=new S().subVectors(s.target,s.position).normalize();if(s.position.copy(a.multiplyScalar(-e).add(s.target)),i===0){this.setView(s),this._viewer?.setDirty();return}await this.animateToView(s,i,n,void 0,!1,!0)}get animationLooping(){return this._animationLooping}async _animationLoop(){if(!this._animationLooping){for(this._animationLooping=!0;(this.viewLooping||!this._infiniteLooping)&&!(this.isDisabled()||this._cameraViews.length<1);){if(this._viewQueue.length===0)if(this._infiniteLooping)this._viewQueue.push(...this._cameraViews);else break;await this.animateToView(this._viewQueue.shift()),await Qn(2+this.viewPauseTime)}this._animationLooping=!1}}getCurrentCameraView(e,t=!0){return this.getView(e,t)}setCurrentCameraView(e){return this.setView(e)}async focusView(e){return this.animateToView(e)}_postFrame(){if(!this.enabled||!this._viewer)return;const e=this._viewer.scene.mainCamera;if(!e)return;if(!this._viewer.timeline.shouldRun()||!this._cameraViews.length){e.setInteractions(!0,Qr.PluginType+"-postFrame"),this._lastAnimTime=-1;return}e.setInteractions(!1,Qr.PluginType+"-postFrame");const t=this._viewer.timeline.time;if(t==this._lastAnimTime)return;this._lastAnimTime=t;const i=[],n=this.animDuration||1e3,s=this.viewPauseTime||0,a=this._cameraViews;let o=0;for(let A=0;A<a.length;A++){const g=a[A],y=Math.max(2,g.duration*n)/1e3;i.push({time:o,index:A,duration:y}),o+=y+s/1e3}const l=i.sort((A,g)=>-A.time+g.time).find(A=>A.time<=t);if(!l)return;const c=l.index,h=l.time,u=l.duration??.5,d=u<1e-6?1:(t-h)/u;if(d>1)return;const{getPosition:p,getTarget:m}=sT(this.camViews);return p(d,c,e.position),m(d,c,e.target),e.setDirty(),!0}},Qr.PluginType="CameraViews",Qr);Bs([G("cameraViews")],os.prototype,"_cameraViews",2),Bs([he(os.prototype._animationLoop),G(),se("Loop All Views")],os.prototype,"viewLooping",2),Bs([rt("setDirty"),G(),He("View Pause Time")],os.prototype,"viewPauseTime",2),Bs([rt("setDirty"),G(),Li("Ease",Object.keys(Kc).map(r=>({label:r})))],os.prototype,"animEase",2),Bs([rt("setDirty"),G(),Fe("Duration",[10,1e4],10)],os.prototype,"animDuration",2),Bs([rt("setDirty"),G(),Li("Interpolation",["spherical","linear"].map(r=>({label:r,value:r.split(" ")[0]})))],os.prototype,"interpolateMode",2),Bs([G()],os.prototype,"rotationOffset",2),Bs([ct("Reset To First View",{sendArgs:!1})],os.prototype,"resetToFirstView",1),Bs([ct("Add Current View")],os.prototype,"addCurrentView",1),Bs([ct("Focus Next",{sendArgs:!1})],os.prototype,"focusNext",2),Bs([ct("Focus Previous",{sendArgs:!1})],os.prototype,"focusPrevious",2),Bs([ct("Animate All Views")],os.prototype,"animateAllViews",1),Bs([ct("Stop All Animations")],os.prototype,"stopAllAnimations",1);let Q0=os;var ZV=Object.defineProperty,eH=Object.getOwnPropertyDescriptor,yo=(r,e,t,i)=>{for(var n=i>1?void 0:i?eH(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&ZV(e,t,n),n};f.DropzonePlugin=class extends mt{constructor(e){super(),this.enabled=!0,this._allowedExtensions=void 0,this.autoImport=!0,this.autoAdd=!0,this.importOptions={autoImportZipContents:!0,forceImporterReprocess:!1,useMeshLines:Il.UseMeshLines,createUniqueNames:Il.CreateUniqueNames},this.addOptions={autoCenter:!0,importConfig:!0,autoScale:!0,autoScaleRadius:2,centerGeometries:!1,centerGeometriesKeepPosition:!0,license:"",clearSceneObjects:!1,disposeSceneObjects:!1,autoSetBackground:!1,autoSetEnvironment:!0},e&&(this._domElement=e.domElement,this.allowedExtensions=e.allowedExtensions,this.autoImport=e.autoImport??this.autoImport,this.autoAdd=e.autoAdd??this.autoAdd,this.importOptions={...this.importOptions,...e.importOptions},this.addOptions={...this.addOptions,...e.addOptions})}get allowedExtensions(){return this._allowedExtensions}set allowedExtensions(e){this._allowedExtensions=e,this._inputEl&&(this._inputEl.accept=e?e.map(t=>"."+t).join(", "):"")}promptForFile(){this.isDisabled()||(this.allowedExtensions=this._allowedExtensions,this._inputEl?.click())}async promptForUrl(){if(this.isDisabled()||!this._viewer)return;const e=await this._viewer.dialog.prompt("Enter URL: Enter a public URL for a 3d file with extension","",!0);!e||!e.length||await this.load(e,{},!0)}async load(e,t,i=!1){if(!this._viewer){console.warn("DropzonePlugin: viewer not set");return}if(this.autoImport){const n=this._viewer.assetManager,s=Vu(e);if(this._allowedExtensions&&!this._allowedExtensions.includes(s)){i&&await this._viewer.dialog.alert(`DropzonePlugin: file extension ${s} not allowed`);return}const o=[...await n.importer.import(e,{...this.importOptions,...t??{}})??[]].flat(2).filter(l=>!!l)??[];return this.autoAdd?await n.loadImported(o,{...this.addOptions,...t??{}}):o}else i&&await this._viewer.dialog.alert("DropzonePlugin: autoImport is disabled, file was not imported")}onAdded(e){super.onAdded(e),this._inputEl=document.createElement("input"),this._inputEl.type="file",this._domElement||(this._domElement=e.canvas),this._dropzone=new gm(this._domElement,this._inputEl,{drop:this._onFileDrop.bind(this)}),this.allowedExtensions=this._allowedExtensions}onRemove(e){this._dropzone?.destroy(),this._dropzone=void 0,this._inputEl=void 0,super.onRemove(e)}async _onFileDrop({files:e,nativeEvent:t}){if(!e||this.isDisabled())return;const i=this._viewer;if(!i)return;if(this._allowedExtensions!==void 0)for(const o of e.keys())this._allowedExtensions.includes(o.split(".").pop()?.toLowerCase()??"")||e.delete(o);if(e.size<1)return;const n=i.assetManager;let s,a;if(this.autoImport&&(s=await n.importer.importFiles(e,{allowedExtensions:this.allowedExtensions,...this.importOptions}),this.autoAdd)){const o=[...s?.values()??[]].flat(2).filter(l=>!!l)??[];a=await n.loadImported(o,{...this.addOptions})}this.dispatchEvent({type:"drop",files:e,imported:s,assets:a,nativeEvent:t})}},f.DropzonePlugin.PluginType="Dropzone",f.DropzonePlugin.OldPluginType="DropzonePlugin",yo([se(),G()],f.DropzonePlugin.prototype,"enabled",2),yo([G()],f.DropzonePlugin.prototype,"autoImport",2),yo([se(),G()],f.DropzonePlugin.prototype,"autoAdd",2),yo([Bi(),G()],f.DropzonePlugin.prototype,"importOptions",2),yo([Bi(),G()],f.DropzonePlugin.prototype,"addOptions",2),yo([ct("Select Local files")],f.DropzonePlugin.prototype,"promptForFile",1),yo([ct("Import from URL")],f.DropzonePlugin.prototype,"promptForUrl",1),f.DropzonePlugin=yo([vt("Dropzone")],f.DropzonePlugin);const tH=`
#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )
vec3 Uncharted2ToneMapping(vec3 color){color*=toneMappingExposure;return saturate(Uncharted2Helper(color)/Uncharted2Helper(vec3(1.0)));}vec3 CustomToneMapping(vec3 color){return Uncharted2ToneMapping(color);}`,iH=`int getToneMapBit(in int number){
#ifdef WebGL2Context
return(number/2)% 2;
#else
return int(mod(floor(float(number)/2.),2.));
#endif
}vec3 TonemappingSaturation(vec3 rgb){const vec3 W=vec3(0.2125,0.7154,0.0721);vec3 intensity=vec3(dot(rgb,W));return mix(intensity,rgb,toneMappingSaturation);}vec3 TonemappingContrast(vec3 color){return(color-vec3(0.5))*toneMappingContrast+vec3(0.5);}vec4 ToneMapping(in vec4 color){vec4 outColor=color;
#if defined( TONE_MAPPING )
outColor.rgb=toneMapping(outColor.rgb);outColor.rgb=TonemappingContrast(outColor.rgb);outColor.rgb=TonemappingSaturation(outColor.rgb);
#endif
return outColor;}`,nH=`bool doTonemap=true;
#ifdef HAS_GBUFFER
#ifdef GBUFFER_HAS_FLAGS
doTonemap=getToneMapBit(getGBufferFlags(vUv).a)>0;
#endif
#if TONEMAP_BACKGROUND < 1
if(isBackground)doTonemap=false;
#endif
#endif
if(doTonemap)diffuseColor=ToneMapping(diffuseColor);`;var sH=Object.defineProperty,sI=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&sH(e,t,n),n};const Ug=class extends mt{constructor(){super(),this.enabled=!0,this._beforeRender=this._beforeRender.bind(this)}_beforeRender(e,t,i){return this._pass?(this._pass.enabled=!this.isDisabled(),this._pass.enabled):!1}onAdded(e){super.onAdded(e),this._pass=this._createPass(),this._pass.onDirty?.push(e.setDirty),this._pass.beforeRender=SS(this._beforeRender,this._pass.beforeRender),e.renderManager.registerPass(this._pass)}onRemove(e){this._pass&&(e.renderManager.unregisterPass(this._pass),this._pass.dispose&&this._pass.dispose()),this._pass=void 0,super.onRemove(e)}get pass(){return this._pass}toJSON(e){return super.toJSON(e)}fromJSON(e,t){return super.fromJSON(e,t)}setDirty(){this._pass&&(this._pass.enabled=!this.isDisabled()),this._viewer?.setDirty(),this.uiConfig?.uiRefresh?.(!0,"postFrame",100)}};sI([G(),se("Enabled"),he(Ug.prototype.setDirty)],Ug.prototype,"enabled"),sI([G("pass")],Ug.prototype,"_pass");let Pl=Ug;const rI=`#ifndef UNPACK_GBUFFER_SNIPPET
#define UNPACK_GBUFFER_SNIPPET
uniform sampler2D tNormalDepth;float unpack16(vec2 value){return value.x+value.y/255.0;}vec3 unpackNormal(vec2 enc){vec2 fenc=enc*4.0-2.0;float f=dot(fenc,fenc);float g=sqrt(max(0.0,1.0-f/4.0));return vec3(fenc*g,1.0-f/2.0);}float unpackDepth(vec2 uncodedDepth){float x=unpack16(uncodedDepth.xy);return x*x;}
#define getDepth(uv) unpackDepth(texture2D(tNormalDepth, uv).xy)
void getDepthNormal(const in vec2 uv,out float depth,out vec3 normal){vec4 uncodedDepth=texture2D(tNormalDepth,uv);depth=unpackDepth(uncodedDepth.xy);normal=unpackNormal(uncodedDepth.zw);}vec3 getViewNormal(const in vec2 uv){return unpackNormal(texture2D(tNormalDepth,uv).zw);}
#if defined(GBUFFER_HAS_FLAGS) && GBUFFER_HAS_FLAGS == 1
uniform sampler2D tGBufferFlags;
#endif
ivec4 getGBufferFlags(const in vec2 uv){
#if defined(GBUFFER_HAS_FLAGS) && GBUFFER_HAS_FLAGS == 1
return ivec4(texture2D(tGBufferFlags,uv)*255.);
#else
return ivec4(1);
#endif
}
#if defined(GBUFFER_HAS_DEPTH_TEXTURE) && GBUFFER_HAS_DEPTH_TEXTURE == 1
uniform sampler2D tGBufferDepthTexture;float getDepthTexture(vec2 coord,float cameraNear,float cameraFar){float fragCoordZ=texture2D(tGBufferDepthTexture,coord).x;float viewZ=perspectiveDepthToViewZ(fragCoordZ,cameraNear,cameraFar);return viewZToOrthographicDepth(viewZ,cameraNear,cameraFar);}
#endif
#endif
`;var rH=Object.defineProperty,aH=Object.getOwnPropertyDescriptor,Fg=(r,e,t,i)=>{for(var n=i>1?void 0:i?aH(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&rH(e,t,n),n};f.GBufferPlugin=class extends Pl{constructor(e=Qt,t=!0,i=!0,n=!0,s=!1,a=tr){super(),this.renderFlagsBuffer=n,this.renderDepthTexture=s,this.depthTextureType=a,this.passId="gbuffer",this.textures=[],this.unpackExtension={shaderExtender:o=>{const c=["gbuffer_unpack","packing"].find(h=>o.fragmentShader.includes(`#include <${h}>`));o.fragmentShader=bt(o.fragmentShader,`#include <${c}>`,`
`+rI+`
`,{append:c==="packing"})},extraUniforms:{tNormalDepth:()=>({value:this.normalDepthTexture}),tGBufferFlags:()=>({value:this.flagsTexture}),tGBufferDepthTexture:()=>({value:this.depthTexture})},extraDefines:{HAS_NORMAL_DEPTH_BUFFER:()=>this.normalDepthTexture?1:void 0,GBUFFER_HAS_DEPTH_TEXTURE:()=>this.depthTexture?1:void 0,GBUFFER_HAS_FLAGS:()=>this.flagsTexture?1:void 0,HAS_GBUFFER:()=>this.isPrimaryGBuffer&&this.normalDepthTexture?1:void 0},priority:100,isCompatible:()=>!0},this._isPrimaryGBufferSet=!1,this.enabled=i,this.bufferType=e,this.isPrimaryGBuffer=t}get normalDepthTexture(){return this.textures[0]}get flagsTexture(){return this.textures[1]}get depthTexture(){return this.target?.depthTexture??void 0}createMaterial(){const e=this._viewer?.renderManager.isWebGL2&&this.renderFlagsBuffer;return new ng(e,{blending:gn,transparent:!0})}_createTargetAndMaterial(e=!0){if(!this._viewer)return;e&&this._disposeTarget();const t=this._viewer?.renderManager.isWebGL2&&this.renderFlagsBuffer;if(!this.target){const i=this._viewer.renderManager;this.target=this._viewer.renderManager.createTarget({depthBuffer:!0,samples:this._viewer.renderManager.zPrepass&&this.isPrimaryGBuffer&&i.msaa?typeof i.msaa!="number"?f.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:i.msaa:0,type:this.bufferType,textureCount:t?2:1,depthTexture:this.renderDepthTexture,depthTextureType:this.depthTextureType,wrapS:di,wrapT:di}),Array.isArray(this.target.textures)&&this.target.textures.length>1?(this.target.textures[0].name="gbufferDepthNormal",this.target.textures[1].name="gbufferFlags",this.textures=[...this.target.textures]):(this.target.texture.name="gbufferDepthNormal",this.textures.push(this.target.texture))}this.material||(this.material=this.createMaterial()),this.isPrimaryGBuffer&&(this._viewer.renderManager.gbufferTarget=this.target,this._viewer.renderManager.gbufferUnpackExtension=this.unpackExtension,this._viewer.renderManager.screenPass.material.registerMaterialExtensions([this.unpackExtension]),this._isPrimaryGBufferSet=!0)}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.textures=[],this._isPrimaryGBufferSet&&(this._viewer.renderManager.gbufferTarget=void 0,this._viewer.renderManager.gbufferUnpackExtension=void 0,this._isPrimaryGBufferSet=!1))}_createPass(){if(this._createTargetAndMaterial(!0),!this.target)throw new Error("GBufferPlugin: target not created");if(!this.material)throw new Error("GBufferPlugin: material not created");this.material.userData.isGBufferMaterial=!0;const e=new f.GBufferRenderPass(this.passId,()=>this.target,this.material,new ee(1,1,1),1),t=e.preprocessMaterial;return e.preprocessMaterial=i=>t(i,i.userData.renderToDepth),e.preprocessObject=i=>{if(i.customGBufferMaterial){const n=i.customGBufferMaterial;n.allowOverride=!1;const s=i.material;i.forcedOverrideMaterial=n;const a=Array.isArray(s)?s[0]:s;return a&&(n.userData.renderToGBuffer=a.userData.renderToGBuffer,n.userData.renderToDepth=a.userData.renderToDepth,n.userData.pluginsDisabled=a.userData.pluginsDisabled,n.side=a.side),n}return i.material},e.postprocessObject=i=>{i.customGBufferMaterial&&delete i.forcedOverrideMaterial},e.before=["render"],e.after=[],e.required=["render"],e}_beforeRender(e,t,i){return!(!super._beforeRender(e,t,i)||!this.material)}registerGBufferUpdater(e,t){this.material&&this.material.flagUpdaters.set(e,t)}unregisterGBufferUpdater(e){this.material&&this.material.flagUpdaters.delete(e)}onRemove(e){return this._disposeTarget(),this.material?.dispose(),this.material=void 0,super.onRemove(e)}getDepthNormal(){return this.textures.length>0?this.textures[0]:void 0}getFlagsTexture(){return this.textures.length>1?this.textures[1]:void 0}getTarget(){return this.target}getUnpackSnippet(){return rI}updateShaderProperties(e){if(e.uniforms.tNormalDepth?e.uniforms.tNormalDepth.value=this.normalDepthTexture??void 0:this._viewer?.console.warn("BaseRenderer: no uniform: tNormalDepth"),e.uniforms.tGBufferFlags){e.uniforms.tGBufferFlags.value=this.flagsTexture??void 0;const t=e.uniforms.tGBufferFlags.value?1:0;t!==e.defines.GBUFFER_HAS_FLAGS&&(e.defines.GBUFFER_HAS_FLAGS=t,e.needsUpdate=!0)}return this}},f.GBufferPlugin.PluginType="GBuffer",Fg([Dr(void 0,{readOnly:!0})],f.GBufferPlugin.prototype,"normalDepthTexture",1),Fg([Dr(void 0,{readOnly:!0})],f.GBufferPlugin.prototype,"flagsTexture",1),Fg([Dr(void 0,{readOnly:!0})],f.GBufferPlugin.prototype,"depthTexture",1),f.GBufferPlugin=Fg([vt("G-Buffer Plugin")],f.GBufferPlugin);class qd extends mt{constructor(e=""){super(),this.priority=-100,this._shaderPatch="",this.computeCacheKey=t=>this.isDisabled()?"0":"1",this._shaderPatch=e,this.setDirty=this.setDirty.bind(this)}set uniformsNeedUpdate(e){e&&this.setDirty()}shaderExtender(e,t,i){this.isDisabled()||(e.fragmentShader=bt(e.fragmentShader,"#glMarker",`
`+this._shaderPatch+`
`,{prepend:!0}))}getUiConfig(){return this.uiConfig}isCompatible(e){return!0}setDirty(){this.__setDirty?.(),this._viewer?.renderManager.screenPass.setDirty()}fromJSON(e,t){return e.pass&&(e={...e},e.extension={...e.pass},delete e.extension.enabled,delete e.pass),e.extension&&(e={...e,...e.extension},delete e.extension),super.fromJSON(e,t)}onAdded(e){super.onAdded(e),e.forPlugin(f.GBufferPlugin,t=>{t.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this))},t=>{t.unregisterGBufferUpdater(this.constructor.PluginType)},this),e.renderManager.screenPass.material.registerMaterialExtensions([this])}onRemove(e){e.getPlugin(f.GBufferPlugin)?.unregisterGBufferUpdater(this.constructor.PluginType),e.renderManager.screenPass.material.unregisterMaterialExtensions([this]),super.onRemove(e)}updateGBufferFlags(e,t){}}var oH=Object.defineProperty,lH=Object.getOwnPropertyDescriptor,Dl=(r,e,t,i)=>{for(var n=i>1?void 0:i?lH(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&oH(e,t,n),n};const cH=Sw;f.TonemapPlugin=class extends qd{constructor(){super(...arguments),this.extraUniforms={toneMappingContrast:{value:1},toneMappingSaturation:{value:1}},this.extraDefines={TONEMAP_BACKGROUND:()=>this.tonemapBackground===!1||this._viewer?.scene.backgroundTonemap===!1?"0":"1"},this.enabled=!0,this.toneMapping=BA,this.tonemapBackground=!0,this.exposure=1,this.priority=-100,this.parsFragmentSnippet=()=>this.isDisabled()?"":ma`
            uniform float toneMappingContrast;
            uniform float toneMappingSaturation;
            ${iH}
        `,this._shaderPatch=nH,this._rendererState={}}onObjectRender(e,t,i){if(this.isDisabled())return;const{toneMapping:n,toneMappingExposure:s}=i;this._rendererState.toneMapping=n,this._rendererState.toneMappingExposure=s,i.toneMapping=this.toneMapping,i.toneMappingExposure=this.exposure,t.toneMapped=!0,t.needsUpdate=!0}onAfterRender(e,t,i){i.toneMapping=this._rendererState.toneMapping,i.toneMappingExposure=this._rendererState.toneMappingExposure}fromJSON(e,t){return e.extension&&e.clipBackground!==void 0&&(this._viewer?this._viewer.renderManager.screenPass.clipBackground=e.clipBackground:console.warn("TonemapPlugin: no viewer attached, clipBackground ignored"),delete e.clipBackground),super.fromJSON(e,t)}updateGBufferFlags(e,t){const i=(t.material.userData.gBufferData?.tonemapEnabled??t.material?.userData.postTonemap)===!1?0:1;e.w=U_(e.w,1,i),super.updateGBufferFlags(e,t)}},f.TonemapPlugin.PluginType="Tonemap",lt.tonemapping_pars_fragment=lt.tonemapping_pars_fragment.replace("vec3 CustomToneMapping( vec3 color ) { return color; }",tH),Dl([G(),he(f.TonemapPlugin.prototype.setDirty),se("Enabled")],f.TonemapPlugin.prototype,"enabled",2),Dl([Li("Mode",[["Linear",ww],["Reinhard",Cw],["Cineon",xw],["ACESFilmic",BA],["Uncharted2",cH],["AgX",Ew]].map(r=>({label:r[0],value:r[1]}))),he(f.TonemapPlugin.prototype.setDirty),G()],f.TonemapPlugin.prototype,"toneMapping",2),Dl([he(f.TonemapPlugin.prototype.setDirty),G()],f.TonemapPlugin.prototype,"tonemapBackground",2),Dl([he(f.TonemapPlugin.prototype.setDirty),Fe("Exposure",[0,2*Math.PI],.01),G()],f.TonemapPlugin.prototype,"exposure",2),Dl([Fe("Saturation",[0,2],.01),_a({propKey:"toneMappingSaturation"}),G()],f.TonemapPlugin.prototype,"saturation",2),Dl([Fe("Contrast",[0,2],.01),_a({propKey:"toneMappingContrast"}),G()],f.TonemapPlugin.prototype,"contrast",2),f.TonemapPlugin=Dl([vt("Tonemapping")],f.TonemapPlugin);const hH="0.6.0";var uH=Object.defineProperty,dH=Object.getOwnPropertyDescriptor,wh=(r,e,t,i)=>{for(var n=i>1?void 0:i?dH(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&uH(e,t,n),n};function j0(r){const e=[];let t=Object.getPrototypeOf(r);for(;t;)t.constructor?.PluginType&&e.push(t.constructor.PluginType),t.constructor?.OldPluginType&&e.push(t.constructor.OldPluginType),t=Object.getPrototypeOf(t);return e}f.ThreeViewer=class extends xi{constructor({debug:e=!1,...t}){super(),this.type="ThreeViewer",this.enabled=!0,this.renderEnabled=!0,this.timeline=new f.ViewerTimeline,this.plugins={},this.maxFramePerLoop=1,this.rendersPerFrame=1,this.resizeObserver=window?.ResizeObserver?new window.ResizeObserver(o=>this.resize()):void 0,this._needsResize=!1,this._isRenderingFrame=!1,this._needsReset=!0,this._lastCameraPosition=new S,this._lastCameraQuat=new $e,this._lastCameraTarget=new S,this._tempVec=new S,this._tempQuat=new $e,this._lastMainCamera=void 0,this.serializePluginsIgnored=[],this.resize=()=>{this._needsResize=!0,this.setDirty()},this.deleteImportedViewerConfigOnLoad=!0,this.deleteImportedViewerConfigOnLoadWait=2e3,this.loadConfigResources=async(o,l)=>{if(o.__isLoadedResources)return o;const c=Ev(o,this);return await Qm.ImportMeta(c,l)},this._setActiveCameraView=o=>{if(o.type==="setView"){if(!o.camera){this.console.warn("Cannot find camera",o);return}this._scene.mainCamera.setViewFromCamera(o.camera)}else if(o.type==="activateMain"){let l=o.camera;l===void 0&&this._lastMainCamera&&(this._lastMainCamera.parent&&(l=this._lastMainCamera),this._lastMainCamera=void 0),l&&this._scene.mainCamera!==l&&(this._lastMainCamera=this._scene.mainCamera),l?.setCanvas(this._canvas,!1),this._scene.mainCamera=l===null?void 0:l||void 0}},this._defaultConfig={assetType:"config",type:this.type,version:f.ThreeViewer.VERSION,metadata:{generator:"ThreePipe",version:2},plugins:[]},this._lastSize=new K,this._onContextRestore=o=>{this.enabled=!0,this._canvas.width=this._lastSize.width,this._canvas.height=this._lastSize.height,this.resize(),this._scene.setDirty({refreshScene:!0,frameFade:!1})},this._onContextLost=o=>{this._lastSize.set(this._canvas.width,this._canvas.height),this._canvas.width=2,this._canvas.height=2,this.resize(),this.enabled=!1},this._stopPropagation=o=>{this.scene.mainCamera.canUserInteract&&o.stopPropagation()},this._onListeners={},this._pluginListeners={add:[],remove:[]},this.debug=e,e&&(f.ThreeViewer.ViewerDebugging=!0),this._canvas=t.canvas||hS();const i=getComputedStyle(this._canvas);!this._canvas.style.width&&i.maxWidth==="none"&&(this._canvas.style.width="100%"),!this._canvas.style.height&&i.maxHeight==="none"&&(this._canvas.style.height="100%");let n=t.container;if(n&&!t.canvas&&n.appendChild(this._canvas),n||(n=this._canvas.parentElement??void 0),n||(n=globalThis.document?.body),!n)throw new Error("No container(or canvas).");this._container=n,this.setDirty=this.setDirty.bind(this),this._animationLoop=this._animationLoop.bind(this),e&&t.statsJS!==!1&&(this.renderStats=new HS(this._container),this.renderStats.show()),window.threeViewers||(window.threeViewers=[]),window.threeViewers.push(this);let s;if(t.camera?.isCamera)s=t.camera,s.assetType||ht.upgradeCamera.call(s);else{s=t.camera?.type==="orthographic"?new Sd(t.camera?.controlsMode??"orbit",this._canvas):new th(t.camera?.controlsMode??"orbit",this._canvas),s.name="Default Camera"+(s.type==="OrthographicCamera"?" (Ortho)":"");const o=t.camera?.position||[0,0,5];Array.isArray(o)?s.position.fromArray(o):s.position.copy(o);const l=t.camera?.target||[0,0,0];Array.isArray(l)?s.target.fromArray(l):s.target.copy(l),s.setDirty(),s.userData.autoLookAtTarget=!0,t.rootScene&&this.console.error("ThreeViewer: Camera must also be passed in options when rootScene is passed in options.")}this.addEventListener("postFrame",()=>{const o=this._scene.mainCamera;if(o&&o.canUserInteract){const l=this.getPlugin("ProgressivePlugin")?.postFrameConvergedRecordingDelta();if(l!==void 0&&l===0)return;typeof o.controls?.update=="function"&&o.controls?.update()}}),this.addEventListener("preFrame",()=>{const o=this._scene.mainCamera;o.getWorldPosition(this._tempVec).sub(this._lastCameraPosition).lengthSq()+this._tempVec.subVectors(o.target,this._lastCameraTarget).lengthSq()+o.getWorldQuaternion(this._tempQuat).angleTo(this._lastCameraQuat)>1e-6&&o.setDirty()}),this.object3dManager=new Og,this._scene=t.rootScene??new f.RootScene(s,kM(this)),this._scene.mainCamera!==s&&(this._scene.mainCamera=s),this._scene.setBackgroundColor(t.backgroundColor??"#ffffff"),this._scene.addEventListener("setView",this._setActiveCameraView),this._scene.addEventListener("activateMain",this._setActiveCameraView),this._scene.addEventListener("materialUpdate",o=>this.setDirty(this._scene,o)),this._scene.addEventListener("materialChanged",o=>this.setDirty(this._scene,o)),this._scene.addEventListener("objectUpdate",o=>this.setDirty(this._scene,o)),this._scene.addEventListener("textureUpdate",o=>this.setDirty(this._scene,o)),this._scene.addEventListener("sceneUpdate",o=>{this.setDirty(this._scene,o),o.geometryChanged!==!1&&this.renderManager.resetShadows()}),this._scene.addEventListener("mainCameraUpdate",()=>{this._scene.mainCamera.getWorldPosition(this._lastCameraPosition),this._lastCameraTarget.copy(this._scene.mainCamera.target),this._scene.mainCamera.getWorldQuaternion(this._lastCameraQuat)}),this._scene.modelRoot.scale.setScalar(t.modelRootScale??1),this.object3dManager.setRoot(this._scene),(t.isAntialiased!==void 0||t.useRgbm!==void 0||t.useGBufferDepth!==void 0)&&this.console.warn("isAntialiased, useRgbm and useGBufferDepth are deprecated, use msaa, rgbm and zPrepass instead.");const a=t.rmClass??f.ViewerRenderManager;this.renderManager=new a({canvas:this._canvas,msaa:t.msaa??t.isAntialiased??!1,rgbm:t.rgbm??t.useRgbm??!0,zPrepass:t.zPrepass??t.useGBufferDepth??!1,depthBuffer:!(t.zPrepass??t.useGBufferDepth??!1),stencilBuffer:t.stencil,screenShader:t.screenShader,renderScale:typeof t.renderScale=="string"?t.renderScale==="auto"?Math.min(t.maxRenderScale||2,window.devicePixelRatio):parseFloat(t.renderScale):t.renderScale,maxHDRIntensity:t.maxHDRIntensity,powerPreference:t.powerPreference}),this.renderManager.addEventListener("animationLoop",this._animationLoop),this.renderManager.addEventListener("resize",()=>this._scene.mainCamera.refreshAspect()),this.renderManager.addEventListener("update",o=>{o.change==="registerPass"&&o.pass?.materialExtension?this.assetManager.materials.registerMaterialExtension(o.pass.materialExtension):o.change==="unregisterPass"&&o.pass?.materialExtension&&this.assetManager.materials.unregisterMaterialExtension(o.pass.materialExtension),this.setDirty(this.renderManager,o)}),this.assetManager=new Lg(this,t.assetManager),t.cacheImportedAssets!==void 0&&(this.assetManager.importer.cacheImportedAssets=t.cacheImportedAssets),this.resizeObserver&&this.resizeObserver.observe(this._canvas),window&&window.addEventListener("resize",this.resize),this._canvas.addEventListener("webglcontextrestored",this._onContextRestore,!1),this._canvas.addEventListener("webglcontextlost",this._onContextLost,!1),t.dropzone&&this.addPluginSync(new f.DropzonePlugin(typeof t.dropzone=="object"?t.dropzone:void 0)),t.tonemap!==!1&&this.addPluginSync(new f.TonemapPlugin);for(const o of t.plugins??[])this.addPluginSync(o);if(this.console.log("ThreePipe Viewer instance initialized, version: ",f.ThreeViewer.VERSION),t.load){const l=[t.load.src].flat().filter(c=>c).map(async c=>c&&this.load(c));t.load.environment&&l.push(this.setEnvironmentMap(t.load.environment)),t.load.background&&l.push(this.setBackgroundMap(t.load.background)),Promise.all(l).then(t.onLoad)}t.stopPointerEventPropagation&&(this._canvas.addEventListener("pointerdown",this._stopPropagation),this._canvas.addEventListener("touchstart",this._stopPropagation),this._canvas.addEventListener("mousedown",this._stopPropagation))}get materialManager(){return this.assetManager.materials}get scene(){return this._scene}get container(){return this._canvas.parentElement!==this._container&&this.console.error("ThreeViewer: Canvas is not in the container, this might cause issues with some plugins."),this._container}get canvas(){return this._canvas}get console(){return f.ThreeViewer.Console}get dialog(){return f.ThreeViewer.Dialog}async load(e,t){if(e)return await this.assetManager.addAssetSingle(e,t)}async import(e,t){if(e)return await this.assetManager.importer.importSingle(e,t)}async setEnvironmentMap(e,{setBackground:t=!1,...i}={}){return this._scene.environment=e&&!e.isTexture?await this.assetManager.importer.importSingle(e,i)||null:e||null,t?this.setBackgroundMap(this._scene.environment):this._scene.environment}async setBackgroundMap(e,{setEnvironment:t=!1,...i}={}){return this._scene.background=e&&!e.isTexture?await this.assetManager.importer.importSingle(e,i)||null:e||null,t?this.setEnvironmentMap(this._scene.background):this._scene.background}async export(e,t){return e||(e=this._scene.modelRoot),e.type===this.type?Mv(e.exportConfig()):e.constructor?.PluginType?Mv(this.exportPluginConfig(e)):await this.assetManager.exporter.exportObject(e,t)}async exportScene(e,t=!0){const i=t?this.getPlugin("AssetExporterPlugin"):void 0;return i?i.exportScene(e):this.assetManager.exporter.exportObject(this._scene.modelRoot,e)}async getScreenshotBlob({mimeType:e="image/jpeg",quality:t=90}={}){const i=this.getPlugin("CanvasSnapshotPlugin");if(i)return i.getFile("snapshot."+e.split("/")[1],{mimeType:e,quality:t,waitForProgressive:!0});const n=async()=>new Promise(s=>{this._canvas.toBlob(a=>{s(a)},e,t)});return this.renderEnabled?await this.doOnce("postFrame",async()=>{this.renderEnabled=!1;const s=await n();return this.renderEnabled=!0,s}):n()}async getScreenshotDataUrl({mimeType:e="image/jpeg",quality:t=.9}={}){return this.renderEnabled?await this.doOnce("postFrame",()=>this._canvas.toDataURL(e,t)):this._canvas.toDataURL(e,t)}dispose(e=!0){if(this.renderEnabled=!1,e){const t=[],i=[];for(const[n,s]of[...Object.entries(this.plugins)])n!==s.constructor.OldPluginType&&(s.isViewerPluginSync?t.push(s):i.push(s));for(const n of t)this.removePluginSync(n,!0);for(const n of i)this.removePlugin(n,!0)}this._scene.dispose(e),this.renderManager.dispose(e),e&&(this.object3dManager.dispose(),this._canvas.removeEventListener("webglcontextrestored",this._onContextRestore,!1),this._canvas.removeEventListener("webglcontextlost",this._onContextLost,!1),window.threeViewers?.splice(window.threeViewers.indexOf(this),1),this.resizeObserver&&this.resizeObserver.unobserve(this._canvas),window.removeEventListener("resize",this.resize)),this.dispatchEvent({type:"dispose",clear:e})}setDirty(e,t){this._needsReset=!0,e=e??this,this.dispatchEvent({...t??{},type:"update",source:e})}_animationLoop(e){if(this.enabled){if(this._isRenderingFrame){this.console.warn("animation loop: frame skip");return}this._isRenderingFrame=!0,this.renderStats?.begin();for(let t=0;t<this.maxFramePerLoop;t++){let i=!1;if(this.renderEnabled&&(this._needsReset&&(this.renderManager.reset(),this._needsReset=!1),this._needsResize)){const n=[Math.floor(this._canvas.clientWidth),Math.floor(this._canvas.clientHeight)];if(e.xrFrame){const s=this.renderManager.webglRenderer.xr.getCamera()?.cameras[0]?.viewport;s?((s.x!==0||s.y!==0)&&this.console.warn("x and y must be 0?"),n[0]=s.width,n[1]=s.height,this.console.log("resize for xr",n)):this._needsResize=!1}this._needsResize&&(this.renderManager.setSize(...n),this._needsResize=!1,i=!0)}if(this.dispatchEvent({...e,type:"preFrame",target:this}),this.dispatch("preFrame",{time:e.time,deltaTime:e.deltaTime,timeline:this.timeline,resized:i}),this.renderEnabled){const n=Object.entries(this.plugins).filter(([a,o])=>o.dirty&&a!==o.constructor.OldPluginType);if(n.length>0&&this.setDirty(n),this._needsReset&&(this.renderManager.reset(),this._needsReset=!1),this.renderManager.needsRender)for(let a=0;a<this.rendersPerFrame;a++){this._scene._isMainRendering=!0,this.dispatchEvent({type:"preRender",target:this});const o=()=>{const l=this._scene.mainCamera;this._scene.renderCamera=l,l.visible&&this.renderManager.render(this._scene,this.renderManager.defaultRenderToScreen)};if(this.debug)o();else try{o()}catch(l){if(this.console.error("ThreeViewer: Uncaught error while rendering frame."),this.console.error(l),this.debug)throw l;this.renderEnabled=!1,this.dispatchEvent({type:"renderError",error:l})}this._scene._isMainRendering=!1,this.dispatchEvent({type:"postRender",target:this})}}this.timeline.update(this),this.dispatchEvent({type:"postFrame",target:this}),this.renderEnabled&&this.renderManager.onPostFrame(),this.object3dManager.onPostFrame(this.timeline),this.timeline.update2(this)}this.renderStats?.end(),this._isRenderingFrame=!1}}getPlugin(e){return this.plugins[typeof e=="string"?e:e.PluginType]}getPlugins(e){const t=typeof e=="string"?e:e.PluginType,i=Object.values(this.plugins),n=[];for(const s of i)j0(s).includes(t)&&n.push(s);return n}async getOrAddPlugin(e,...t){const i=this.getPlugin(e);return i||this.addPlugin(e,...t)}getOrAddPluginSync(e,...t){const i=this.getPlugin(e);return i||this.addPluginSync(e,...t)}async addPlugin(e,...t){const i=this._resolvePluginOrClass(e,...t);if(!i)throw new Error("ThreeViewer: Plugin is not defined");const n=i.constructor.PluginType;if(!i.constructor.PluginType)return this.console.error("ThreeViewer: PluginType is not defined for",i),i;for(const a of i.dependencies||[])await this.getOrAddPlugin(a);if(this.plugins[n]){if(this.plugins[n]===i)return i;this.console.error(`ThreeViewer: Plugin of type ${n} already exists, removing and disposing old plugin. This might break functionality, ensure only one plugin of a type is added`,this.plugins[n],i),await this.removePlugin(this.plugins[n])}this.plugins[n]=i;const s=i.constructor.OldPluginType;return s&&this.plugins[s]&&this.console.error(`ThreeViewer: Plugin type mismatch ${s}`),s&&(this.plugins[s]=i),await i.onAdded(this),this._onPluginAdd(i),i}addPluginSync(e,...t){const i=this._resolvePluginOrClass(e,...t);if(!i)throw new Error("ThreeViewer: Plugin is not defined");const n=i.constructor.PluginType;if(!i.constructor.PluginType)return this.console.error("ThreeViewer: PluginType is not defined for",i),i;for(const a of i.dependencies||[])this.getOrAddPluginSync(a);if(this.plugins[n]){if(this.plugins[n]===i)return i;this.console.error(`ThreeViewer: Plugin of type ${n} already exists, removing and disposing old plugin. This might break functionality, ensure only one plugin of a type is added`,this.plugins[n],i),this.removePluginSync(this.plugins[n])}const s=()=>{this.plugins[n]=i;const a=i.constructor.OldPluginType;a&&this.plugins[a]&&this.console.error(`ThreeViewer: Plugin type mismatch ${a}`),a&&(this.plugins[a]=i),i.onAdded(this)};if(this.debug)s();else try{s()}catch(a){this.console.error("ThreeViewer: Error adding plugin, check console for details",a),delete this.plugins[n]}return this._onPluginAdd(i),i}async addPlugins(e){for(const t of e)await this.addPlugin(t)}addPluginsSync(e){for(const t of e)this.addPluginSync(t)}async removePlugin(e,t=!0){const i=e.constructor.PluginType;this.plugins[i]&&(await e.onRemove(this),this._onPluginRemove(e,t))}removePluginSync(e,t=!0){const i=e.constructor.PluginType;this.plugins[i]&&(e.onRemove(this),this._onPluginRemove(e,t))}setSize(e){this._canvas.style.width=e?.width?e.width+"px":"100%",this._canvas.style.height=e?.height?e.height+"px":"100%",this._canvas.offsetHeight,this.resize()}setRenderSize(e,t="contain",i=1,n){const s=n||this.container.getBoundingClientRect(),a=s.height,o=s.width,l=Math.floor(e.width),c=Math.floor(e.height),h=l/c,u=o/a,d=i;let p,m;switch(t){case"contain":u>h?(p=a*h,m=a):(p=o,m=o/h);break;case"cover":u>h?(p=o,m=o/h):(p=a*h,m=a);break;case"fill":p=o,m=a;break;case"scale-down":l<o&&c<a?(p=l,m=c):u>h?(p=a*h,m=a):(p=o,m=o/h);break;case"none":p=l,m=c;break;default:throw new Error(`Invalid mode: ${t}`)}this.setSize({width:p,height:m}),this.renderManager.renderScale=d*c/m}traverseSceneObjects(e){this._scene.modelRoot.traverse(e)}async addSceneObject(e,t){let i=e;if(e.userData?.rootSceneModelRoot){const n=e;this._scene.loadModelRoot(n,t),t?.importConfig!==!1&&(n.importedViewerConfig?(await this.importConfig(n.importedViewerConfig,n.importedBundledResources),n._deletedImportedViewerConfig&&delete n._deletedImportedViewerConfig):n._deletedImportedViewerConfig&&this.console.error("ThreeViewer - Imported viewer config was deleted, cannot import it again. Set `viewer.deleteImportedViewerConfigOnLoad` to `false` to keep it in the object for reuse workflows.")),this.deleteImportedViewerConfigOnLoad&&n.importedViewerConfig&&setTimeout(()=>{n.importedViewerConfig&&(delete n.importedViewerConfig,n._deletedImportedViewerConfig=!0)},this.deleteImportedViewerConfigOnLoadWait),setTimeout(()=>{n.importedBundledResources&&(delete n.importedBundledResources,n._deletedImportedBundledResources=!0)},this.deleteImportedViewerConfigOnLoadWait),i=this._scene.modelRoot}else this._scene.addObject(e,t);return i}serializePlugins(e,t){return t&&t.length===0?[]:t?.map(i=>{const n=this.getPlugin(i);return n?this.serializePlugin(n,e):void 0}).filter(i=>!!i)??Object.entries(this.plugins).map(i=>{if(!(t&&!t.includes(i[1].constructor.PluginType))&&i[0]!==i[1].constructor.OldPluginType)return this.serializePlugin(i[1],e)}).filter(i=>!!i)}serializePlugin(e,t){if(!this.serializePluginsIgnored.includes(e.constructor.PluginType))return e.serializeWithViewer!==!1?e.toJSON?.(t):void 0}deserializePlugins(e,t){return e.forEach(i=>{if(!i.type){this.console.warn("Invalid plugin to import ",i);return}if(this.serializePluginsIgnored.includes(i.type))return;const n=this.getPlugin(i.type);n&&n.fromJSON&&n.fromJSON(i,t)}),this}exportPluginConfig(e){if((e&&typeof e=="string"||e.PluginType)&&(e=this.getPlugin(e)),!e)return{};const t=Fr(),i=e.toJSON?.(t);return i?(i.resources=pd(t),i):{}}async importPluginConfig(e,t){const i=e.type;if(t=t||this.getPlugin(i),!t){this.console.warn(`No plugin found for type ${i} to import config`);return}if(!t.fromJSON){this.console.warn(`Plugin ${i} does not support importing presets`);return}const n=e.resources||{};e.resources&&delete e.resources;const s=await this.loadConfigResources(n);return await t.fromJSON(e,s),s&&(e.resources=s),t}exportPluginsConfig(e){const t=Fr(),i=this.serializePlugins(t,e);return Sv(t),{...this._defaultConfig,plugins:i,resources:pd(t)}}exportConfig(e=!1,t){return this.toJSON(e,t)}async importConfig(e,t){if(e.type!==this.type&&e.type!=="ViewerApp"&&e.type!=="ThreeViewer"){if(this.getPlugin(e.type))return this.importPluginConfig(e);this.console.error(`Unknown config type ${e.type} to import`);return}let i=await this.loadConfigResources(e.resources||{});if(t){const n={_context:i._context},s=[...Object.keys(i),...Object.keys(t||{})];for(const a of s)a==="object"?n[a]=i[a]||t[a]:n[a]={...i[a],...t[a]};i=n}return e.resources=i,this.fromJSON(e,i),this}toJSON(e=!0,t,i){typeof e!="boolean"&&(e=!0),t!==void 0&&!Array.isArray(t)&&(t=void 0),i=i||Fr();const n=Object.assign({...this._defaultConfig,metadata:{...this._defaultConfig.metadata},plugins:this.serializePlugins(i,t)},We.Serialize(this,i,!0));return e||Sv(i),n.resources=pd(i),n}fromJSON(e,t){const i={...e};return t&&i.metadata&&i.type==="ViewerApp"&&(t._configMetadata={...i.metadata,viewerVersion:i.version}),i.backgroundIntensity!==void 0&&i.scene?.backgroundIntensity===void 0&&(this.console.warn("old file format, backgroundIntensity moved to RootScene"),this._scene.backgroundIntensity=i.backgroundIntensity,delete i.backgroundIntensity),i.useLegacyLights!==void 0&&(i.useLegacyLights&&this.console.warn("useLegacyLights support removed since threepipe v0.5.0"),delete i.useLegacyLights),i.background!==void 0&&i.scene?.background===void 0&&(this.console.warn("old file format, background moved to RootScene"),i.background==="envMapBackground"?i.background="environment":typeof i.background=="number"?i.background=new ee().setHex(i.background,Bt):typeof i.background=="string"?i.background=new ee().setStyle(i.background,Bt):i.background?.isColor&&(i.background=new ee(i.background)),i.background?.isColor?(this._scene.backgroundColor=i.background,this._scene.background=null):i.background?(this._scene.backgroundColor=new ee("#ffffff"),i.scene||(i.scene={}),i.scene.background=i.background):(this._scene.backgroundColor=null,this._scene.background=null),delete i.background),!t&&i.resources&&i.resources.__isLoadedResources&&(t=i.resources,delete i.resources),t?.__isLoadedResources?(Array.isArray(i.plugins)&&(this.deserializePlugins(i.plugins,t),delete i.plugins),We.Deserialize(i,this,t,!0),this):(this.console.error("ThreeViewer: meta in fromJSON is not available or is not loaded resources, call viewer.loadConfigResources first, or directly use viewer.importConfig"),null)}async doOnce(e,t){return new Promise(i=>{const n=async(...s)=>{this.removeEventListener(e,n),i(await t?.(...s))};this.addEventListener(e,n)})}dispatchEvent(e){super.dispatchEvent(e),super.dispatchEvent({...e,type:"*",eType:e.type})}async exportBlob(e,t){const i=this.getPlugin("FileTransferPlugin");if(t=t??e.name??"file",!i){Qu(e,t);return}await i.exportFile(e,t)}_resolvePluginOrClass(e,...t){let i;if(e.prototype){const n=this.getPlugin(e);if(n)return this.console.error(`Plugin of type ${n.constructor.PluginType} already exists, no new plugin created`,n),n;try{i=new e(...t)}catch(s){this.console.error("ThreeViewer: Error creating plugin",s);return}}else i=e;return i}_renderEnabledChanged(){this.dispatchEvent({type:this.renderEnabled?"renderEnabled":"renderDisabled"})}async fitToView(e,t=1.5,i,n){await this.getOrAddPluginSync(Q0)?.animateToFitObject(e,t,i,n,{min:(this.scene.mainCamera.controls?.minDistance??.5)+.5,max:1e3})}get canvasTexture(){if(!this._canvas)throw new Error("Canvas not found");return this._canvasTexture||(this._canvasTexture=new qo(this._canvas),this._canvasTexture.flipY=!1,this._canvasTexture.needsUpdate=!0),this._canvasTexture}on(e,t){if(this._onListeners[e]||(this._onListeners[e]=[]),!this._onListeners[e].includes(t))return this._onListeners[e].push(t),()=>this.off(e,t)}off(e,t){const i=this._onListeners[e]?.indexOf(t)??-1;i!==-1&&this._onListeners[e]?.splice(i,1)}dispatch(e,t){const i=this._onListeners[e];if(i){const n=i.slice().sort((s,a)=>(s.order??0)-(a.order??0));for(const s of n)s.callback({...t,type:e,target:this})}}_onPluginAdd(e){const t={type:"addPlugin",target:this,plugin:e};this.dispatchEvent(t);const i=j0(e);this._pluginListeners.add.filter(n=>!n.p.length||n.p.find(s=>i.includes(s))).forEach(n=>n.l(t)),this.setDirty(e)}_onPluginRemove(e,t=!1){const i={type:"removePlugin",target:this,plugin:e};this.dispatchEvent(i);const n=j0(e);this._pluginListeners.remove.filter(s=>!s.p.length||s.p.find(a=>n.includes(a))).forEach(s=>s.l(i)),delete this.plugins[e.constructor.PluginType],e.constructor.OldPluginType&&delete this.plugins[e.constructor.OldPluginType],t&&e.dispose(),this.setDirty(e)}addPluginListener(e,t,...i){this._pluginListeners[e].push({p:i.filter(n=>!!n),l:t})}removePluginListener(e,t){this._pluginListeners[e]=this._pluginListeners[e].filter(i=>i.l!==t)}forPlugin(e,t,i,n){const s=()=>{if(i){const o=()=>{const l=this.getPlugin(e);l&&(this.removePluginListener("remove",o),i(l))};this.addPluginListener("remove",o,typeof e=="string"?e:e.PluginType),n?.constructor.PluginType&&this.addPluginListener("remove",o,n.constructor.PluginType)}},a=this.getPlugin(e);if(a)t(a),s();else{const o=()=>{const l=this.getPlugin(e);l&&(this.removePluginListener("add",o),t(l),s())};this.addPluginListener("add",o,typeof e=="string"?e:e.PluginType,typeof e=="string"?void 0:e.OldPluginType)}}get renderer(){return this.console.error("ThreeViewer: renderer is deprecated, use renderManager instead"),this.renderManager}getManager(){return this.assetManager}getPluginByType(e){return this.plugins[e]}},f.ThreeViewer.VERSION=hH,f.ThreeViewer.ConfigTypeSlug="vjson",f.ThreeViewer.Console={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},f.ThreeViewer.Dialog=FS,f.ThreeViewer.ViewerDebugging=!1,wh([G()],f.ThreeViewer.prototype,"type",2),wh([he(f.ThreeViewer.prototype._renderEnabledChanged),se("Enable Rendering",{tags:["advanced"]})],f.ThreeViewer.prototype,"renderEnabled",2),wh([Bi(void 0,{label:"Rendering",expanded:!0}),G("renderManager")],f.ThreeViewer.prototype,"renderManager",2),wh([Bi(void 0,{label:"Scene",expanded:!0}),G("scene")],f.ThreeViewer.prototype,"_scene",2),wh([Bi(void 0,{label:"Timeline",expanded:!0,tags:["advanced"]}),G("timeline")],f.ThreeViewer.prototype,"timeline",2),f.ThreeViewer=wh([Aa("Viewer")],f.ThreeViewer);const fH="168",pH={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},mH={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},gH=0,AH=1,yH=2,_H=3,vH=0,bH=1,wH=2,CH=3,xH=0,SH=1,EH=2,MH=0,TH=1,IH=2,PH=3,DH=4,RH=5,BH=100,LH=101,OH=102,UH=103,FH=104,NH=200,kH=201,GH=202,zH=203,VH=204,HH=205,QH=206,jH=207,WH=208,qH=209,XH=210,YH=211,$H=212,KH=213,JH=214,ZH=0,e4=1,t4=2,i4=3,n4=4,s4=5,r4=6,a4=7,o4=0,l4=1,c4=2,h4=0,u4=1,d4=2,f4=3,p4=4,m4=5,g4=6,A4=7,y4="attached",_4="detached",v4=300,b4=301,w4=302,C4=303,x4=304,S4=306,E4=1e3,M4=1001,T4=1002,I4=1003,P4=1004,D4=1004,R4=1005,B4=1005,L4=1006,O4=1007,U4=1007,F4=1008,N4=1008,k4=1009,G4=1010,z4=1011,V4=1012,H4=1013,Q4=1014,j4=1015,W4=1016,q4=1017,X4=1018,Y4=1020,$4=35902,K4=1021,J4=1022,Z4=1023,eQ=1024,tQ=1025,iQ=1026,nQ=1027,sQ=1028,rQ=1029,aQ=1030,oQ=1031,lQ=1032,cQ=1033,hQ=33776,uQ=33777,dQ=33778,fQ=33779,pQ=35840,mQ=35841,gQ=35842,AQ=35843,yQ=36196,_Q=37492,vQ=37496,bQ=37808,wQ=37809,CQ=37810,xQ=37811,SQ=37812,EQ=37813,MQ=37814,TQ=37815,IQ=37816,PQ=37817,DQ=37818,RQ=37819,BQ=37820,LQ=37821,OQ=36492,UQ=36494,FQ=36495,NQ=36283,kQ=36284,GQ=36285,zQ=36286,VQ=2200,HQ=2201,QQ=2202,jQ=2300,WQ=2301,qQ=2302,XQ=2400,YQ=2401,$Q=2402,KQ=2500,JQ=2501,ZQ=0,e5=1,t5=2,i5=3200,n5=3201,s5=3202,r5=3203,a5=0,o5=1,l5="",c5="srgb",h5="srgb-linear",u5="display-p3",d5="display-p3-linear",f5="rgbm-16",p5="linear",m5="srgb",g5="rec709",A5="p3",y5=0,_5=7680,v5=7681,b5=7682,w5=7683,C5=34055,x5=34056,S5=5386,E5=512,M5=513,T5=514,I5=515,P5=516,D5=517,R5=518,B5=519,L5=512,O5=513,U5=514,F5=515,N5=516,k5=517,G5=518,z5=519,V5=35044,H5=35048,Q5=35040,j5=35045,W5=35049,q5=35041,X5=35046,Y5=35050,$5=35042,K5="100",J5="300 es",Z5=2e3,ej=2001,tj=3e3,ij=3001,aI=new S,oI=new S,W0=new et;class lI extends _e{constructor(e=new Gs,t=new $c({color:Math.random()*16777215})){super(e,t),this.isWireframe=!0,this.type="Wireframe"}computeLineDistances(){const e=this.geometry,t=e.attributes.instanceStart,i=e.attributes.instanceEnd,n=new Float32Array(2*t.count);for(let a=0,o=0,l=t.count;a<l;a++,o+=2)aI.fromBufferAttribute(t,a),oI.fromBufferAttribute(i,a),n[o]=o===0?0:n[o-1],n[o+1]=n[o]+aI.distanceTo(oI);const s=new Gu(n,2,1);return e.setAttribute("instanceDistanceStart",new Rn(s,1,0)),e.setAttribute("instanceDistanceEnd",new Rn(s,1,1)),this}onBeforeRender(e){const t=this.material.uniforms;t&&t.resolution&&(e.getViewport(W0),this.material.uniforms.resolution.value.set(W0.z,W0.w))}}function cI(r,e=1024){const i=new K,n=new K,s=[new K,new K,new K],a=[],o=document.createElement("canvas"),l=e,c=e;o.width=l,o.height=c;const h=o.getContext("2d");h.lineWidth=1,h.strokeStyle="rgb( 63, 63, 63 )",h.textAlign="center",h.fillStyle="rgb( 255, 255, 255 )",h.fillRect(0,0,l,c);const u=r.index,d=r.attributes.uv;if(u)for(let m=0,A=u.count;m<A;m+=3)a[0]=u.getX(m),a[1]=u.getX(m+1),a[2]=u.getX(m+2),s[0].fromBufferAttribute(d,a[0]),s[1].fromBufferAttribute(d,a[1]),s[2].fromBufferAttribute(d,a[2]),p(a,s,m/3);else for(let m=0,A=d.count;m<A;m+=3)a[0]=m,a[1]=m+1,a[2]=m+2,s[0].fromBufferAttribute(d,a[0]),s[1].fromBufferAttribute(d,a[1]),s[2].fromBufferAttribute(d,a[2]),p(a,s,m/3);return o;function p(m,A,g){h.beginPath(),i.set(0,0);for(let y=0,v=A.length;y<v;y++){const _=A[y];i.x+=_.x,i.y+=_.y,y===0?h.moveTo(_.x*(l-2)+.5,(1-_.y)*(c-2)+.5):h.lineTo(_.x*(l-2)+.5,(1-_.y)*(c-2)+.5)}h.closePath(),h.stroke(),i.divideScalar(A.length),h.font="18px Arial",h.fillStyle="rgb( 63, 63, 63 )",h.fillText(g,i.x*l,(1-i.y)*c),i.x>.95&&h.fillText(g,i.x%1*l,(1-i.y)*c),h.font="12px Arial",h.fillStyle="rgb( 191, 191, 191 )";for(let y=0,v=A.length;y<v;y++){const _=A[y];n.addVectors(i,_).divideScalar(2);const b=m[y];h.fillText("abc"[y]+b,n.x*l,(1-n.y)*c),n.x>.95&&h.fillText("abc"[y]+b,n.x%1*l,(1-n.y)*c)}}}class nj{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const i=this.workersResolve[e];if(i&&i(t),this.queue.length){const{resolve:n,msg:s,transfer:a}=this.queue.shift();this.workersResolve[e]=n,this.workers[e].postMessage(s,a)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise(i=>{const n=this._getIdleWorker();n!==-1?(this._initWorker(n),this.workerStatus|=1<<n,this.workersResolve[n]=i,this.workers[n].postMessage(e,t)):this.queue.push({resolve:i,msg:e,transfer:t})})}dispose(){this.workers.forEach(e=>e.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}const sj=0,hI=2,rj=1,uI=2,aj=0,oj=1,lj=10,cj=0,dI=9,fI=15,pI=16,mI=22,gI=37,AI=43,yI=76,_I=83,vI=97,bI=100,wI=103,CI=109,xI=165,SI=166;class hj{constructor(){this.vkFormat=0,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=0,this.levels=[],this.dataFormatDescriptor=[{vendorId:0,descriptorType:0,descriptorBlockSize:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null}}class Xd{constructor(e,t,i,n){this._dataView=new DataView(e.buffer,e.byteOffset+t,i),this._littleEndian=n,this._offset=0}_nextUint8(){const e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){const e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){const e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){const e=this._dataView.getUint32(this._offset,this._littleEndian)+4294967296*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,e}_nextInt32(){const e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_skip(e){return this._offset+=e,this}_scan(e,t=0){const i=this._offset;let n=0;for(;this._dataView.getUint8(this._offset)!==t&&n<e;)n++,this._offset++;return n<e&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+i,n)}}const ls=[171,75,84,88,32,50,48,187,13,10,26,10];function EI(r){return typeof TextDecoder<"u"?new TextDecoder().decode(r):Buffer.from(r).toString("utf8")}function uj(r){const e=new Uint8Array(r.buffer,r.byteOffset,ls.length);if(e[0]!==ls[0]||e[1]!==ls[1]||e[2]!==ls[2]||e[3]!==ls[3]||e[4]!==ls[4]||e[5]!==ls[5]||e[6]!==ls[6]||e[7]!==ls[7]||e[8]!==ls[8]||e[9]!==ls[9]||e[10]!==ls[10]||e[11]!==ls[11])throw new Error("Missing KTX 2.0 identifier.");const t=new hj,i=17*Uint32Array.BYTES_PER_ELEMENT,n=new Xd(r,ls.length,i,!0);t.vkFormat=n._nextUint32(),t.typeSize=n._nextUint32(),t.pixelWidth=n._nextUint32(),t.pixelHeight=n._nextUint32(),t.pixelDepth=n._nextUint32(),t.layerCount=n._nextUint32(),t.faceCount=n._nextUint32();const s=n._nextUint32();t.supercompressionScheme=n._nextUint32();const a=n._nextUint32(),o=n._nextUint32(),l=n._nextUint32(),c=n._nextUint32(),h=n._nextUint64(),u=n._nextUint64(),d=new Xd(r,ls.length+i,3*s*8,!0);for(let X=0;X<s;X++)t.levels.push({levelData:new Uint8Array(r.buffer,r.byteOffset+d._nextUint64(),d._nextUint64()),uncompressedByteLength:d._nextUint64()});const p=new Xd(r,a,o,!0),m={vendorId:p._skip(4)._nextUint16(),descriptorType:p._nextUint16(),versionNumber:p._nextUint16(),descriptorBlockSize:p._nextUint16(),colorModel:p._nextUint8(),colorPrimaries:p._nextUint8(),transferFunction:p._nextUint8(),flags:p._nextUint8(),texelBlockDimension:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],bytesPlane:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],samples:[]},A=(m.descriptorBlockSize/4-6)/4;for(let X=0;X<A;X++){const W={bitOffset:p._nextUint16(),bitLength:p._nextUint8(),channelType:p._nextUint8(),samplePosition:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],sampleLower:-1/0,sampleUpper:1/0};64&W.channelType?(W.sampleLower=p._nextInt32(),W.sampleUpper=p._nextInt32()):(W.sampleLower=p._nextUint32(),W.sampleUpper=p._nextUint32()),m.samples[X]=W}t.dataFormatDescriptor.length=0,t.dataFormatDescriptor.push(m);const g=new Xd(r,l,c,!0);for(;g._offset<c;){const X=g._nextUint32(),W=g._scan(X),ce=EI(W),ue=g._scan(X-W.byteLength);t.keyValue[ce]=ce.match(/^ktx/i)?EI(ue):ue,g._offset%4&&g._skip(4-g._offset%4)}if(u<=0)return t;const y=new Xd(r,h,u,!0),v=y._nextUint16(),_=y._nextUint16(),b=y._nextUint32(),T=y._nextUint32(),E=y._nextUint32(),M=y._nextUint32(),I=[];for(let X=0;X<s;X++)I.push({imageFlags:y._nextUint32(),rgbSliceByteOffset:y._nextUint32(),rgbSliceByteLength:y._nextUint32(),alphaSliceByteOffset:y._nextUint32(),alphaSliceByteLength:y._nextUint32()});const C=h+y._offset,x=C+b,D=x+T,U=D+E,O=new Uint8Array(r.buffer,r.byteOffset+C,b),N=new Uint8Array(r.buffer,r.byteOffset+x,T),H=new Uint8Array(r.buffer,r.byteOffset+D,E),V=new Uint8Array(r.buffer,r.byteOffset+U,M);return t.globalData={endpointCount:v,selectorCount:_,imageDescs:I,endpointsData:O,selectorsData:N,tablesData:H,extendedData:V},t}let q0,Ta,X0;const Y0={env:{emscripten_notify_memory_growth:function(r){X0=new Uint8Array(Ta.exports.memory.buffer)}}};class dj{init(){return q0||(q0=typeof fetch<"u"?fetch("data:application/wasm;base64,"+MI).then(e=>e.arrayBuffer()).then(e=>WebAssembly.instantiate(e,Y0)).then(this._init):WebAssembly.instantiate(Buffer.from(MI,"base64"),Y0).then(this._init),q0)}_init(e){Ta=e.instance,Y0.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!Ta)throw new Error("ZSTDDecoder: Await .init() before decoding.");const i=e.byteLength,n=Ta.exports.malloc(i);X0.set(e,n),t=t||Number(Ta.exports.ZSTD_findDecompressedSize(n,i));const s=Ta.exports.malloc(t),a=Ta.exports.ZSTD_decompress(s,t,n,i),o=X0.slice(s,s+a);return Ta.exports.free(n),Ta.exports.free(s),o}}const MI="AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ",$0=new WeakMap;let K0=0,J0;class dr extends oi{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new nj,this.workerSourceURL="",this.workerConfig=null,typeof MSC_TRANSCODER<"u"&&console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.')}setTranscoderPath(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerPool.setWorkerLimit(e),this}async detectSupportAsync(e){return this.workerConfig={astcSupported:await e.hasFeatureAsync("texture-compression-astc"),etc1Supported:await e.hasFeatureAsync("texture-compression-etc1"),etc2Supported:await e.hasFeatureAsync("texture-compression-etc2"),dxtSupported:await e.hasFeatureAsync("texture-compression-bc"),bptcSupported:await e.hasFeatureAsync("texture-compression-bptc"),pvrtcSupported:await e.hasFeatureAsync("texture-compression-pvrtc")},this}detectSupport(e){return e.isWebGPURenderer===!0?this.workerConfig={astcSupported:e.hasFeature("texture-compression-astc"),etc1Supported:e.hasFeature("texture-compression-etc1"),etc2Supported:e.hasFeature("texture-compression-etc2"),dxtSupported:e.hasFeature("texture-compression-bc"),bptcSupported:e.hasFeature("texture-compression-bptc"),pvrtcSupported:e.hasFeature("texture-compression-pvrtc")}:this.workerConfig={astcSupported:e.extensions.has("WEBGL_compressed_texture_astc"),etc1Supported:e.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:e.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:e.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:e.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:e.extensions.has("WEBGL_compressed_texture_pvrtc")||e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")},this}init(){if(!this.transcoderPending){const e=new ti(this.manager);e.setPath(this.transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new ti(this.manager);i.setPath(this.transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const n=i.loadAsync("basis_transcoder.wasm");this.transcoderPending=Promise.all([t,n]).then(([s,a])=>{const o=dr.BasisWorker,l=["/* constants */","let _EngineFormat = "+JSON.stringify(dr.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(dr.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(dr.BasisFormat),"/* basis_transcoder.js */",s,"/* worker */",o.substring(o.indexOf("{")+1,o.lastIndexOf("}"))].join(`
`);this.workerSourceURL=URL.createObjectURL(new Blob([l])),this.transcoderBinary=a,this.workerPool.setWorkerCreator(()=>{const c=new Worker(this.workerSourceURL),h=this.transcoderBinary.slice(0);return c.postMessage({type:"init",config:this.workerConfig,transcoderBinary:h},[h]),c})}),K0>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),K0++}return this.transcoderPending}load(e,t,i,n){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const s=new ti(this.manager);s.setResponseType("arraybuffer"),s.setCrossOrigin(this.crossOrigin),s.setWithCredentials(this.withCredentials),s.load(e,a=>{this.parse(a,t,n)},i,n)}parse(e,t,i){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if($0.has(e))return $0.get(e).promise.then(t).catch(i);this.createTexture(e).then(n=>t?t(n):null).catch(i)}_createTextureFrom(e,t){const{faces:i,width:n,height:s,format:a,type:o,error:l,dfdFlags:c}=e;if(o==="error")return Promise.reject(l);let h;if(t.faceCount===6)h=new fx(i,a,Qt);else{const u=i[0].mipmaps;h=t.layerCount>1?new dx(u,n,s,t.layerCount,a,Qt):new ua(u,n,s,a,Qt)}return h.minFilter=i[0].mipmaps.length===1?at:Dn,h.magFilter=at,h.generateMipmaps=!1,h.needsUpdate=!0,h.colorSpace=TI(t),h.premultiplyAlpha=!!(c&rj),h}async createTexture(e,t={}){const i=uj(new Uint8Array(e));if(i.vkFormat!==cj)return pj(i);const n=t,s=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:n},[e])).then(a=>this._createTextureFrom(a.data,i));return $0.set(e,{promise:s}),s}dispose(){return this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),K0--,this}}dr.BasisFormat={ETC1S:0,UASTC_4x4:1},dr.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},dr.EngineFormat={RGBAFormat:qt,RGBA_ASTC_4x4_Format:Mf,RGBA_BPTC_Format:iu,RGBA_ETC2_EAC_Format:Ef,RGBA_PVRTC_4BPPV1_Format:Cf,RGBA_S3TC_DXT5_Format:eu,RGB_ETC1_Format:xf,RGB_ETC2_Format:Sf,RGB_PVRTC_4BPPV1_Format:wf,RGBA_S3TC_DXT1_Format:Zh},dr.BasisWorker=`function () {

	let config;
	let transcoderPending;
	let BasisModule;

	const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
	const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
	const BasisFormat = _BasisFormat; // eslint-disable-line no-undef

	self.addEventListener( 'message', function ( e ) {

		const message = e.data;

		switch ( message.type ) {

			case 'init':
				config = message.config;
				init( message.transcoderBinary );
				break;

			case 'transcode':
				transcoderPending.then( () => {

					try {

						const { faces, buffers, width, height, hasAlpha, format, dfdFlags } = transcode( message.buffer );

						self.postMessage( { type: 'transcode', id: message.id, faces, width, height, hasAlpha, format, dfdFlags }, buffers );

					} catch ( error ) {

						console.error( error );

						self.postMessage( { type: 'error', id: message.id, error: error.message } );

					}

				} );
				break;

		}

	} );

	function init( wasmBinary ) {

		transcoderPending = new Promise( ( resolve ) => {

			BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
			BASIS( BasisModule ); // eslint-disable-line no-undef

		} ).then( () => {

			BasisModule.initializeBasis();

			if ( BasisModule.KTX2File === undefined ) {

				console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );

			}

		} );

	}

	function transcode( buffer ) {

		const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );

		function cleanup() {

			ktx2File.close();
			ktx2File.delete();

		}

		if ( ! ktx2File.isValid() ) {

			cleanup();
			throw new Error( 'THREE.KTX2Loader:	Invalid or unsupported .ktx2 file' );

		}

		const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
		const width = ktx2File.getWidth();
		const height = ktx2File.getHeight();
		const layerCount = ktx2File.getLayers() || 1;
		const levelCount = ktx2File.getLevels();
		const faceCount = ktx2File.getFaces();
		const hasAlpha = ktx2File.getHasAlpha();
		const dfdFlags = ktx2File.getDFDFlags();

		const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );

		if ( ! width || ! height || ! levelCount ) {

			cleanup();
			throw new Error( 'THREE.KTX2Loader:	Invalid texture' );

		}

		if ( ! ktx2File.startTranscoding() ) {

			cleanup();
			throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );

		}

		const faces = [];
		const buffers = [];

		for ( let face = 0; face < faceCount; face ++ ) {

			const mipmaps = [];

			for ( let mip = 0; mip < levelCount; mip ++ ) {

				const layerMips = [];

				let mipWidth, mipHeight;

				for ( let layer = 0; layer < layerCount; layer ++ ) {

					const levelInfo = ktx2File.getImageLevelInfo( mip, layer, face );

					if ( face === 0 && mip === 0 && layer === 0 && ( levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0 ) ) {

						console.warn( 'THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions.' );

					}

					if ( levelCount > 1 ) {

						mipWidth = levelInfo.origWidth;
						mipHeight = levelInfo.origHeight;

					} else {

						// Handles non-multiple-of-four dimensions in textures without mipmaps. Textures with
						// mipmaps must use multiple-of-four dimensions, for some texture formats and APIs.
						// See mrdoob/three.js#25908.
						mipWidth = levelInfo.width;
						mipHeight = levelInfo.height;

					}

					const dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, layer, 0, transcoderFormat ) );
					const status = ktx2File.transcodeImage( dst, mip, layer, face, transcoderFormat, 0, - 1, - 1 );

					if ( ! status ) {

						cleanup();
						throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );

					}

					layerMips.push( dst );

				}

				const mipData = concat( layerMips );

				mipmaps.push( { data: mipData, width: mipWidth, height: mipHeight } );
				buffers.push( mipData.buffer );

			}

			faces.push( { mipmaps, width, height, format: engineFormat } );

		}

		cleanup();

		return { faces, buffers, width, height, hasAlpha, format: engineFormat, dfdFlags };

	}

	//

	// Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
	// device capabilities, and texture dimensions. The list below ranks the formats separately
	// for ETC1S and UASTC.
	//
	// In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
	// significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
	// chooses RGBA32 only as a last resort and does not expose that option to the caller.
	const FORMAT_OPTIONS = [
		{
			if: 'astcSupported',
			basisFormat: [ BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
			engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
			priorityETC1S: Infinity,
			priorityUASTC: 1,
			needsPowerOfTwo: false,
		},
		{
			if: 'bptcSupported',
			basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
			engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
			priorityETC1S: 3,
			priorityUASTC: 2,
			needsPowerOfTwo: false,
		},
		{
			if: 'dxtSupported',
			basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
			engineFormat: [ EngineFormat.RGBA_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
			priorityETC1S: 4,
			priorityUASTC: 5,
			needsPowerOfTwo: false,
		},
		{
			if: 'etc2Supported',
			basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
			engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
			priorityETC1S: 1,
			priorityUASTC: 3,
			needsPowerOfTwo: false,
		},
		{
			if: 'etc1Supported',
			basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.ETC1 ],
			engineFormat: [ EngineFormat.RGB_ETC1_Format ],
			priorityETC1S: 2,
			priorityUASTC: 4,
			needsPowerOfTwo: false,
		},
		{
			if: 'pvrtcSupported',
			basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
			transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
			engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
			priorityETC1S: 5,
			priorityUASTC: 6,
			needsPowerOfTwo: true,
		},
	];

	const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {

		return a.priorityETC1S - b.priorityETC1S;

	} );
	const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {

		return a.priorityUASTC - b.priorityUASTC;

	} );

	function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {

		let transcoderFormat;
		let engineFormat;

		const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;

		for ( let i = 0; i < options.length; i ++ ) {

			const opt = options[ i ];

			if ( ! config[ opt.if ] ) continue;
			if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
			if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
			if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;

			transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
			engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];

			return { transcoderFormat, engineFormat };

		}

		console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );

		transcoderFormat = TranscoderFormat.RGBA32;
		engineFormat = EngineFormat.RGBAFormat;

		return { transcoderFormat, engineFormat };

	}

	function isPowerOfTwo( value ) {

		if ( value <= 2 ) return true;

		return ( value & ( value - 1 ) ) === 0 && value !== 0;

	}

	/** Concatenates N byte arrays. */
	function concat( arrays ) {

		if ( arrays.length === 1 ) return arrays[ 0 ];

		let totalByteLength = 0;

		for ( let i = 0; i < arrays.length; i ++ ) {

			const array = arrays[ i ];
			totalByteLength += array.byteLength;

		}

		const result = new Uint8Array( totalByteLength );

		let byteOffset = 0;

		for ( let i = 0; i < arrays.length; i ++ ) {

			const array = arrays[ i ];
			result.set( array, byteOffset );

			byteOffset += array.byteLength;

		}

		return result;

	}

}`;const fj=new Set([qt,Ro,Jr]),Z0={[CI]:qt,[vI]:qt,[gI]:qt,[AI]:qt,[wI]:Ro,[_I]:Ro,[pI]:Ro,[mI]:Ro,[bI]:Jr,[yI]:Jr,[fI]:Jr,[dI]:Jr,[SI]:tu,[xI]:tu},eb={[CI]:Ut,[vI]:Yt,[gI]:Qt,[AI]:Qt,[wI]:Ut,[_I]:Yt,[pI]:Qt,[mI]:Qt,[bI]:Ut,[yI]:Yt,[fI]:Qt,[dI]:Qt,[SI]:Qt,[xI]:Qt};async function pj(r){const{vkFormat:e}=r;if(Z0[e]===void 0)throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");let t;r.supercompressionScheme===hI&&(J0||(J0=new Promise(async s=>{const a=new dj;await a.init(),s(a)})),t=await J0);const i=[];for(let s=0;s<r.levels.length;s++){const a=Math.max(1,r.pixelWidth>>s),o=Math.max(1,r.pixelHeight>>s),l=r.pixelDepth?Math.max(1,r.pixelDepth>>s):0,c=r.levels[s];let h;if(r.supercompressionScheme===sj)h=c.levelData;else if(r.supercompressionScheme===hI)h=t.decode(c.levelData,c.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let u;eb[e]===Ut?u=new Float32Array(h.buffer,h.byteOffset,h.byteLength/Float32Array.BYTES_PER_ELEMENT):eb[e]===Yt?u=new Uint16Array(h.buffer,h.byteOffset,h.byteLength/Uint16Array.BYTES_PER_ELEMENT):u=h,i.push({data:u,width:a,height:o,depth:l})}let n;if(fj.has(Z0[e]))n=r.pixelDepth===0?new Vn(i[0].data,r.pixelWidth,r.pixelHeight):new Ff(i[0].data,r.pixelWidth,r.pixelHeight,r.pixelDepth);else{if(r.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");n=new ua(i,r.pixelWidth,r.pixelHeight)}return n.mipmaps=i,n.type=eb[e],n.format=Z0[e],n.colorSpace=TI(r),n.needsUpdate=!0,Promise.resolve(n)}function TI(r){const e=r.dataFormatDescriptor[0];return e.colorPrimaries===oj?e.transferFunction===uI?Ct:Bt:e.colorPrimaries===lj?e.transferFunction===uI?nu:su:(e.colorPrimaries===aj||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${e.colorPrimaries}"`),ai)}class II extends Lx{constructor(e){super(e)}parse(e,t){const i=new Aj(e,1);return{mipmaps:i.mipmaps(t),width:i.pixelWidth,height:i.pixelHeight,format:i.glInternalFormat,isCubemap:i.numberOfFaces===6,mipmapCount:i.numberOfMipmapLevels}}}const mj=64,gj=0;class Aj{constructor(e,t){this.arrayBuffer=e;const i=new Uint8Array(this.arrayBuffer,0,12);if(i[0]!==171||i[1]!==75||i[2]!==84||i[3]!==88||i[4]!==32||i[5]!==49||i[6]!==49||i[7]!==187||i[8]!==13||i[9]!==10||i[10]!==26||i[11]!==10){console.error("texture missing KTX identifier");return}const n=Uint32Array.BYTES_PER_ELEMENT,s=new DataView(this.arrayBuffer,12,13*n),o=s.getUint32(0,!0)===67305985;if(this.glType=s.getUint32(1*n,o),this.glTypeSize=s.getUint32(2*n,o),this.glFormat=s.getUint32(3*n,o),this.glInternalFormat=s.getUint32(4*n,o),this.glBaseInternalFormat=s.getUint32(5*n,o),this.pixelWidth=s.getUint32(6*n,o),this.pixelHeight=s.getUint32(7*n,o),this.pixelDepth=s.getUint32(8*n,o),this.numberOfArrayElements=s.getUint32(9*n,o),this.numberOfFaces=s.getUint32(10*n,o),this.numberOfMipmapLevels=s.getUint32(11*n,o),this.bytesOfKeyValueData=s.getUint32(12*n,o),this.glType!==0){console.warn("only compressed formats currently supported");return}else this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels);if(this.pixelHeight===0||this.pixelDepth!==0){console.warn("only 2D textures currently supported");return}if(this.numberOfArrayElements!==0){console.warn("texture arrays not currently supported");return}if(this.numberOfFaces!==t){console.warn("number of faces expected"+t+", but found "+this.numberOfFaces);return}this.loadType=gj}mipmaps(e){const t=[];let i=mj+this.bytesOfKeyValueData,n=this.pixelWidth,s=this.pixelHeight;const a=e?this.numberOfMipmapLevels:1;for(let o=0;o<a;o++){const l=new Int32Array(this.arrayBuffer,i,1)[0];i+=4;for(let c=0;c<this.numberOfFaces;c++){const h=new Uint8Array(this.arrayBuffer,i,l);t.push({data:h,width:n,height:s}),i+=l,i+=3-(l+3)%4}n=Math.max(1,n*.5),s=Math.max(1,s*.5)}return t}}class yj{parse(e){const t={},i=e.split(`
`);let n=null,s=t;const a=[t];for(const o of i)if(o.includes("=")){const l=o.split("="),c=l[0].trim(),h=l[1].trim();if(h.endsWith("{")){const u={};a.push(u),s[c]=u,s=u}else if(h.endsWith("(")){const u=h.slice(0,-1);s[c]=u;const d={};a.push(d),s=d}else s[c]=h}else if(o.endsWith("{")){const l=s[n]||{};a.push(l),s[n]=l,s=l}else if(o.endsWith("}")){if(a.pop(),a.length===0)continue;s=a[a.length-1]}else if(o.endsWith("(")){const l={};a.push(l),n=o.split("(")[0].trim()||n,s[n]=l,s=l}else o.endsWith(")")?(a.pop(),s=a[a.length-1]):n=o.trim();return t}}class PI extends oi{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new ti(s.manager);a.setPath(s.path),a.setResponseType("arraybuffer"),a.setRequestHeader(s.requestHeader),a.setWithCredentials(s.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}parse(e){const t=new yj;function i(C){const x={};new ti().setResponseType("arraybuffer");for(const U in C){if(U.endsWith("png")){const O=new Blob([C[U]],{type:{type:"image/png"}});x[U]=URL.createObjectURL(O)}if(U.endsWith("usd")||U.endsWith("usda")){if(n(C[U]))throw Error("THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.");const O=Qd(C[U]);x[U]=t.parse(O)}}return x}function n(C){const x=C.slice(0,7),D=new Uint8Array([80,88,82,45,85,83,68,67]);return x.every((U,O)=>U===D[O])}function s(C){if(C.length<1)return;const x=Object.keys(C)[0];let D=!1;if(x.endsWith("usda"))return C[x];if(x.endsWith("usdc"))D=!0;else if(x.endsWith("usd"))if(n(C[x]))D=!0;else return C[x];if(D)throw Error("THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.")}const a=U0(new Uint8Array(e)),o=i(a),l=s(a),c=Qd(l),h=t.parse(c);function u(C){if(C){if("prepend references"in C){const D=C["prepend references"].split("@"),U=D[1].replace(/^.\//,""),O=D[2].replace(/^<\//,"").replace(/>$/,"");return d(o[U],O)}return d(C)}}function d(C,x){if(C){if(x!==void 0){const D=`def Mesh "${x}"`;if(D in C)return C[D]}for(const D in C){const U=C[D];if(D.startsWith("def Mesh"))return U;if(typeof U=="object"){const O=d(U);if(O)return O}}}}function p(C){if(!C)return;const x=new Je;let D=null,U=null,O=null,N=-1;if("int[] faceVertexIndices"in C&&(D=JSON.parse(C["int[] faceVertexIndices"])),"int[] faceVertexCounts"in C&&(U=JSON.parse(C["int[] faceVertexCounts"]),D=m(D,U)),"point3f[] points"in C){const H=JSON.parse(C["point3f[] points"].replace(/[()]*/g,""));N=H.length;let V=new Ze(new Float32Array(H),3);D!==null&&(V=A(V,D)),x.setAttribute("position",V)}if("float2[] primvars:st"in C&&(C["texCoord2f[] primvars:st"]=C["float2[] primvars:st"]),"texCoord2f[] primvars:st"in C){O=JSON.parse(C["texCoord2f[] primvars:st"].replace(/[()]*/g,""));let H=new Ze(new Float32Array(O),2);D!==null&&(H=A(H,D)),x.setAttribute("uv",H)}if("int[] primvars:st:indices"in C&&O!==null){const H=new Ze(new Float32Array(O),2);let V=JSON.parse(C["int[] primvars:st:indices"]);V=m(V,U),x.setAttribute("uv",A(H,V))}if("normal3f[] normals"in C){const H=JSON.parse(C["normal3f[] normals"].replace(/[()]*/g,""));let V=new Ze(new Float32Array(H),3);if(H.length===N)D!==null&&(V=A(V,D));else{let X=Array.from(Array(H.length/3).keys());X=m(X,U),V=A(V,X)}x.setAttribute("normal",V)}else x.computeVertexNormals();return x}function m(C,x){const D=[];for(let U=0;U<x.length;U++){const O=x[U],N=U*O;if(O===3){const H=C[N+0],V=C[N+1],X=C[N+2];D.push(H,V,X)}else if(O===4){const H=C[N+0],V=C[N+1],X=C[N+2],W=C[N+3];D.push(H,V,X),D.push(H,X,W)}else console.warn("THREE.USDZLoader: Face vertex count of %s unsupported.",O)}return D}function A(C,x){const D=C.array,U=C.itemSize,O=new D.constructor(x.length*U);let N=0,H=0;for(let V=0,X=x.length;V<X;V++){N=x[V]*U;for(let W=0;W<U;W++)O[H++]=D[N++]}return new Ze(O,U)}function g(C){if(C){if("rel material:binding"in C){const U=C["rel material:binding"].replace(/^<\//,"").replace(/>$/,"").split("/");return y(h,` "${U[1]}"`)}return y(C)}}function y(C,x=""){for(const D in C){const U=C[D];if(D.startsWith("def Material"+x))return U;if(typeof U=="object"){const O=y(U,x);if(O)return O}}}function v(C,x){x["float inputs:rotation"]&&(C.rotation=parseFloat(x["float inputs:rotation"])),x["float2 inputs:scale"]&&(C.repeat=new K().fromArray(JSON.parse("["+x["float2 inputs:scale"].replace(/[()]*/g,"")+"]"))),x["float2 inputs:translation"]&&(C.offset=new K().fromArray(JSON.parse("["+x["float2 inputs:translation"].replace(/[()]*/g,"")+"]")))}function _(C){const x=new Jo;if(C!==void 0){const D=C["token outputs:surface.connect"],U=/(\w+).output/.exec(D)[1],O=C[`def Shader "${U}"`];if(O!==void 0){if("color3f inputs:diffuseColor.connect"in O){const N=O["color3f inputs:diffuseColor.connect"],H=b(h,/(\w+).output/.exec(N)[1]);x.map=T(H),x.map.colorSpace=Ct,'def Shader "Transform2d_diffuse"'in C&&v(x.map,C['def Shader "Transform2d_diffuse"'])}else if("color3f inputs:diffuseColor"in O){const N=O["color3f inputs:diffuseColor"].replace(/[()]*/g,"");x.color.fromArray(JSON.parse("["+N+"]"))}if("color3f inputs:emissiveColor.connect"in O){const N=O["color3f inputs:emissiveColor.connect"],H=b(h,/(\w+).output/.exec(N)[1]);x.emissiveMap=T(H),x.emissiveMap.colorSpace=Ct,x.emissive.set(16777215),'def Shader "Transform2d_emissive"'in C&&v(x.emissiveMap,C['def Shader "Transform2d_emissive"'])}else if("color3f inputs:emissiveColor"in O){const N=O["color3f inputs:emissiveColor"].replace(/[()]*/g,"");x.emissive.fromArray(JSON.parse("["+N+"]"))}if("normal3f inputs:normal.connect"in O){const N=O["normal3f inputs:normal.connect"],H=b(h,/(\w+).output/.exec(N)[1]);x.normalMap=T(H),x.normalMap.colorSpace=ai,'def Shader "Transform2d_normal"'in C&&v(x.normalMap,C['def Shader "Transform2d_normal"'])}if("float inputs:roughness.connect"in O){const N=O["float inputs:roughness.connect"],H=b(h,/(\w+).output/.exec(N)[1]);x.roughness=1,x.roughnessMap=T(H),x.roughnessMap.colorSpace=ai,'def Shader "Transform2d_roughness"'in C&&v(x.roughnessMap,C['def Shader "Transform2d_roughness"'])}else"float inputs:roughness"in O&&(x.roughness=parseFloat(O["float inputs:roughness"]));if("float inputs:metallic.connect"in O){const N=O["float inputs:metallic.connect"],H=b(h,/(\w+).output/.exec(N)[1]);x.metalness=1,x.metalnessMap=T(H),x.metalnessMap.colorSpace=ai,'def Shader "Transform2d_metallic"'in C&&v(x.metalnessMap,C['def Shader "Transform2d_metallic"'])}else"float inputs:metallic"in O&&(x.metalness=parseFloat(O["float inputs:metallic"]));if("float inputs:clearcoat.connect"in O){const N=O["float inputs:clearcoat.connect"],H=b(h,/(\w+).output/.exec(N)[1]);x.clearcoat=1,x.clearcoatMap=T(H),x.clearcoatMap.colorSpace=ai,'def Shader "Transform2d_clearcoat"'in C&&v(x.clearcoatMap,C['def Shader "Transform2d_clearcoat"'])}else"float inputs:clearcoat"in O&&(x.clearcoat=parseFloat(O["float inputs:clearcoat"]));if("float inputs:clearcoatRoughness.connect"in O){const N=O["float inputs:clearcoatRoughness.connect"],H=b(h,/(\w+).output/.exec(N)[1]);x.clearcoatRoughness=1,x.clearcoatRoughnessMap=T(H),x.clearcoatRoughnessMap.colorSpace=ai,'def Shader "Transform2d_clearcoatRoughness"'in C&&v(x.clearcoatRoughnessMap,C['def Shader "Transform2d_clearcoatRoughness"'])}else"float inputs:clearcoatRoughness"in O&&(x.clearcoatRoughness=parseFloat(O["float inputs:clearcoatRoughness"]));if("float inputs:ior"in O&&(x.ior=parseFloat(O["float inputs:ior"])),"float inputs:occlusion.connect"in O){const N=O["float inputs:occlusion.connect"],H=b(h,/(\w+).output/.exec(N)[1]);x.aoMap=T(H),x.aoMap.colorSpace=ai,'def Shader "Transform2d_occlusion"'in C&&v(x.aoMap,C['def Shader "Transform2d_occlusion"'])}}}return x}function b(C,x){for(const D in C){const U=C[D];if(D.startsWith(`def Shader "${x}"`))return U;if(typeof U=="object"){const O=b(U,x);if(O)return O}}}function T(C){if("asset inputs:file"in C){const x=C["asset inputs:file"].replace(/@*/g,"").trim(),U=new Za().load(o[x]),O={'"clamp"':di,'"mirror"':Kr,'"repeat"':Pn};return"token inputs:wrapS"in C&&(U.wrapS=O[C["token inputs:wrapS"]]),"token inputs:wrapT"in C&&(U.wrapT=O[C["token inputs:wrapT"]]),U}return null}function E(C){const x=p(u(C)),D=_(g(C)),U=x?new _e(x,D):new ft;if("matrix4d xformOp:transform"in C){const O=JSON.parse("["+C["matrix4d xformOp:transform"].replace(/[()]*/g,"")+"]");U.matrix.fromArray(O),U.matrix.decompose(U.position,U.quaternion,U.scale)}return U}function M(C,x){for(const D in C)if(D.startsWith("def Scope"))M(C[D],x);else if(D.startsWith("def Xform")){const U=E(C[D]);/def Xform "(\w+)"/.test(D)&&(U.name=/def Xform "(\w+)"/.exec(D)[1]),x.add(U),M(C[D],U)}}const I=new Vi;return M(h,I),I}}const _s=new ee;class DI extends oi{constructor(e){super(e),this.propertyNameMapping={},this.customPropertyMapping={}}load(e,t,i,n){const s=this,a=new ti(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}setPropertyNameMapping(e){this.propertyNameMapping=e}setCustomPropertyNameMapping(e){this.customPropertyMapping=e}parse(e){function t(g,y=0){const v=/^ply([\s\S]*)end_header(\r\n|\r|\n)/;let _="";const b=v.exec(g);b!==null&&(_=b[1]);const T={comments:[],elements:[],headerLength:y,objInfo:""},E=_.split(/\r\n|\r|\n/);let M;function I(C,x){const D={type:C[0]};return D.type==="list"?(D.name=C[3],D.countType=C[1],D.itemType=C[2]):D.name=C[1],D.name in x&&(D.name=x[D.name]),D}for(let C=0;C<E.length;C++){let x=E[C];if(x=x.trim(),x==="")continue;const D=x.split(/\s+/),U=D.shift();switch(x=D.join(" "),U){case"format":T.format=D[0],T.version=D[1];break;case"comment":T.comments.push(x);break;case"element":M!==void 0&&T.elements.push(M),M={},M.name=D[0],M.count=parseInt(D[1]),M.properties=[];break;case"property":M.properties.push(I(D,A.propertyNameMapping));break;case"obj_info":T.objInfo=x;break;default:console.log("unhandled",U,D)}}return M!==void 0&&T.elements.push(M),T}function i(g,y){switch(y){case"char":case"uchar":case"short":case"ushort":case"int":case"uint":case"int8":case"uint8":case"int16":case"uint16":case"int32":case"uint32":return parseInt(g);case"float":case"double":case"float32":case"float64":return parseFloat(g)}}function n(g,y){const v={};for(let _=0;_<g.length;_++){if(y.empty())return null;if(g[_].type==="list"){const b=[],T=i(y.next(),g[_].countType);for(let E=0;E<T;E++){if(y.empty())return null;b.push(i(y.next(),g[_].itemType))}v[g[_].name]=b}else v[g[_].name]=i(y.next(),g[_].type)}return v}function s(){const g={indices:[],vertices:[],normals:[],uvs:[],faceVertexUvs:[],colors:[],faceVertexColors:[]};for(const y of Object.keys(A.customPropertyMapping))g[y]=[];return g}function a(g){const y=g.map(_=>_.name);function v(_){for(let b=0,T=_.length;b<T;b++){const E=_[b];if(y.includes(E))return E}return null}return{attrX:v(["x","px","posx"])||"x",attrY:v(["y","py","posy"])||"y",attrZ:v(["z","pz","posz"])||"z",attrNX:v(["nx","normalx"]),attrNY:v(["ny","normaly"]),attrNZ:v(["nz","normalz"]),attrS:v(["s","u","texture_u","tx"]),attrT:v(["t","v","texture_v","ty"]),attrR:v(["red","diffuse_red","r","diffuse_r"]),attrG:v(["green","diffuse_green","g","diffuse_g"]),attrB:v(["blue","diffuse_blue","b","diffuse_b"])}}function o(g,y){const v=s(),_=/end_header\s+(\S[\s\S]*\S|\S)\s*$/;let b,T;(T=_.exec(g))!==null?b=T[1].split(/\s+/):b=[];const E=new _j(b);e:for(let M=0;M<y.elements.length;M++){const I=y.elements[M],C=a(I.properties);for(let x=0;x<I.count;x++){const D=n(I.properties,E);if(!D)break e;c(v,I.name,D,C)}}return l(v)}function l(g){let y=new Je;g.indices.length>0&&y.setIndex(g.indices),y.setAttribute("position",new Ee(g.vertices,3)),g.normals.length>0&&y.setAttribute("normal",new Ee(g.normals,3)),g.uvs.length>0&&y.setAttribute("uv",new Ee(g.uvs,2)),g.colors.length>0&&y.setAttribute("color",new Ee(g.colors,3)),(g.faceVertexUvs.length>0||g.faceVertexColors.length>0)&&(y=y.toNonIndexed(),g.faceVertexUvs.length>0&&y.setAttribute("uv",new Ee(g.faceVertexUvs,2)),g.faceVertexColors.length>0&&y.setAttribute("color",new Ee(g.faceVertexColors,3)));for(const v of Object.keys(A.customPropertyMapping))g[v].length>0&&y.setAttribute(v,new Ee(g[v],A.customPropertyMapping[v].length));return y.computeBoundingSphere(),y}function c(g,y,v,_){if(y==="vertex"){g.vertices.push(v[_.attrX],v[_.attrY],v[_.attrZ]),_.attrNX!==null&&_.attrNY!==null&&_.attrNZ!==null&&g.normals.push(v[_.attrNX],v[_.attrNY],v[_.attrNZ]),_.attrS!==null&&_.attrT!==null&&g.uvs.push(v[_.attrS],v[_.attrT]),_.attrR!==null&&_.attrG!==null&&_.attrB!==null&&(_s.setRGB(v[_.attrR]/255,v[_.attrG]/255,v[_.attrB]/255).convertSRGBToLinear(),g.colors.push(_s.r,_s.g,_s.b));for(const b of Object.keys(A.customPropertyMapping))for(const T of A.customPropertyMapping[b])g[b].push(v[T])}else if(y==="face"){const b=v.vertex_indices||v.vertex_index,T=v.texcoord;b.length===3?(g.indices.push(b[0],b[1],b[2]),T&&T.length===6&&(g.faceVertexUvs.push(T[0],T[1]),g.faceVertexUvs.push(T[2],T[3]),g.faceVertexUvs.push(T[4],T[5]))):b.length===4&&(g.indices.push(b[0],b[1],b[3]),g.indices.push(b[1],b[2],b[3])),_.attrR!==null&&_.attrG!==null&&_.attrB!==null&&(_s.setRGB(v[_.attrR]/255,v[_.attrG]/255,v[_.attrB]/255).convertSRGBToLinear(),g.faceVertexColors.push(_s.r,_s.g,_s.b),g.faceVertexColors.push(_s.r,_s.g,_s.b),g.faceVertexColors.push(_s.r,_s.g,_s.b))}}function h(g,y){const v={};let _=0;for(let b=0;b<y.length;b++){const T=y[b],E=T.valueReader;if(T.type==="list"){const M=[],I=T.countReader.read(g+_);_+=T.countReader.size;for(let C=0;C<I;C++)M.push(E.read(g+_)),_+=E.size;v[T.name]=M}else v[T.name]=E.read(g+_),_+=E.size}return[v,_]}function u(g,y,v){function _(b,T,E){switch(T){case"int8":case"char":return{read:M=>b.getInt8(M),size:1};case"uint8":case"uchar":return{read:M=>b.getUint8(M),size:1};case"int16":case"short":return{read:M=>b.getInt16(M,E),size:2};case"uint16":case"ushort":return{read:M=>b.getUint16(M,E),size:2};case"int32":case"int":return{read:M=>b.getInt32(M,E),size:4};case"uint32":case"uint":return{read:M=>b.getUint32(M,E),size:4};case"float32":case"float":return{read:M=>b.getFloat32(M,E),size:4};case"float64":case"double":return{read:M=>b.getFloat64(M,E),size:8}}}for(let b=0,T=g.length;b<T;b++){const E=g[b];E.type==="list"?(E.countReader=_(y,E.countType,v),E.valueReader=_(y,E.itemType,v)):E.valueReader=_(y,E.type,v)}}function d(g,y){const v=s(),_=y.format==="binary_little_endian",b=new DataView(g,y.headerLength);let T,E=0;for(let M=0;M<y.elements.length;M++){const I=y.elements[M],C=I.properties,x=a(C);u(C,b,_);for(let D=0;D<I.count;D++){T=h(E,C),E+=T[1];const U=T[0];c(v,I.name,U,x)}}return l(v)}function p(g){let y=0,v=!0,_="";const b=[],T=new TextDecoder().decode(g.subarray(0,5)),E=/^ply\r\n/.test(T);do{const M=String.fromCharCode(g[y++]);M!==`
`&&M!=="\r"?_+=M:(_==="end_header"&&(v=!1),_!==""&&(b.push(_),_=""))}while(v&&y<g.length);return E===!0&&y++,{headerText:b.join("\r")+"\r",headerLength:y}}let m;const A=this;if(e instanceof ArrayBuffer){const g=new Uint8Array(e),{headerText:y,headerLength:v}=p(g),_=t(y,v);if(_.format==="ascii"){const b=new TextDecoder().decode(g);m=o(b,_)}else m=d(e,_)}else m=o(e,t(e));return m}}class _j{constructor(e){this.arr=e,this.i=0}empty(){return this.i>=this.arr.length}next(){return this.arr[this.i++]}}class RI extends oi{constructor(e){super(e)}load(e,t,i,n){const s=this,a=new ti(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){n?n(l):console.error(l),s.manager.itemError(e)}},i,n)}parse(e){function t(c){const h=new DataView(c),u=32/8*3+32/8*3*3+16/8,d=h.getUint32(80,!0);if(80+32/8+d*u===h.byteLength)return!0;const m=[115,111,108,105,100];for(let A=0;A<5;A++)if(i(m,h,A))return!1;return!0}function i(c,h,u){for(let d=0,p=c.length;d<p;d++)if(c[d]!==h.getUint8(u+d))return!1;return!0}function n(c){const h=new DataView(c),u=h.getUint32(80,!0);let d,p,m,A=!1,g,y,v,_,b;for(let D=0;D<70;D++)h.getUint32(D,!1)==1129270351&&h.getUint8(D+4)==82&&h.getUint8(D+5)==61&&(A=!0,g=new Float32Array(u*3*3),y=h.getUint8(D+6)/255,v=h.getUint8(D+7)/255,_=h.getUint8(D+8)/255,b=h.getUint8(D+9)/255);const T=84,E=50,M=new Je,I=new Float32Array(u*3*3),C=new Float32Array(u*3*3),x=new ee;for(let D=0;D<u;D++){const U=T+D*E,O=h.getFloat32(U,!0),N=h.getFloat32(U+4,!0),H=h.getFloat32(U+8,!0);if(A){const V=h.getUint16(U+48,!0);(V&32768)===0?(d=(V&31)/31,p=(V>>5&31)/31,m=(V>>10&31)/31):(d=y,p=v,m=_)}for(let V=1;V<=3;V++){const X=U+V*12,W=D*3*3+(V-1)*3;I[W]=h.getFloat32(X,!0),I[W+1]=h.getFloat32(X+4,!0),I[W+2]=h.getFloat32(X+8,!0),C[W]=O,C[W+1]=N,C[W+2]=H,A&&(x.set(d,p,m).convertSRGBToLinear(),g[W]=x.r,g[W+1]=x.g,g[W+2]=x.b)}}return M.setAttribute("position",new Ze(I,3)),M.setAttribute("normal",new Ze(C,3)),A&&(M.setAttribute("color",new Ze(g,3)),M.hasColors=!0,M.alpha=b),M}function s(c){const h=new Je,u=/solid([\s\S]*?)endsolid/g,d=/facet([\s\S]*?)endfacet/g,p=/solid\s(.+)/;let m=0;const A=/[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source,g=new RegExp("vertex"+A+A+A,"g"),y=new RegExp("normal"+A+A+A,"g"),v=[],_=[],b=[],T=new S;let E,M=0,I=0,C=0;for(;(E=u.exec(c))!==null;){I=C;const x=E[0],D=(E=p.exec(x))!==null?E[1]:"";for(b.push(D);(E=d.exec(x))!==null;){let N=0,H=0;const V=E[0];for(;(E=y.exec(V))!==null;)T.x=parseFloat(E[1]),T.y=parseFloat(E[2]),T.z=parseFloat(E[3]),H++;for(;(E=g.exec(V))!==null;)v.push(parseFloat(E[1]),parseFloat(E[2]),parseFloat(E[3])),_.push(T.x,T.y,T.z),N++,C++;H!==1&&console.error("THREE.STLLoader: Something isn't right with the normal of face number "+m),N!==3&&console.error("THREE.STLLoader: Something isn't right with the vertices of face number "+m),m++}const U=I,O=C-I;h.userData.groupNames=b,h.addGroup(U,O,M),M++}return h.setAttribute("position",new Ee(v,3)),h.setAttribute("normal",new Ee(_,3)),h}function a(c){return typeof c!="string"?new TextDecoder().decode(c):c}function o(c){if(typeof c=="string"){const h=new Uint8Array(c.length);for(let u=0;u<c.length;u++)h[u]=c.charCodeAt(u)&255;return h.buffer||h}else return c}const l=o(e);return t(l)?n(l):s(a(e))}}class vj{constructor(e,t,i){this.variables=[],this.currentTextureIndex=0;let n=Ut;const s={passThruTexture:{value:null}},a=c(u(),s),o=new e0(a);this.setDataType=function(d){return n=d,this},this.addVariable=function(d,p,m){const A=this.createShaderMaterial(p),g={name:d,initialValueTexture:m,material:A,dependencies:null,renderTargets:[],wrapS:null,wrapT:null,minFilter:mi,magFilter:mi};return this.variables.push(g),g},this.setVariableDependencies=function(d,p){d.dependencies=p},this.init=function(){if(i.capabilities.maxVertexTextures===0)return"No support for vertex shader textures.";for(let d=0;d<this.variables.length;d++){const p=this.variables[d];p.renderTargets[0]=this.createRenderTarget(e,t,p.wrapS,p.wrapT,p.minFilter,p.magFilter),p.renderTargets[1]=this.createRenderTarget(e,t,p.wrapS,p.wrapT,p.minFilter,p.magFilter),this.renderTexture(p.initialValueTexture,p.renderTargets[0]),this.renderTexture(p.initialValueTexture,p.renderTargets[1]);const m=p.material,A=m.uniforms;if(p.dependencies!==null)for(let g=0;g<p.dependencies.length;g++){const y=p.dependencies[g];if(y.name!==p.name){let v=!1;for(let _=0;_<this.variables.length;_++)if(y.name===this.variables[_].name){v=!0;break}if(!v)return"Variable dependency not found. Variable="+p.name+", dependency="+y.name}A[y.name]={value:null},m.fragmentShader=`
uniform sampler2D `+y.name+`;
`+m.fragmentShader}}return this.currentTextureIndex=0,null},this.compute=function(){const d=this.currentTextureIndex,p=this.currentTextureIndex===0?1:0;for(let m=0,A=this.variables.length;m<A;m++){const g=this.variables[m];if(g.dependencies!==null){const y=g.material.uniforms;for(let v=0,_=g.dependencies.length;v<_;v++){const b=g.dependencies[v];y[b.name].value=b.renderTargets[d].texture}}this.doRenderTarget(g.material,g.renderTargets[p])}this.currentTextureIndex=p},this.getCurrentRenderTarget=function(d){return d.renderTargets[this.currentTextureIndex]},this.getAlternateRenderTarget=function(d){return d.renderTargets[this.currentTextureIndex===0?1:0]},this.dispose=function(){o.dispose();const d=this.variables;for(let p=0;p<d.length;p++){const m=d[p];m.initialValueTexture&&m.initialValueTexture.dispose();const A=m.renderTargets;for(let g=0;g<A.length;g++)A[g].dispose()}};function l(d){d.defines.resolution="vec2( "+e.toFixed(1)+", "+t.toFixed(1)+" )"}this.addResolutionDefine=l;function c(d,p){p=p||{};const m=new nn({name:"GPUComputationShader",uniforms:p,vertexShader:h(),fragmentShader:d});return l(m),m}this.createShaderMaterial=c,this.createRenderTarget=function(d,p,m,A,g,y){return d=d||e,p=p||t,m=m||di,A=A||di,g=g||mi,y=y||mi,new ds(d,p,{wrapS:m,wrapT:A,minFilter:g,magFilter:y,format:qt,type:n,depthBuffer:!1})},this.createTexture=function(){const d=new Float32Array(e*t*4),p=new Vn(d,e,t,qt,Ut);return p.needsUpdate=!0,p},this.renderTexture=function(d,p){s.passThruTexture.value=d,this.doRenderTarget(a,p),s.passThruTexture.value=null},this.doRenderTarget=function(d,p){const m=i.getRenderTarget(),A=i.xr.enabled,g=i.shadowMap.autoUpdate;i.xr.enabled=!1,i.shadowMap.autoUpdate=!1,o.material=d,i.setRenderTarget(p),o.render(i),o.material=a,i.xr.enabled=A,i.shadowMap.autoUpdate=g,i.setRenderTarget(m)};function h(){return`void main()	{

	gl_Position = vec4( position, 1.0 );

}
`}function u(){return`uniform sampler2D passThruTexture;

void main() {

	vec2 uv = gl_FragCoord.xy / resolution.xy;

	gl_FragColor = texture2D( passThruTexture, uv );

}
`}}}const Ni=new ts,Ng=new S,BI=new K,LI=new K,OI=new K;class bj{constructor(e){this.geometry=e.geometry,this.randomFunction=Math.random,this.indexAttribute=this.geometry.index,this.positionAttribute=this.geometry.getAttribute("position"),this.normalAttribute=this.geometry.getAttribute("normal"),this.colorAttribute=this.geometry.getAttribute("color"),this.uvAttribute=this.geometry.getAttribute("uv"),this.weightAttribute=null,this.distribution=null}setWeightAttribute(e){return this.weightAttribute=e?this.geometry.getAttribute(e):null,this}build(){const e=this.indexAttribute,t=this.positionAttribute,i=this.weightAttribute,n=e?e.count/3:t.count/3,s=new Float32Array(n);for(let l=0;l<n;l++){let c=1,h=3*l,u=3*l+1,d=3*l+2;e&&(h=e.getX(h),u=e.getX(u),d=e.getX(d)),i&&(c=i.getX(h)+i.getX(u)+i.getX(d)),Ni.a.fromBufferAttribute(t,h),Ni.b.fromBufferAttribute(t,u),Ni.c.fromBufferAttribute(t,d),c*=Ni.getArea(),s[l]=c}const a=new Float32Array(n);let o=0;for(let l=0;l<n;l++)o+=s[l],a[l]=o;return this.distribution=a,this}setRandomGenerator(e){return this.randomFunction=e,this}sample(e,t,i,n){const s=this.sampleFaceIndex();return this.sampleFace(s,e,t,i,n)}sampleFaceIndex(){const e=this.distribution[this.distribution.length-1];return this.binarySearch(this.randomFunction()*e)}binarySearch(e){const t=this.distribution;let i=0,n=t.length-1,s=-1;for(;i<=n;){const a=Math.ceil((i+n)/2);if(a===0||t[a-1]<=e&&t[a]>e){s=a;break}else e<t[a]?n=a-1:i=a+1}return s}sampleFace(e,t,i,n,s){let a=this.randomFunction(),o=this.randomFunction();a+o>1&&(a=1-a,o=1-o);const l=this.indexAttribute;let c=e*3,h=e*3+1,u=e*3+2;return l&&(c=l.getX(c),h=l.getX(h),u=l.getX(u)),Ni.a.fromBufferAttribute(this.positionAttribute,c),Ni.b.fromBufferAttribute(this.positionAttribute,h),Ni.c.fromBufferAttribute(this.positionAttribute,u),t.set(0,0,0).addScaledVector(Ni.a,a).addScaledVector(Ni.b,o).addScaledVector(Ni.c,1-(a+o)),i!==void 0&&(this.normalAttribute!==void 0?(Ni.a.fromBufferAttribute(this.normalAttribute,c),Ni.b.fromBufferAttribute(this.normalAttribute,h),Ni.c.fromBufferAttribute(this.normalAttribute,u),i.set(0,0,0).addScaledVector(Ni.a,a).addScaledVector(Ni.b,o).addScaledVector(Ni.c,1-(a+o)).normalize()):Ni.getNormal(i)),n!==void 0&&this.colorAttribute!==void 0&&(Ni.a.fromBufferAttribute(this.colorAttribute,c),Ni.b.fromBufferAttribute(this.colorAttribute,h),Ni.c.fromBufferAttribute(this.colorAttribute,u),Ng.set(0,0,0).addScaledVector(Ni.a,a).addScaledVector(Ni.b,o).addScaledVector(Ni.c,1-(a+o)),n.r=Ng.x,n.g=Ng.y,n.b=Ng.z),s!==void 0&&this.uvAttribute!==void 0&&(BI.fromBufferAttribute(this.uvAttribute,c),LI.fromBufferAttribute(this.uvAttribute,h),OI.fromBufferAttribute(this.uvAttribute,u),s.set(0,0).addScaledVector(BI,a).addScaledVector(LI,o).addScaledVector(OI,1-(a+o))),this}}const kg=0,wj=1,Cj=new S,UI=new x_,tb=new Es,FI=new S,Gg=new ts;class xj{constructor(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new ib,this.unassigned=new ib,this.vertices=[]}setFromPoints(e){if(e.length>=4){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.vertices.push(new NI(e[t]));this.compute()}return this}setFromObject(e){const t=[];return e.updateMatrixWorld(!0),e.traverse(function(i){const n=i.geometry;if(n!==void 0){const s=n.attributes.position;if(s!==void 0)for(let a=0,o=s.count;a<o;a++){const l=new S;l.fromBufferAttribute(s,a).applyMatrix4(i.matrixWorld),t.push(l)}}}),this.setFromPoints(t)}containsPoint(e){const t=this.faces;for(let i=0,n=t.length;i<n;i++)if(t[i].distanceToPoint(e)>this.tolerance)return!1;return!0}intersectRay(e,t){const i=this.faces;let n=-1/0,s=1/0;for(let a=0,o=i.length;a<o;a++){const l=i[a],c=l.distanceToPoint(e.origin),h=l.normal.dot(e.direction);if(c>0&&h>=0)return null;const u=h!==0?-c/h:0;if(!(u<=0)&&(h>0?s=Math.min(u,s):n=Math.max(u,n),n>s))return null}return n!==-1/0?e.at(n,t):e.at(s,t),t}intersectsRay(e){return this.intersectRay(e,Cj)!==null}makeEmpty(){return this.faces=[],this.vertices=[],this}addVertexToFace(e,t){return e.face=t,t.outside===null?this.assigned.append(e):this.assigned.insertBefore(t.outside,e),t.outside=e,this}removeVertexFromFace(e,t){return e===t.outside&&(e.next!==null&&e.next.face===t?t.outside=e.next:t.outside=null),this.assigned.remove(e),this}removeAllVerticesFromFace(e){if(e.outside!==null){const t=e.outside;let i=e.outside;for(;i.next!==null&&i.next.face===e;)i=i.next;return this.assigned.removeSubList(t,i),t.prev=i.next=null,e.outside=null,t}}deleteFaceVertices(e,t){const i=this.removeAllVerticesFromFace(e);if(i!==void 0)if(t===void 0)this.unassigned.appendChain(i);else{let n=i;do{const s=n.next;t.distanceToPoint(n.point)>this.tolerance?this.addVertexToFace(n,t):this.unassigned.append(n),n=s}while(n!==null)}return this}resolveUnassignedPoints(e){if(this.unassigned.isEmpty()===!1){let t=this.unassigned.first();do{const i=t.next;let n=this.tolerance,s=null;for(let a=0;a<e.length;a++){const o=e[a];if(o.mark===kg){const l=o.distanceToPoint(t.point);if(l>n&&(n=l,s=o),n>1e3*this.tolerance)break}}s!==null&&this.addVertexToFace(t,s),t=i}while(t!==null)}return this}computeExtremes(){const e=new S,t=new S,i=[],n=[];for(let s=0;s<3;s++)i[s]=n[s]=this.vertices[0];e.copy(this.vertices[0].point),t.copy(this.vertices[0].point);for(let s=0,a=this.vertices.length;s<a;s++){const o=this.vertices[s],l=o.point;for(let c=0;c<3;c++)l.getComponent(c)<e.getComponent(c)&&(e.setComponent(c,l.getComponent(c)),i[c]=o);for(let c=0;c<3;c++)l.getComponent(c)>t.getComponent(c)&&(t.setComponent(c,l.getComponent(c)),n[c]=o)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(e.x),Math.abs(t.x))+Math.max(Math.abs(e.y),Math.abs(t.y))+Math.max(Math.abs(e.z),Math.abs(t.z))),{min:i,max:n}}computeInitialHull(){const e=this.vertices,t=this.computeExtremes(),i=t.min,n=t.max;let s=0,a=0;for(let d=0;d<3;d++){const p=n[d].point.getComponent(d)-i[d].point.getComponent(d);p>s&&(s=p,a=d)}const o=i[a],l=n[a];let c,h;s=0,UI.set(o.point,l.point);for(let d=0,p=this.vertices.length;d<p;d++){const m=e[d];if(m!==o&&m!==l){UI.closestPointToPoint(m.point,!0,FI);const A=FI.distanceToSquared(m.point);A>s&&(s=A,c=m)}}s=-1,tb.setFromCoplanarPoints(o.point,l.point,c.point);for(let d=0,p=this.vertices.length;d<p;d++){const m=e[d];if(m!==o&&m!==l&&m!==c){const A=Math.abs(tb.distanceToPoint(m.point));A>s&&(s=A,h=m)}}const u=[];if(tb.distanceToPoint(h.point)<0){u.push($s.create(o,l,c),$s.create(h,l,o),$s.create(h,c,l),$s.create(h,o,c));for(let d=0;d<3;d++){const p=(d+1)%3;u[d+1].getEdge(2).setTwin(u[0].getEdge(p)),u[d+1].getEdge(1).setTwin(u[p+1].getEdge(0))}}else{u.push($s.create(o,c,l),$s.create(h,o,l),$s.create(h,l,c),$s.create(h,c,o));for(let d=0;d<3;d++){const p=(d+1)%3;u[d+1].getEdge(2).setTwin(u[0].getEdge((3-d)%3)),u[d+1].getEdge(0).setTwin(u[p+1].getEdge(1))}}for(let d=0;d<4;d++)this.faces.push(u[d]);for(let d=0,p=e.length;d<p;d++){const m=e[d];if(m!==o&&m!==l&&m!==c&&m!==h){s=this.tolerance;let A=null;for(let g=0;g<4;g++){const y=this.faces[g].distanceToPoint(m.point);y>s&&(s=y,A=this.faces[g])}A!==null&&this.addVertexToFace(m,A)}}return this}reindexFaces(){const e=[];for(let t=0;t<this.faces.length;t++){const i=this.faces[t];i.mark===kg&&e.push(i)}return this.faces=e,this}nextVertexToAdd(){if(this.assigned.isEmpty()===!1){let e,t=0;const i=this.assigned.first().face;let n=i.outside;do{const s=i.distanceToPoint(n.point);s>t&&(t=s,e=n),n=n.next}while(n!==null&&n.face===i);return e}}computeHorizon(e,t,i,n){this.deleteFaceVertices(i),i.mark=wj;let s;t===null?s=t=i.getEdge(0):s=t.next;do{const a=s.twin,o=a.face;o.mark===kg&&(o.distanceToPoint(e)>this.tolerance?this.computeHorizon(e,a,o,n):n.push(s)),s=s.next}while(s!==t);return this}addAdjoiningFace(e,t){const i=$s.create(e,t.tail(),t.head());return this.faces.push(i),i.getEdge(-1).setTwin(t.twin),i.getEdge(0)}addNewFaces(e,t){this.newFaces=[];let i=null,n=null;for(let s=0;s<t.length;s++){const a=t[s],o=this.addAdjoiningFace(e,a);i===null?i=o:o.next.setTwin(n),this.newFaces.push(o.face),n=o}return i.next.setTwin(n),this}addVertexToHull(e){const t=[];return this.unassigned.clear(),this.removeVertexFromFace(e,e.face),this.computeHorizon(e.point,null,e.face,t),this.addNewFaces(e,t),this.resolveUnassignedPoints(this.newFaces),this}cleanup(){return this.assigned.clear(),this.unassigned.clear(),this.newFaces=[],this}compute(){let e;for(this.computeInitialHull();(e=this.nextVertexToAdd())!==void 0;)this.addVertexToHull(e);return this.reindexFaces(),this.cleanup(),this}}class $s{constructor(){this.normal=new S,this.midpoint=new S,this.area=0,this.constant=0,this.outside=null,this.mark=kg,this.edge=null}static create(e,t,i){const n=new $s,s=new zg(e,n),a=new zg(t,n),o=new zg(i,n);return s.next=o.prev=a,a.next=s.prev=o,o.next=a.prev=s,n.edge=s,n.compute()}getEdge(e){let t=this.edge;for(;e>0;)t=t.next,e--;for(;e<0;)t=t.prev,e++;return t}compute(){const e=this.edge.tail(),t=this.edge.head(),i=this.edge.next.head();return Gg.set(e.point,t.point,i.point),Gg.getNormal(this.normal),Gg.getMidpoint(this.midpoint),this.area=Gg.getArea(),this.constant=this.normal.dot(this.midpoint),this}distanceToPoint(e){return this.normal.dot(e)-this.constant}}class zg{constructor(e,t){this.vertex=e,this.prev=null,this.next=null,this.twin=null,this.face=t}head(){return this.vertex}tail(){return this.prev?this.prev.vertex:null}length(){const e=this.head(),t=this.tail();return t!==null?t.point.distanceTo(e.point):-1}lengthSquared(){const e=this.head(),t=this.tail();return t!==null?t.point.distanceToSquared(e.point):-1}setTwin(e){return this.twin=e,e.twin=this,this}}class NI{constructor(e){this.point=e,this.prev=null,this.next=null,this.face=null}}class ib{constructor(){this.head=null,this.tail=null}first(){return this.head}last(){return this.tail}clear(){return this.head=this.tail=null,this}insertBefore(e,t){return t.prev=e.prev,t.next=e,t.prev===null?this.head=t:t.prev.next=t,e.prev=t,this}insertAfter(e,t){return t.prev=e,t.next=e.next,t.next===null?this.tail=t:t.next.prev=t,e.next=t,this}append(e){return this.head===null?this.head=e:this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e,this}appendChain(e){for(this.head===null?this.head=e:this.tail.next=e,e.prev=this.tail;e.next!==null;)e=e.next;return this.tail=e,this}remove(e){return e.prev===null?this.head=e.next:e.prev.next=e.next,e.next===null?this.tail=e.prev:e.next.prev=e.prev,this}removeSubList(e,t){return e.prev===null?this.head=t.next:e.prev.next=t.next,t.next===null?this.tail=e.prev:t.next.prev=e.prev,this}isEmpty(){return this.head===null}}class Rl{constructor(){this.toJSON=null}onAdded(e){e.assetManager.importer.addImporter(this._importer)}onRemove(e){e.assetManager.importer.removeImporter(this._importer)}dispose(){}}var Sj=Object.defineProperty,Ej=Object.getOwnPropertyDescriptor,Ia=(r,e,t,i)=>{for(var n=i>1?void 0:i?Ej(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Sj(e,t,n),n};f.BaseGroundPlugin=class extends mt{constructor(){super(),this._transformNeedRefresh=!0,this.visible=!0,this.size=8,this.yOffset=0,this.renderToDepth=!0,this.tonemapGround=!0,this.limitCameraAboveGround=!1,this.autoAdjustTransform=!0,this.enableRefreshTransform=!0,this._cameraLimitsSet=!1,this._cameraLastMaxPolarAngle=Math.PI,this.useModelBounds=!0,this._refreshMaterial=this._refreshMaterial.bind(this),this._refreshTransform=this._refreshTransform.bind(this),this._refreshCameraLimits=this._refreshCameraLimits.bind(this),this.refresh=this.refresh.bind(this),this._refresh2=this._refresh2.bind(this),this._onSceneUpdate=this._onSceneUpdate.bind(this),this._preRender=this._preRender.bind(this),this._postFrame=this._postFrame.bind(this),this._geometry=ni.upgradeGeometry.call(new ca(1,1,1,1)),this._geometry.attributes.uv2=this._geometry.attributes.uv.clone(),this._geometry.attributes.uv2.needsUpdate=!0,this._mesh=this._createMesh(),this._mesh.userData.physicsMass=0,this._mesh.userData.physicsBodyType="static",this._mesh.userData.userSelectable=!1,this._mesh.userData.isGroundMesh=!0,this._mesh.castShadow=!0,this._mesh.receiveShadow=!0,this._mesh.name||(this._mesh.name="Ground Plane"),this._mesh.visible=!1,this._defaultMaterial=this._mesh.material,this.refresh()}get enabled(){return this.visible}set enabled(e){this.visible=e}onAdded(e){super.onAdded(e),e.scene.addObject(this._mesh,{addToRoot:!0}),e.scene.addEventListener("sceneUpdate",this._onSceneUpdate),e.scene.addEventListener("addSceneObject",this._onSceneUpdate),e.addEventListener("preRender",this._preRender),e.addEventListener("postFrame",this._postFrame),this.refresh()}onRemove(e){return this._mesh?.dispose(!0),this._removeMaterial(),e.scene.removeEventListener("sceneUpdate",this._onSceneUpdate),e.scene.removeEventListener("addSceneObject",this._onSceneUpdate),e.removeEventListener("postFrame",this._postFrame),e.removeEventListener("preRender",this._preRender),super.onRemove(e)}_postFrame(){this._transformNeedRefresh&&this._refreshTransform(),this._viewer}_preRender(){this._viewer}dispose(){this._removeMaterial(),this._geometry.dispose(),this._material?.dispose(),this._mesh?.dispose?.(),super.dispose()}_removeMaterial(){!this._material||this._material===this._defaultMaterial||(this._material.userData.renderToDepth=this._material.userData.__renderToDepth,this._material.userData.__renderToDepth=void 0,this._material=this._defaultMaterial)}_onSceneUpdate(e){e?.object?.assetType==="widget"||e?.object?.userData?.isWidgetRoot||e?.geometryChanged!==!1&&e?.updateGround!==!1&&this.refreshTransform()}refreshTransform(){this.enableRefreshTransform&&(this._transformNeedRefresh=!0)}refresh(){this._viewer&&(this._refreshMaterial(),this.refreshTransform(),this._refreshCameraLimits())}_refresh2(){this.refresh()}_refreshCameraLimits(){const e=this._viewer?.scene.mainCamera.controls;if(e){if(e.maxPolarAngle===void 0){console.warn("refreshCameraLimits only available with orbit controls.");return}this.limitCameraAboveGround?(this._cameraLimitsSet||(this._cameraLastMaxPolarAngle=e.maxPolarAngle),e.maxPolarAngle=Math.PI/2,this._cameraLimitsSet=!0):this._cameraLimitsSet&&(e.maxPolarAngle=this._cameraLastMaxPolarAngle,this._cameraLimitsSet=!1)}}_refreshTransform(){if(!this._mesh||!this._viewer)return!1;let e=!1;if(this.visible!==this._mesh.visible&&(this._mesh.visible=this.visible,e=!0),this.isDisabled())return e&&this._viewer?.scene.setDirty(),!1;if(this.autoAdjustTransform){this._mesh.userData.bboxVisible=!1;const t=this.useModelBounds?this._viewer.scene.getModelBounds(!0,!0,!0):this._viewer.scene.getBounds(!0,!0,!0);this._mesh.userData.bboxVisible=!0;const i=t.getCenter(new S).sub(new S(0,t.getSize(new S).y/2+this.yOffset,0));e=e||i.clone().sub(this._mesh.position).length()>1e-4,e&&this._mesh.position.copy(i)}return e=e||Math.abs(this._mesh.scale.x-this.size)>1e-4,e&&(this._mesh.scale.setScalar(this.size),this._mesh.setRotationFromEuler(new Pt(-Math.PI/2,0,this._mesh.rotation.z)),this._mesh.matrixWorldNeedsUpdate=!0,this._mesh.setDirty({refreshScene:!1,source:f.BaseGroundPlugin.PluginType})),this._mesh.visible=this.size>=1e-4,this._transformNeedRefresh=!1,!0}_createMesh(e){return e?e.geometry=this._geometry:e=new rg(this._geometry,this._createMaterial()),e}setGeometry(e){e?this._geometry&&this._geometry.dispose():e=this._geometry,e&&(this._geometry=e,ni.upgradeGeometry.call(this._geometry),this._geometry.attributes.uv2||(this._geometry.attributes.uv2=this._geometry.attributes.uv.clone(),this._geometry.attributes.uv2.needsUpdate=!0),this._mesh&&(this._mesh.geometry=this._geometry))}_createMaterial(e){return e||(e=new si({name:"BaseGroundMaterial",color:16777215,roughness:.8,metalness:.5})),e.userData.runtimeMaterial=!0,e}_refreshMaterial(){this._viewer&&(this.isDisabled()||(this._material||(this._material=this._defaultMaterial,this._viewer.scene.setDirty()),this._material.userData.__renderToDepth===void 0&&(this._material.userData.__renderToDepth=this._material.userData.renderToDepth),this._material.userData.renderToDepth!==this.renderToDepth&&(this._material.userData.renderToDepth=this.renderToDepth),this._material.userData.gBufferData||(this._material.userData.gBufferData={}),this._material.userData.gBufferData.__tonemapEnabled===void 0&&(this._material.userData.gBufferData.__tonemapEnabled=this._material.userData.gBufferData.tonemapEnabled),this._material.userData.gBufferData.tonemapEnabled!==this.tonemapGround&&(this._material.userData.gBufferData.tonemapEnabled=this.tonemapGround),this._viewer.setDirty(this)))}get material(){return this._material}get mesh(){return this._mesh}fromJSON(e,t){return e.options&&console.error("todo: support old webgi v0 file"),super.fromJSON(e,t)?(this.refresh(),this):null}},f.BaseGroundPlugin.PluginType="BaseGroundPlugin",f.BaseGroundPlugin.OldPluginType="Ground",Ia([se("Visible"),he(f.BaseGroundPlugin.prototype.refreshTransform),G()],f.BaseGroundPlugin.prototype,"visible",2),Ia([Ot("Size"),Zt(f.BaseGroundPlugin.prototype._onSceneUpdate),G()],f.BaseGroundPlugin.prototype,"size",2),Ia([Ot("Height (yOffset)"),Zt(f.BaseGroundPlugin.prototype._onSceneUpdate),G()],f.BaseGroundPlugin.prototype,"yOffset",2),Ia([se("Render to Depth"),he(f.BaseGroundPlugin.prototype._refresh2),G()],f.BaseGroundPlugin.prototype,"renderToDepth",2),Ia([se("Tonemap Ground"),he(f.BaseGroundPlugin.prototype._refresh2),G()],f.BaseGroundPlugin.prototype,"tonemapGround",2),Ia([se("Limit Camera Above Ground"),he(f.BaseGroundPlugin.prototype._refreshCameraLimits),G()],f.BaseGroundPlugin.prototype,"limitCameraAboveGround",2),Ia([se("Auto Adjust Transform"),he(f.BaseGroundPlugin.prototype.refreshTransform),G()],f.BaseGroundPlugin.prototype,"autoAdjustTransform",2),Ia([G("material"),Bi(),jt({obj:"mesh",key:"material",allowUndefined:!0})],f.BaseGroundPlugin.prototype,"_material",2),f.BaseGroundPlugin=Ia([vt("Ground Plane")],f.BaseGroundPlugin);class Vg extends mt{constructor(){super(...arguments),this.enabled=!0,this.toJSON=void 0,this._cameraChanged=e=>{this._unregisterControls(e.lastCamera),this._registerControls(e.camera)}}onAdded(e){super.onAdded(e),this._registerControls(e.scene.mainCamera),e.scene.addEventListener("mainCameraChange",this._cameraChanged)}onRemove(e){this._unregisterControls(e.scene.mainCamera),e.scene.removeEventListener("mainCameraChange",this._cameraChanged),super.onRemove(e)}_registerControls(e){e?.setControlsCtor?.(this.controlsKey,this._controlsCtor)}_unregisterControls(e){e?.removeControlsCtor?.(this.controlsKey)}}var Mj=Object.defineProperty,Tj=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Mj(e,t,n),n};const nb=class extends mt{constructor(e,t){super(),this.container=t,this.enabled=!0,this._mainDiv=Pr({id:"assetManager"+e,addToBody:!1,innerHTML:""}),this._contentDiv=Pr({id:"assetManager"+e+"Content",addToBody:!1,innerHTML:""}),this.enabled||(this._mainDiv.style.display="none"),this._mainDiv.appendChild(this._contentDiv),this._onProcessStateUpdate=this._onProcessStateUpdate.bind(this)}_onEnabledChange(){this.enabled||(this._mainDiv.style.display="none")}onAdded(e){super.onAdded(e),(this.container??e.container).appendChild(this._mainDiv),this._updateMainDiv(e.assetManager.processState),e.assetManager.addEventListener("processStateUpdate",this._onProcessStateUpdate)}_onProcessStateUpdate(){this._viewer&&this._updateMainDiv(this._viewer.assetManager.processState)}onRemove(e){return this._mainDiv.remove(),e.assetManager.removeEventListener("processStateUpdate",this._onProcessStateUpdate),super.onRemove(e)}};Tj([se("Enabled"),he(nb.prototype._onEnabledChange),G()],nb.prototype,"enabled");let kI=nb;class GI extends nh{constructor(e,t=120){super({vertexShader:Cl.vertexShader,fragmentShader:ma`
                uniform vec4 weight;
                uniform vec4 weight2;
                varying vec2 vUv;
                void main() {
                    vec4 texel = clamp(weight * tDiffuseTexelToLinear ( texture2D( tDiffuse, vUv ) ) + weight2 * tDiffuse2TexelToLinear ( texture2D( tDiffuse2, vUv ) ), vec4(0), vec4(MAX_INTENSITY));
                    gl_FragColor = texel;
                    #include <colorspace_fragment>
                }
            `,uniforms:{tDiffuse:{value:null},tDiffuse2:{value:e},weight:{value:new et(1,1,1,1)},weight2:{value:new et(1,1,1,1)}},defines:{MAX_INTENSITY:t}},"tDiffuse","tDiffuse2"),this.clear=!1,this.needsSwap=!0}}var Ij=Object.defineProperty,Pj=Object.getOwnPropertyDescriptor,Yd=(r,e,t,i)=>{for(var n=i>1?void 0:i?Pj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Ij(e,t,n),n};f.SSAAPlugin=class extends mt{constructor(e=1){super(),this.enabled=!0,this.rendersPerFrame=1,this.jitterRenderCamera=!0,this.jitterLightCameras=!0,this._hasSetOffsetRC=!1,this._hasSetOffsetLC=!1,this.trackedJitterCameras=new Map,this.dependencies=[f.ProgressivePlugin],this._objectAdd=t=>{const i=t.object;i&&i.shadow&&i.shadow.camera&&i.shadow.mapSize&&this.trackedJitterCameras.set(i.shadow.camera,i.shadow.mapSize)},this._objectRemove=t=>{const i=t.object;if(i&&i.shadow&&i.shadow.camera){const n=i.shadow.camera;this._clearJitter(n),this.trackedJitterCameras.delete(n)}},this._preRender=()=>{const t=this._viewer;if(!t||!this.enabled||t.renderManager.frameCount<=1)return;this.rendersPerFrame=t.rendersPerFrame;const i=t.scene.renderCamera;this.jitterRenderCamera&&this._jitter(i,{width:t.renderManager.renderSize.x*t.renderManager.renderScale,height:t.renderManager.renderSize.y*t.renderManager.renderScale},t.renderManager.frameCount,!0),this.jitterLightCameras&&Array.from(this.trackedJitterCameras.entries()).forEach(n=>this._jitter(...n,t.renderManager.frameCount)),this._hasSetOffsetRC=this.jitterRenderCamera,this._hasSetOffsetLC=this.jitterLightCameras,t.renderManager.resetShadows()},this._postRender=()=>{const t=this._viewer;t&&(this._hasSetOffsetRC&&(this._clearJitter(t.scene.renderCamera),this._hasSetOffsetRC=!1),this._hasSetOffsetLC&&(Array.from(this.trackedJitterCameras.keys()).forEach(i=>this._clearJitter(i)),this._hasSetOffsetLC=!1))},this.jitterOffsets=[{x:0,y:0},{x:-.5,y:0},{x:-.375,y:-.25},{x:-.1875,y:-.125},{x:-.125,y:-.375},{x:.0625,y:-.0625},{x:.125,y:-.3125},{x:.375,y:-.4375},{x:.3125,y:-.1875},{x:.25,y:.0625},{x:.4375,y:.25},{x:.1875,y:.3125},{x:0,y:.4375},{x:-.0625,y:.1875},{x:-.25,y:.375},{x:-.4375,y:.5},{x:-.3125,y:.125}],this.rendersPerFrame=e}onAdded(e){super.onAdded(e),e.addEventListener("preRender",this._preRender),e.addEventListener("postRender",this._postRender),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove)}onRemove(e){return e.removeEventListener("preRender",this._preRender),e.removeEventListener("postRender",this._postRender),e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),super.onRemove(e)}setDirty(){this._viewer&&(this._viewer.rendersPerFrame=this.rendersPerFrame,this._viewer.setDirty(),this.uiConfig?.uiRefresh?.(!0,"postFrame"))}_jitter(e,t,i,n=!1){if(e.userData.disableJitter)return;if(e.userData.__jittered){this._viewer?.console.warn("SSAAPlugin: Camera already jittered");return}const s={...this.jitterOffsets[i%this.jitterOffsets.length]},a=e.aspect,o=e.autoAspect||!n?t.height:t.width/a;e.setViewOffset(t.width,o,s.x,s.y,t.width,o),e.userData.__jittered=!0}_clearJitter(e){e.userData.__jittered&&(e.clearViewOffset(),delete e.userData.__jittered)}},f.SSAAPlugin.PluginType="SSAAPlugin",Yd([G(),se("Enabled"),he(f.SSAAPlugin.prototype.setDirty)],f.SSAAPlugin.prototype,"enabled",2),Yd([G(),Fe("Renders/Frame",[1,32],1),he(f.SSAAPlugin.prototype.setDirty)],f.SSAAPlugin.prototype,"rendersPerFrame",2),Yd([G(),se("Render Camera"),he(f.SSAAPlugin.prototype.setDirty)],f.SSAAPlugin.prototype,"jitterRenderCamera",2),Yd([G(),se("Light Cameras"),he(f.SSAAPlugin.prototype.setDirty)],f.SSAAPlugin.prototype,"jitterLightCameras",2),f.SSAAPlugin=Yd([vt("SSAA Plugin")],f.SSAAPlugin);var Dj=Object.defineProperty,Rj=Object.getOwnPropertyDescriptor,sb=(r,e,t,i)=>{for(var n=i>1?void 0:i?Rj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Dj(e,t,n),n};f.ProgressivePlugin=class extends Pl{constructor(e=32,t=Qt,i=!0){super(),this.passId="progressive",this._targets=new Map,this.maxFrameCount=e,this.enabled=i,this.bufferType=t}get texture(){return this.target?.texture}get target(){return this._viewer?this._targets.get(this._viewer.scene.renderCamera.uuid):void 0}getTarget(e){return this._viewer?this._targets.get((e||this._viewer.scene.renderCamera).uuid):void 0}get textures(){return this._viewer?Array.from(this._targets.values()).map(e=>e.texture):[]}get mainTexture(){return this._viewer?this.getTarget(this._viewer.scene.mainCamera)?.texture:void 0}_createTarget(e,t=!1){if(!this._viewer)return;if(e=e??this._viewer.scene.renderCamera,t&&this._disposeTarget(e),this._targets.has(e.uuid))return this._targets.get(e.uuid);const i=this._viewer.renderManager.composerTarget.clone(!0);return i.texture.name="progressiveLastBuffer_"+e.uuid,this._targets.set(e.uuid,i),i}_disposeTarget(e){if(this._viewer)if(!e)this._targets.forEach(t=>this._viewer.renderManager.disposeTarget(t)),this._targets.clear();else{const t=this._targets.get(e.uuid);t&&(this._viewer.renderManager.disposeTarget(t),this._targets.delete(e.uuid))}}_createPass(){const e=new zI(this.passId,()=>this.target??this._createTarget(),this._viewer?.renderManager.maxHDRIntensity);return e.dirty=()=>(this._viewer?.renderManager.frameCount||0)<this.maxFrameCount,e}onAdded(e){super.onAdded(e)}onRemove(e){return this._disposeTarget(),super.onRemove(e)}isConverged(e=!1){return(this._viewer?.renderManager.frameCount||0)>=this.maxFrameCount-1+(e?1:0)}updateShaderProperties(e){return e.uniforms.tLastFrame&&(e.uniforms.tLastFrame.value=this.target?.texture??void 0),this}postFrameConvergedRecordingDelta(e="CanvasRecorder"){return-1}get convergedPromise(){return new Promise(e=>{if(this.isConverged())this._viewer?.doOnce("postFrame",()=>e());else{const t=()=>{this.isConverged(!0)&&(this._viewer?.removeEventListener("postRender",t),this._viewer?.doOnce("postFrame",()=>e()))};this._viewer?.addEventListener("postRender",t)}})}fromJSON(e,t){if(e.jitter!==void 0){const i=this._viewer?.getPlugin(f.SSAAPlugin);i?(e={...e},i.enabled=e.jitter,delete e.jitter):console.warn("Loading old webgi v0 file, add SSAAPlugin to get anti-aliasing")}return super.fromJSON(e,t)}},f.ProgressivePlugin.PluginType="ProgressivePlugin",f.ProgressivePlugin.OldPluginType="Progressive",sb([G(),He("Frame count")],f.ProgressivePlugin.prototype,"maxFrameCount",2),sb([Dr("Last Texture",{readOnly:!0})],f.ProgressivePlugin.prototype,"mainTexture",1),f.ProgressivePlugin=sb([vt("Progressive Plugin")],f.ProgressivePlugin);class zI extends GI{constructor(e,t,i=120){super(void 0,i),this.passId=e,this.target=t,this.before=["screen"],this.after=["render"],this.required=["render"],this.dirty=()=>!1,this.copyToWriteBuffer=!0}render(e,t,i,n,s){if(!this.enabled)return;const a=tt(this.target);if(!a){console.warn("ProgressiveBlendPass: target not defined");return}if(this.needsSwap=!1,e.renderManager.frameCount<1){i?.texture&&e.renderManager.blit(a,{source:i.texture,respectColorSpace:!1});return}super.render(e,t,i,n,s),this.copyToWriteBuffer&&(e.renderManager.blit(a,{source:t.texture,respectColorSpace:!1}),this.needsSwap=!0)}beforeRender(e,t,i){if(!this.enabled)return;if(!this.target){console.error("ProgressiveBlendPass: render target undefined");return}let n=1/(Math.max(i.frameCount,0)+1);this.uniforms.weight.value.set(n,n,n,n),n=1-n,this.uniforms.weight2.value.set(n,n,n,n),this.uniforms.tDiffuse2.value=tt(this.target)?.texture,this.material.uniformsNeedUpdate=!0}}const Bj=`#if defined(HAS_DEPTH_BUFFER)
#if DEPTH_PACKING == 3200
#define unpackDepth(rgba_depth) (1.0 - rgba_depth.r)
#elif DEPTH_PACKING == 3201
#define unpackDepth(rgba_depth) unpackRGBAToDepth(rgba_depth)
#elif DEPTH_PACKING == 3202
#define unpackDepth(rgba_depth) unpackRGBToDepth(rgba_depth.rgb)
#elif DEPTH_PACKING == 3203
#define unpackDepth(rgba_depth) unpackRGToDepth(rgba_depth.rg)
#endif
uniform sampler2D tDepthBuffer;
#define getDepth(uv) unpackDepth(texture2D(tDepthBuffer, uv))
#endif
`;var Lj=Object.defineProperty,Oj=Object.getOwnPropertyDescriptor,rb=(r,e,t,i)=>{for(var n=i>1?void 0:i?Oj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Lj(e,t,n),n};f.DepthBufferPlugin=class extends Pl{constructor(e=Qt,t=!1,i=!0,n=sc){super(),this.passId="depth",this.material=new VI({depthPacking:sc,blending:gn,transparent:!0}),this.unpackExtension={shaderExtender:s=>{const o=["depth_buffer_unpack","gbuffer_unpack","packing"].find(l=>s.fragmentShader.includes(`#include <${l}>`));s.fragmentShader=bt(s.fragmentShader,`#include <${o}>`,`
`+Bj+`
`,{append:o==="packing"})},extraUniforms:{tDepthBuffer:()=>({value:this.target?.texture})},extraDefines:{DEPTH_PACKING:sc,HAS_DEPTH_BUFFER:()=>this.target?.texture?1:void 0,HAS_GBUFFER:()=>this.isPrimaryGBuffer&&this.target?.texture?1:void 0},priority:100,isCompatible:()=>!0},this._isPrimaryGBufferSet=!1,this.enabled=i,this.depthPacking=n,this.bufferType=e,this.isPrimaryGBuffer=t}_getClearColor(){return this.depthPacking===If?new ee(0,0,0):new ee(1,1,1)}_depthPackingChanged(){this.material.depthPacking=this.depthPacking,this.material.needsUpdate=!0,this._pass&&(this._pass.clearColor=this._getClearColor()),this.unpackExtension&&this.unpackExtension.extraDefines&&(this.unpackExtension.extraDefines.DEPTH_PACKING=this.depthPacking,this.unpackExtension.setDirty?.()),this.setDirty()}_createTarget(e=!0){if(!this._viewer)return;e&&this._disposeTarget();const t=this._viewer.renderManager;this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!0,samples:this._viewer.renderManager.zPrepass&&this.isPrimaryGBuffer&&t.msaa?typeof t.msaa!="number"?f.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:t.msaa:0,type:this.bufferType})),this.texture=this.target.texture,this.texture.name="depthBuffer",this.isPrimaryGBuffer&&(this._viewer.renderManager.gbufferTarget=this.target,this._viewer.renderManager.gbufferUnpackExtension=this.unpackExtension,this._viewer.renderManager.screenPass.material.registerMaterialExtensions([this.unpackExtension]),this._isPrimaryGBufferSet=!0)}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0,this._isPrimaryGBufferSet&&(this._viewer.renderManager.gbufferTarget=void 0,this._viewer.renderManager.gbufferUnpackExtension=void 0,this._isPrimaryGBufferSet=!1))}_createPass(){if(this._createTarget(!0),!this.target)throw new Error("DepthBufferPlugin: target not created");this.material.userData.isGBufferMaterial=!0;const e=new f.GBufferRenderPass(this.passId,()=>this.target,this.material,this._getClearColor(),1),t=e.preprocessMaterial;return e.preprocessMaterial=i=>t(i,i.userData.renderToDepth),e.before=["render"],e.after=[],e.required=["render"],e}onRemove(e){return this._disposeTarget(),super.onRemove(e)}},f.DepthBufferPlugin.PluginType="DepthBufferPlugin",rb([Dr("Depth Buffer",{readOnly:!0})],f.DepthBufferPlugin.prototype,"texture",2),rb([he(f.DepthBufferPlugin.prototype._depthPackingChanged),Li("Depth Packing",dv.DepthPackingStrategies.uiConfig)],f.DepthBufferPlugin.prototype,"depthPacking",2),f.DepthBufferPlugin=rb([vt("Depth Buffer Plugin")],f.DepthBufferPlugin);class VI extends Ec{constructor(e){super(e),this.reset()}onBeforeRender(e,t,i,n,s,a){super.onBeforeRender(e,t,i,n,s,a);let o=s.material;Array.isArray(o)&&(o=o[0]),o&&(o.map!==void 0&&(this.map=o.map),o.side!==void 0&&(this.side=o.side??us),o.alphaMap!==void 0&&(this.alphaMap=o.alphaMap),o.alphaTest!==void 0&&(this.alphaTest=o.alphaTest<1e-4?1e-4:o.alphaTest),o.alphaHash!==void 0&&(this.alphaHash=o.alphaHash),o.displacementMap!==void 0&&(this.displacementMap=o.displacementMap),o.displacementScale!==void 0&&(this.displacementScale=o.displacementScale),o.displacementBias!==void 0&&(this.displacementBias=o.displacementBias),o.wireframe!==void 0&&(this.wireframe=o.wireframe),o.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=o.wireframeLinewidth),this.needsUpdate=!0,e.resetCurrentMaterial&&e.resetCurrentMaterial())}onAfterRender(e,t,i,n,s,a){super.onAfterRender(e,t,i,n,s,a),this.reset()}reset(){this.map=null,this.side=Zi,this.alphaMap=null,this.alphaTest=.001,this.alphaHash=!1,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1}}var Uj=Object.defineProperty,Fj=Object.getOwnPropertyDescriptor,ab=(r,e,t,i)=>{for(var n=i>1?void 0:i?Fj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Uj(e,t,n),n};f.NormalBufferPlugin=class extends Pl{constructor(e=Yt,t=!0){super(),this.passId="normal",this.material=new HI({blending:gn}),this.renderTransparent=!0,this.enabled=t,this.bufferType=e}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!0,samples:0,type:this.bufferType,magFilter:mi,minFilter:mi,generateMipmaps:!1,colorSpace:Bt})),this.texture=this.target.texture,this.texture.name="normalBuffer")}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(this._createTarget(!0),!this.target)throw new Error("NormalBufferPlugin: target not created");this.material.userData.isGBufferMaterial=!0;const e=new f.GBufferRenderPass(this.passId,()=>this.target,this.material,new ee(0,0,0),1),t=e.preprocessMaterial;return e.preprocessMaterial=i=>t(i,this.renderTransparent?!0:i.userData.renderToDepth),e.preprocessObject=i=>{if(i.customNormalMaterial){const n=i.customNormalMaterial;n.allowOverride=!1,i.forcedOverrideMaterial=n;return}return i.material},e.postprocessObject=i=>{i.customNormalMaterial&&delete i.forcedOverrideMaterial},e.before=["render"],e.after=[],e.required=["render"],e}onRemove(e){return this._disposeTarget(),super.onRemove(e)}},f.NormalBufferPlugin.PluginType="NormalBufferPlugin",ab([Dr("Normal Buffer",{readOnly:!0})],f.NormalBufferPlugin.prototype,"texture",2),ab([se("Render Transparent"),Zt(f.NormalBufferPlugin.prototype.setDirty),G()],f.NormalBufferPlugin.prototype,"renderTransparent",2),f.NormalBufferPlugin=ab([vt("Normal Buffer Plugin")],f.NormalBufferPlugin);class HI extends a_{constructor(e){super(e),this.reset()}onBeforeRender(e,t,i,n,s,a){if(super.onBeforeRender(e,t,i,n,s,a),!s.material)return;const o=s.material;o.bumpMap!==void 0&&(this.bumpMap=o.bumpMap),o.bumpScale!==void 0&&(this.bumpScale=o.bumpScale),o.alphaTest!==void 0&&(this.alphaTest=o.alphaTest<1e-4?1e-4:o.alphaTest),o.alphaHash!==void 0&&(this.alphaHash=o.alphaHash),o.normalMap!==void 0&&(this.normalMap=o.normalMap),o.normalMapType!==void 0&&(this.normalMapType=o.normalMapType),o.normalScale!==void 0&&this.normalScale.copy(o.normalScale),o.displacementMap!==void 0&&(this.displacementMap=o.displacementMap),o.displacementScale!==void 0&&(this.displacementScale=o.displacementScale),o.displacementBias!==void 0&&(this.displacementBias=o.displacementBias),o.flatShading!==void 0&&(this.flatShading=o.flatShading),o.side!==void 0&&(this.side=o.side),o.wireframe!==void 0&&(this.wireframe=o.wireframe),o.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=o.wireframeLinewidth),e.resetCurrentMaterial&&e.resetCurrentMaterial()}onAfterRender(e,t,i,n,s,a){super.onAfterRender(e,t,i,n,s,a),this.reset()}reset(){this.bumpMap=null,this.bumpScale=1,this.alphaTest=0,this.normalMap=null,this.normalMapType=Us,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.flatShading=!1,this.side=Zi,this.wireframe=!1,this.wireframeLinewidth=1}}var Nj=Object.defineProperty,kj=Object.getOwnPropertyDescriptor,Hg=(r,e,t,i)=>{for(var n=i>1?void 0:i?kj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Nj(e,t,n),n};f.FrameFadePlugin=class extends Pl{constructor(e=!0){super(),this.passId="frameFade",this.dependencies=[f.ProgressivePlugin],this.isEditor=!1,this.fadeOnActiveCameraChange=!0,this.fadeOnMaterialUpdate=!0,this.fadeOnSceneUpdate=!0,this._pointerEnabled=!0,this.saveFrameTimeThreshold=500,this._fadeCam=async t=>t.frameFade!==!1&&!this.isEditor&&this.fadeOnActiveCameraChange&&this.startTransition(t.fadeDuration||1e3),this._fadeMat=async t=>t.frameFade!==!1&&!this.isEditor&&this.fadeOnMaterialUpdate&&this.startTransition(t.fadeDuration||200),this._fadeScene=async t=>t.frameFade!==!1&&!this.isEditor&&this.fadeOnSceneUpdate&&this.startTransition(t.fadeDuration||500),this._fadeObjectUpdate=async t=>t.frameFade&&!this.isEditor&&this.startTransition(t.fadeDuration||500),this._onPointerMove=t=>{const i=this._viewer?.canvas;if(!i){this._pointerEnabled=!1;return}if(!t.buttons||t.target!==i){this._pointerEnabled=!0;return}const n=i.getBoundingClientRect(),s=(t.clientX-n.left)/n.width,a=(t.clientY-n.top)/n.height;this._pointerEnabled=s<0||s>1||a<0||a>1},this.enabled=e,this.startTransition=this.startTransition.bind(this),this.stopTransition=this.stopTransition.bind(this),this._fadeCam=this._fadeCam.bind(this),this._fadeMat=this._fadeMat.bind(this),this.isDisabled=(t=>()=>!this._pointerEnabled||t())(this.isDisabled)}async startTransition(e){!this._viewer||!this._pass||this.isDisabled()||(this._target||(this._target=this._viewer.renderManager.getTempTarget({sizeMultiplier:1,minFilter:at,magFilter:at,colorSpace:this._viewer.renderManager.composerTarget.texture.colorSpace})),this._pass.fadeTimeState<this.saveFrameTimeThreshold&&(this._pass.toSaveFrame=!0),this._pass.fadeTimeState=Math.max(e,this._pass.fadeTimeState),this._pass.fadeTime=this._pass.fadeTimeState,this.setDirty(),await Qn(e))}stopTransition(){this._pass&&(this._pass.fadeTimeState=0)}onAdded(e){super.onAdded(e),e.scene.addEventListener("mainCameraUpdate",this.stopTransition),e.scene.addEventListener("mainCameraChange",this._fadeCam),e.scene.addEventListener("materialUpdate",this._fadeMat),e.scene.addEventListener("sceneUpdate",this._fadeScene),e.scene.addEventListener("objectUpdate",this._fadeObjectUpdate),window.addEventListener("pointermove",this._onPointerMove)}onRemove(e){e.scene.removeEventListener("mainCameraUpdate",this.stopTransition),e.scene.removeEventListener("mainCameraChange",this._fadeCam),e.scene.removeEventListener("materialUpdate",this._fadeMat),e.scene.removeEventListener("sceneUpdate",this._fadeScene),e.scene.removeEventListener("objectUpdate",this._fadeObjectUpdate),window.removeEventListener("pointermove",this._onPointerMove),super.onRemove(e)}setDirty(){super.setDirty(),!this.isDisabled()&&this._viewer?.setDirty()}get dirty(){return!this.isDisabled()&&!!this._pass&&this._pass.fadeTimeState>0}set dirty(e){console.error("FrameFadePlugin.dirty is readonly")}_createPass(){return new QI(this.passId,this,this._viewer?.renderManager.maxHDRIntensity)}get canFrameFade(){return this._target&&this._pointerEnabled&&this.dirty&&this._pass&&this._pass.fadeTimeState>.001&&this._viewer&&this._viewer.scene.renderCamera===this._viewer.scene.mainCamera}get lastFrame(){return this._viewer?.getPlugin(f.ProgressivePlugin)?.texture}get target(){return this._target}_beforeRender(){return!super._beforeRender()||!this._pass?!1:(this.isDisabled()&&this.stopTransition(),this._pass.fadeTimeState<.001&&(this._pass.toSaveFrame=!1,this._target&&this._viewer&&(this._viewer.renderManager.releaseTempTarget(this._target),this._target=void 0)),!0)}},f.FrameFadePlugin.PluginType="FrameFadePlugin",Hg([G(),se()],f.FrameFadePlugin.prototype,"fadeOnActiveCameraChange",2),Hg([G(),se()],f.FrameFadePlugin.prototype,"fadeOnMaterialUpdate",2),Hg([G(),se()],f.FrameFadePlugin.prototype,"fadeOnSceneUpdate",2),f.FrameFadePlugin=Hg([vt("FrameFade Plugin")],f.FrameFadePlugin);class QI extends GI{constructor(e,t,i=120){super(void 0,i),this.passId=e,this.plugin=t,this.before=["progressive","taa"],this.after=["render"],this.required=["render","progressive"],this.dirty=()=>!1,this.fadeTime=0,this.fadeTimeState=0,this.toSaveFrame=!1,this._lastTime=0}render(e,t,i,n,s){this.needsSwap=!1;const a=this.plugin.target;if(!this.plugin.canFrameFade||!a)return;const o=this.plugin.lastFrame;this.toSaveFrame&&o&&(e.renderManager.blit(a,{source:o,respectColorSpace:!1}),this._lastTime=0,this.toSaveFrame=!1),this.uniforms.tDiffuse2.value=a.texture;const l=this.fadeTimeState/this.fadeTime;this.uniforms.weight2.value.setScalar(l),this.uniforms.weight2.value.w=1,this.uniforms.weight.value.setScalar(1-l),this.uniforms.weight.value.w=1,super.render(e,t,i,n,s),this.needsSwap=!0;const c=Cn();this._lastTime<10&&(this._lastTime=c-10);const h=c-this._lastTime;this._lastTime=c,this.fadeTimeState-=h}}const Gj=`#include <randomHelpers>
#include <common>
#include <packing>
#define THREE_PACKING_INCLUDED
#include <cameraHelpers>
varying vec2 vUv;uniform sampler2D tLastThis;
#ifndef D_frameCount
#define D_frameCount
uniform float frameCount;
#endif
uniform vec4 saoData;uniform vec4 saoBiasEpsilon;uniform vec2 screenSize;const float INV_NUM_SAMPLES=1.0/float(NUM_SAMPLES);int getSelectionBit(in int number){
#ifdef WebGL2Context
return(number/8)% 2;
#else
return int(mod(floor(float(number)/8.),2.));
#endif
}vec3 packFloatToRGB(const in float x){const vec3 code=vec3(1.0,255.0,65025.0);vec3 pack=vec3(code*x);pack.gb=fract(pack.gb);pack.rg-=pack.gb*(1.0/256.0);return pack;}vec3 getPositionFromOffset(const in vec2 uvOffset){
#if defined(HAS_DEPTH_BUFFER) || defined(HAS_NORMAL_DEPTH_BUFFER)
float d=getDepth(uvOffset);
#else
float d=0.5;
#endif
#if LINEAR_DEPTH == 0
float centerViewZ=viewZFromNDCZ(d);return screenToView3(uvOffset,centerViewZ);
#else
d=mix(-cameraNearFar.x,-cameraNearFar.y,d);return screenToView3(uvOffset,d);
#endif
}float getOcclusion(const in vec2 uv,const in int id,const in float randomAngle,const in float occlusionSphereRadius,const in vec3 centerPosition,const in vec3 centerNormal){float screenSpaceRadius=(float(id)+mod(randomAngle,1.)+0.5)*INV_NUM_SAMPLES;float angle=screenSpaceRadius*(float(NUM_SPIRAL_TURNS)*6.28318)+randomAngle;screenSpaceRadius=(screenSpaceRadius*occlusionSphereRadius);vec2 uvOffset=uv+floor(screenSpaceRadius*vec2(cos(angle),sin(angle)))/screenSize;
#if CHECK_GBUFFER_FLAG == 1
if(getSelectionBit(getGBufferFlags(uvOffset.xy).a)<1)return 0.0;
#endif
vec3 samplePosition=getPositionFromOffset(uvOffset);vec3 direction=samplePosition-centerPosition;float d2=dot(direction,direction)/(saoBiasEpsilon.w*saoBiasEpsilon.w);float ao=max((dot(centerNormal,direction)/saoBiasEpsilon.w-saoBiasEpsilon.x)/(saoBiasEpsilon.z*d2+saoBiasEpsilon.y),0.0);return ao;}void main(){float centerDepth=0.5;vec3 centerNormal=vec3(0,1,0);
#ifdef HAS_NORMAL_DEPTH_BUFFER
getDepthNormal(vUv,centerDepth,centerNormal);
#else
#ifdef HAS_DEPTH_BUFFER
centerDepth=getDepth(vUv);
#endif
#endif
#if LINEAR_DEPTH == 0
float centerViewZ=viewZFromNDCZ(centerDepth);
#else
float centerViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,centerDepth);
#endif
vec3 centerPosition=screenToView3(vUv,centerViewZ);float occlusionSphereScreenRadius=saoData.z*saoBiasEpsilon.w/(-centerPosition.z);float randomAngle=6.2*random3(vec3(vUv,frameCount*0.1));float sum=0.0;sum+=getOcclusion(vUv,0,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#if NUM_SAMPLES > 1
sum+=getOcclusion(vUv,1,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 2
sum+=getOcclusion(vUv,2,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 3
sum+=getOcclusion(vUv,3,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 4
sum+=getOcclusion(vUv,4,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 5
sum+=getOcclusion(vUv,5,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 6
sum+=getOcclusion(vUv,6,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 7
sum+=getOcclusion(vUv,7,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 8
sum+=getOcclusion(vUv,8,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 9
sum+=getOcclusion(vUv,9,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
#if NUM_SAMPLES > 10
sum+=getOcclusion(vUv,10,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);
#endif
float aoValue=sum*saoData.y*INV_NUM_SAMPLES;aoValue=1.-clamp(aoValue,0.,1.);
#if SSAO_PACKING == 1
gl_FragColor.gba=packFloatToRGB(centerDepth);gl_FragColor.r=aoValue;
#elif SSAO_PACKING == 2
gl_FragColor.rgb=vec3(aoValue);gl_FragColor.a=1.;
#elif SSAO_PACKING == 3
gl_FragColor.rgba=packDepthToRGBA(aoValue);
#elif SSAO_PACKING == 4
gl_FragColor.rgb=packFloatToRGB(aoValue);gl_FragColor.a=1.;
#endif
}`,zj=`
#ifndef USE_TRANSMISSION
#if defined(SSAO_ENABLED) && SSAO_ENABLED > 0
vec3 screenPos_ao=viewToScreen(vViewPosition.xyz);
#if SSAO_ENABLED == 2
if(screenPos_ao.x>ssaoSplitX){
#endif
float ambientOcclusion=tSSAOMapTexelToLinear(texture2D(tSSAOMap,viewToScreen(vViewPosition.xyz).xy)).r;reflectedLight.indirectDiffuse*=ambientOcclusion;
#if defined( USE_ENVMAP )
float dotNV=saturate(dot(geometryNormal,geometryViewDir));reflectedLight.indirectSpecular*=computeSpecularOcclusion(dotNV,ambientOcclusion,material.roughness);
#endif
#else
#include <aomap_fragment>
#endif
#if SSAO_ENABLED == 2
}
#endif
#endif
`;var Vj=Object.defineProperty,Hj=Object.getOwnPropertyDescriptor,Ks=(r,e,t,i)=>{for(var n=i>1?void 0:i?Hj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Vj(e,t,n),n};f.SSAOPlugin=class extends Pl{constructor(e=Qt,t=1,i=!0,n=1){super(),this.passId="ssao",this.dependencies=[f.GBufferPlugin],this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("SSAOPlugin: pass/viewer not created yet");const s=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==s&&(this._gbufferUnpackExtension&&this._pass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension=s,this._gbufferUnpackExtension?this._pass.material.registerMaterialExtensions([this._gbufferUnpackExtension]):this._viewer.console.warn("SSAOPlugin: GBuffer unpack extension removed"))},this.enabled=i,this.bufferType=e,this.sizeMultiplier=t,this.packing=n}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!1,type:this.bufferType,sizeMultiplier:this.sizeMultiplier,colorSpace:Bt})),this.texture=this.target.texture,this.texture.name="ssaoBuffer")}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(!this._viewer)throw new Error("SSAOPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("SSAOPlugin: GBuffer target not created. GBufferPlugin or DepthBufferPlugin is required.");return this._createTarget(!0),new f.SSAOPluginPass(this.passId,()=>this.target,this.packing)}onAdded(e){super.onAdded(e),e.forPlugin(f.GBufferPlugin,t=>{t.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this))},t=>{t.unregisterGBufferUpdater(this.constructor.PluginType)},this),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged)}onRemove(e){return this._disposeTarget(),super.onRemove(e)}fromJSON(e,t){return e.passes?.ssao&&(e={...e},e.pass=e.passes.ssao,delete e.passes,e.pass.enabled!==void 0&&(e.enabled=e.pass.enabled)),super.fromJSON(e,t)}updateGBufferFlags(e,t){if(!t.material||!t.material.userData)return;const i=t.material.userData.ssaoCastDisabled||t.material.userData.pluginsDisabled,n=i?0:1;e.w=U_(e.w,3,n),i&&this._pass&&(this._pass.checkGBufferFlag=!0)}get aoTarget(){return console.warn("SSAOPlugin: aoTarget is deprecated, use target instead"),this.target}},f.SSAOPlugin.PluginType="SSAOPlugin",f.SSAOPlugin.OldPluginType="SSAO",Ks([Dr("SSAO Buffer",{readOnly:!0,tags:["debug"]})],f.SSAOPlugin.prototype,"texture",2),Ks([Bi(void 0,{unwrapContents:!0})],f.SSAOPlugin.prototype,"_pass",2),f.SSAOPlugin=Ks([vt("SSAO Plugin")],f.SSAOPlugin),f.SSAOPluginPass=class extends nh{constructor(e,t,i=1){super({defines:{LINEAR_DEPTH:1,NUM_SAMPLES:11,NUM_SPIRAL_TURNS:3,SSAO_PACKING:i,PERSPECTIVE_CAMERA:1,CHECK_GBUFFER_FLAG:0},uniforms:{screenSize:{value:new K(0,0)},saoData:{value:new et},frameCount:{value:0},cameraNearFar:{value:new K(.1,1e3)},projection:{value:new fe},saoBiasEpsilon:{value:new et(1,1,1,1)},sceneBoundingRadius:{value:0},ssaoSplitX:{value:.5}},vertexShader:V_.defaultVertex,fragmentShader:Gj},"tDiffuse"),this.passId=e,this.target=t,this.before=["render"],this.after=["gbuffer","depth"],this.required=["render"],this.intensity=.25,this.occlusionWorldRadius=1,this.autoRadius=!1,this.bias=.001,this.falloff=1.3,this.numSamples=8,this.checkGBufferFlag=!1,this.split=0,this.copyToWriteBuffer=!1,this._projScale=1,this.materialExtension={extraUniforms:{tSSAOMap:()=>({value:tt(this.target)?.texture??null}),ssaoSplitX:this.material.uniforms.ssaoSplitX},shaderExtender:(n,s,a)=>{n.defines?.SSAO_ENABLED&&(n.fragmentShader=bt(n.fragmentShader,"#include <aomap_fragment>",zj))},onObjectRender:(n,s,a)=>{const o=this.enabled&&a.userData.screenSpaceRendering!==!1&&!s.userData?.pluginsDisabled&&!s.userData?.ssaoDisabled?this.split>0?2:1:0;s.defines.SSAO_ENABLED!==o&&(s.defines.SSAO_ENABLED=o,s.needsUpdate=!0)},parsFragmentSnippet:()=>ma`
             uniform sampler2D tSSAOMap;
            #if defined(SSAO_ENABLED) && SSAO_ENABLED == 2
            uniform float ssaoSplitX;
            #endif
             ${av("tSSAOMap",tt(this.target)?.texture.colorSpace)}
             #include <simpleCameraHelpers>
        `,computeCacheKey:()=>(this.enabled?"1":"0")+tt(this.target)?.texture?.colorSpace,uuid:f.SSAOPlugin.PluginType,...YM(this._getUiConfig.bind(this),f.SSAOPlugin.PluginType),isCompatible:n=>n.isPhysicalMaterial},this.needsSwap=!1,this.clear=!0}render(e,t,i,n,s){if(this.needsSwap=!1,!this.enabled)return;const a=tt(this.target);if(!a){console.warn("SSAOPluginPass: target not defined");return}this._updateParameters(),super.render(e,a,i,n,s),this.copyToWriteBuffer&&(e.renderManager.blit(t,{source:a.texture,respectColorSpace:!0}),this.needsSwap=!0)}_updateParameters(){const e=this.material.uniforms.saoData.value;e.y=this.intensity,e.z=this.occlusionWorldRadius,e.z*=this._projScale*.25;const t=this.material.uniforms.saoBiasEpsilon.value;t.x=this.bias,t.y=.001,t.z=this.falloff,this.autoRadius?t.w=Math.min(this.material.uniforms.sceneBoundingRadius.value,100):t.w=1}beforeRender(e,t,i){if(!this.enabled)return;this.updateShaderProperties([t,i,e]);const n=Math.max(1,e.mainCamera.fov??1),s=i?.webglRenderer.domElement.height||1,a=1;this._projScale=s/(2*a*Math.tan(.5*n*Ft.DEG2RAD))}_getUiConfig(e){return{type:"folder",label:"SSAO",children:[{type:"checkbox",label:"Enabled",get value(){return!(e.userData.ssaoDisabled??!1)},set value(t){t!==!(e.userData.ssaoDisabled??!1)&&(e.userData.ssaoDisabled=!t,e.setDirty())},onChange:this.setDirty},{type:"checkbox",label:"Cast SSAO",get value(){return!(e.userData.ssaoCastDisabled??!1)},set value(t){t!==!(e.userData.ssaoCastDisabled??!1)&&(e.userData.ssaoCastDisabled=!t,e.setDirty())},onChange:this.setDirty}]}}},Ks([G(),Fe("Intensity",[0,4],1e-4),Zt(f.SSAOPluginPass.prototype.setDirty)],f.SSAOPluginPass.prototype,"intensity",2),Ks([G(),Fe("Occlusion World Radius",[.1,8],.01),Zt(f.SSAOPluginPass.prototype.setDirty)],f.SSAOPluginPass.prototype,"occlusionWorldRadius",2),Ks([G(),Zt(f.SSAOPluginPass.prototype.setDirty),se()],f.SSAOPluginPass.prototype,"autoRadius",2),Ks([G(),Fe("Bias",[1e-5,.01],1e-5),Zt(f.SSAOPluginPass.prototype.setDirty)],f.SSAOPluginPass.prototype,"bias",2),Ks([G(),Fe("Falloff",[.01,3],.01),Zt(f.SSAOPluginPass.prototype.setDirty)],f.SSAOPluginPass.prototype,"falloff",2),Ks([G(),Fe("Num Samples",[1,11],1,{tags:["performance"]}),Tm("NUM_SAMPLES",void 0,void 0,f.SSAOPluginPass.prototype.setDirty)],f.SSAOPluginPass.prototype,"numSamples",2),Ks([Im("CHECK_GBUFFER_FLAG")],f.SSAOPluginPass.prototype,"checkGBufferFlag",2),Ks([Fe("Split",[0,1],.01,{tags:["debug"]}),G(),_a({propKey:"ssaoSplitX",onChange:f.SSAOPluginPass.prototype.setDirty})],f.SSAOPluginPass.prototype,"split",2),f.SSAOPluginPass=Ks([vt("SSAO Pass")],f.SSAOPluginPass);const Qj='#RenderTargetPreviewPluginContainer{position:absolute;left:0;bottom:0;width:100%;z-index:1000;display:flex;flex-wrap:wrap;flex-direction:row;gap:5px;padding:5px;pointer-events:none;height:auto}.RenderTargetPreviewPluginTarget{position:relative;width:200px;height:200px}.RenderTargetPreviewPluginCollapsed{height:25px}.RenderTargetPreviewPluginTargetHeader{position:absolute;top:0;left:0;right:0;background:#00000080;color:#fff;padding:2px;font-size:16px;height:20px;font-family:monospace;text-align:center;pointer-events:auto;cursor:pointer}.RenderTargetPreviewPluginTargetHeader:after{content:"-";position:absolute;right:2px;width:20px;height:20px;line-height:16px}.RenderTargetPreviewPluginCollapsed .RenderTargetPreviewPluginTargetHeader:after{content:"+";line-height:20px}';var jj=Object.defineProperty,Wj=Object.getOwnPropertyDescriptor,jI=(r,e,t,i)=>{for(var n=i>1?void 0:i?Wj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&jj(e,t,n),n};f.RenderTargetPreviewPlugin=class extends mt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=null,this.mainDiv=Pr({id:"RenderTargetPreviewPluginContainer",addToBody:!1}),this.targetBlocks=[],this._postRender=()=>{if(this._viewer)for(const t of this.targetBlocks){if(!t.visible)continue;const i=tt(t.target);if(!i)continue;const n=t.div.getBoundingClientRect();let s=t.textureIndex!==void 0&&i.textures?.[t.textureIndex]?i.textures[t.textureIndex]:i.texture;const a=this._viewer.canvas.getBoundingClientRect();n.x=n.x-a.x,n.y=a.height+a.y-n.y-n.height,Array.isArray(s)&&(s=s[0]);const o=this._viewer.renderManager.webglRenderer.outputColorSpace;t.originalColorSpace||(this._viewer.renderManager.webglRenderer.outputColorSpace=Ct),this._viewer.renderManager.blit(null,{source:s,clear:!t.transparent,respectColorSpace:!t.originalColorSpace,viewport:new et(n.x,n.y,n.width,n.height),material:t.material}),this._viewer.renderManager.webglRenderer.outputColorSpace=o}},this.enabled=e}onAdded(e){super.onAdded(e),e.addEventListener("postRender",this._postRender),this.stylesheet=hl(Qj,e.container),this.refreshUi()}onRemove(e){e.removeEventListener("postRender",this._postRender),this.stylesheet?.remove(),this.stylesheet=void 0,this.refreshUi(),super.onRemove(e)}addTarget(e,t,i=!1,n=!1,s=!0,a,o){if(!e)return this;const l=document.createElement("div"),c={target:e,name:t,transparent:i,div:l,originalColorSpace:n,visible:s,textureIndex:o};a&&(c.material=a?.isMaterial?a:new r0(a).material),l.classList.add("RenderTargetPreviewPluginTarget"),c.visible||l.classList.add("RenderTargetPreviewPluginCollapsed");const h=document.createElement("div");return h.classList.add("RenderTargetPreviewPluginTargetHeader"),h.innerText=t,h.onclick=()=>{c.visible=!c.visible,c.visible?l.classList.remove("RenderTargetPreviewPluginCollapsed"):l.classList.add("RenderTargetPreviewPluginCollapsed"),this._viewer?.setDirty()},h.oncontextmenu=u=>{u.preventDefault(),u.stopPropagation(),Zu.Create({Download:()=>this.downloadTarget(e,o),Remove:()=>this.removeTarget(e)},u.clientX,u.clientY)},l.appendChild(h),this.mainDiv.appendChild(l),this.targetBlocks.push(c),this.refreshUi(),this}removeTarget(e){const t=this.targetBlocks.findIndex(i=>i.target===e);if(t>=0){const i=this.targetBlocks[t];this.targetBlocks.splice(t,1),i.div.remove()}return this.refreshUi(),this}downloadTarget(e,t){if(!this._viewer)return this;const i=tt(e);if(!i)return this;const n=this._viewer.renderManager.exportRenderTarget(i,"auto",t??0);return this._viewer.exportBlob(n,"renderTarget."+(n.ext||"png")),this}refreshUi(){if(this.mainDiv){if(!this._viewer){this.mainDiv.parentElement&&this.mainDiv.remove(),this.mainDiv.style.display="none",this.mainDiv.style.zIndex="1000";return}this.mainDiv.parentElement||this._viewer.container?.appendChild(this.mainDiv),this.mainDiv.style.display=this.isDisabled()?"none":"flex",this.mainDiv.style.zIndex=parseInt(this._viewer.canvas.style.zIndex||"0")+1+"",this._viewer?.setDirty()}}setDirty(){this.refreshUi()}dispose(){for(const e of this.targetBlocks)this.removeTarget(e.target);super.dispose()}},f.RenderTargetPreviewPlugin.PluginType="RenderTargetPreviewPlugin",jI([se("Enabled"),he(f.RenderTargetPreviewPlugin.prototype.refreshUi)],f.RenderTargetPreviewPlugin.prototype,"enabled",2),f.RenderTargetPreviewPlugin=jI([vt("Render Target Preview Plugin")],f.RenderTargetPreviewPlugin);const qj='#GeometryUVPreviewPluginContainer{position:absolute;left:0;bottom:0;width:100%;z-index:1000;display:flex;flex-wrap:wrap;flex-direction:row;gap:5px;padding:5px;pointer-events:none;height:auto}.GeometryUVPreviewPluginTarget{position:relative;width:200px;height:200px}.GeometryUVPreviewPluginCollapsed{height:25px}.GeometryUVPreviewPluginTargetHeader{position:absolute;top:0;left:0;right:0;background:#00000080;color:#fff;padding:2px;font-size:16px;height:20px;font-family:monospace;text-align:center;pointer-events:auto;cursor:pointer}.GeometryUVPreviewPluginTargetHeader:after{content:"-";position:absolute;right:2px;width:20px;height:20px;line-height:16px}.GeometryUVPreviewPluginCollapsed .GeometryUVPreviewPluginTargetHeader:after{content:"+";line-height:20px}';var Xj=Object.defineProperty,Yj=Object.getOwnPropertyDescriptor,WI=(r,e,t,i)=>{for(var n=i>1?void 0:i?Yj(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Xj(e,t,n),n};f.GeometryUVPreviewPlugin=class extends mt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=null,this.mainDiv=Pr({id:"GeometryUVPreviewPluginContainer",addToBody:!1}),this.targetBlocks=[],this._postRender=()=>{if(this._viewer)for(const t of this.targetBlocks){if(!t.visible)continue;const i=tt(t.target);i?.attributes?.uv&&(t.uvCanvas||(t.uvCanvas=cI(i,1024),t.uvCanvas.style.width="100%",t.uvCanvas.style.height="100%"),t.uvCanvas&&t.uvCanvas.parentElement!==t.div&&t.div.appendChild(t.uvCanvas))}},this.enabled=e}onAdded(e){super.onAdded(e),e.addEventListener("postRender",this._postRender),this.stylesheet=hl(qj,e.container),this.refreshUi()}onRemove(e){e.removeEventListener("postRender",this._postRender),this.stylesheet?.remove(),this.stylesheet=void 0,this.refreshUi(),super.onRemove(e)}addGeometry(e,t,i=!0){if(!e)return this;const n=document.createElement("div"),s={target:e,name:t,div:n,visible:i};n.classList.add("GeometryUVPreviewPluginTarget"),s.visible||n.classList.add("GeometryUVPreviewPluginCollapsed");const a=document.createElement("div");return a.classList.add("GeometryUVPreviewPluginTargetHeader"),a.innerText=t,a.onclick=()=>{s.visible=!s.visible,s.visible?n.classList.remove("GeometryUVPreviewPluginCollapsed"):n.classList.add("GeometryUVPreviewPluginCollapsed"),this._viewer?.setDirty()},a.oncontextmenu=o=>{o.preventDefault(),o.stopPropagation(),Zu.Create({Download:()=>this.downloadGeometryUV(s),Remove:()=>this.removeGeometry(e)},o.clientX,o.clientY)},n.appendChild(a),this.mainDiv.appendChild(n),this.targetBlocks.push(s),this.refreshUi(),this}removeGeometry(e){const t=this.targetBlocks.findIndex(i=>i.target===e);if(t>=0){const i=this.targetBlocks[t];this.targetBlocks.splice(t,1),i.div.remove()}return this.refreshUi(),this}downloadGeometryUV(e){if(!this._viewer)return this;if(!e.uvCanvas)return this;const i=e.uvCanvas.toDataURL("image/png"),n=document.createElement("a");return document.body.appendChild(n),n.style.display="none",n.href=i,n.download="renderTarget.png",n.click(),document.body.removeChild(n),URL.revokeObjectURL(i),this}refreshUi(){if(this.mainDiv){if(!this._viewer){this.mainDiv.parentElement&&this.mainDiv.remove(),this.mainDiv.style.display="none",this.mainDiv.style.zIndex="1000";return}this.mainDiv.parentElement||this._viewer.container?.appendChild(this.mainDiv),this.mainDiv.style.display=this.isDisabled()?"none":"flex",this.mainDiv.style.zIndex=parseInt(this._viewer.canvas.style.zIndex||"0")+1+"",this._viewer?.setDirty()}}setDirty(){this.refreshUi()}dispose(){for(const e of this.targetBlocks)this.removeGeometry(e.target);super.dispose()}},f.GeometryUVPreviewPlugin.PluginType="GeometryUVPreviewPlugin",WI([se("Enabled"),he(f.GeometryUVPreviewPlugin.prototype.refreshUi)],f.GeometryUVPreviewPlugin.prototype,"enabled",2),f.GeometryUVPreviewPlugin=WI([vt("Render Target Preview Plugin")],f.GeometryUVPreviewPlugin);var $j=Object.defineProperty,Kj=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&$j(e,t,n),n};const Qb=class Qb extends mt{constructor(){super(),this.enabled=!0,this.serializeWithViewer=!1,this.uiConfig={}}onAdded(e){super.onAdded(e),this.uiConfig=e.uiConfig,this.uiConfig.expanded=!0}};Qb.PluginType="ViewerUiConfigPlugin";let Qg=Qb;Kj([G("viewer")],Qg.prototype,"_viewer");var Jj=Object.defineProperty,Zj=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Jj(e,t,n),n};const jb=class jb extends mt{constructor(){super(),this.enabled=!0,this.serializeWithViewer=!1,this.uiConfig={}}onAdded(e){super.onAdded(e),this.uiConfig=e.scene.uiConfig,this._scene=e.scene}};jb.PluginType="SceneUiConfigPlugin";let jg=jb;Zj([G("scene")],jg.prototype,"_scene");var eW=Object.defineProperty,tW=Object.getOwnPropertyDescriptor,Wg=(r,e,t,i)=>{for(var n=i>1?void 0:i?tW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&eW(e,t,n),n};f.FullScreenPlugin=class extends mt{constructor(){super(),this.toJSON=void 0,this.enabled=!0,this._lastSize=["100%","100%"],this._lastFsElement=null,this._fsChangeHandler=e=>{if(this.isFullScreen())this.dispatchEvent({type:"enter"});else{const t=this._lastFsElement||this._viewer?.canvas;t&&(t.style.width=this._lastSize[0],t.style.height=this._lastSize[1]),document.removeEventListener("webkitfullscreenchange",this._fsChangeHandler,!1),document.removeEventListener("mozfullscreenchange",this._fsChangeHandler,!1),document.removeEventListener("fullscreenchange",this._fsChangeHandler,!1),document.removeEventListener("MSFullscreenChange",this._fsChangeHandler,!1),this.dispatchEvent({type:"exit"})}},this.enter=this.enter.bind(this),this.exit=this.exit.bind(this)}async enter(e){if(this.isFullScreen())return;const t=e||this._viewer?.canvas;if(t){if(this._lastFsElement=t,document.addEventListener&&(document.addEventListener("webkitfullscreenchange",this._fsChangeHandler,!1),document.addEventListener("mozfullscreenchange",this._fsChangeHandler,!1),document.addEventListener("fullscreenchange",this._fsChangeHandler,!1),document.addEventListener("MSFullscreenChange",this._fsChangeHandler,!1)),this._lastSize=[t.style.width,t.style.height],t.style.width="100%",t.style.height="100%",t.requestFullscreen)return t.requestFullscreen();if(t.mozRequestFullScreen)return t.mozRequestFullScreen();if(t.webkitRequestFullscreen)return t.webkitRequestFullscreen();if(t.msRequestFullscreen)return t.msRequestFullscreen()}}async exit(){if(document.exitFullscreen)return document.exitFullscreen();if(document.mozCancelFullScreen)return document.mozCancelFullScreen();if(document.webkitExitFullscreen)return document.webkitExitFullscreen();if(document.msExitFullscreen)return document.msExitFullscreen()}async toggle(e){return this.isFullScreen()?this.exit():this.enter(e)}isFullScreen(){return document.webkitIsFullScreen||document.mozFullScreen||document.msFullscreenElement!==void 0}},f.FullScreenPlugin.PluginType="FullScreenPlugin",Wg([ct("Enter FullScreen",{sendArgs:!1})],f.FullScreenPlugin.prototype,"enter",1),Wg([ct("Exit FullScreen",{sendArgs:!1})],f.FullScreenPlugin.prototype,"exit",1),Wg([ct("Toggle FullScreen",{sendArgs:!1})],f.FullScreenPlugin.prototype,"toggle",1),f.FullScreenPlugin=Wg([vt("Full Screen")],f.FullScreenPlugin);const iW='#assetManagerLoadingScreen{z-index:50;position:absolute;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";bottom:0;right:0;min-width:100%;min-height:100%;color:#333;font-size:1rem;gap:1rem;display:flex;align-content:center;justify-content:center;align-items:center;flex-direction:column;opacity:1;transition:opacity .5s ease-in-out,min-width .5s,min-height .5s,bottom .5s,right .5s;overflow:hidden;background:transparent;background-blend-mode:luminosity;--b-opacity: .8;--b-background: #fff;--b-blur: 24px;-webkit-backdrop-filter:blur(var(--b-blur));backdrop-filter:blur(var(--b-blur));pointer-events:none}#assetManagerLoadingScreen:before{content:"";position:absolute;top:0;left:0;width:100%;height:100%;z-index:-1;opacity:var(--b-opacity);background:var(--b-background)}#assetManagerLoadingScreenContent{padding-top:.5rem}.loadingScreenProcessState{font-weight:700}#assetManagerLoadingScreen.minimizedLoadingScreen{top:unset;left:unset;bottom:2rem;right:2rem;min-width:0;min-height:0;max-width:80vw;max-height:80vh;width:max-content;height:max-content;padding:1.5rem;border-radius:.5rem}.loadingScreenFilesElement{min-height:4rem;padding:1rem}.loadingScreenLogoElement{margin-bottom:.5rem;max-width:80%}.loadingScreenLogoElement img{min-height:3rem;max-height:5rem;max-width:100%;object-fit:contain}.loadingScreenLogoImage{width:max-content;height:max-content}.minimizedLoadingScreen .loadingScreenLoadingElement{display:none}.minimizedLoadingScreen .loadingScreenFilesElement{min-height:0}.minimizedLoadingScreen .loadingScreenLogoElement{min-height:0;display:none}.minimizedLoadingScreen #assetManagerLoadingScreenContent{display:none}',nW=".loader{width:48px;height:48px;border:5px solid #333;border-bottom-color:transparent;border-radius:50%;display:inline-block;box-sizing:border-box;animation:rotation 1s linear infinite}@keyframes rotation{0%{transform:rotate(0)}to{transform:rotate(360deg)}}";var sW=Object.defineProperty,rW=Object.getOwnPropertyDescriptor,Yi=(r,e,t,i)=>{for(var n=i>1?void 0:i?rW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&sW(e,t,n),n};f.LoadingScreenPlugin=class extends kI{constructor(e){super("LoadingScreen",e),this.styles=iW,this.spinners=[{styles:nW,html:'<span class="loader"></span>'}],this.loader=0,this.loadingTextHeader="Loading Files",this.errorTextHeader="Error Loading Files",this.showFileNames=!0,this.showProcessStates=!0,this.showProgress=!0,this.hideOnOnlyErrors=!0,this.hideOnFilesLoad=!0,this.hideOnSceneObjectLoad=!1,this.minimizeOnSceneObjectLoad=!0,this.showOnFilesLoading=!0,this.showOnSceneEmpty=!0,this.hideDelay=500,this.backgroundOpacity=.5,this.backgroundBlur=24,this.background="#ffffff",this.textColor="#222222",this.logoImage=f.LoadingScreenPlugin.LS_DEFAULT_LOGO,this._isPreviewing=!1,this._previewState=new Map([["file.glb",{state:"downloading",progress:50}],["environment.hdr",{state:"adding"}]]),this.loadingElement=Pr({classList:["loadingScreenLoadingElement"],addToBody:!1}),this.filesElement=Pr({classList:["loadingScreenFilesElement"],addToBody:!1}),this.logoElement=Pr({classList:["loadingScreenLogoElement"],addToBody:!1}),this._isHidden=!1,this._temp=document.createElement("template"),this.isEditor=!1,this._sceneUpdate=t=>{if(!this._viewer||!t.hierarchyChanged)return;const i=this._viewer.scene.modelRoot.children;if(i.length===0&&this.showOnSceneEmpty&&!this.isEditor&&this.show(),i.length>0){const n=this._viewer.assetManager.processState,s=[...n.values()].filter(a=>a.state==="error");this._updateVisibility(n,s.length)||(this.hideOnSceneObjectLoad?this.hideWithDelay():this.minimizeOnSceneObjectLoad&&this._viewer.scene.environment&&Qn(this.hideDelay+300).then(()=>this.minimize()))}else this.minimizeOnSceneObjectLoad&&this.maximize()},this._mainDiv.prepend(this.loadingElement),this._mainDiv.prepend(this.logoElement),this._mainDiv.appendChild(this.filesElement)}refresh(){this._viewer&&this._updateMainDiv(this._isPreviewing?this._previewState:this._viewer.assetManager.processState,!1)}togglePreview(){this.maximize(),this._isPreviewing=!this._isPreviewing,this.refresh(),this._isPreviewing?this.show():this.hideWithDelay()}get visible(){return!this._isHidden}async hide(){this._isHidden=!0,this._mainDiv.style.opacity="0",await Qn(502),this._isHidden&&(this._mainDiv.style.display="none",this._showMainDiv())}async hideWithDelay(){if(this._isHidden=!0,await Qn(this.hideDelay),!!this._isHidden)return this.hide()}show(){this._isHidden&&(this._isHidden=!1,this._showMainDiv(),this._mainDiv.style.display="flex")}_showMainDiv(){this._mainDiv.style.opacity="1"}minimize(){this._mainDiv.classList.add("minimizedLoadingScreen"),this.showFileNames||(this.loadingElement.style.display="block")}maximize(){this._mainDiv.classList.remove("minimizedLoadingScreen"),this.loadingElement.style.display=""}_setHTML(e,t){this._temp.innerHTML=t,this._temp.innerHTML.trim()!==e.innerHTML.trim()&&(e.innerHTML=t)}_updateMainDiv(e,t=!0){if(!this._viewer||!this._contentDiv)return;if(!this.enabled){this._mainDiv.style.display="none";return}if(this.showFileNames){let n="";e.forEach((s,a)=>{n+=(this.showProcessStates?`<span class="loadingScreenProcessState">${ks(s.state)}</span>: `:"")+ks((a||"").split("/").pop()||"")+(this.showProgress&&s.progress?" - "+(s.progress.toFixed(0)+"%"):"")+"<br>"}),this._setHTML(this.filesElement,n)}else this._setHTML(this.filesElement,"");const i=[...e.values()].filter(n=>n.state==="error");i.length>0&&i.length===e.size&&!this.hideOnOnlyErrors?this._setHTML(this._contentDiv,ks(this.errorTextHeader)):this._setHTML(this._contentDiv,ks(this.loadingTextHeader)),this._setHTML(this.loadingElement,this.spinners[this.loader].html),this._mainDiv.style.setProperty("--b-opacity",this.backgroundOpacity.toString()),this._mainDiv.style.setProperty("--b-background",this.background),this._mainDiv.style.setProperty("--b-blur",this.backgroundBlur+"px"),this._mainDiv.style.color=this.textColor,this._setHTML(this.logoElement,this.logoImage?`<img class="loadingScreenLogoImage" src=${JSON.stringify(this.logoImage)}/>`:""),t&&this._updateVisibility(e,i.length)}_updateVisibility(e,t){return this._viewer?this.hideOnFilesLoad&&(e.size===0||t===e.size&&this.hideOnOnlyErrors)&&!this._isHidden?(this.hideDelay?this.hideWithDelay():this.hide(),!0):e.size>0&&this.showOnFilesLoading&&this._isHidden?(this._viewer.scene.modelRoot.children.length>0&&this.minimizeOnSceneObjectLoad&&this._viewer.scene.environment?this.minimize():this.maximize(),this.show(),!0):!1:!1}onAdded(e){this.stylesheet=hl(this.styles,e.container),this.stylesheetLoader=this.spinners.map(t=>hl(t.styles,e.container)),e.scene.addEventListener("sceneUpdate",this._sceneUpdate),super.onAdded(e)}onRemove(e){return e.scene.removeEventListener("sceneUpdate",this._sceneUpdate),this.stylesheet?.remove(),this.stylesheet=void 0,this.stylesheetLoader?.forEach(t=>t.remove()),this.stylesheetLoader=void 0,super.onRemove(e)}},f.LoadingScreenPlugin.PluginType="LoadingScreenPlugin",f.LoadingScreenPlugin.LS_DEFAULT_LOGO="https://threepipe.org/logo.svg",Yi([Li("Loader",["Spinner 1"].map((r,e)=>({value:e,label:r}))),G()],f.LoadingScreenPlugin.prototype,"loader",2),Yi([He("Loading text header"),he(f.LoadingScreenPlugin.prototype.refresh),G()],f.LoadingScreenPlugin.prototype,"loadingTextHeader",2),Yi([He("Error text header"),G()],f.LoadingScreenPlugin.prototype,"errorTextHeader",2),Yi([se("Show file names"),he(f.LoadingScreenPlugin.prototype.refresh),G()],f.LoadingScreenPlugin.prototype,"showFileNames",2),Yi([se("Show process states"),he(f.LoadingScreenPlugin.prototype.refresh),G()],f.LoadingScreenPlugin.prototype,"showProcessStates",2),Yi([se("Show progress"),he(f.LoadingScreenPlugin.prototype.refresh),G()],f.LoadingScreenPlugin.prototype,"showProgress",2),Yi([se("Hide on only errors"),G()],f.LoadingScreenPlugin.prototype,"hideOnOnlyErrors",2),Yi([se("Hide on files load"),G()],f.LoadingScreenPlugin.prototype,"hideOnFilesLoad",2),Yi([se("Hide on scene object load"),G()],f.LoadingScreenPlugin.prototype,"hideOnSceneObjectLoad",2),Yi([se("Minimize on scene object load"),G()],f.LoadingScreenPlugin.prototype,"minimizeOnSceneObjectLoad",2),Yi([se("Show when files start loading"),G()],f.LoadingScreenPlugin.prototype,"showOnFilesLoading",2),Yi([se("Show when scene empty"),G()],f.LoadingScreenPlugin.prototype,"showOnSceneEmpty",2),Yi([He("Hide delay (ms)"),G()],f.LoadingScreenPlugin.prototype,"hideDelay",2),Yi([Fe("Background Opacity",[0,1]),he(f.LoadingScreenPlugin.prototype.refresh),G()],f.LoadingScreenPlugin.prototype,"backgroundOpacity",2),Yi([Fe("Background Blur",[0,100]),he(f.LoadingScreenPlugin.prototype.refresh),G()],f.LoadingScreenPlugin.prototype,"backgroundBlur",2),Yi([He("Background Color"),he(f.LoadingScreenPlugin.prototype.refresh),G()],f.LoadingScreenPlugin.prototype,"background",2),Yi([He("Text Color"),he(f.LoadingScreenPlugin.prototype.refresh),G()],f.LoadingScreenPlugin.prototype,"textColor",2),Yi([He("Logo Image"),he(f.LoadingScreenPlugin.prototype.refresh),G()],f.LoadingScreenPlugin.prototype,"logoImage",2),Yi([ct("Toggle preview")],f.LoadingScreenPlugin.prototype,"togglePreview",1),Yi([ct("Minimize")],f.LoadingScreenPlugin.prototype,"minimize",1),Yi([ct("Maximize")],f.LoadingScreenPlugin.prototype,"maximize",1),f.LoadingScreenPlugin=Yi([vt("Loading Screen")],f.LoadingScreenPlugin);class qI extends _l{constructor(){super(),this.isWidget=!0,this.assetType="widget",this._object=null,this.boundingScaleMultiplier=1,this.position.set(0,0,0),this.visible=!1,this.renderOrder=100,this.userData.bboxVisible=!1,this._updater=this._updater.bind(this),this.detach=this.detach.bind(this),this.addEventListener("dispose",this.detach)}_updater(){const e=this._object;if(e){const t=new En().expandByObject(e,!1);t.getCenter(this.position);let i=t.getBoundingSphere(new un).radius;i<=0&&(e.getWorldPosition(this.position),i=.1),this.scale.setScalar(i*this.boundingScaleMultiplier).clampScalar(.01,1e8),this.setVisible(!0)}else this.setVisible(!1)}setVisible(e){e!==this.visible&&(this.visible=e,this.setDirty?.({sceneUpdate:!1}))}attach(e){this.detach();let t=!1;return e.traverseAncestors(i=>i.isRootScene&&(t=!0)),t?e?(this._object=e,this._object.addEventListener("objectUpdate",this._updater),this._object.addEventListener("geometryUpdate",this._updater),this._updater(),this):this:this}detach(){return this._object?(this._object?.removeEventListener("objectUpdate",this._updater),this._object?.removeEventListener("geometryUpdate",this._updater),this._object=null,this._updater(),this):this}get object(){return this._object}}var aW=Object.defineProperty,oW=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&aW(e,t,n),n};const ob=class extends _l{constructor(e,t=!0){super(),this.isWidget=!0,this.assetType="widget",this.visible=!0,this._objectUpdated=!1,this.uiConfig=pm("Widget",this,{tags:"widget"}),this.object=e,this.object.updateMatrixWorld(),this.object.updateProjectionMatrix&&this.object.updateProjectionMatrix(),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.detach=this.detach.bind(this),this._objectUpdate=this._objectUpdate.bind(this),this._objectBeforeRender=this._objectBeforeRender.bind(this),t&&this.attach(e),this.traverse(i=>{i.userData.__keepShadowDef=!0,i.castShadow=!1,i.receiveShadow=!1}),this.renderOrder=100}update(e=!0){e&&qe.setDirty.call(this)}_objectUpdate(){this._objectUpdated=!0}_objectBeforeRender(){this.visible&&this._objectUpdated&&(this._objectUpdated=!1,this.object&&this.update())}attach(e){if(this.object&&this.detach(),this.object=e,this.object){this.update();const t=this.object;t.addEventListener("beforeRender",this._objectBeforeRender),t.addEventListener("objectUpdate",this._objectUpdate),t.addEventListener("geometryUpdate",this._objectUpdate),this.uiConfig&&this.object.uiConfig?.children?.push(this.uiConfig),this.visible=!0}return this}detach(){if(!this.object)return this;const e=this.object;if(e.removeEventListener("beforeRender",this._objectBeforeRender),e.removeEventListener("objectUpdate",this._objectUpdate),e.removeEventListener("geometryUpdate",this._objectUpdate),this.uiConfig){const t=this.object.uiConfig?.children?.indexOf(this.uiConfig);t!==void 0&&t>=0&&this.object.uiConfig?.children?.splice(t,1)}return this.object=void 0,this.visible=!1,this}dispose(){this.detach()}};oW([se(),Zt(ob.prototype.update)],ob.prototype,"visible");let Ch=ob;class XI extends Ch{constructor(e){super(e),this.camera=e,this.traverse(t=>{t.userData.__keepShadowDef=!0,t.castShadow=!1,t.receiveShadow=!1})}preRender(){this.visible&&this._objectBeforeRender()}attach(e){return super.attach(e),this}detach(){return super.detach()}}class qg extends Ch{constructor(e){super(e),this.light=e,this.traverse(t=>{t.userData.__keepShadowDef=!0,t.castShadow=!1,t.receiveShadow=!1})}preRender(){this.visible&&this._objectBeforeRender()}}var lW=Object.defineProperty,$d=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&lW(e,t,n),n};const fr=class FP extends Ch{constructor(e,t,i){super(e),this._vector=new S,this._boneMatrix=new fe,this._matrixWorldInv=new fe,this.lineWidth=5,this.color1=new ee(0,0,1),this.color2=new ee(0,1,0),this.autoUpdate=!0,t&&this.color1.set(t),i&&this.color2.set(i);const n=new Gs;this.hMaterial=new ji({vertexColors:!0,linewidth:this.lineWidth,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1}),this.hMaterial.userData.renderToGBuffer=!1,this.hMaterial.userData.renderToDepth=!1,this.lineSegments=new va(n,this.hMaterial),this.lineSegments.frustumCulled=!1,this.add(this.lineSegments),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.update()}updateMatrixWorld(e){this.object&&this.autoUpdate&&this.update(!1),super.updateMatrixWorld(e)}update(e=!0){if(!this.lineSegments||!this.object)return;const t=this.object;this.hMaterial.linewidth=this.lineWidth;const i=[],n=[];this._matrixWorldInv.copy(t.matrixWorld).invert(),t.parent&&t.parent.isBone&&(this._boneMatrix.multiplyMatrices(this._matrixWorldInv,t.parent.matrixWorld),this._vector.setFromMatrixPosition(this._boneMatrix),i.push(this._vector.x,this._vector.y,this._vector.z),n.push(this.color1.r,this.color1.g,this.color1.b),this._boneMatrix.multiplyMatrices(this._matrixWorldInv,t.matrixWorld),this._vector.setFromMatrixPosition(this._boneMatrix),i.push(this._vector.x,this._vector.y,this._vector.z),n.push(this.color2.r,this.color2.g,this.color2.b));const s=this.lineSegments.geometry;i.length>0?(s.setPositions(i),s.setColors(n)):(s.setPositions([0,0,0,0,0,0]),s.setColors([0,0,0,0,0,0])),super.update(e)}dispose(){this.lineSegments.geometry.dispose(),this.lineSegments.material.dispose(),super.dispose()}static Check(e){return e.isBone}static Create(e){return new FP(e)}};$d([Zt(fr.prototype.update)],fr.prototype,"hMaterial"),$d([Zt(fr.prototype.update),Fe(void 0,[.1,20],.01)],fr.prototype,"lineWidth"),$d([Zt(fr.prototype.update),xn()],fr.prototype,"color1"),$d([Zt(fr.prototype.update),xn()],fr.prototype,"color2"),$d([se(),Zt(fr.prototype.update)],fr.prototype,"autoUpdate");let cW=fr;class YI extends qI{constructor(){super();const e=new ji({color:"#ff2222",transparent:!0,opacity:.9,linewidth:5,resolution:new K(1024,1024),worldUnits:!1,dashed:!1,toneMapped:!1,depthTest:!0,depthWrite:!1,allowOverride:!1});e.userData.renderToGBuffer=!1,e.userData.renderToDepth=!1,this.lineMaterial=e;const t=new Gs;t.setPositions([1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,1,0,1,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,1].map(n=>n-.5));const i=new va(t,e);i.computeLineDistances(),i.scale.set(1,1,1),i.visible=!0,this.add(i)}_updater(){super._updater();const e=this.object;if(e){const i=new En().expandByObject(e,!1).getSize(this.scale);i.lengthSq()<=0&&(e.getWorldPosition(this.position),i.set(2,2,2)),i.multiplyScalar(this.boundingScaleMultiplier).clampScalar(.01,1e8),this.setVisible(!0)}}}var hW=Object.defineProperty,uW=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&hW(e,t,n),n};const lb=class NP extends XI{constructor(e){super(e),this._vector=new S,this._camera=new fu,this._colorFrustum=new ee(16755200),this._colorCone=new ee(16711680),this._colorUp=new ee(43775),this._colorTarget=new ee(16777215),this._colorCross=new ee(3355443),this.showFar=!1;const t=new Gs,i=new ji({color:16777215,linewidth:3,vertexColors:!0,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1,allowOverride:!1});i.userData.renderToGBuffer=!1,i.userData.renderToDepth=!1;const{vertices:n,colors:s,pointMap:a}=dW();t.setPositions(n),t.setColors(s),this.line=new va(t,i),this.line.frustumCulled=!1,this.add(this.line),this.pointMap=a,this.update(),this.setColors(this._colorFrustum,this._colorCone,this._colorUp,this._colorTarget,this._colorCross)}setColors(e,t,i,n,s){const a=this.line.geometry,o=a.getAttribute("instanceColorStart"),l=a.getAttribute("instanceColorEnd");let c=0;function h(u){o.setXYZ(c,u.r,u.g,u.b),l.setXYZ(c,u.r,u.g,u.b),c++}h(i),h(i),h(i),h(s),h(s),h(s),h(s),h(e),h(e),h(e),h(e),h(t),h(t),h(t),h(t),h(e),h(e),h(e),h(e),h(e),h(e),h(e),h(e),h(n),h(s),o.needsUpdate=!0,l.needsUpdate=!0}update(){if(!this.camera||!this.line)return;const e=this.line.geometry,t=this.pointMap,i=1,n=1,{_camera:s,_vector:a}=this;this.camera.updateProjectionMatrix(),s.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),cn("c",t,e,s,0,0,-1,a),cn("t",t,e,s,0,0,1,a),cn("n1",t,e,s,-i,-n,-1,a),cn("n2",t,e,s,i,-n,-1,a),cn("n3",t,e,s,-i,n,-1,a),cn("n4",t,e,s,i,n,-1,a),cn("f1",t,e,s,-i,-n,1,a),cn("f2",t,e,s,i,-n,1,a),cn("f3",t,e,s,-i,n,1,a),cn("f4",t,e,s,i,n,1,a),cn("u1",t,e,s,i*.7,n*1.1,-1,a),cn("u2",t,e,s,-i*.7,n*1.1,-1,a),cn("u3",t,e,s,0,n*2,-1,a),cn("cf1",t,e,s,-i,0,1,a),cn("cf2",t,e,s,i,0,1,a),cn("cf3",t,e,s,0,-n,1,a),cn("cf4",t,e,s,0,n,1,a),cn("cn1",t,e,s,-i,0,-1,a),cn("cn2",t,e,s,i,0,-1,a),cn("cn3",t,e,s,0,-n,-1,a),cn("cn4",t,e,s,0,n,-1,a),e.getAttribute("instanceStart").needsUpdate=!0,e.getAttribute("instanceEnd").needsUpdate=!0,e.computeBoundingBox(),e.computeBoundingSphere(),this.setColors(this._colorFrustum,this._colorCone,this._colorUp,this._colorTarget,this._colorCross),this.line.geometry.instanceCount=this.showFar?1/0:15,super.update()}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),super.dispose()}static Check(e){return e.isCamera}static Create(e){return new NP(e)}};uW([se(),Zt(lb.prototype.update)],lb.prototype,"showFar");let $I=lb;function cn(r,e,t,i,n,s,a,o){o.set(n,s,a).unproject(i);const l=e[r];if(l!==void 0){const c=t.getAttribute("instanceStart"),h=t.getAttribute("instanceEnd");for(let u=0,d=l.length;u<d;u++){const p=Math.floor(l[u]/2);(l[u]%2===0?c:h).setXYZ(p,o.x,o.y,o.z)}}}function dW(){const r=[],e=[],t={};i("u1","u2"),i("u2","u3"),i("u3","u1"),i("cn1","cn2"),i("cn3","cn4"),i("cf1","cf2"),i("cf3","cf4"),i("n1","n2"),i("n2","n4"),i("n4","n3"),i("n3","n1"),i("p","n1"),i("p","n2"),i("p","n3"),i("p","n4"),i("f1","f2"),i("f2","f4"),i("f4","f3"),i("f3","f1"),i("n1","f1"),i("n2","f2"),i("n3","f3"),i("n4","f4"),i("c","t"),i("p","c");function i(s,a){n(s),n(a)}function n(s){r.push(0,0,0),e.push(0,0,0),t[s]===void 0&&(t[s]=[]),t[s].push(r.length/3-1)}return{vertices:r,colors:e,pointMap:t}}var fW=Object.defineProperty,cb=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&fW(e,t,n),n};const Bl=class kP extends qg{constructor(e,t,i){super(e),this.lineWidth=5,this.size=.5,this._v1=new S,this._v2=new S,this._v3=new S,this.color=i,t!==void 0&&(this.size=t);let n=new Ed;this.hMaterial=new ji({color:16711680,linewidth:3,vertexColors:!1,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1,allowOverride:!1}),this.hMaterial.userData.renderToGBuffer=!1,this.hMaterial.userData.renderToDepth=!1,this.lightPlane=new ag(n,this.hMaterial),this.add(this.lightPlane),n=new Ed,n.setPositions([0,0,0,0,0,1]),this.targetLine=new ag(n,this.hMaterial),this.add(this.targetLine),this.update(),this.traverse(s=>{s.userData.__keepShadowDef=!0,s.castShadow=!1,s.receiveShadow=!1})}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose(),super.dispose()}update(){!this.light||!this.lightPlane||(this._v1.setFromMatrixPosition(this.light.matrixWorld),this._v2.setFromMatrixPosition(this.light.target.matrixWorld),this._v3.subVectors(this._v2,this._v1),this.lightPlane.geometry.setPositions([-this.size,this.size,0,this.size,this.size,0,this.size,-this.size,0,-this.size,-this.size,0,-this.size,this.size,0]),this.lightPlane.lookAt(this._v2),this.lightPlane.material=this.hMaterial,this.targetLine.material=this.hMaterial,this.hMaterial.color.set(this.color??this.light.color),this.hMaterial.linewidth=this.lineWidth,this.targetLine.lookAt(this._v2),this.targetLine.scale.z=this.light.intensity/3,super.update())}static Check(e){return e.isDirectionalLight}static Create(e){return new kP(e)}};cb([he(Bl.prototype.update)],Bl.prototype,"hMaterial"),cb([he(Bl.prototype.update),Fe(void 0,[.1,20],.01)],Bl.prototype,"lineWidth"),cb([he(Bl.prototype.update),Fe(void 0,[.01,10],.01)],Bl.prototype,"size");let KI=Bl;var pW=Object.defineProperty,Xg=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&pW(e,t,n),n};const Pa=class GP extends Ch{constructor(e){super(e),this._vertexHandles=[],this.handleSize=.05,this.editableHandleSize=.1,this.handleColor=37885,this.editableHandleColor=15663205,this.autoUpgradeChildren=!1,this.line=e,this._cubeGeometry=new gi(1,1,1,2,2,2),ni.upgradeGeometry.call(this._cubeGeometry),this._cubeMaterial=new is({color:this.handleColor,transparent:!0,opacity:.95,allowOverride:!1}),this._cubeMaterial.userData.renderToGBuffer=!1,this._cubeMaterial.userData.renderToDepth=!1,this._cubeMaterial2=this._cubeMaterial.clone(),this._cubeMaterial2.color.set(this.editableHandleColor),this.update()}update(){if(super.update(),!this.line||!this.line.geometry)return;const e=this.line.geometry,t=e.getAttribute("position"),i=e.getPositions?e.getPositions():t?.array,n=i?i.length/3:0;if(!i||!n)return;const a=this.line.geometry.userData?.generationParams?.curve;if(a){const l=ZI(a),c=this._vertexHandles;this._vertexHandles=[];for(let h=l.length;h<c.length;h++)this.remove(c[h]);for(let h=0;h<l.length;h++){const u=l[h],d=c[h]??new _e(this._cubeGeometry,this._cubeMaterial2);d.renderOrder=100;const p=u[0];isFinite(p[0])||(p[0]=0),isFinite(p[1])||(p[1]=0),isFinite(p[2])||(p[2]=0),d.position.fromArray(p),d.scale.setScalar(this.editableHandleSize),d.frustumCulled=!1,d.castShadow=!1,d.receiveShadow=!1,d.userData.__keepShadowDef=!0,d.parent||this.add(d),this._vertexHandles.push(d),d.userData.isWidgetHandle=!0,d.userData.transformControls={mode:"translate",space:"local",showX:!0,showY:!0,showZ:!0,lockProps:["mode"]},d.__handle=u,d.setDirty=m=>{if(m.change!=="transform")return;const A=d.__handle,g=A[0],y=A[1],v=d.position;if(Math.abs(g[0]-v.x)+Math.abs(g[1]-v.y)+Math.abs(g[2]-v.z)<=1e-4)return;g[0]=v.x,g[1]=v.y,g[2]=v.z;let b=a,T=y;if(T.startsWith("curves.")){const E=T.indexOf(".",7),M=parseInt(T.slice(7,E)||"0");T=T.slice(E+1),M>=0&&M<a.curves.length&&(b=a.curves[M])}if(T.startsWith("points.")){const E=parseInt(T.slice(7)||"0",10);b.points?.[E]?.set(g[0],g[1],g[2])}else b[T]?.set(g[0],g[1],g[2]);e.setDirty&&e.setDirty({regenerate:!0})}}if(l.length)return}this._clearVertexCubes();const o=this._vertexHandles;this._vertexHandles=[];for(let l=n;l<o.length;l++)this.remove(o[l]);for(let l=0;l<n;l++){const c=i[l*3],h=i[l*3+1],u=i[l*3+2],d=o[l]??new _e(this._cubeGeometry,this._cubeMaterial);d.position.set(isFinite(c)?c:0,isFinite(h)?h:0,isFinite(u)?u:0),d.scale.setScalar(this.handleSize),d.frustumCulled=!1,d.castShadow=!1,d.receiveShadow=!1,d.userData.__keepShadowDef=!0,d.parent||this.add(d),this._vertexHandles.push(d)}}_clearVertexCubes(){for(const e of this._vertexHandles)this.remove(e);this._vertexHandles=[]}dispose(){this._clearVertexCubes(),this._cubeGeometry.dispose(),this._cubeMaterial.dispose(),super.dispose()}static Check(e){return e.isLine||e.isLineSegments2}static Create(e){return new GP(e)}};Xg([he(Pa.prototype.update),Fe(void 0,[.001,.2],.001)],Pa.prototype,"handleSize"),Xg([he(Pa.prototype.update),Fe(void 0,[.001,.5],.001)],Pa.prototype,"editableHandleSize"),Xg([he(Pa.prototype.update),xn()],Pa.prototype,"handleColor"),Xg([he(Pa.prototype.update),xn()],Pa.prototype,"editableHandleColor");let JI=Pa;function ZI(r){const e=[];return r.v0?.toArray&&e.push([r.v0.toArray(),"v0"]),r.v1?.toArray&&e.push([r.v1.toArray(),"v1"]),r.v2?.toArray&&e.push([r.v2.toArray(),"v2"]),r.v3?.toArray&&e.push([r.v3.toArray(),"v3"]),r.points!==void 0&&r.points.forEach((t,i)=>{e.push([t.toArray(),"points."+i])}),r.curves!==void 0&&r.curves.forEach((t,i)=>{const n=ZI(t);n.forEach(s=>{s[1]="curves."+i+"."+s[1]}),e.push(...n)}),e}var mW=Object.defineProperty,hb=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&mW(e,t,n),n};const Ll=class zP extends qg{constructor(e,t,i){super(e),this.lineWidth=5,this.size=.5,this.color=i,t!==void 0&&(this.size=t);const n=new Zv(new Is(.5,4,2));this.hMaterial=new ji({color:16711680,linewidth:3,vertexColors:!1,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1,allowOverride:!1}),this.hMaterial.userData.renderToGBuffer=!1,this.hMaterial.userData.renderToDepth=!1,this.lightSphere=new lI(n,this.hMaterial),this.lightSphere.computeLineDistances(),this.add(this.lightSphere),this.update(),this.traverse(s=>{s.userData.__keepShadowDef=!0,s.castShadow=!1,s.receiveShadow=!1})}dispose(){this.lightSphere.geometry.dispose(),this.lightSphere.material.dispose(),super.dispose()}update(){!this.light||!this.lightSphere||(this.hMaterial.color.set(this.color??this.light.color),this.hMaterial.linewidth=this.lineWidth,this.lightSphere.scale.setScalar(this.size),super.update())}static Check(e){return e.isPointLight}static Create(e){return new zP(e)}};hb([he(Ll.prototype.update)],Ll.prototype,"hMaterial"),hb([he(Ll.prototype.update),Fe(void 0,[.1,20],.01)],Ll.prototype,"lineWidth"),hb([he(Ll.prototype.update),Fe(void 0,[.01,10],.01)],Ll.prototype,"size");let eP=Ll;var gW=Object.defineProperty,Kd=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&gW(e,t,n),n};const pr=class VP extends Ch{constructor(e,t,i){super(e),this._vector=new S,this._boneMatrix=new fe,this._matrixWorldInv=new fe,this.lineWidth=5,this.color1=new ee(0,0,1),this.color2=new ee(0,1,0),this.autoUpdate=!0,t&&this.color1.set(t),i&&this.color2.set(i),this.bones=ub(e);const n=new Gs;this.hMaterial=new ji({vertexColors:!0,linewidth:this.lineWidth,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1,allowOverride:!1}),this.hMaterial.userData.renderToGBuffer=!1,this.hMaterial.userData.renderToDepth=!1,this.lineSegments=new va(n,this.hMaterial),this.lineSegments.frustumCulled=!1,this.add(this.lineSegments),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.update()}updateMatrixWorld(e){this.object&&this.visible&&this.autoUpdate&&this.update(!1),super.updateMatrixWorld(e)}update(e=!0){if(!this.lineSegments||!this.object)return;this.hMaterial.linewidth=this.lineWidth;const t=this.lineSegments.geometry,i=[],n=[];for(const a of this.bones)a.parent&&a.parent.isBone&&(i.push(0,0,0),i.push(0,0,0),n.push(this.color1.r,this.color1.g,this.color1.b),n.push(this.color2.r,this.color2.g,this.color2.b));this._matrixWorldInv.copy(this.object.matrixWorld).invert();let s=0;for(const a of this.bones)a.parent&&a.parent.isBone&&(this._boneMatrix.multiplyMatrices(this._matrixWorldInv,a.parent.matrixWorld),this._vector.setFromMatrixPosition(this._boneMatrix),i[3*s]=this._vector.x,i[3*s+1]=this._vector.y,i[3*s+2]=this._vector.z,this._boneMatrix.multiplyMatrices(this._matrixWorldInv,a.matrixWorld),this._vector.setFromMatrixPosition(this._boneMatrix),i[3*s+3]=this._vector.x,i[3*s+4]=this._vector.y,i[3*s+5]=this._vector.z,s+=2);i.length>0?(t.setPositions(i),t.setColors(n)):(t.setPositions([0,0,0,1,0,0]),t.setColors([1,0,0,0,1,0])),super.update(e)}dispose(){this.lineSegments.geometry.dispose(),this.lineSegments.material.dispose(),super.dispose()}static Check(e){let t=!1;return e.traverseAncestors(i=>{i._hasSkeletonHelper&&(t=!0)}),t?!1:ub(e).length>0}static Create(e){const t=new VP(e);return e._hasSkeletonHelper=!0,t}};Kd([Zt(pr.prototype.update)],pr.prototype,"hMaterial"),Kd([Zt(pr.prototype.update),Fe(void 0,[.1,20],.01)],pr.prototype,"lineWidth"),Kd([Zt(pr.prototype.update),xn()],pr.prototype,"color1"),Kd([Zt(pr.prototype.update),xn()],pr.prototype,"color2"),Kd([se(),Zt(pr.prototype.update)],pr.prototype,"autoUpdate");let tP=pr;function ub(r){const e=[];r.isBone===!0&&e.push(r);for(const t of r.children)e.push(...ub(t));return e}var AW=Object.defineProperty,iP=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&AW(e,t,n),n};const Jd=class HP extends qg{constructor(e,t,i){super(e),this.lineWidth=5,this._v1=new S,this.color=i;const n=new Gs,s=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let a=0,o=1,l=32;a<l;a++,o++){const c=a/l*Math.PI*2,h=o/l*Math.PI*2;s.push(Math.cos(c),Math.sin(c),1,Math.cos(h),Math.sin(h),1)}n.setPositions(s),this.hMaterial=new ji({color:16711680,linewidth:3,vertexColors:!1,worldUnits:!1,dashed:!1,alphaToCoverage:!0,toneMapped:!1,transparent:!0,depthTest:!0,depthWrite:!1,allowOverride:!1}),this.hMaterial.userData.renderToGBuffer=!1,this.hMaterial.userData.renderToDepth=!1,this.cone=new va(n,this.hMaterial),this.add(this.cone),this.update(),this.traverse(a=>{a.userData.__keepShadowDef=!0,a.castShadow=!1,a.receiveShadow=!1})}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose(),super.dispose()}update(){if(!this.light||!this.cone)return;this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1);const e=this.light.distance?this.light.distance:1e3,t=e*Math.tan(this.light.angle);this.cone.scale.set(t,t,e),this._v1.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(this._v1),this.hMaterial.color.set(this.color??this.light.color),this.hMaterial.linewidth=this.lineWidth,super.update()}static Check(e){return e.isSpotLight}static Create(e){return new HP(e)}};iP([he(Jd.prototype.update)],Jd.prototype,"hMaterial"),iP([he(Jd.prototype.update),Fe(void 0,[.1,20],.01)],Jd.prototype,"lineWidth");let nP=Jd;const jr=class jr{constructor(){this._initialMatrix=new fe,this._chainActive=!1}onSelectionChanged(){this._chainActive=!1}onDuplicated(e){this._initialMatrix.copy(e),this._chainActive=!0}applyOffset(e,t,i="simple"){if(!this._chainActive)return!1;const n=jr._iP,s=jr._iQ,a=jr._iS;this._initialMatrix.decompose(n,s,a);const o=t.position.clone().sub(n),l=s.invert().premultiply(t.quaternion.clone()).normalize(),c=t.scale.clone().divide(a),h=o.lengthSq()>1e-10,u=Math.abs(l.x)>1e-6||Math.abs(l.y)>1e-6||Math.abs(l.z)>1e-6,d=Math.abs(c.x-1)>1e-6||Math.abs(c.y-1)>1e-6||Math.abs(c.z-1)>1e-6;if(!h&&!u&&!d)return!1;const p=i==="compound",m=jr._rel;for(const A of e)p?(m.copy(A.position).sub(n),d&&m.multiply(c),u&&m.applyQuaternion(l),A.position.copy(t.position).add(m)):h&&A.position.add(o),u&&A.quaternion.premultiply(l).normalize(),d&&A.scale.multiply(c),A.updateMatrixWorld(!0),A.setDirty?.({change:"transform"});return!0}saveState(){return{matrix:this._initialMatrix.clone(),active:this._chainActive}}restoreState(e){this._initialMatrix.copy(e.matrix),this._chainActive=e.active}reset(){this._initialMatrix.identity(),this._chainActive=!1}};jr._iP=new S,jr._iQ=new $e,jr._iS=new S,jr._rel=new S;let Yg=jr;class sP{constructor(){this._state=null}get state(){return this._state}get isEmpty(){return!this._state}copy(e){const t=xd(e);t.length&&(this._state={objects:t,mode:"copy",sourceParents:this._parentMap(t)})}cut(e){const t=xd(e);t.length&&(this._state={objects:t,mode:"cut",sourceParents:this._parentMap(t)})}paste(e){return this._state?this._state.mode==="copy"?this._pasteFromCopy(e):this._pasteFromCut(e):null}clear(){this._state=null}_pasteFromCopy(e){const t=this._state;if(!t)return null;const i=[],n=new Map;for(const s of t.objects){const a=s.clone(!0);ig(s,a);const o=e??s.parent;o&&(o.add(a),n.set(a,o)),i.push(a)}return{objects:i,undo:()=>{for(const s of i)s.removeFromParent()},redo:()=>{for(const s of i){const a=n.get(s);a&&!s.parent&&a.add(s)}}}}_pasteFromCut(e){const t=this._state;if(!t)return null;const i=t.objects,n=t.sourceParents;for(const s of i){const a=e??n.get(s);a&&s.parent!==a&&(s.removeFromParent(),a.add(s))}return this._state=null,{objects:i,undo:()=>{for(const s of i){const a=n.get(s);a&&s.parent!==a&&(s.removeFromParent(),a.add(s))}this._state=t},redo:()=>{for(const s of i){const a=e??n.get(s);a&&s.parent!==a&&(s.removeFromParent(),a.add(s))}this._state=null}}}_parentMap(e){const t=new Map;for(const i of e)t.set(i,i.parent);return t}}var yW=Object.defineProperty,Zd=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&yW(e,t,n),n};function rP(r){for(;r.parent&&r.assetType!=="widget"&&!r.userData.allowPicking;)r=r.parent;return r}const _o=(xo=class extends mt{constructor(e=YI,t=!0,i=!1){super(),this.enabled=!0,this._extraWidgets=[],this._clipboard=new sP,this._duplicateTracker=new Yg,this.duplicateMode="simple",this.dependencies=[Q0],this.selectionMode="object",this.autoFocusHover=!1,this.autoApplyMaterialOnDrop=!0,this.widgetEnabled=!0,this.multiSelectEnabled=!0,this._onKeyDown=n=>{if(this.isDisabled()||n.target?.tagName==="TEXTAREA"||n.target?.tagName==="INPUT")return;const s=n.ctrlKey||n.metaKey;s&&n.code==="KeyA"?(n.preventDefault(),this.selectAll()):s&&n.code==="KeyD"?(n.preventDefault(),this.duplicateSelected(n.shiftKey?this.duplicateMode==="simple"?"compound":"simple":void 0)):s&&n.code==="KeyC"?(n.preventDefault(),this.copySelected()):s&&n.code==="KeyX"?(n.preventDefault(),this.cutSelected()):s&&n.code==="KeyV"?(n.preventDefault(),this.pasteFromClipboard()):n.code==="Escape"?this.clearSelection():n.code==="Delete"||n.code==="Backspace"?(n.preventDefault(),this.deleteSelected()):n.code==="KeyH"&&!s?(n.preventDefault(),n.shiftKey?this.unhideAll():this.toggleVisibilitySelected()):n.code==="KeyF"&&!s?(n.preventDefault(),this.focusSelected()):n.altKey&&!s&&(n.code==="KeyG"||n.code==="KeyR"||n.code==="KeyS")&&(n.preventDefault(),this.resetTransform(n.code==="KeyG"?"position":n.code==="KeyR"?"rotation":"scale"))},this._mainCameraChange=()=>{!this._picker||!this._viewer||(this._picker.camera=this._viewer.scene.mainCamera)},this._addSceneObject=n=>{n.object?.userData?.isWidgetRoot&&n.object.parent===this._viewer?.scene&&this._picker?.extraObjects.push(n.object)},this._sceneUpdate=n=>{if(n?.change==="removedFromParent"&&n.object?.userData?.isWidgetRoot&&this._picker){const s=this._picker.extraObjects.indexOf(n.object);s>=0&&this._picker.extraObjects.splice(s,1)}},this._objCompChange=n=>{n.object&&n.object===this.getSelectedObject()&&this.refreshUiChildren(n.object)},this._onObjectSelectEvent=n=>{n.source!==xo.PluginType&&(n.object===void 0&&n.value===void 0?console.error("PickingPlugin - Error handling object/material `select` event `e.object` or `e.value` must be set for picking, `value` can be null to unselect"):this.setSelectedObject(n.object||n.value,this.autoFocus||n.focusCamera,n.trackUndo??!0))},this._selectedObjectChanged=n=>{if(!this._viewer)return;this._duplicateTracker.onSelectionChanged(),this.dispatchEvent(n);const s=this._picker?.selectedObject||void 0,a=this._viewer.getPlugin(f.FrameFadePlugin);a&&(s?a.disable(this):a.enable(this)),s?this._viewer.scene.disableAutoNearFar("PickingPlugin"):this._viewer.scene.enableAutoNearFar("PickingPlugin"),this.refreshUiChildren(s);const o=this._widget;o&&this.widgetEnabled&&(s?.isObject3D?o.attach(s):o.detach()),this._updateExtraWidgets(),this._viewer.setDirty(),this.autoFocus&&this.selectionMode==="object"&&this.focusObject(s)},this._hoverObjectChanged=n=>{if(!this._viewer)return;this.dispatchEvent(n);const s=this._picker?.hoverObject||void 0,a=this._hoverWidget;a&&this.widgetEnabled&&(s?.isObject3D?a.attach(s):a.detach()),this._viewer?.setDirty(),this.autoFocusHover&&this.selectionMode==="object"&&this.focusObject(s)},this._onObjectHit=n=>{if(!this._viewer)return;if(this.isDisabled()){n.intersects.selectedObject=null;return}let s=n.intersects.selectedObject;if(s){const a=s;s=rP(s),s.assetType==="widget"&&s.object&&(n.intersects.selectedObject=s.object,n.intersects.selectedWidget=s,n.intersects.selectedHandle=a.userData.isWidgetHandle?a:void 0)}this.dispatchEvent(n)},this._selectionModeChanged=n=>{this._viewer&&(this.dispatchEvent(n),!this.isDisabled()&&this.uiConfig?.uiRefresh?.(!0,"postFrame",1))},this._multiSelectChanged=n=>{if(this._viewer&&(this.dispatchEvent(n),!this.multiSelectEnabled&&this._picker&&this._picker.selectedObjects.length>1)){const s=this._picker.selectedObject;this._picker.setSelected(s,!1)}},this._onDrop=async n=>{if(!this._viewer||!this.autoApplyMaterialOnDrop)return;const a=n.assets?.find(l=>l.isMaterial),o=this.getSelectedObject();if(o&&o?.isObject3D&&a&&await this._viewer.dialog.confirm("Applying material: Apply material to the selected object?")){let l=o.material;Array.isArray(l)&&(console.warn("Dropping on material array not yet fully supported."),l=l[0]);let c=Array.from(l?.appliedMeshes??[]);(c.length>1?!await this._viewer.dialog.confirm("Applying material: Apply to all objects using this material?"):c.length<1)&&(c=[o]);for(const u of c)u&&(u.material=a)}},this._pickPromptUi={type:"button",label:"Select an object to see its properties",readOnly:!0,hidden:()=>this.getSelectedObject()!==void 0},this._uiConfigChildren=[{label:"Enabled",type:"checkbox",property:[this,"enabled"]},{label:"Hover Enabled",type:"checkbox",property:[this,"hoverEnabled"],onChange:()=>this.uiConfig.uiRefresh?.(!0)},{label:"Auto Focus",type:"checkbox",property:[this,"autoFocus"],onChange:()=>{const n=this.getSelectedObject();this.autoFocus&&n&&this.setSelectedObject(n,!0)}},{label:"Auto Focus on Hover",type:"checkbox",hidden:()=>!this.hoverEnabled,property:[this,"autoFocusHover"]},{label:"Widget Enabled",type:"checkbox",property:[this,"widgetEnabled"]},{label:"Multi-Select",type:"checkbox",property:[this,"multiSelectEnabled"]},{label:"Duplicate Mode",type:"dropdown",property:[this,"duplicateMode"],children:["simple","compound"].map(n=>({label:n,value:n}))}],this.uiConfig={type:"folder",label:"Picker",expanded:!0,children:[...this._uiConfigChildren,this._pickPromptUi]},this.canRemoveMaterial=n=>{if(!n.material)return!1;const s=Array.isArray(n.material)?n.material:n.material?[n.material]:[];return s.length&&(s.length!==1||!s[0].userData?.isPlaceholder)},this.removeMaterial=n=>{if(!n.material)return;const s=n.material;return n.material=this.getPlaceholderMaterial(n),()=>n.material=s},this.materialTypes=[{cls:gs,def:Ds.DummyMaterial,name:"Unlit"},{cls:Yn,def:Ds.DummyLineBasicMaterial,line:!0,name:"Basic Line"},{cls:ji,def:Ds.DummyLineMaterial,line:!0,name:"Line"},{cls:si,name:"Physical"}],this._selectionWidgetClass=e,e&&(this._widget=new e,this._hoverWidget=new e,this._hoverWidget.lineMaterial&&(this._hoverWidget.lineMaterial.linewidth/=2,this._hoverWidget.lineMaterial.color.set("#aa2222"))),this._pickUi=t,this.autoFocus=i,this.dispatchEvent=this.dispatchEvent.bind(this)}get picker(){return this._picker}get hoverEnabled(){return this._picker?.hoverEnabled??!1}set hoverEnabled(e){this._picker&&(this._picker.hoverEnabled=e,this.uiConfig&&this.uiConfig.uiRefresh?.())}_widgetEnabledChange(){this._widget&&(this.widgetEnabled&&this._picker?.selectedObject?.isObject3D?this._widget.attach(this._picker.selectedObject):this._widget.detach(),this._updateExtraWidgets(),this.uiConfig?.uiRefresh?.(!0))}_updateExtraWidgets(){if(!this._viewer||!this._selectionWidgetClass)return;const t=(this._picker?.selectedObjects||[]).filter((i,n)=>n>0&&i?.isObject3D);for(let i=t.length;i<this._extraWidgets.length;i++)this._extraWidgets[i].detach();for(let i=0;i<t.length;i++){if(!this._extraWidgets[i]){const n=new this._selectionWidgetClass;n.lineMaterial&&(n.lineMaterial.color.set("#ff8844"),n.lineMaterial.opacity=.7),this._extraWidgets.push(n),this._viewer.scene.addObject(n,{addToRoot:!0})}this.widgetEnabled?this._extraWidgets[i].attach(t[i]):this._extraWidgets[i].detach()}}setDirty(){this._viewer&&(this.isDisabled()&&this.getSelectedObject()&&this.setSelectedObject(void 0),this._viewer.setDirty())}getSelectedObject(){return this._picker?.selectedObject||void 0}getSelectedObjects(){return this._picker?.selectedObjects||[]}toggleSelectedObject(e){if(!this._picker||this.isDisabled()||!e||!this.multiSelectEnabled)return;const t=[...this._picker.selectedObjects],i=t.indexOf(e);i>=0?t.splice(i,1):t.unshift(e),this._picker.setSelected(t.length?t.length===1?t[0]:t:null,!0)}selectAll(){if(!this._picker||!this._viewer||this.isDisabled()||!this.multiSelectEnabled)return;const e=[];this._viewer.scene.modelRoot.traverse(t=>{t.isObject3D&&t.visible&&t.assetType==="model"&&t.userData.userSelectable!==!1&&t.material&&e.push(t)}),e.length&&this._picker.setSelected(e.length===1?e[0]:e,!0)}clearSelection(){this._picker&&this._picker.setSelected(null,!0)}_setSelectedFromArray(e){!e||!e.length?this._picker?.setSelected(null,!1):e.length===1?this._picker?.setSelected(e[0],!1):this._picker?.setSelected(e,!1)}async deleteSelected(){const e=this.getSelectedObjects().filter(n=>n?.isObject3D);if(!e.length)return;const t=await ZM(e);if(!t)return;const i=[...e];this._setSelectedFromArray(null),this._undoManager?.record({undo:()=>{t.undo(),this._setSelectedFromArray(i)},redo:()=>{this._setSelectedFromArray(null),t.redo()}})}duplicateSelected(e){const t=e??this.duplicateMode,i=this.getSelectedObjects().filter(h=>h?.isObject3D);if(!i.length)return;const{clones:n,undo:s,redo:a}=eT(i);if(!n.length)return;const o=this._duplicateTracker.saveState(),l=new fe().compose(n[0].position,n[0].quaternion,n[0].scale);this._duplicateTracker.applyOffset(n,i[0],t),this._setSelectedFromArray(n),this._duplicateTracker.onDuplicated(l);const c=[...i];this._undoManager?.record({undo:()=>{s(),this._setSelectedFromArray(c),this._duplicateTracker.restoreState(o)},redo:()=>{a(),this._setSelectedFromArray(n),this._duplicateTracker.onDuplicated(l)}})}copySelected(){const e=this.getSelectedObjects().filter(t=>t?.isObject3D);e.length&&this._clipboard.copy(e)}cutSelected(){const e=this.getSelectedObjects().filter(t=>t?.isObject3D);e.length&&this._clipboard.cut(e)}pasteFromClipboard(){if(this._clipboard.isEmpty)return;const e=this._getPasteDestination(),t=this._clipboard.paste(e);if(!t)return;const i=this.getSelectedObjects();this._setSelectedFromArray(t.objects),this._viewer?.setDirty();const{objects:n,undo:s,redo:a}=t;this._undoManager?.record({undo:()=>{s(),this._setSelectedFromArray(i),this._viewer?.setDirty()},redo:()=>{a(),this._setSelectedFromArray(n),this._viewer?.setDirty()}})}_getPasteDestination(){const e=this.getSelectedObject();return e?.isObject3D?this._isContainer(e)?e:e.parent:null}_isContainer(e){return!e.material&&!e.geometry&&!e.isLight&&!e.isCamera&&e.assetType!=="light"&&e.assetType!=="camera"&&e.assetType!=="widget"}toggleVisibilitySelected(){const e=this.getSelectedObjects().filter(s=>s?.isObject3D);if(!e.length)return;const i=!e[0].visible,n=new Map;for(const s of e)n.set(s,s.visible);for(const s of e)s.visible=i,s.setDirty?.();this._viewer?.setDirty(),this._undoManager?.record({undo:()=>{for(const[s,a]of n)s.visible=a,s.setDirty?.();this._viewer?.setDirty()},redo:()=>{for(const s of e)s.visible=i,s.setDirty?.();this._viewer?.setDirty()}})}unhideAll(){if(!this._viewer)return;const e=[];if(this._viewer.scene.modelRoot.traverse(t=>{t.isObject3D&&!t.visible&&e.push(t)}),!!e.length){for(const t of e)t.visible=!0,t.setDirty?.();this._viewer.setDirty(),this._undoManager?.record({undo:()=>{for(const t of e)t.visible=!1,t.setDirty?.();this._viewer?.setDirty()},redo:()=>{for(const t of e)t.visible=!0,t.setDirty?.();this._viewer?.setDirty()}})}}focusSelected(){const e=this.getSelectedObjects().filter(t=>t?.isObject3D);e.length&&this.focusObject(e.length===1?e[0]:e)}resetTransform(e){const t=this.getSelectedObjects().filter(s=>s?.isObject3D);if(!t.length)return;const i=t.map(s=>({obj:s,position:s.position.clone(),quaternion:s.quaternion.clone(),scale:s.scale.clone()})),n=()=>{for(const s of t)e==="position"?s.position.set(0,0,0):e==="rotation"?s.quaternion.identity():s.scale.set(1,1,1),s.updateMatrixWorld(!0),s.setDirty?.({change:"transform"});this._viewer?.setDirty()};n(),this._undoManager?.record({undo:()=>{for(const s of i)s.obj.position.copy(s.position),s.obj.quaternion.copy(s.quaternion),s.obj.scale.copy(s.scale),s.obj.updateMatrixWorld(!0),s.obj.setDirty?.({change:"transform"});this._viewer?.setDirty()},redo:()=>{n()}})}setSelectedObject(e,t=!1,i=!0){const n=this.isDisabled();if(n&&e||!this._picker)return;const s=this.autoFocus;this.autoFocus=!1,this._picker.setSelected(e||null,i),this.autoFocus=s,!n&&e&&this.selectionMode==="object"&&(s||t)&&this.focusObject(e)}onAdded(e){super.onAdded(e),this.setDirty(),this._picker=new CE(e.scene.modelRoot,e.canvas,e.scene.mainCamera,t=>{if(!t.material&&!t.userData.userSelectable)return!1;let n=t;n=rP(n);let s=!1;for(;n;){if(!n.visible||((n.assetType==="model"||n.assetType==="light")&&(s=!0),n.userData.userSelectable===!1)||n.userData.bboxVisible===!1)return!1;n=n.parent}return s}),this._picker.extraObjects.push(...e.scene.children.filter(t=>t.userData.isWidgetRoot)),this._viewer?.scene.addEventListener("addSceneObject",this._addSceneObject),this._viewer?.scene.addEventListener("sceneUpdate",this._sceneUpdate),this._widget&&e.scene.addObject(this._widget,{addToRoot:!0}),this._hoverWidget&&e.scene.addObject(this._hoverWidget,{addToRoot:!0}),this._picker.addEventListener("selectedObjectChanged",this._selectedObjectChanged),this._picker.addEventListener("hoverObjectChanged",this._hoverObjectChanged),this._picker.addEventListener("hitObject",this._onObjectHit),this._picker.addEventListener("selectionModeChanged",this._selectionModeChanged),this._picker.addEventListener("multiSelectChanged",this._multiSelectChanged),window.addEventListener("keydown",this._onKeyDown),e.scene.addEventListener("select",this._onObjectSelectEvent),e.scene.addEventListener("materialChanged",this._objCompChange),e.scene.addEventListener("geometryChanged",this._objCompChange),e.scene.addEventListener("texturesChanged",this._objCompChange),e.scene.addEventListener("mainCameraChange",this._mainCameraChange),e.forPlugin("DropzonePlugin",t=>{t.addEventListener("drop",this._onDrop)},t=>{t.removeEventListener("drop",this._onDrop)}),e.forPlugin("UndoManagerPlugin",t=>{this._picker&&(this._picker.undoManager=t.undoManager,this._undoManager=t.undoManager)},()=>{this._picker&&(this._picker.undoManager=void 0,this._undoManager=void 0)},this)}onRemove(e){window.removeEventListener("keydown",this._onKeyDown),e.scene.removeEventListener("select",this._onObjectSelectEvent),e.scene.removeEventListener("materialChanged",this._objCompChange),e.scene.removeEventListener("geometryChanged",this._objCompChange),e.scene.removeEventListener("texturesChanged",this._objCompChange),e.scene.removeEventListener("mainCameraChange",this._mainCameraChange),e.scene.removeEventListener("addSceneObject",this._addSceneObject),e.scene.removeEventListener("sceneUpdate",this._sceneUpdate),this._widget?.removeFromParent(),this._hoverWidget?.removeFromParent();for(const t of this._extraWidgets)t.removeFromParent();this._extraWidgets=[],this._picker&&(this._picker.removeEventListener("selectedObjectChanged",this._selectedObjectChanged),this._picker.removeEventListener("hoverObjectChanged",this._hoverObjectChanged),this._picker.removeEventListener("hitObject",this._onObjectHit),this._picker.removeEventListener("selectionModeChanged",this._selectionModeChanged),this._picker.removeEventListener("multiSelectChanged",this._multiSelectChanged),this._picker.dispose(),this._picker.undoManager=void 0,this._picker=void 0),this._undoManager=void 0,this._clipboard.clear(),this._duplicateTracker.reset(),super.onRemove(e)}dispose(){super.dispose(),this._widget?.dispose?.(),this._hoverWidget?.dispose?.();for(const e of this._extraWidgets)e.dispose?.();this._extraWidgets=[]}async focusObject(e){this._viewer?.fitToView(e??void 0,1.25,1e3,"easeOut")}get widget(){return this._widget}refreshUiChildren(e){if(this._pickUi){const t=this.uiConfig;if(t.children=[...this._uiConfigChildren],e){if(e.isObject3D){const l=e;t.children.push(...this.objectSelectionUiConfig(l))}const i=e.uiConfig;i?.type==="folder"&&an(i,"expanded",!0,!0),i&&t.children.push(i);const n=e?.isObject3D?e:void 0,s=e?.isMaterial?e:n?.material,a=s?Array.isArray(s)?s:[s]:[],o=e?.isBufferGeometry?e:n?.geometry;if(o?.uiConfig&&o!==e){const l=o.uiConfig;l.type==="folder"&&an(l,"expanded",!0,!0),t.children.push(l)}a.forEach(l=>{l?.uiConfig&&l!==e&&t.children?.push(l.uiConfig)}),e.isObject3D&&t.children.push(...this.objectMaterialManageUiConfig(e))}else t.children.push(this._pickPromptUi);t.uiRefresh?.()}}objectSelectionUiConfig(e){return[{type:"button",label:"Focus",value:()=>{e.isObject3D&&(e.assetType&&e.parentRoot?e.dispatchEvent({type:"select",ui:!0,object:e,bubbleToParent:!0,focusCamera:!0}):this.setSelectedObject(e,!0))}},{type:"button",label:"Select Parent",hidden:()=>!e.parent,value:()=>{if(!e.isObject3D)return;const t=e.parent;t&&(t.assetType&&t.parentRoot?t.dispatchEvent({type:"select",ui:!0,bubbleToParent:!0,object:t}):this.setSelectedObject(t,!1))}}]}objectMaterialManageUiConfig(e){return[{label:"Remove Material(s)",type:"button",hidden:()=>!this.canRemoveMaterial(e),value:()=>this.removeMaterial(e)},...this.materialTypes.map(t=>({label:`New ${t.name} Material`,type:"button",hidden:t.line?(()=>!e.isLineSegments2&&!e.isLine&&!e.isLineSegments&&!e.isWireframe||!(!e.materials?.length||e.materials.length===1&&e.materials[0]===t.def)):()=>!(!e.materials?.length||e.materials.length===1&&e.materials[0].userData?.isPlaceholder)||!e.isMesh,value:()=>{const i=e.material;return e.material=new t.cls,()=>e.material=i}}))]}getPlaceholderMaterial(e){const t=[this.materialTypes[0].def];if(!t[0])throw new Error("No default material found");const i=e.isLineSegments2||e.isWireframe?this.materialTypes.find(n=>n.cls===ji)?.def:e.isLine||e.isLineSegments?this.materialTypes.find(n=>n.cls===Yn)?.def:null;return i||t[0]}},xo.PluginType="Picking",xo.OldPluginType="PickingPlugin",xo);Zd([G(),he(_o.prototype.setDirty)],_o.prototype,"enabled"),Zd([jt({obj:"_picker",key:"selectionMode"})],_o.prototype,"selectionMode"),Zd([G()],_o.prototype,"autoFocus"),Zd([he(_o.prototype._widgetEnabledChange)],_o.prototype,"widgetEnabled"),Zd([jt({obj:"_picker",key:"multiSelectEnabled"})],_o.prototype,"multiSelectEnabled");let vs=_o;class aP{constructor(){this.multiObjects=[],this._dummy=null,this._dummyStart=new fe,this._startStates=[],this._startWorldMatrices=[]}get dummy(){return this._dummy}get hasMultiSelect(){return this.multiObjects.length>1}get hasStartStates(){return this._startStates.length>0}setup(e,t){this.multiObjects=e,this._dummy||(this._dummy=new ft,this._dummy.userData.isMultiSelectDummy=!0,t.scene.addObject(this._dummy,{addToRoot:!0}));const i=new S;for(const n of e)n.updateWorldMatrix(!0,!1),i.add(new S().setFromMatrixPosition(n.matrixWorld));return i.divideScalar(e.length),this._dummy.position.copy(i),this._dummy.quaternion.identity(),this._dummy.scale.setScalar(1),this._dummy.updateMatrixWorld(!0),this._dummy}clear(e){this.multiObjects=[],this._startStates=[],this._startWorldMatrices=[],this._dummy&&(e.scene.remove(this._dummy),this._dummy=null)}captureStart(){!this._dummy||!this.multiObjects.length||(this._dummy.updateMatrixWorld(!0),this._dummyStart.copy(this._dummy.matrixWorld),this._startStates=this.multiObjects.map(e=>({position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()})),this._startWorldMatrices=this.multiObjects.map(e=>(e.updateWorldMatrix(!0,!1),e.matrixWorld.clone())))}applyDelta(){if(!this._dummy||!this.multiObjects.length||!this._startWorldMatrices.length)return;this._dummy.updateMatrixWorld(!0);const e=this._dummyStart.clone().invert(),t=this._dummy.matrixWorld.clone().multiply(e);for(let i=0;i<this.multiObjects.length;i++){const n=this.multiObjects[i],s=t.clone().multiply(this._startWorldMatrices[i]),a=new fe;n.parent&&a.copy(n.parent.matrixWorld).invert(),a.clone().multiply(s).decompose(n.position,n.quaternion,n.scale),n.updateMatrixWorld(!0),n.setDirty?.({change:"transform",frameFade:!1})}}updateDummyPosition(){if(!this._dummy||!this.multiObjects.length)return;const e=new S;for(const t of this.multiObjects)t.updateWorldMatrix(!0,!1),e.add(new S().setFromMatrixPosition(t.matrixWorld));e.divideScalar(this.multiObjects.length),this._dummy.position.copy(e),this._dummy.quaternion.identity(),this._dummy.scale.setScalar(1),this._dummy.updateMatrixWorld(!0)}recordUndo(e){if(!this.multiObjects.length||!this._startStates.length)return;const t=[...this.multiObjects],i=this._startStates.map(a=>({position:a.position.clone(),quaternion:a.quaternion.clone(),scale:a.scale.clone()})),n=t.map(a=>({position:a.position.clone(),quaternion:a.quaternion.clone(),scale:a.scale.clone()}));let s=!1;for(let a=0;a<t.length;a++)if(!i[a].position.equals(n[a].position)||!i[a].quaternion.equals(n[a].quaternion)||!i[a].scale.equals(n[a].scale)){s=!0;break}s&&e.record({undo:()=>{for(let a=0;a<t.length;a++)t[a].position.copy(i[a].position),t[a].quaternion.copy(i[a].quaternion),t[a].scale.copy(i[a].scale),t[a].updateMatrixWorld(!0),t[a].setDirty?.({change:"transform"});this.updateDummyPosition()},redo:()=>{for(let a=0;a<t.length;a++)t[a].position.copy(n[a].position),t[a].quaternion.copy(n[a].quaternion),t[a].scale.copy(n[a].scale),t[a].updateMatrixWorld(!0),t[a].setDirty?.({change:"transform"});this.updateDummyPosition()}})}}var _W=Object.defineProperty,vW=Object.getOwnPropertyDescriptor,mr=(r,e,t,i)=>{for(var n=i>1?void 0:i?vW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&_W(e,t,n),n};f.TransformControlsPlugin=class extends mt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.dependencies=[vs],this._isInteracting=!1,this._viewerListeners={postFrame:()=>{!this.transformControls||this._viewer}},this._transformState={obj:null,position:new S,rotation:new Pt,scale:new S},this.selectionFilterTest=void 0,this._multi=new aP,this._mainCameraChange=()=>{!this.transformControls||!this._viewer||(this.transformControls.camera=this._viewer.scene.mainCamera)},lr.ObjectConstructors.MeshBasicMaterial=gs,lr.ObjectConstructors.LineBasicMaterial=Yn,this.enabled=e}setDirty(){if(!this._viewer)return;const e=this._viewer.getPlugin(vs),t=!this.isDisabled();if(this.transformControls)if(!t)this.transformControls.detach(),this._multi.clear(this._viewer);else{const i=e.getSelectedObjects().filter(n=>n?.isObject3D);i.length>1?this.transformControls.attach(this._multi.setup(i,this._viewer)):i.length===1?(this._multi.clear(this._viewer),this.transformControls.attach(i[0])):(this._multi.clear(this._viewer),this.transformControls.detach())}this._viewer.setDirty()}onAdded(e){super.onAdded(e),this.setDirty(),this.transformControls=new f.TransformControls2(e.scene.mainCamera,e.canvas),this._mainCameraChange=this._mainCameraChange.bind(this),e.scene.addEventListener("mainCameraChange",this._mainCameraChange),this.transformControls.addEventListener("dragging-changed",i=>{if(!this?._viewer)return;const n=this._viewer.scene.mainCamera.controls;typeof n?.stopDamping=="function"&&n?.enabled&&n.stopDamping(),this._viewer.scene.mainCamera.setInteractions(!i.value,f.TransformControlsPlugin.PluginType)}),this.transformControls.addEventListener("axis-changed",i=>{if(!this?._viewer)return;this._isInteracting=!!i.value;const n=this._viewer.scene.mainCamera.controls;typeof n?.stopDamping=="function"&&n?.enabled&&n.stopDamping(),this._viewer.setDirty()}),e.scene.addObject(this.transformControls,{addToRoot:!0}),e.getPlugin(vs).addEventListener("selectedObjectChanged",i=>{if(!this.transformControls)return;if(this.isDisabled()){this.transformControls.object&&this.transformControls.detach(),this._multi.clear(this._viewer);return}const n=(i.objects||[]).filter(s=>s?.isObject3D);if(n.length>1)this.transformControls.attach(this._multi.setup(n,this._viewer));else if(i.object){this._multi.clear(this._viewer);let s=i.intersects?.selectedHandle??i.intersects?.selectedObject??i.object;if(this.selectionFilterTest&&(s=this.selectionFilterTest(s)),!s||!s.isObject3D){this.transformControls.detach();return}this.transformControls.attach(s)}else this._multi.clear(this._viewer),this.transformControls.detach()}),e.forPlugin("UndoManagerPlugin",i=>{this.undoManager=i.undoManager},()=>this.undoManager=void 0,this),this.transformControls.addEventListener("mouseDown",()=>{if(!this.transformControls)return;if(this._multi.hasMultiSelect){this._multi.captureStart();return}const i=this.transformControls.object;i&&(this._transformState.obj=i,this._transformState.position=i.position.clone(),this._transformState.rotation=i.rotation.clone(),this._transformState.scale=i.scale.clone())}),this.transformControls.addEventListener("objectChange",()=>{this._multi.hasMultiSelect&&this._multi.applyDelta()}),this.transformControls.addEventListener("mouseUp",()=>{if(!this.transformControls)return;if(this._multi.hasMultiSelect&&this._multi.hasStartStates){this.undoManager&&this._multi.recordUndo(this.undoManager);return}const i=this.transformControls.object;if(!i||this._transformState.obj!==i||!this.undoManager)return;const n={translate:"position",rotate:"rotation",scale:"scale"}[this.transformControls.getMode()];if(!n||this._transformState[n].equals(i[n]))return;const s={last:this._transformState[n].clone(),current:i[n].clone(),set:a=>{i[n].copy(a),i.updateMatrixWorld(!0),this.transformControls?.dispatchEvent({type:"change"}),this.transformControls?.dispatchEvent({type:"objectChange"})},undo:()=>s.set(s.last),redo:()=>s.set(s.current)};this.undoManager.record(s)})}onRemove(e){e.scene.removeEventListener("mainCameraChange",this._mainCameraChange),this._multi.clear(e),this.transformControls&&(this.transformControls.detach(),e.scene.remove(this.transformControls),this.transformControls.dispose()),this.transformControls=void 0,super.onRemove(e)}centerAllMeshes(){return this._viewer?.scene.centerAllGeometries(!0)}},f.TransformControlsPlugin.PluginType="TransformControlsPlugin",mr([se(),he(f.TransformControlsPlugin.prototype.setDirty)],f.TransformControlsPlugin.prototype,"enabled",2),mr([Bi(void 0,{expanded:!0})],f.TransformControlsPlugin.prototype,"transformControls",2),mr([ct("Center All Meshes")],f.TransformControlsPlugin.prototype,"centerAllMeshes",1),f.TransformControlsPlugin=mr([vt("Transform Controls")],f.TransformControlsPlugin),f.TransformControls2=class extends lr{constructor(e,t){super(e,t),this.isWidget=!0,this.assetType="widget",this.setDirty=qe.setDirty.bind(this),this.refreshUi=qe.refreshUi.bind(this),this.lockProps=void 0,this._savedSettings={},this.visible=!1,this.userData.bboxVisible=!1,this.size=1.25,this.addEventListener("objectChange",()=>{this?.object?.setDirty&&this.object.setDirty({frameFade:!1,change:"transform"})}),this.addEventListener("change",()=>{this.setDirty({frameFade:!1})}),this._keyUpListener=this._keyUpListener.bind(this),this._keyDownListener=this._keyDownListener.bind(this),window.addEventListener("keydown",this._keyDownListener),window.addEventListener("keyup",this._keyUpListener),this.traverse(i=>{i.castShadow=!1,i.receiveShadow=!1,i.userData.__keepShadowDef=!0})}_keyDownListener(e){if(!this.enabled||!this.object)return;if(!nE(e,{toggleSpace:()=>{this.space=this.space==="local"?"world":"local"},adjustSize:i=>{this.size=Math.max(this.size+i,.1)},toggleAxis:i=>{i===0?this.showX=!this.showX:i===1?this.showY=!this.showY:this.showZ=!this.showZ},toggleEnabled:()=>{this.enabled=!this.enabled}})){if(e.metaKey||e.ctrlKey||e.target?.tagName==="TEXTAREA"||e.target?.tagName==="INPUT")return;switch(e.code){case"ShiftLeft":case"ShiftRight":this.translationSnap=.5,this.rotationSnap=Ft.degToRad(15),this.scaleSnap=.25;break;case"KeyW":this.mode="translate";break;case"KeyE":this.mode="rotate";break;case"KeyR":this.mode="scale";break;default:return}}this.setDirty({refreshScene:!0,frameFade:!0})}_keyUpListener(e){if(this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.translationSnap=null,this.rotationSnap=null,this.scaleSnap=null;break}this.object&&e.code}}attach(e){let t=!1;if(this.traverseAncestors(i=>t=t||i===e),t)return this;if(this._savedSettings.lockProps&&(this.lockProps=this._savedSettings.lockProps),Object.assign(this,this._savedSettings),this._savedSettings={},e.userData.transformControls){const i=["translationSnap","rotationSnap","scaleSnap","space","mode","showX","showY","showZ","lockProps"];for(const n of i)e.userData.transformControls[n]!==void 0&&(this._savedSettings[n]=this[n],this[n]=e.userData.transformControls[n])}return super.attach(e)}detach(){return this._savedSettings.lockProps&&(this.lockProps=this._savedSettings.lockProps),Object.assign(this,this._savedSettings),this._savedSettings={},super.detach()}dispose(){window.removeEventListener("keydown",this._keyDownListener),window.removeEventListener("keyup",this._keyUpListener),super.dispose()}get modelObject(){return this}},mr([Li("Mode",["translate","rotate","scale"].map(r=>({label:r})))],f.TransformControls2.prototype,"mode",2),mr([Li("Space",["world","local"].map(r=>({label:r})))],f.TransformControls2.prototype,"space",2),mr([Fe("Size",[.1,10],.01)],f.TransformControls2.prototype,"size",2),mr([se("Show X")],f.TransformControls2.prototype,"showX",2),mr([se("Show Y")],f.TransformControls2.prototype,"showY",2),mr([se("Show Z")],f.TransformControls2.prototype,"showZ",2),f.TransformControls2=mr([vt("Transform Controls")],f.TransformControls2);var bW=Object.defineProperty,wW=Object.getOwnPropertyDescriptor,Fn=(r,e,t,i)=>{for(var n=i>1?void 0:i?wW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&bW(e,t,n),n};f.PivotControlsPlugin=class extends mt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.dependencies=[vs],this._isInteracting=!1,this._viewerListeners={preFrame:()=>{!this.pivotControls||!this._viewer||this.pivotControls.updateGizmoScale()}},this._transformState={obj:null,position:new S,rotation:new Pt,scale:new S},this.selectionFilterTest=void 0,this._multi=new aP,this._mainCameraChange=()=>{!this.pivotControls||!this._viewer||(this.pivotControls.camera=this._viewer.scene.mainCamera)},Qc.ObjectConstructors.MeshBasicMaterial=gs,Qc.ObjectConstructors.LineBasicMaterial=Yn,this.enabled=e}setDirty(){if(!this._viewer)return;const e=this._viewer.getPlugin(vs),t=!this.isDisabled();if(this.pivotControls)if(!t)this.pivotControls.detach(),this._multi.clear(this._viewer);else{const i=e.getSelectedObjects().filter(n=>n?.isObject3D);i.length>1?this.pivotControls.attach(this._multi.setup(i,this._viewer)):i.length===1?(this._multi.clear(this._viewer),this.pivotControls.attach(i[0])):(this._multi.clear(this._viewer),this.pivotControls.detach())}this._viewer.setDirty()}onAdded(e){super.onAdded(e),this.setDirty(),this.pivotControls=new f.PivotControls2(e.scene.mainCamera,e.canvas),this._mainCameraChange=this._mainCameraChange.bind(this),e.scene.addEventListener("mainCameraChange",this._mainCameraChange),this.pivotControls.addEventListener("dragging-changed",i=>{if(!this?._viewer)return;const n=this._viewer.scene.mainCamera.controls;typeof n?.stopDamping=="function"&&n?.enabled&&n.stopDamping(),this._viewer.scene.mainCamera.setInteractions(!i.value,f.PivotControlsPlugin.PluginType)}),this.pivotControls.addEventListener("change",()=>{this?._viewer&&this._viewer.setDirty()}),e.scene.addObject(this.pivotControls,{addToRoot:!0}),e.getPlugin(vs).addEventListener("selectedObjectChanged",i=>{if(!this.pivotControls)return;if(this.isDisabled()){this.pivotControls.object&&this.pivotControls.detach(),this._multi.clear(this._viewer);return}const n=(i.objects||[]).filter(s=>s?.isObject3D);if(n.length>1)this.pivotControls.attach(this._multi.setup(n,this._viewer));else if(i.object){this._multi.clear(this._viewer);let s=i.intersects?.selectedHandle??i.intersects?.selectedObject??i.object;if(this.selectionFilterTest&&(s=this.selectionFilterTest(s)),!s||!s.isObject3D){this.pivotControls.detach();return}this.pivotControls.attach(s)}else this._multi.clear(this._viewer),this.pivotControls.detach()}),e.forPlugin("UndoManagerPlugin",i=>{this.undoManager=i.undoManager},()=>this.undoManager=void 0,this),this.pivotControls.addEventListener("mouseDown",()=>{if(!this.pivotControls)return;if(this._multi.hasMultiSelect){this._multi.captureStart();return}const i=this.pivotControls.object;i&&(this._transformState.obj=i,this._transformState.position=i.position.clone(),this._transformState.rotation=i.rotation.clone(),this._transformState.scale=i.scale.clone())}),this.pivotControls.addEventListener("objectChange",()=>{this._multi.hasMultiSelect&&this._multi.applyDelta()}),this.pivotControls.addEventListener("mouseUp",i=>{if(!this.pivotControls)return;if(this._multi.hasMultiSelect&&this._multi.hasStartStates){this.undoManager&&this._multi.recordUndo(this.undoManager);return}const n=this.pivotControls.object;if(!n||this._transformState.obj!==n||!this.undoManager)return;const s=i.mode,a={translate:"position",rotate:"rotation",scale:"scale"}[s];if(!a||this._transformState[a].equals(n[a]))return;const o={last:this._transformState[a].clone(),current:n[a].clone(),set:l=>{n[a].copy(l),n.updateMatrixWorld(!0),this.pivotControls?.dispatchEvent({type:"change"}),this.pivotControls?.dispatchEvent({type:"objectChange"})},undo:()=>o.set(o.last),redo:()=>o.set(o.current)};this.undoManager.record(o)})}onRemove(e){e.scene.removeEventListener("mainCameraChange",this._mainCameraChange),this._multi.clear(e),this.pivotControls&&(this.pivotControls.detach(),e.scene.remove(this.pivotControls),this.pivotControls.dispose()),this.pivotControls=void 0,super.onRemove(e)}},f.PivotControlsPlugin.PluginType="PivotControlsPlugin",Fn([se(),he(f.PivotControlsPlugin.prototype.setDirty)],f.PivotControlsPlugin.prototype,"enabled",2),Fn([Bi(void 0,{expanded:!0})],f.PivotControlsPlugin.prototype,"pivotControls",2),f.PivotControlsPlugin=Fn([vt("Pivot Controls")],f.PivotControlsPlugin),f.PivotControls2=class extends Qc{constructor(e,t){super(e,t),this.isWidget=!0,this.assetType="widget",this.setDirty=qe.setDirty.bind(this),this.refreshUi=qe.refreshUi.bind(this),this.visible=!1,this.userData.bboxVisible=!1,this.addEventListener("objectChange",()=>{this?.object?.setDirty&&this.object.setDirty({frameFade:!1,change:"transform"})}),this.addEventListener("change",()=>{this.setDirty({frameFade:!1})}),this.traverse(i=>{i.castShadow=!1,i.receiveShadow=!1,i.userData.__keepShadowDef=!0})}_onVisibilityChange(){this.updateHandleVisibility(),this.setDirty&&this.setDirty({frameFade:!1})}_onRebuild(){this.domElement&&(this.rebuild(),this.setDirty&&this.setDirty({frameFade:!1}))}get modelObject(){return this}},Fn([Li("Space",["world","local"].map(r=>({label:r}))),he(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"space",2),Fn([Fe("Gizmo Scale",[.1,10],.01),he(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"gizmoScale",2),Fn([se("Fixed Size"),he(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"fixed",2),Fn([se("Depth Test"),he(f.PivotControls2.prototype._onRebuild)],f.PivotControls2.prototype,"depthTest",2),Fn([se("Annotations")],f.PivotControls2.prototype,"annotations",2),Fn([Fe("Translation Snap",[.01,5],.01)],f.PivotControls2.prototype,"translationSnap",2),Fn([Fe("Rotation Snap (deg)",[1,90],1)],f.PivotControls2.prototype,"rotationSnap",2),Fn([Fe("Scale Snap",[.01,1],.01)],f.PivotControls2.prototype,"scaleSnap",2),Fn([se("Uniform Scale (Alt)")],f.PivotControls2.prototype,"uniformScaleEnabled",2),Fn([se("Disable Axes"),he(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"disableAxes",2),Fn([se("Disable Sliders"),he(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"disableSliders",2),Fn([se("Disable Rotations"),he(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"disableRotations",2),Fn([se("Disable Scaling"),he(f.PivotControls2.prototype._onVisibilityChange)],f.PivotControls2.prototype,"disableScaling",2),f.PivotControls2=Fn([vt("Pivot Controls")],f.PivotControls2);var CW=Object.defineProperty,xW=Object.getOwnPropertyDescriptor,Da=(r,e,t,i)=>{for(var n=i>1?void 0:i?xW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&CW(e,t,n),n};const db=new S,oP=new S;f.PivotEditPlugin=class extends mt{constructor(e=!0){super(),this.dependencies=[vs],this.enabled=!0,this.editPivot=!1,this.showPivotMarker=!0,this.markerScale=.5,this.markerColor=16776960,this.toJSON=void 0,this._pivotGizmo=null,this._markerRoot=null,this._markerWidget=null,this._pivotMarker=null,this._selectedObject=null,this._viewerListeners={preFrame:()=>this._updateMarker()},this._onKeyDown=null,this.enabled=e}onAdded(e){super.onAdded(e);const t=e.getPlugin(vs);t.addEventListener("hitObject",s=>{s.intersects?.selectedHandle?.userData.isPivotMarker&&(s.intersects.consumed=!0,this.editPivot=!this.editPivot,this._onEditPivotChange())}),t.addEventListener("selectedObjectChanged",s=>{const a=s.object,o=a!==this._selectedObject;this._selectedObject=a,this._markerWidget&&(this._markerWidget.object=this._selectedObject),this.editPivot&&o&&(this.editPivot=!1,this._onEditPivotChange()),this._updateMarker()}),e.forPlugin("UndoManagerPlugin",s=>{this.undoManager=s.undoManager},()=>this.undoManager=void 0,this),this._onKeyDown=s=>{this.isDisabled()||s.metaKey||s.ctrlKey||s.target?.tagName==="TEXTAREA"||s.target?.tagName==="INPUT"||(s.code==="KeyP"?(this.editPivot=!this.editPivot,this._onEditPivotChange()):s.code==="Escape"&&this.editPivot&&(this.editPivot=!1,this._onEditPivotChange()))},window.addEventListener("keydown",this._onKeyDown);const i=new is({color:this.markerColor,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,opacity:.9});this._pivotMarker=new _e(new Is(1,8,8),i),this._pivotMarker.renderOrder=1e3,this._pivotMarker.userData.isWidgetHandle=!0,this._pivotMarker.userData.isPivotMarker=!0;const n=new _l;n.isWidget=!0,n.assetType="widget",n.object=this._selectedObject,n.attach=s=>(n.object=s,n),n.detach=()=>(n.object=void 0,n),this._markerWidget=n,this._markerWidget.add(this._pivotMarker),this._markerRoot=new _l,this._markerRoot.userData.isWidgetRoot=!0,this._markerRoot.add(this._markerWidget),this._markerRoot.visible=!1,this._markerRoot.traverse(s=>{s.castShadow=!1,s.receiveShadow=!1,s.userData.__keepShadowDef=!0}),e.scene.addObject(this._markerRoot,{addToRoot:!0})}onRemove(e){this._onKeyDown&&(window.removeEventListener("keydown",this._onKeyDown),this._onKeyDown=null),this._destroyGizmo(e),this._markerRoot&&(e.scene.remove(this._markerRoot),this._pivotMarker&&(this._pivotMarker.geometry.dispose(),this._pivotMarker.material.dispose()),this._markerRoot=null,this._markerWidget=null,this._pivotMarker=null),super.onRemove(e)}pivotToCenter(){this._selectedObject?.pivotToBoundsCenter&&(this._recordUndo(this._selectedObject.pivotToBoundsCenter(!0)),this._refreshAfterPivotChange())}pivotToBottom(){if(!this._selectedObject?.pivotToPoint)return;const e=new En().expandByObject(this._selectedObject,!0,!0),t=e.getCenter(new S);this._applyPivot(new S(t.x,e.min.y,t.z))}pivotToOrigin(){this._applyPivot(new S(0,0,0))}pivotToPoint(e){this._applyPivot(e)}_applyPivot(e){if(!this._selectedObject?.pivotToPoint)return;const t=this._selectedObject.pivotToPoint(e,!0);this._recordUndo(t),this._refreshAfterPivotChange()}_updateMarker(){if(!this._markerRoot||!this._pivotMarker||!this._viewer)return;if(this.isDisabled()||!this.showPivotMarker||!this._selectedObject){this._markerRoot.visible=!1;return}this._selectedObject.updateWorldMatrix(!0,!1),db.setFromMatrixPosition(this._selectedObject.matrixWorld),this._markerRoot.position.copy(db),this._markerRoot.visible=!0;const e=this._viewer.scene.mainCamera;let t;e.isOrthographicCamera?t=(e.top-e.bottom)/e.zoom:(oP.setFromMatrixPosition(e.matrixWorld),t=db.distanceTo(oP)*Math.min(1.9*Math.tan(Math.PI*e.fov/360)/e.zoom,7)),this._pivotMarker.scale.setScalar(t*this.markerScale*.05)}_onEditPivotChange(){this._viewer&&(this.editPivot?this._attachGizmo():this._detachGizmo(),this._viewer.setDirty())}_attachGizmo(){if(!this._viewer||!this._selectedObject)return;this._setTransformControlsEnabled(!1),this._pivotGizmo||(lr.ObjectConstructors.MeshBasicMaterial=gs,lr.ObjectConstructors.LineBasicMaterial=Yn,this._pivotGizmo=new lr(this._viewer.scene.mainCamera,this._viewer.canvas),this._pivotGizmo.setMode("translate"),this._pivotGizmo.userData.bboxVisible=!1,this._pivotGizmo.visible=!1,this._pivotGizmo.traverse(t=>{t.castShadow=!1,t.receiveShadow=!1,t.userData.__keepShadowDef=!0}),this._pivotGizmo.addEventListener("mouseUp",()=>{if(!this._selectedObject?.pivotToPoint||!this._pivotGizmo?.object)return;const t=new S().setFromMatrixPosition(this._pivotGizmo.object.matrixWorld),i=this._selectedObject.pivotToPoint(t,!0);this._recordUndo(i),this._refreshAfterPivotChange()}),this._pivotGizmo.addEventListener("change",()=>{this._viewer&&this._viewer.setDirty()}),this._pivotGizmo.addEventListener("dragging-changed",t=>{if(!this._viewer)return;const i=this._viewer.scene.mainCamera.controls;typeof i?.stopDamping=="function"&&i?.enabled&&i.stopDamping(),this._viewer.scene.mainCamera.setInteractions(!t.value,f.PivotEditPlugin.PluginType)}),this._viewer.scene.addObject(this._pivotGizmo,{addToRoot:!0})),this._selectedObject.updateWorldMatrix(!0,!1);const e=new S().setFromMatrixPosition(this._selectedObject.matrixWorld);if(this._pivotGizmo.object)this._pivotGizmo.object.position.copy(e),this._pivotGizmo.object.updateMatrixWorld(!0);else{const t=new ft;t.position.copy(e),this._viewer.scene.addObject(t,{addToRoot:!0}),this._pivotGizmo.attach(t)}}_detachGizmo(){if(this._pivotGizmo){const e=this._pivotGizmo.object;this._pivotGizmo.detach(),e&&this._viewer&&this._viewer.scene.remove(e)}this._setTransformControlsEnabled(!0)}_destroyGizmo(e){this._pivotGizmo&&(this._detachGizmo(),e.scene.remove(this._pivotGizmo),this._pivotGizmo.dispose(),this._pivotGizmo=null)}_setTransformControlsEnabled(e){if(!this._viewer)return;const t=this._viewer.getPlugin("TransformControlsPlugin");t&&(e?t.setDirty():t.transformControls?.detach());const i=this._viewer.getPlugin("PivotControlsPlugin");i&&(e?i.setDirty():i.pivotControls?.detach())}_onEnabledChange(){this.isDisabled()&&this.editPivot&&(this.editPivot=!1,this._onEditPivotChange()),this._updateMarker(),this._viewer&&this._viewer.setDirty()}_refreshAfterPivotChange(){this._viewer&&(this.editPivot&&this._selectedObject&&this._pivotGizmo?.object&&(this._selectedObject.updateWorldMatrix(!0,!1),this._pivotGizmo.object.position.setFromMatrixPosition(this._selectedObject.matrixWorld),this._pivotGizmo.object.updateMatrixWorld(!0)),this._updateMarker(),this._viewer.setDirty())}_onDirty(){this._viewer&&this._viewer.setDirty()}_onMarkerColorChange(){this._pivotMarker&&this._pivotMarker.material.color.set(this.markerColor),this._viewer&&this._viewer.setDirty()}_recordUndo(e){if(!this.undoManager||!this._selectedObject)return;const t=this._selectedObject;t.updateWorldMatrix(!0,!1);const i=new S().setFromMatrixPosition(t.matrixWorld);this.undoManager.record({undo:()=>{e(),this._refreshAfterPivotChange()},redo:()=>{t.pivotToPoint&&(t.pivotToPoint(i,!0),this._refreshAfterPivotChange())}})}},f.PivotEditPlugin.PluginType="PivotEditPlugin",Da([se(),he(f.PivotEditPlugin.prototype._onEnabledChange)],f.PivotEditPlugin.prototype,"enabled",2),Da([se("Edit Pivot"),he(f.PivotEditPlugin.prototype._onEditPivotChange)],f.PivotEditPlugin.prototype,"editPivot",2),Da([se("Show Pivot Marker"),he(f.PivotEditPlugin.prototype._onDirty)],f.PivotEditPlugin.prototype,"showPivotMarker",2),Da([Fe("Marker Scale",[.1,5],.1),he(f.PivotEditPlugin.prototype._onDirty)],f.PivotEditPlugin.prototype,"markerScale",2),Da([xn("Marker Color"),he(f.PivotEditPlugin.prototype._onMarkerColorChange)],f.PivotEditPlugin.prototype,"markerColor",2),Da([ct("Pivot to Center")],f.PivotEditPlugin.prototype,"pivotToCenter",1),Da([ct("Pivot to Bottom")],f.PivotEditPlugin.prototype,"pivotToBottom",1),Da([ct("Pivot to Origin")],f.PivotEditPlugin.prototype,"pivotToOrigin",1),f.PivotEditPlugin=Da([vt("Pivot Edit")],f.PivotEditPlugin);var SW=Object.defineProperty,EW=Object.getOwnPropertyDescriptor,lP=(r,e,t,i)=>{for(var n=i>1?void 0:i?EW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&SW(e,t,n),n};f.EditorViewWidgetPlugin=class extends mt{constructor(e="top-left",t=128){super(),this.placement=e,this.size=t,this.enabled=!0,this._needsRender=!1,this._viewerListeners={postRender:i=>{!this._viewer||!this.widget||this.isDisabled()||(this._needsRender=!0)},postFrame:i=>{!this._viewer||!this.widget||this.isDisabled()||!this._needsRender||(this.widget.update(),this.widget.render(),this.widget.animating&&this._viewer.scene.mainCamera.setDirty(),this._needsRender=!1)}},this.setDirty=this.setDirty.bind(this),this._mainCameraChange=this._mainCameraChange.bind(this),this._mainCameraUpdate=this._mainCameraUpdate.bind(this)}setDirty(){!this._viewer||!this.widget||(this.widget.domContainer.style.display=this.isDisabled()?"none":"block")}onAdded(e){super.onAdded(e),this.widget=new wv(e.scene.mainCamera,e.canvas,this.placement,this.size),this.widget.target=e.scene.mainCamera.target,this.widget.addEventListener("animating-changed",t=>{const i=t.detail.value;e.scene.mainCamera.setInteractions(!i,f.EditorViewWidgetPlugin.PluginType)}),this.widget.addEventListener("update",()=>this._needsRender=!0),e.scene.addEventListener("mainCameraChange",this._mainCameraChange),e.scene.addEventListener("mainCameraUpdate",this._mainCameraUpdate)}onRemove(e){this.widget?.dispose(),this.widget=void 0,e.scene.removeEventListener("mainCameraChange",this._mainCameraChange),e.scene.removeEventListener("mainCameraUpdate",this._mainCameraUpdate),super.onRemove(e)}_mainCameraChange(){!this._viewer||!this.widget||(this.widget.camera=this._viewer.scene.mainCamera)}_mainCameraUpdate(){!this._viewer||!this.widget||(this.widget.target=this._viewer.scene.mainCamera.target)}setOrientation(e){this.widget&&this.widget.setOrientation(e)}},f.EditorViewWidgetPlugin.PluginType="EditorViewWidgetPlugin",lP([se(),he(f.EditorViewWidgetPlugin.prototype.setDirty)],f.EditorViewWidgetPlugin.prototype,"enabled",2),f.EditorViewWidgetPlugin=lP([vt("Editor View Widget")],f.EditorViewWidgetPlugin);const Wb=class Wb extends Vg{constructor(){super(...arguments),this.controlsKey="deviceOrientation",this._controlsCtor=(e,t)=>new f.DeviceOrientationControls2(e)}};Wb.PluginType="DeviceOrientationControlsPlugin";let fb=Wb;const qb=class qb extends Vg{constructor(){super(...arguments),this.controlsKey="pointerLock",this._controlsCtor=(e,t)=>new f.PointerLockControls2(e,t?.ownerDocument?t:(t||document).documentElement)}};qb.PluginType="PointerLockControlsPlugin";let pb=qb;const Xb=class Xb extends Vg{constructor(){super(...arguments),this.controlsKey="threeFirstPerson",this._controlsCtor=(e,t)=>new f.FirstPersonControls2(e,t||document.documentElement)}};Xb.PluginType="ThreeFirstPersonControlsPlugin";let mb=Xb;var MW=Object.defineProperty,cP=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&MW(e,t,n),n};const ef=(Hh=class extends mt{constructor(e=!0,t=1e3){super(),this.enabled=!0,this.limit=1e3,this.toJSON=void 0,this.undoEditingWaitTime=2e3,this.undoCommandTypes={setValue:"ThreeViewerUM_set",action:"ThreeViewerUM_action"},this.undoPresets={[this.undoCommandTypes.setValue]:i=>{const n=()=>{i.onUndoRedo&&i.onUndoRedo(i)};return{undo:()=>{console.log("undo",i.lastVal),i.binding&&(this.setValue(i.binding,i.lastVal,i.props,i.uid,void 0,!1),n())},redo:()=>{i.binding&&(this.setValue(i.binding,i.val,i.props,i.uid,void 0,!1),n())}}},[this.undoCommandTypes.action]:i=>{const n=()=>{i.onUndoRedo&&i.onUndoRedo(i)};return{undo:async()=>{await i.undo.call(i.target,...i.args),n()},redo:async()=>{await i.redo.call(i.target,...i.args),n()}}}},this.enabled=e,this.limit=t}undo(){this.undoManager?.undo()}redo(){this.undoManager?.redo()}_refresh(){this.undoManager&&(this.undoManager.enabled=this.enabled,this.undoManager.limit=this.limit,this.undoManager.options.debug=this._viewer?.debug||this.undoManager.options.debug,this.undoManager&&Object.assign(this.undoManager.presets,this.undoPresets))}onAdded(e){super.onAdded(e),this.undoManager=new M_({bindHotKeys:!0,limit:this.limit,debug:e.debug||qu("debugUndo")!==null,hotKeyRoot:document}),this._refresh()}onRemove(e){this.undoManager?.dispose(),this.undoManager=void 0,super.onRemove(e)}recordUndo(e){return $u(this.undoManager,e,this.undoCommandTypes.setValue,this.undoEditingWaitTime)}async performAction(e,t,i,n,s){const a=()=>e===void 0?t(...i):t.call(e,...i);let o=await a();const l=typeof o=="function"?o:o?.undo?.bind(o),c=typeof o!="function"?o?.action?.bind(o):null,h=typeof o=="function"?a:o?.redo?.bind(o)??c;typeof c=="function"&&(o=await c()),typeof l=="function"&&this.recordUndo({type:"UiConfigMethods_action",uid:n,target:e,undo:l,redo:h,args:i,onUndoRedo:s})}setValue(e,t,i,n,s,a=!0,o){return!(!G_(this.undoManager,e,t,i,n,this.undoCommandTypes.setValue,a,this.undoEditingWaitTime,!0,o).undoable&&!s)}setValues(e,t,i,n,s,a,o=!0,l){const c=hP(e,t);return this.setValue([c,"value"],i,n,s,a,o,l)}},Hh.PluginType="UndoManagerPlugin",Hh);cP([he(ef.prototype._refresh)],ef.prototype,"enabled"),cP([he(ef.prototype._refresh)],ef.prototype,"limit");let TW=ef;function hP(r,e){return{p:new Proxy([],{get(t,i,...n){if(i==="length")return r.length;const s=Number(i);if(isNaN(s)||s<0||s>=r.length)return Reflect.get(Array.prototype,i,...n)||Reflect.get(t,i,...n);const[a,o]=r[s];return a?.[o]??e[s]},set(t,i,n,...s){const a=Number(i);if(isNaN(a)||a<0||a>=r.length)return Reflect.set(t,i,n,...s);const[o,l]=r[a];return o?(o[l]=n,!0):!1},has(t,i,...n){const s=Number(i);return isNaN(s)||s<0||s>=r.length?Reflect.has(Array.prototype,i,...n)||Reflect.has(t,i,...n):!0}}),get value(){return this.p},set value(t){r.length!==t.length&&console.error(`UndoManager - setValues: bindings length (${r.length}) does not match value length (${t.length})`);for(let i=0;i<Math.min(t.length,r.length);i++)this.p[i]=t[i]}}}var IW=Object.defineProperty,PW=Object.getOwnPropertyDescriptor,Ol=(r,e,t,i)=>{for(var n=i>1?void 0:i?PW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&IW(e,t,n),n};f.Rhino3dmLoadPlugin=class extends Rl{constructor(){super(...arguments),this._importer=new qi(ur,["3dm"],["model/vnd.3dm","model/3dm"],!0),this.importMaterials=!0,this.forceLayerMaterials=!1,this.replaceWithInstancedMesh=!1,this.hideLineMesh=!1,this.hidePointMesh=!0,this.loadUserDataStrings=!0}_refresh(){ur.ImportMaterials=this.importMaterials,ur.ForceLayerMaterials=this.forceLayerMaterials,ur.ReplaceWithInstancedMesh=this.replaceWithInstancedMesh,ur.HideLineMesh=this.hideLineMesh,ur.HidePointMesh=this.hidePointMesh,ur.LoadUserDataStrings=this.loadUserDataStrings,ur.LoadUserDataWarnings=!1}onAdded(e){if(!window.WebAssembly)throw new Error("Rhino3dmLoadPlugin requires WebAssembly support");super.onAdded(e),this._refresh()}},f.Rhino3dmLoadPlugin.PluginType="Rhino3dmLoadPlugin",Ol([he(f.Rhino3dmLoadPlugin.prototype._refresh),se()],f.Rhino3dmLoadPlugin.prototype,"importMaterials",2),Ol([he(f.Rhino3dmLoadPlugin.prototype._refresh),se()],f.Rhino3dmLoadPlugin.prototype,"forceLayerMaterials",2),Ol([he(f.Rhino3dmLoadPlugin.prototype._refresh),se()],f.Rhino3dmLoadPlugin.prototype,"replaceWithInstancedMesh",2),Ol([he(f.Rhino3dmLoadPlugin.prototype._refresh),se()],f.Rhino3dmLoadPlugin.prototype,"hideLineMesh",2),Ol([he(f.Rhino3dmLoadPlugin.prototype._refresh),se()],f.Rhino3dmLoadPlugin.prototype,"hidePointMesh",2),Ol([he(f.Rhino3dmLoadPlugin.prototype._refresh),se()],f.Rhino3dmLoadPlugin.prototype,"loadUserDataStrings",2),f.Rhino3dmLoadPlugin=Ol([vt("Rhino 3dm Loader")],f.Rhino3dmLoadPlugin);const Yb=class Yb extends Rl{constructor(){super(...arguments),this._importer=new qi(class extends PI{constructor(){super(...arguments),this.currentUrl=""}async loadAsync(e,t){this.currentUrl=e;const i=await super.loadAsync(e,t);if(this.currentUrl="",!i.children.length)throw new Error("No mesh found in USDZ file, note that usdc files are not supported.");return i}parse(e){if(this.currentUrl.endsWith(".usda")&&typeof e!="string"){const t=this.currentUrl.split("/").pop();if(t){const i={};i[t]=new Uint8Array(e),e=Tg(i).buffer}}return super.parse(e)}},["usdz","usda"],["model/vnd.usd+zip","model/vnd.usdz+zip","model/vnd.usda"],!1)}};Yb.PluginType="USDZLoadPlugin";let gb=Yb;const $b=class $b extends Rl{constructor(){super(...arguments),this._importer=new qi(class extends DI{transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new _e(e,new si({color:new ee(1,1,1),vertexColors:e.hasAttribute("color")})):void 0}},["ply"],["text/plain+ply"],!1)}};$b.PluginType="PLYLoadPlugin";let Ab=$b;const Kb=class Kb extends Rl{constructor(){super(...arguments),this._importer=new qi(class extends RI{transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new _e(e,new si({color:new ee(1,1,1),vertexColors:e.hasAttribute("color")})):void 0}},["stl"],["model/stl","model/x.stl-binary","model/x.stl-ascii"],!1)}};Kb.PluginType="STLLoadPlugin";let yb=Kb;const Jb=class Jb extends Rl{constructor(){super(...arguments),this._importer=new qi(II,["ktx"],["image/ktx"],!1)}};Jb.PluginType="KTXLoadPlugin";let _b=Jb;const Qh=class Qh extends Rl{constructor(){super(...arguments),this._importer=new qi(uP,["ktx2"],["image/ktx2"],!1)}onAdded(e){this._importer.onCtor=t=>t.setTranscoderPath(Qh.TRANSCODER_LIBRARY_PATH).detectSupport(e.renderManager.renderer),super.onAdded(e),e.assetManager.exporter.getExporter("gltf","glb")?.extensions?.push(dP)}onRemove(e){const t=e.assetManager.exporter.getExporter("gltf","glb"),i=t?.extensions?.indexOf(dP);i!==void 0&&i!==-1&&t?.extensions?.splice(i,1),super.onRemove(e)}};Qh.PluginType="KTX2LoadPlugin",Qh.TRANSCODER_LIBRARY_PATH="https://cdn.jsdelivr.net/gh/BinomialLLC/basis_universal@1.16.4/webgl/transcoder/build/",Qh.SAVE_SOURCE_BLOBS=!1;let tf=Qh;class uP extends dr{_initTexture(e){Td.call(e),e.userData.mimeType="image/ktx2",e.toJSON=i=>QE(e,i,e.name,"image/ktx2");const t=e.clone;return e.clone=()=>{const i=t.call(e);return i.source!==e.source&&(i.source._sourceImgBuffer=e.source._sourceImgBuffer),this._initTexture(i)},e}async createTexture(e,t){const i=tf.SAVE_SOURCE_BLOBS?new Uint8Array(e.slice(0)):void 0,n=await super.createTexture(e,t);return tf.SAVE_SOURCE_BLOBS&&i&&(n.source._sourceImgBuffer=i,n.source._canSerialize=!0),this._initTexture(n),n}}const vb="KHR_texture_basisu",dP=r=>({writeTexture:(e,t)=>{if(e.userData.mimeType!=="image/ktx2")return;if(t.source!==void 0&&t.source!==null){console.warn("ktx2 export: source already set");return}const i=e.source._sourceImgBuffer||e.__sourceBuffer;if(!i){console.warn("ktx2 export: no source buffer for ktx2");return}t.extensions=t.extensions||{};const n={},s=new Blob([i],{type:"image/ktx2"});n.source=r.processImageBlob(s,e),t.extensions[vb]=n,r.extensionsUsed[vb]=!0}}),lf=class lf extends cm{constructor(e=!0,t=document.head){super(),this.rootNode=t,this.enabled=!0,this.toJSON=void 0,this._initializing=void 0,e&&this.initialize()}get initialized(){return!!window.MeshoptDecoder}async initialize(){if(this.initialized)return;if(this._initializing)return await this._initializing;const e=document.createElement("script");e.type="module";const t=Math.random().toString(36).substring(7);e.innerHTML=`
import { MeshoptDecoder } from ${JSON.stringify(lf.DECODER_URL)};
window.MeshoptDecoder = MeshoptDecoder; // setting it before ready as GLTFLoader supports it.
MeshoptDecoder.ready.then(() => {
window.dispatchEvent(new CustomEvent('${t}'))
});
`,this._initializing=new Promise(i=>{window.addEventListener(t,()=>i(),{once:!0}),this.rootNode.appendChild(e),this._script=e}),await this._initializing,this.dispatchEvent({type:"initialized"})}dispose(){this._script&&(this._script.remove(),delete window.MeshoptDecoder),this._script=void 0}onAdded(){}onRemove(){}};lf.PluginType="GLTFMeshOptDecodePlugin",lf.DECODER_URL="https://unpkg.com/meshoptimizer@0.20.0/meshopt_decoder.module.js";let bb=lf;var DW=Object.defineProperty,RW=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&DW(e,t,n),n};const Zb=class Zb extends mt{constructor(){super(),this.enabled=!0,this.exportOptions={name:"scene",viewerConfig:!0,encodeUint16Rgbe:!1,convertMeshToIndexed:!1,embedUrlImagePreviews:!1,embedUrlImages:!1,encrypt:!1,encryptKey:"",ignoreInvalidMorphTargetTracks:!0,ignoreEmptyTextures:!0},this.uiConfig={type:"folder",label:"Asset Export",expanded:!0,children:[{type:"input",property:[this.exportOptions,"name"]},{type:"folder",label:"GLB Export",expanded:!0,children:[{type:"checkbox",label:"Viewer Config (All Settings)",property:[this.exportOptions,"viewerConfig"],onChange:()=>this.uiConfig.uiRefresh?.(!0)},{type:"checkbox",label:"Embed Image Previews",property:[this.exportOptions,"embedUrlImagePreviews"]},{type:"checkbox",label:"Encrypt",property:[this.exportOptions,"encrypt"],onChange:()=>this.uiConfig.uiRefresh?.(!0)},{type:"input",label:"Encrypt Password",hidden:()=>!this.exportOptions.encrypt,property:[this.exportOptions,"encryptKey"]},{type:"checkbox",label:"Compress hdr env maps",hidden:()=>!this.exportOptions.viewerConfig,property:[this.exportOptions,"encodeUint16Rgbe"]},{type:"checkbox",label:"Ignore invalid animations",property:[this.exportOptions,"ignoreInvalidMorphTargetTracks"]},{type:"checkbox",label:"Ignore invalid textures",property:[this.exportOptions,"ignoreInvalidTextures"]},{type:"button",label:"Export GLB",property:[this,"downloadSceneGlb"]}]},{type:"button",label:"Export Config",value:async()=>{const e=new Blob([JSON.stringify(this._viewer?.exportConfig(!1),null,2)],{type:"application/json"});e&&await this._viewer?.exportBlob(e,this.exportOptions.name+"."+f.ThreeViewer.ConfigTypeSlug)}},{type:"button",label:"Export Selected",hidden:()=>!this._viewer?.getPlugin("PickingPlugin"),value:async()=>this.exportSelected(this.exportOptions,!0)}]},this.exportScene=this.exportScene.bind(this)}onAdded(e){super.onAdded(e)}onRemove(e){return super.onRemove(e)}async exportScene(e){return this._viewer?.assetManager.exporter?.exportObject(this._viewer?.scene.modelRoot,e||{...this.exportOptions})}async downloadSceneGlb(){const e=await this.exportScene(this.exportOptions);e&&await this._viewer?.exportBlob(e,this.exportOptions.name+"."+e.ext)}async exportSelected(e,t=!0){const i=this._viewer?.getPlugin("PickingPlugin")?.getSelectedObject();if(!i){this._viewer?.dialog.alert("Export Selected: Nothing selected");return}const n=i.name||"selected",s=await this._viewer.assetManager.exporter.exportObject(i,e??this.exportOptions);return s&&t&&await this._viewer?.exportBlob(s,n+"."+s.ext),s}};Zb.PluginType="AssetExporterPlugin";let $g=Zb;RW([G()],$g.prototype,"exportOptions");var BW=Object.defineProperty,LW=Object.getOwnPropertyDescriptor,xh=(r,e,t,i)=>{for(var n=i>1?void 0:i?LW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&BW(e,t,n),n};f.CanvasSnapshotPlugin=class extends mt{constructor(){super(),this.enabled=!0,this.filename="snapshot",this._downloading=!1,this.defaultOptions={waitForProgressive:!0,displayPixelRatio:window.devicePixelRatio,scale:1,timeout:0,quality:.9,tileRows:1,tileColumns:1,progressiveFrames:64,rect:{x:0,y:0,width:1,height:1,normalized:!0,assumeClientRect:!1}},this.downloadSnapshot=this.downloadSnapshot.bind(this)}async getFile(e,t={waitForProgressive:!0}){return await this._getFile(e||this.filename,{...t,getDataUrl:!1})}async getDataUrl(e={}){return await this._getFile("",{...e,getDataUrl:!0})??""}async _getFile(e,t={}){await this._viewer?.doOnce("postFrame");const i=this._viewer,n=this._viewer?.canvas;if(!i||!n)return;i.scene.mainCamera.setInteractions(!1,f.CanvasSnapshotPlugin.PluginType);const s=i.renderManager.renderScale;t.displayPixelRatio!==void 0&&t.displayPixelRatio!==s&&(i.renderManager.renderScale=t.displayPixelRatio),t.timeout&&await Qn(t.timeout);const a=i.getPlugin(f.ProgressivePlugin);let o=t.waitForProgressive??!!a;o&&!a&&(i.console.warn("CanvasSnapshotPlugin: ProgressivePlugin required to wait for progressive rendering"),o=!1),t.progressiveFrames&&!o&&i.console.warn("CanvasSnapshotPlugin: waitForProgressive must be true to use progressiveFrames");const l=a?.maxFrameCount;if(o&&a)for(a.maxFrameCount=Math.max(t.progressiveFrames??64,a.maxFrameCount),i.setDirty(),await i.doOnce("postFrame");!a.isConverged(!0);)await i.doOnce("postFrame");else i.setDirty(),await i.doOnce("postFrame");delete t.displayPixelRatio;let c;if(t.tileRows&&t.tileRows>1||t.tileColumns&&t.tileColumns>1){const h=await wd.GetTiledFiles(n,e,Math.max(1,t.tileRows||1),Math.max(1,t.tileColumns||1),t);if(Array.isArray(h))if(h.length===1)c=h[0];else if(h.length===0)c=void 0;else if(t.getDataUrl)c=h;else{const u={};for(const p of h)u[p.name]=new Uint8Array(await p.arrayBuffer());const d=Tg(u);c=new File([d],e+".zip",{type:"application/zip",lastModified:Date.now()})}else c=h}else c=await wd.GetFile(n,e,t);return t.displayPixelRatio=i.renderManager.renderScale,a&&l!==void 0&&(a.maxFrameCount=l),i.scene.mainCamera.setInteractions(!0,f.CanvasSnapshotPlugin.PluginType,!1),i.renderManager.renderScale=s,c}async downloadSnapshot(e,t={waitForProgressive:!0}){if(!this._viewer)return;for(;this._downloading;)console.warn("CanvasSnipperPlugin: Another rendering already in progress, waiting..."),await Qn(100);this._downloading=!0;const i=await this.getFile(e,{...this.defaultOptions,...t}).catch(n=>(this._viewer?.console.error("CanvasSnapshotPlugin: Error exporting file",n),null));i&&await this._viewer.exportBlob(i,i.name),this._downloading=!1}async _downloadPng(){return this.downloadSnapshot(void 0,{mimeType:"image/png"})}async _downloadJpeg(){return this.downloadSnapshot(void 0,{mimeType:"image/jpeg"})}async _downloadWebp(){return this.downloadSnapshot(void 0,{mimeType:"image/webp"})}},f.CanvasSnapshotPlugin.PluginType="CanvasSnapshotPlugin",xh([He("Filename"),G()],f.CanvasSnapshotPlugin.prototype,"filename",2),xh([Bi(void 0,{label:"Options"}),G()],f.CanvasSnapshotPlugin.prototype,"defaultOptions",2),xh([ct("Download .png")],f.CanvasSnapshotPlugin.prototype,"_downloadPng",1),xh([ct("Download .jpeg")],f.CanvasSnapshotPlugin.prototype,"_downloadJpeg",1),xh([ct("Download .webp")],f.CanvasSnapshotPlugin.prototype,"_downloadWebp",1),f.CanvasSnapshotPlugin=xh([vt("Image Export (Canvas Snapshot)")],f.CanvasSnapshotPlugin);const ew=class ew extends f.CanvasSnapshotPlugin{constructor(){super(),console.warn("CanvasSnipperPlugin is deprecated, use CanvasSnapshotPlugin")}};ew.PluginType="CanvasSnipper";let wb=ew;const tw=class tw extends mt{constructor(){super(),this.enabled=!0,this.toJSON=void 0,this.defaultActions={exportFile:async(e,t,i)=>{Qu(e,t)}},this.actions={...this.defaultActions},this._updateProcessState=this._updateProcessState.bind(this)}async exportFile(e,t=e.name||"file_export"){this.dispatchEvent({type:"transferFile",path:t,state:"exporting",progress:0}),await this.actions.exportFile(e,t,({state:i,progress:n})=>{this.dispatchEvent({type:"transferFile",path:t,state:i??"exporting",progress:n})}),this.dispatchEvent({type:"transferFile",path:t,state:"done"})}onAdded(e){super.onAdded(e),this.addEventListener("transferFile",this._updateProcessState)}onRemove(e){this.removeEventListener("transferFile",this._updateProcessState),super.onRemove(e)}_updateProcessState(e){this._viewer&&this._viewer.assetManager.setProcessState(e.path,e.state!=="done"?{state:e.state,progress:e.progress?e.progress*100:void 0}:void 0)}};tw.PluginType="FileTransferPlugin";let Cb=tw;const OW="vec4 Vignette(in vec4 color){vec2 uv=vUv*(1.0-vUv);float vig=uv.x*uv.y*16.0;vig=pow(vig,power);return vec4(mix(color.rgb,vec3(bgcolor),1.-vig),color.a);}";var UW=Object.defineProperty,FW=Object.getOwnPropertyDescriptor,Kg=(r,e,t,i)=>{for(var n=i>1?void 0:i?FW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&UW(e,t,n),n};f.VignettePlugin=class extends qd{constructor(e=!0){super(),this.extraUniforms={power:{value:1},bgcolor:{value:new ee}},this.power=.5,this.color=new ee(0),this.priority=-50,this.parsFragmentSnippet=()=>this.isDisabled()?"":ma`
            uniform float power;
            uniform vec3 bgcolor;
            ${OW}
        `,this._shaderPatch="diffuseColor = Vignette(diffuseColor);",this.enabled=e}get bgcolor(){return console.warn("VignettePlugin.bgcolor is deprecated, use VignettePlugin.color instead"),this.color}set bgcolor(e){console.warn("VignettePlugin.bgcolor is deprecated, use VignettePlugin.color instead"),this.color=e}},f.VignettePlugin.PluginType="Vignette",Kg([he(f.VignettePlugin.prototype.setDirty),se("Enable"),G()],f.VignettePlugin.prototype,"enabled",2),Kg([Fe("Power",[.1,4],.01),_a({propKey:"power"}),G()],f.VignettePlugin.prototype,"power",2),Kg([xn("Color",r=>({onChange:()=>r?.setDirty()})),_a({propKey:"bgcolor"}),G("bgcolor")],f.VignettePlugin.prototype,"color",2),f.VignettePlugin=Kg([vt("Vignette")],f.VignettePlugin);const NW="vec4 ChromaticAberration(in vec4 color){vec2 distFromCenter=vUv-0.5;vec2 aberrated=aberrationIntensity*pow(abs(distFromCenter),vec2(2.0));vec4 outColor=vec4(tDiffuseTexelToLinear(texture2D(tDiffuse,vUv+aberrated)).r,color.g,tDiffuseTexelToLinear(texture2D(tDiffuse,vUv-aberrated)).b,color.a);return outColor;}";var kW=Object.defineProperty,GW=Object.getOwnPropertyDescriptor,xb=(r,e,t,i)=>{for(var n=i>1?void 0:i?GW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&kW(e,t,n),n};f.ChromaticAberrationPlugin=class extends qd{constructor(e=!0){super(),this.extraUniforms={aberrationIntensity:{value:1}},this.intensity=.5,this.priority=-50,this.parsFragmentSnippet=()=>this.isDisabled()?"":ma`
            uniform float aberrationIntensity;
            ${NW}
        `,this._shaderPatch="diffuseColor = ChromaticAberration(diffuseColor);",this.enabled=e}get aberrationIntensity(){return console.warn("ChromaticAberrationPlugin.aberrationIntensity is deprecated, use ChromaticAberrationPlugin.intensity instead"),this.intensity}set aberrationIntensity(e){console.warn("ChromaticAberrationPlugin.aberrationIntensity is deprecated, use ChromaticAberrationPlugin.intensity instead"),this.intensity=e}},f.ChromaticAberrationPlugin.PluginType="ChromaticAberration",xb([he(f.ChromaticAberrationPlugin.prototype.setDirty),se("Enable"),G()],f.ChromaticAberrationPlugin.prototype,"enabled",2),xb([Fe("Intensity",[0,.3],.001),_a({propKey:"aberrationIntensity"}),G("aberrationIntensity")],f.ChromaticAberrationPlugin.prototype,"intensity",2),f.ChromaticAberrationPlugin=xb([vt("ChromaticAberration")],f.ChromaticAberrationPlugin);const zW="vec4 FilmicGrain(in vec4 color){float x=(vUv.x+4.0)*(vUv.y+4.0)*(10.0);vec4 grain=vec4(mod((mod(x,13.0)+1.0)*(mod(x,123.0)+1.0),0.01)-0.005)*grainIntensity;return vec4(grainMultiply ?(color.rgb*vec3(1.-grain)):(color.rgb+vec3(grain)),color.a);}";var VW=Object.defineProperty,HW=Object.getOwnPropertyDescriptor,Jg=(r,e,t,i)=>{for(var n=i>1?void 0:i?HW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&VW(e,t,n),n};f.FilmicGrainPlugin=class extends qd{constructor(e=!0){super(),this.extraUniforms={grainIntensity:{value:1},grainMultiply:{value:!1}},this.intensity=10,this.multiply=!1,this.priority=-50,this.parsFragmentSnippet=()=>this.isDisabled()?"":ma`
            uniform float grainIntensity;
            uniform bool grainMultiply;
            ${zW}
        `,this._shaderPatch="diffuseColor = FilmicGrain(diffuseColor);",this.enabled=e}get grainIntensity(){return console.warn("FilmicGrainPlugin.grainIntensity is deprecated, use FilmicGrainPlugin.intensity instead"),this.intensity}set grainIntensity(e){console.warn("FilmicGrainPlugin.grainIntensity is deprecated, use FilmicGrainPlugin.intensity instead"),this.intensity=e}},f.FilmicGrainPlugin.PluginType="FilmicGrain",Jg([he(f.FilmicGrainPlugin.prototype.setDirty),se("Enable"),G()],f.FilmicGrainPlugin.prototype,"enabled",2),Jg([Fe("Intensity",[0,20],.01),_a({propKey:"grainIntensity"}),G("grainIntensity")],f.FilmicGrainPlugin.prototype,"intensity",2),Jg([se("Multiply"),_a({propKey:"grainMultiply"}),G("grainMultiply")],f.FilmicGrainPlugin.prototype,"multiply",2),f.FilmicGrainPlugin=Jg([vt("FilmicGrain")],f.FilmicGrainPlugin);var QW=Object.defineProperty,jW=Object.getOwnPropertyDescriptor,$i=(r,e,t,i)=>{for(var n=i>1?void 0:i?jW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&QW(e,t,n),n};const wi=(Vl=class extends mt{constructor(){super(),this.enabled=!0,this._animations=[],this.autoIncrementTime=!0,this.loopAnimations=!0,this.loopRepetitions=1/0,this.timeScale=1,this.animationSpeed=1,this.animateOnScroll=!1,this.scrollAnimationDamping=.1,this.animateOnPageScroll=!1,this.pageScrollAnimationDamping=.1,this.animateOnDrag=!1,this.dragAxis="y",this.dragAnimationDamping=.3,this.autoplayOnLoad=!1,this.autoplayOnLoadForce=!1,this.syncMaxDuration=!1,this._animationState="none",this._lastAnimationTime=0,this._animationTime=0,this._animationDuration=0,this._scrollAnimationState=0,this._pageScrollAnimationState=0,this._dragAnimationState=0,this._pointerDragHelper=new cS,this._lastFrameTime=0,this._fadeDisabled=!1,this._lastAnimId="",this.stopOnCheckpointEnd=!0,this.autoUnpauseActions=!0,this.autoEnableActions=!0,this.activeActionWeight=1,this.inactiveActionWeight=0,this._objectAdd=e=>{const t=e.object;if(!this._viewer||!t)return;let i=!1;this._refreshAnimations(t,t)&&(i=!0),i&&(this._onPropertyChange(!this.autoplayOnLoad),(this.autoplayOnLoad||this.autoplayOnLoadForce||this._animationState==="playing")&&this.playAnimation())},this._objectRemove=e=>{const t=e.object;if(!this._viewer||!t)return;const i=this._animations.find(n=>n.object===t);i&&(i.mixer.stopAllAction(),this._animations.splice(this._animations.indexOf(i),1),this.dispatchEvent({type:"removeAnimation",animation:i}))},this._sceneUpdate=e=>{if(!this._viewer)return;this._refreshAnimations(this._viewer.scene.modelRoot,this._viewer.scene.modelRoot)&&(this._onPropertyChange(!this.autoplayOnLoad),(this.autoplayOnLoad||this.autoplayOnLoadForce||this._animationState==="playing")&&this.playAnimation())},this.pageScrollHeight=()=>Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)-window.innerHeight,this.uiConfig={type:"folder",label:"GLTF Animation",children:[...bi(this),()=>this._animations.map(e=>({type:"folder",label:`Animation - ${e.object.name||e.object.uuid}`,children:[...e.actions.map(i=>{const n=i.getClip(),s=i.clipData;return s?{type:"folder",label:`Clip - ${n.name}`,children:[{type:"checkbox",label:"Active",property:[s,"active"]},{type:"input",label:"Name",property:[s,"name"]},{type:"monitor",label:"Duration",getValue:()=>n.duration.toFixed(3)},{type:"number",label:"Start Time",property:[s,"startTime"]},{type:"number",label:"Time Scale",property:[s,"timeScale"]}]}:null})]}))]},this.playClips=this.playClips.bind(this),this.playClip=this.playClip.bind(this),this.playAnimation=this.playAnimation.bind(this),this.playPauseAnimation=this.playPauseAnimation.bind(this),this.pauseAnimation=this.pauseAnimation.bind(this),this.stopAnimation=this.stopAnimation.bind(this),this.resetAnimation=this.resetAnimation.bind(this),this._onPropertyChange=this._onPropertyChange.bind(this),this._postFrame=this._postFrame.bind(this),this._wheel=this._wheel.bind(this),this._scroll=this._scroll.bind(this),this._pointerDragHelper.addEventListener("drag",this._drag.bind(this))}get animations(){return[...this._animations]}get animationState(){return this._animationState}get animationTime(){return this._animationTime}get animationDuration(){return this._animationDuration}playPauseAnimation(){this._animationState==="playing"?this.pauseAnimation():this.playAnimation()}setTime(e){this._animationTime=Math.max(0,Math.min(e,this._animationDuration))}onAdded(e){super.onAdded(e),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.scene.addEventListener("sceneUpdate",this._sceneUpdate),e.addEventListener("postFrame",this._postFrame),window.addEventListener("wheel",this._wheel),window.addEventListener("scroll",this._scroll),this._pointerDragHelper.element=e.canvas}onRemove(e){for(;this._animations.length;)this._animations.pop();return e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),e.scene.removeEventListener("sceneUpdate",this._sceneUpdate),e.removeEventListener("postFrame",this._postFrame),window.removeEventListener("wheel",this._wheel),window.removeEventListener("scroll",this._scroll),this._pointerDragHelper.element=void 0,super.onRemove(e)}onStateChange(){this.uiConfig?.uiRefresh?.(!0,"postFrame")}async playClip(e,t=!1){return this.playClips([e],t)}async playClips(e,t=!1){const i=[];return this._animations.forEach(({actions:n})=>{n.forEach(s=>{e.includes(s.getClip().name)&&i.push(s)})}),this.playAnimation(t,i)}async playAnimation(e=!1,t){if(this.isDisabled())return;let i=!1;this._animationState==="playing"&&(this.stopAnimation(!1),i=!0);let n=0;const s=!t;t||(t=[],this._animations.forEach(({actions:o})=>{t.push(...o)})),i?this.resetAnimation():this.animationState!=="paused"&&(t.forEach(o=>{o.reset()}),this._animationTime=0);const a=Oi();this._lastAnimId=a;for(const o of t)o.setLoop(this.loopAnimations?sy:ny,this.loopRepetitions),o.play(),n=Math.max(n,o.getClip().duration/Math.abs(o.timeScale));if(this._animationState="playing",this._viewer?.setDirty(),s){if(!isFinite(this._animationDuration))return;await new Promise(o=>{const l=()=>{this.removeEventListener("checkpointEnd",l),o()};this.addEventListener("checkpointEnd",l)})}else{const o=this.loopAnimations?this.loopRepetitions:1;if(n*=o,!isFinite(n))return;await new Promise(l=>{const c=h=>{h.time>=n&&(this.removeEventListener("animationStep",c),l())};this.addEventListener("animationStep",c)})}a===this._lastAnimId&&this.stopOnCheckpointEnd&&this.stopAnimation(e)}pauseAnimation(){if(this._animationState!=="playing"){console.warn("pauseAnimation called when animation was not playing.");return}this._animationState="paused",this._viewer?.setDirty()}resumeAnimation(){if(this._animationState!=="paused"){console.warn("resumeAnimation called when animation was not paused.");return}this._animationState="playing",this._viewer?.setDirty()}stopAnimation(e=!1){this._animationState="stopped",e?this.resetAnimation():this._viewer?.setDirty(),this._lastAnimId="",this._viewer&&this._fadeDisabled&&(this._viewer.getPlugin("FrameFade")?.enable(this),this._fadeDisabled=!1)}resetAnimation(){if(this._animationState!=="stopped"&&this._animationState!=="none"){this.stopAnimation(!0);return}this._animations.forEach(({mixer:e})=>{e.stopAllAction(),e.setTime(0)}),this._animationTime=0,this._viewer?.setDirty()}_postFrame(){if(!this._viewer)return;const e=this.animateOnScroll,t=this.animateOnPageScroll,i=this.animateOnDrag;if(this.isDisabled()||this._animations.length<1||this._animationState!=="playing"){this._lastFrameTime=0,this._fadeDisabled&&(this._viewer.getPlugin("FrameFade")?.enable(this),this._fadeDisabled=!1);return}const n=this._animationTime;if(this.autoIncrementTime||t||e||i){const o=Cn()/1e3;this._lastFrameTime<1&&(this._lastFrameTime=o-1/30);let l=o-this._lastFrameTime;l*=this.animationSpeed,this._lastFrameTime=o,t?l*=this._pageScrollAnimationState:e&&i?l*=US(this._scrollAnimationState,this._dragAnimationState):e?l*=this._scrollAnimationState:i&&(l*=this._dragAnimationState);const c=this._viewer.getPlugin("Progressive")?.postFrameConvergedRecordingDelta();c&&c>0&&(l=c),c===0&&(l=0);const h=Math.abs(this.timeScale);this._animationTime+=l*(h>0?h:1)}else{const o=Cn()/1e3;this._lastFrameTime=o;const l=Math.abs(this.timeScale)*this.animationSpeed;this._animationTime=this._viewer.timeline.time*(l>0?l:1)}const s=this._animationTime-this._lastAnimationTime;if(this._lastAnimationTime=this._animationTime,Math.abs(s)<1e-4)return;n<1e-4&&this.dispatchEvent({type:"checkpointBegin"});const a=this.timeScale<0?(isFinite(this._animationDuration)?this._animationDuration:0)-this._animationTime:this._animationTime;if(this._animations.map(o=>{o.actions.forEach(l=>{const c=l.clipData?.startTime||0,h=l.clipData?.active??!0;l.clipData?.timeScale!==void 0&&(l.timeScale=l.clipData.timeScale),(c!==void 0&&l._startTime===null||l._startTime!==c)&&(l._startTime=c);let u=l.getClip().duration;this.autoIncrementTime&&this.loopAnimations&&(u*=this.loopRepetitions);const d=h&&a>=c&&(!isFinite(u)||a<u/Math.abs(l.timeScale)+c);this.autoUnpauseActions&&l.paused&&d&&(l.paused=!1),this.autoEnableActions&&!l.enabled&&d&&(l.enabled=!0),this.inactiveActionWeight!==null&&!d&&l.weight?l.setEffectiveWeight(this.inactiveActionWeight):this.activeActionWeight!==null&&d&&!l.weight&&l.setEffectiveWeight(this.activeActionWeight)}),o.mixer.setTime(a)}),this._pageScrollAnimationState=this.pageScrollTime-this._animationTime,Math.abs(this._pageScrollAnimationState)<.001?this._pageScrollAnimationState=0:this._pageScrollAnimationState*=1-this.pageScrollAnimationDamping,Math.abs(this._scrollAnimationState)<.001?this._scrollAnimationState=0:this._scrollAnimationState*=1-this.scrollAnimationDamping,Math.abs(this._dragAnimationState)<.001?this._dragAnimationState=0:this._dragAnimationState*=1-this.dragAnimationDamping,this.dispatchEvent({type:"animationStep",delta:s,time:a}),this._viewer.renderManager.resetShadows(),this._viewer.setDirty(),!this._fadeDisabled){const o=this._viewer.getPlugin("FrameFade");o&&(o.disable(Vl.PluginType),this._fadeDisabled=!0)}this._animationTime>=this._animationDuration&&this.dispatchEvent({type:"checkpointEnd"})}_refreshAnimations(e,t){if(!this._viewer)return!1;const i=e.animations;if(i.length<1)return!1;const n=this._animations.find(a=>a.object===e)||{object:e,mixer:new Kx(t),clips:[],actions:[],duration:0};n.clips=i,n.duration=Math.max(...i.map(a=>a.duration)),(t.userData.gltfAnim_SyncMaxDuration??this.syncMaxDuration)&&(i.forEach(a=>a.duration=n.duration),t.userData.gltfAnim_SyncMaxDuration=!0);const s=i.flatMap(a=>{a.userData.clipActions||(a.userData.clipActions={});const o=a.userData.clipActions?.[e.uuid];if(o&&o.length){const c=[];for(const h of o){const u=n.actions.find(d=>d.clipData?.uid===h.uid);u&&c.push(u)}if(c.length)return c}o||(a.userData.clipActions[e.uuid]=[]);const l=n.mixer.clipAction(a);return l.clipData={uid:Oi(),active:!0,name:a.name,startTime:0,timeScale:1},l.setLoop(this.loopAnimations?sy:ny,this.loopRepetitions),a.userData.clipActions[e.uuid].push(l.clipData),l});return n.actions=s,n.actions.forEach(a=>a.clampWhenFinished=!0),this._animations.push(n),this.uiConfig?.uiRefresh?.(!0,"postFrame"),this.dispatchEvent({type:"addAnimation",animation:n}),!0}_onPropertyChange(e=!0){this._animationDuration=Math.max(...this._animations.map(({duration:t})=>t))*(this.loopAnimations?this.loopRepetitions:1),this._animationState==="playing"&&e!==!1&&this.playAnimation()}get pageScrollTime(){const e=this.pageScrollHeight();return window.scrollY/e*(this.animationDuration-.05)}_scroll(){this.isDisabled()||(this._pageScrollAnimationState=this.pageScrollTime-this.animationTime)}_wheel({deltaY:e}){this.isDisabled()||Math.abs(e)>.001&&(this._scrollAnimationState=-1*Math.sign(e))}_drag(e){this.isDisabled()||!this._viewer||(this._dragAnimationState=this.dragAxis==="x"?e.delta.x*this._viewer.canvas.width/4:e.delta.y*this._viewer.canvas.height/4)}},Vl.PluginType="GLTFAnimation",Vl);$i([Zt(wi.prototype._onPropertyChange),se("Loop"),G()],wi.prototype,"loopAnimations",2),$i([Zt(wi.prototype._onPropertyChange),G()],wi.prototype,"loopRepetitions",2),$i([Fe("Timescale",[-2,2],.01),G()],wi.prototype,"timeScale",2),$i([Fe("Speed",[.1,4],.1),G()],wi.prototype,"animationSpeed",2),$i([se(),G()],wi.prototype,"animateOnScroll",2),$i([Fe("Scroll Damping",[0,1]),G()],wi.prototype,"scrollAnimationDamping",2),$i([se(),G()],wi.prototype,"animateOnPageScroll",2),$i([Fe("Page Scroll Damping",[0,1]),G()],wi.prototype,"pageScrollAnimationDamping",2),$i([se(),G()],wi.prototype,"animateOnDrag",2),$i([Li("Drag Axis",[{label:"x"},{label:"y"}]),G()],wi.prototype,"dragAxis",2),$i([Fe("Drag Damping",[0,1]),G()],wi.prototype,"dragAnimationDamping",2),$i([se(),G()],wi.prototype,"autoplayOnLoad",2),$i([se("syncMaxDuration(dev)"),G()],wi.prototype,"syncMaxDuration",2),$i([dl()],wi.prototype,"animationState",1),$i([dl()],wi.prototype,"animationTime",1),$i([dl()],wi.prototype,"animationDuration",1),$i([ct("Play/Pause",r=>({label:()=>r.animationState==="playing"?"Pause":"Play"}))],wi.prototype,"playPauseAnimation",1),$i([he(wi.prototype.onStateChange)],wi.prototype,"_animationState",2),$i([se()],wi.prototype,"autoUnpauseActions",2),$i([se()],wi.prototype,"autoEnableActions",2),$i([ct("Stop",{sendArgs:!1})],wi.prototype,"stopAnimation",1),$i([ct("Reset",{sendArgs:!1})],wi.prototype,"resetAnimation",1);let WW=wi;const Cr=class Cr extends mt{constructor(){super(),this.toJSON=void 0,this.enabled=!0,this.dependencies=[Gr],this._addSceneObject=e=>{const t=e.object;t?.traverse&&!t.isWidget&&t.traverse(i=>{if(i.isWidget)return;i.userData[Cr.PluginType]?.transforms?.forEach((s,a)=>{s.name===void 0&&(s.name="Transform "+a)});const n={type:"folder",label:"Transform Animation",children:[{type:"button",label:"Add Current Transform",value:()=>{this.addTransform(i),n?.uiRefresh?.()}},()=>i.userData[Cr.PluginType]?.transforms.map((s,a)=>({type:"folder",label:s.name||`Transform ${a}`,children:[{type:"input",label:"Name",property:[s,"name"]},{type:"vec3",label:"Position",property:[s,"position"]},{type:"vec3",label:"Quaternion",property:[s,"quaternion"]},{type:"vec3",label:"Scale",property:[s,"scale"]},{type:"button",label:"Set",value:()=>{this.setTransform(i,s)}},{type:"button",label:"Animate",value:()=>{this.animateTransform(i,s)}}]}))]};i.uiConfig?.children?.push(n)})}}onAdded(e){super.onAdded(e),e.scene.addEventListener("addSceneObject",this._addSceneObject)}onRemove(e){return e.scene.removeEventListener("addSceneObject",this._addSceneObject),super.onRemove(e)}addTransform(e,t){e.userData[Cr.PluginType]||(e.userData[Cr.PluginType]={transforms:[]});const i={name:t||"Transform "+(e.userData[Cr.PluginType].transforms.length+1),position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()};return e.userData[Cr.PluginType].transforms.push(i),i}setTransform(e,t){const i=this.getSavedTransform(t,e);i&&(e.position.copy(i.position),e.quaternion.copy(i.quaternion),e.scale.copy(i.scale),e.setDirty?.(),e.uiConfig?.uiRefresh?.())}getSavedTransform(e,t){return typeof e=="number"?t.userData[Cr.PluginType]?.transforms[e]:typeof e=="string"?t.userData[Cr.PluginType]?.transforms.find(i=>i.name===e):e}animateTransform(e,t,i=2e3){const n=this._viewer?.getPlugin(Gr);n||this._viewer?.console.error("PopmotionPlugin required for animation");const s=this.getSavedTransform(t,e);if(!s)return;const a=new S,o=new $e,l=new S,c=e.position.clone(),h=e.quaternion.clone(),u=e.scale.clone(),d=s.position,p=s.quaternion,m=s.scale;return n?.animate({from:0,to:1,duration:i,onUpdate:A=>{a.lerpVectors(c,d,A),o.slerpQuaternions(h,p,A),l.lerpVectors(u,m,A),e.position.copy(a),e.quaternion.copy(o),e.scale.copy(l),this._viewer?.setDirty(),this._viewer?.renderManager.resetShadows()},onStop:()=>{e.position.copy(s.position),e.quaternion.copy(s.quaternion),e.scale.copy(s.scale),e.setDirty?.(),e.uiConfig?.uiRefresh?.()}})}};Cr.PluginType="TransformAnimationPlugin";let Sb=Cr;var qW=Object.defineProperty,XW=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&qW(e,t,n),n};const fP=(Ua=class extends mt{constructor(){super(),this.enabled=!0,this.dependencies=[Gr],this.animation=new f.AnimationObject(()=>this._viewer,()=>this._viewer,"Viewer Animation"),this.runtimeAnimation=new f.AnimationObject(void 0,()=>this._viewer,"Runtime Animation"),this._fAnimationAdd=e=>{this.rebuildTimeline(),this.dispatchEvent({...e,type:"animationAdd"})},this._fAnimationRemove=e=>{if(this.rebuildTimeline(),this.dispatchEvent(e),e.fromChild&&e.target===this.runtimeAnimation){const t=e.animation.target;t?.userData?.animationObjects&&this._removeAnimationFromObject(e.animation,t);const i=this._visibleBtns.get(e.animation);i&&i.forEach(n=>this._refreshTriggerBtn(e.animation,n))}else this._visibleBtns.delete(e.animation)},this._fAnimationUpdate=e=>{if(this.rebuildTimeline(),this.dispatchEvent({...e,type:"animationUpdate",animation:e.target}),!this._triggerButtonsShown)return;const t=this._visibleBtns.get(e.target);t&&t.forEach(i=>this._refreshTriggerBtn(e.target,i))},this._viewerTimelineUpdate=()=>{!this._viewer||!this._triggerButtonsShown||this._visibleBtns.forEach((e,t)=>{e.forEach(i=>this._refreshTriggerBtn(t,i))})},this._refreshTriggerBtn=(e,t)=>{const i=this._getActiveIndex(e);t.classList.remove("anim-object-uic-trigger-equals"),t.classList.remove("anim-object-uic-trigger-active"),t.dataset.activeIndex=i,i.length&&(t.classList.add("anim-object-uic-trigger-active"),e.isValueSame(parseInt(i))&&t.classList.add("anim-object-uic-trigger-equals"))},this._triggerButtonsShown=!1,this._currentTimeline=[],this._refTimeline=!1,this._viewerListeners={postFrame:()=>{const e=this._viewer?.getPlugin(Gr);this._refTimeline&&e&&(this._refTimeline=!1,this._currentTimeline.forEach(([t,i])=>i.stop()),this._currentTimeline=this.getAllAnimations().map(t=>[t,e.animateObject(t,0,!1,e.timelineDriver)]),this.dispatchEvent({type:"rebuildTimeline",timeline:this._currentTimeline}))}},this._objectAdd=e=>{const t=e.object;t&&(t.isWidget||(Array.isArray(t.userData.animationObjects)&&t.userData.animationObjects.forEach(i=>this._addAnimationObject(i,t)),this._setupUiConfig(t)))},this._objectRemove=e=>{const t=e.object;t&&(Array.isArray(t.userData.animationObjects)&&t.userData.animationObjects.forEach(i=>this._removeAnimationObject(i)),this._cleanUpUiConfig(t))},this._materialAdd=e=>{const t=e.material;t&&(Array.isArray(t.userData.animationObjects)&&t.userData.animationObjects.forEach(i=>this._addAnimationObject(i,t)),this._setupUiConfig(t))},this._materialRemove=e=>{const t=e.material;t&&(Array.isArray(t.userData.animationObjects)&&t.userData.animationObjects.forEach(i=>this._removeAnimationObject(i)),this._cleanUpUiConfig(t))},this._visibleBtns=new Map,this._iObservers=new WeakMap,this._objectUpdate=e=>{const t=e.object||e.material;if(this.isDisabled()||!this._triggerButtonsShown||!t||t!==e.target)return;const i=e.change||e.key;if(!t.assetType||t.assetType==="widget"||!i)return;const n=this._iObservers.get(t)?.filter(s=>(s.key===i||s.key?.endsWith("."+i))&&s.btn?.parentElement);if(n?.length)for(const s of n){const a=Zg(t,s.key);if(!a)return;this._refreshTriggerBtn(a,s.btn)}},this.uiConfig={label:"Viewer Animations",type:"folder",children:[bi(this.animation).filter(e=>{const t=tt(e?.label)??"";return["Animate","Stop","Animate Reverse"].includes(t)})??[],()=>bi(this.animation.animSet).map(t=>tt(t)).filter(Boolean),{type:"checkbox",label:"Run in Parallel",property:[this.animation,"animSetParallel"]},{type:"button",label:"Add Animation",value:()=>{this.animation.addAnimation(),this.uiConfig.uiRefresh?.(!0,"postFrame",1)}},{type:"checkbox",label:"Show Triggers",property:[this,"triggerButtonsShown"]}]},this.animation.animSetParallel=!0,this.animation.uiConfig.uiRefresh=(...e)=>this.uiConfig.uiRefresh?.(...e),this.animation.addEventListener("animationAdd",this._fAnimationAdd),this.animation.addEventListener("animationRemove",this._fAnimationRemove),this.animation.addEventListener("update",this._fAnimationUpdate),this.runtimeAnimation.animSetParallel=!0,this.runtimeAnimation.uiConfig.uiRefresh=(...e)=>this.uiConfig.uiRefresh?.(...e),this.runtimeAnimation.addEventListener("animationAdd",this._fAnimationAdd),this.runtimeAnimation.addEventListener("animationRemove",this._fAnimationRemove),this.runtimeAnimation.addEventListener("update",this._fAnimationUpdate),this._fAnimationAdd({animation:this.animation}),hl(`
        .anim-object-uic-trigger{
            padding: 4px;
            margin-top: -4px;
            cursor: pointer;
            color: var(--tp-label-foreground-color, #777);
            display: none;
        }
        .anim-object-uic-trigger-visible{
        }
        .anim-object-uic-trigger-active{
            color: blue;
        }
        .anim-object-uic-trigger-equals{
            color: red !important;
        }
        .aouic-triggers-visible .anim-object-uic-trigger{
            display: inline-block;
        }
        `)}getAllAnimations(){return[...this.animation.animSet,...this.runtimeAnimation.animSet]}_getActiveIndex(e){if(!e.target)return"";const i=(1e3*(this._viewer?.timeline.time||0)-e.delay)/e.duration,n=e.offsets,s=n.reduce((l,c,h)=>Math.abs(c-i)<Math.abs(n[l]-i)?h:l,0);return Math.abs(n[s]-i)*e.duration<50?s.toString():""}get triggerButtonsShown(){return this._triggerButtonsShown}set triggerButtonsShown(e){const t=this._triggerButtonsShown!==e;this._triggerButtonsShown=e,e?document.body.classList.add("aouic-triggers-visible"):document.body.classList.remove("aouic-triggers-visible"),t&&e&&this._visibleBtns.forEach((i,n)=>{i.forEach(s=>this._refreshTriggerBtn(n,s))})}showTriggers(e=!0){this.triggerButtonsShown=e}rebuildTimeline(){this._refTimeline=!0}getTimeline(){return this._currentTimeline}addAnimation(e,t,i){return i=i||new f.AnimationObject,e!==void 0&&(i.access=e),t?.userData?(t.userData.animationObjects||(t.userData.animationObjects=[]),t.userData.animationObjects.includes(i)||(t.userData.animationObjects.push(i),this._addAnimationObject(i,t),this._setupUiConfig(t))):this.animation.animSet.includes(i)||this.animation.add(i),i}removeAnimation(e,t){t?.userData?(this._removeAnimationFromObject(e,t),this._removeAnimationObject(e),this._cleanUpUiConfig(t)):this.animation.remove(e)}_addAnimationObject(e,t){e.target=t,this.runtimeAnimation.add(e)}_removeAnimationObject(e){this.runtimeAnimation.remove(e),e.target=void 0}_removeAnimationFromObject(e,t){if(e.target=void 0,!t.userData.animationObjects)return;const i=t.userData.animationObjects.indexOf(e);i>=0&&(t.userData.animationObjects.splice(i,1),t.userData.animationObjects.length<1&&delete t.userData.animationObjects)}_setupUiConfig(e){!(e.isObject3D||e.isMaterial)||!e.uiConfig||e.uiConfig?.children?.find(n=>typeof n=="object"&&n.tags?.includes(Ua.PluginType))||(e.uiConfig?.children?.push({type:"folder",label:"Property Animations",tags:["animation",Ua.PluginType],children:[()=>e.userData.animationObjects?.map(n=>n.uiConfig)]}),this._setupUiConfigButtons(e),e.isObject3D&&e.addEventListener("objectUpdate",this._objectUpdate),e.isMaterial&&e.addEventListener("materialUpdate",this._objectUpdate))}_cleanUpUiConfig(e){this._cleanupUiConfigButtons(e);const t=this._iObservers.get(e);if(t&&(t.forEach(({o:n,btn:s})=>{n.disconnect(),s.remove()}),this._iObservers.delete(e)),e.isObject3D&&e.removeEventListener("objectUpdate",this._objectUpdate),e.isMaterial&&e.removeEventListener("materialUpdate",this._objectUpdate),!e.uiConfig)return;const i=e.uiConfig?.children?.findIndex(n=>typeof n=="object"&&n.tags?.includes(Ua.PluginType));i!==void 0&&i>=0&&e.uiConfig.children?.splice(i,1)}_setupUiConfigButtons(e){const t=this._animatableUiConfigs(e);for(const i of t)this.setupUiConfigButton(e,i)}_cleanupUiConfigButtons(e,t){const i=t??this._animatableUiConfigs(e);for(const n of i)this.cleanupUiConfigButton(n)}setupUiConfigButton(e,t,i){if(t._animTriggerInit)return;const n=tt(t.property);if(!n)return;const[s,a]=n;if(!s||typeof a!="string"||s!==e&&!i)return;const o=i?i.endsWith(".")?i+a:i:a,l=Pr({innerHTML:"◆",classList:["anim-object-uic-trigger"],addToBody:!1});l.parentElement&&l.remove(),l.dataset.isAnimObjectTrigger="1",l.title="Add Animation for "+tt(t.label,a),l.addEventListener("click",()=>{const u=this._viewer?.getPlugin("UndoManagerPlugin");let d=Zg(e,o);const p=1e3*(this._viewer?.timeline.time||0);if(d){if(d.values.length>1){const m=d,A=l.dataset.activeIndex||"",g=this._getActiveIndex(d);if(g===A){const y=parseInt(g||"-1"),v=()=>this._refreshTriggerBtn(m,l);u?(y<0?u.performAction(d,d.addKeyframe,[p],"addKeyframe-"+d.access,v):u.performAction(d,d.updateKeyframe,[y],"editKeyframe-"+d.access,v),v()):(y<0?d.addKeyframe(p):d.updateKeyframe(y),v())}else console.error("Active index mismatch",g,A)}}else{d=new f.AnimationObject,d.access=o,d.name=e.name+" "+(tt(t.label,o)||o),d.updateTarget=!0,d.delay=p,d.duration=2e3;const m=d,A={redo:()=>{e.userData.animationObjects||(e.userData.animationObjects=[]),e.userData.animationObjects.push(m),this._addAnimationObject(m,e),this._refreshTriggerBtn(m,l)},undo:()=>{m.removeFromParent(),this._refreshTriggerBtn(m,l)}};A.redo(),u?.undoManager?.record(A)}this._setBtnVisible(d,l,!0)});const c=new IntersectionObserver(u=>{const d=Zg(e,o);if(d)for(const p of u)p.target===l&&this._setBtnVisible(d,l,p.isIntersecting)});c.observe(l),this._iObservers.has(e)||this._iObservers.set(e,[]),this._iObservers.get(e)?.push({o:c,btn:l,key:o});const h=Zg(e,o);h&&this._refreshTriggerBtn(h,l),t._animTriggerInit=!0,t.domChildren=!t.domChildren||Array.isArray(t.domChildren)?[...t.domChildren||[],l]:t.domChildren}cleanupUiConfigButton(e){e&&(e.domChildren=Array.isArray(e.domChildren)?e.domChildren?.filter(t=>!(t instanceof HTMLElement&&t.dataset.isAnimObjectTrigger))||[]:e.domChildren)}_setBtnVisible(e,t,i){this._visibleBtns.has(e)||this._visibleBtns.set(e,new Set);const n=this._visibleBtns.get(e);i?n.has(t)||(t.classList.add("anim-object-uic-trigger-visible"),n.add(t)):(t.classList.remove("anim-object-uic-trigger-visible"),n.delete(t))}_animatableUiConfigs(e){return e.uiConfig?.children?.filter(t=>typeof t=="object"&&t.type&&["vec3","color","number","checkbox","toggle","slider"].includes(t.type)&&Array.isArray(t.property)&&t.property[0]===e&&(!e.constructor?.InterpolateProperties||e.constructor.InterpolateProperties.includes(t.property[1])))||[]}onAdded(e){super.onAdded(e),e.timeline.addEventListener("update",this._viewerTimelineUpdate),e._animGetters={objects:(t,i)=>{if(!e)return;const n=e.object3dManager.findObject(t);return{tar:n,acc:i,onChange:n?()=>{n.setDirty&&n.setDirty({refreshScene:!1,frameFade:!1})}:void 0}},materials:(t,i)=>{if(!e)return;const n=e.object3dManager.findMaterial(t);return{tar:n,acc:i,onChange:n?()=>{n.setDirty&&n.setDirty({frameFade:!1})}:void 0}}},this._setupUiConfig(e.scene),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.object3dManager.getMaterials().forEach(t=>this._materialAdd({material:t})),e.object3dManager.addEventListener("materialAdd",this._materialAdd),e.object3dManager.addEventListener("materialRemove",this._materialRemove)}onRemove(e){this._cleanUpUiConfig(e.scene),e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),e.object3dManager.removeEventListener("materialAdd",this._materialAdd),e.object3dManager.removeEventListener("materialRemove",this._materialRemove),e.object3dManager.getMaterials().forEach(t=>this._materialRemove({material:t})),delete e._animGetters,super.onRemove(e)}fromJSON(e,t){return super.fromJSON(e,t)?this:null}},Ua.PluginType="AnimationObjectPlugin",Ua);XW([G()],fP.prototype,"animation");let YW=fP;const Zg=(r,e)=>r?.userData.animationObjects?.find(t=>t.access===e);var $W=Object.defineProperty,KW=Object.getOwnPropertyDescriptor,pP=(r,e,t,i)=>{for(var n=i>1?void 0:i?KW(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&$W(e,t,n),n};f.ClearcoatTintPlugin=class extends mt{constructor(){super(),this.enabled=!0,this._uniforms={ccTintColor:{value:new ee},ccThickness:{value:0},ccIor:{value:0}},this.materialExtension={parsFragmentSnippet:(e,t)=>this.isDisabled()||!t?.userData._clearcoatTint?.enableTint||!(t.clearcoat>0)?"":ma`
uniform vec3 ccTintColor;
uniform float ccThickness;
uniform float ccIor;
vec3 clearcoatTint(const in float dotNV, const in float dotNL, const in float clearcoat) {
    vec3 tint = ( ccThickness > 0. ? 1. - ccTintColor : ccTintColor); // Set thickness < 0 for glow.
    tint = exp(tint * -(ccThickness * ((dotNL + dotNV) / max(dotNL * dotNV, 1e-3)))); // beer's law
    return mix(vec3(1.0), tint, clearcoat);
}
        `,shaderExtender:(e,t)=>{this.isDisabled()||!t?.userData._clearcoatTint?.enableTint||!(t.clearcoat>0)||(e.fragmentShader=bt(e.fragmentShader,"float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );","float dotNVcc = saturate( dot( geometryClearcoatNormal, -refract(geometryViewDir, geometryClearcoatNormal, 1./ccIor) ) );"),e.fragmentShader=bt(e.fragmentShader,"outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;",`outgoingLight *= clearcoatTint(dotNVcc, dotNVcc, material.clearcoat);
`,{prepend:!0}),e.defines&&(e.defines.USE_UV=""))},onObjectRender:(e,t)=>{const i=t.userData._clearcoatTint;i?.enableTint&&(this._uniforms.ccTintColor.value.set(i.tintColor),this._uniforms.ccThickness.value=i.thickness,this._uniforms.ccIor.value=i.ior,ba({CLEARCOAT_TINT_ENABLED:+!this.isDisabled()},t))},extraUniforms:{},computeCacheKey:e=>(this.isDisabled()?"0":"1")+(e.userData._clearcoatTint?.enableTint?"1":"0")+(e.clearcoat>0?"1":"0"),isCompatible:e=>e.isPhysicalMaterial,getUiConfig:e=>{const t=this._viewer;e.userData._clearcoatTint===void 0&&(e.userData._clearcoatTint={});const i=e.userData._clearcoatTint,n={type:"folder",label:"Clearcoat Tint",onChange:s=>{s.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return i.enableTint||!1},set value(s){s!==i.enableTint&&(s?f.ClearcoatTintPlugin.AddClearcoatTint(e)||t.dialog.alert("Cannot add clearcoat tint."):(i.enableTint=!1,e.setDirty&&e.setDirty()),n.uiRefresh?.(!0,"postFrame"))}},{type:"color",label:"Tint color",hidden:()=>!i.enableTint,property:[i,"tintColor"]},{type:"input",label:"Thickness",hidden:()=>!i.enableTint,property:[i,"thickness"]},{type:"slider",bounds:[.8,2.5],label:"IOR",hidden:()=>!i.enableTint,property:[i,"ior"]}]};return n}},this.setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()},Object.assign(this.materialExtension.extraUniforms,this._uniforms)}static AddClearcoatTint(e,t){const i=e?.userData;if(!i)return null;i._clearcoatTint||(i._clearcoatTint={});const n=i._clearcoatTint;return n.enableTint=!0,n.tintColor===void 0&&(n.tintColor="#ffffff"),n.thickness===void 0&&(n.thickness=.1),n.ior===void 0&&(n.ior=1.5),t&&Object.assign(n,t),e.setDirty&&e.setDirty(),n}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Sh)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Sh.name),super.onRemove(e)}},f.ClearcoatTintPlugin.PluginType="ClearcoatTintPlugin",f.ClearcoatTintPlugin.CLEARCOAT_TINT_GLTF_EXTENSION="WEBGI_materials_clearcoat_tint",pP([se("Enabled",r=>({onChange:r.setDirty})),G()],f.ClearcoatTintPlugin.prototype,"enabled",2),f.ClearcoatTintPlugin=pP([vt("Clearcoat Tint (MatExt)")],f.ClearcoatTintPlugin);class JW{constructor(e){this.parser=e,this.name=Sh.name}async extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return;const s=n.extensions[this.name];t.userData||(t.userData={}),f.ClearcoatTintPlugin.AddClearcoatTint(t),We.Deserialize(s,t.userData._clearcoatTint)}}const Sh={name:"WEBGI_materials_clearcoat_tint",import:r=>new JW(r),export:r=>({writeMaterial:(e,t)=>{if(!e.isMeshStandardMaterial||!e.userData._clearcoatTint?.enableTint)return;t.extensions=t.extensions||{};const i=We.Serialize(e.userData._clearcoatTint);t.extensions[Sh.name]=i,r.extensionsUsed[Sh.name]=!0}}),textures:void 0},ZW=`#include <randomHelpers>
#include <voronoiNoise>
uniform vec2 noiseBumpParams;uniform float noiseBumpScale;uniform float noiseBumpFlakeScale;uniform float noiseFlakeClamp;uniform float noiseFlakeRadius;uniform bool useColorFlakes;uniform vec4 flakeParams;uniform vec3 flakeFallOffParams;vec3 perturbNormalArb_nb(vec3 surf_pos,vec3 surf_norm,vec2 dHdxy,float faceDirection){
#ifdef BUMP_MAP_SCALE_LEGACY
vec3 vSigmaX=(dFdx(surf_pos.xyz));vec3 vSigmaY=(dFdy(surf_pos.xyz));
#else
vec3 vSigmaX=normalize(dFdx(surf_pos.xyz));vec3 vSigmaY=normalize(dFdy(surf_pos.xyz));
#endif
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);}`,e8=`vec3 outColor,outColor1,outColor2,outColor3,outColor4,outColor5;float distFac=length(vViewPosition.xyz);/*float e=floor(log2(0.3*distFac+3.0)/0.3785116);float level_z=0.1*pow(1.3,e)-0.2;*/float level=1.;vec2 uvMod=noiseBumpFlakeScale*noiseBumpParams.xy*vUv*level;float voronoiDist=clamp(voronoi_f1_2d(uvMod,1.,noiseFlakeClamp,noiseFlakeRadius,outColor),0.0,1.0);vec3 oldNormal=normal;normal=perturbNormalArb_nb(-vViewPosition,normal,(2.*outColor.xy-1.)*noiseBumpScale,faceDirection);float oldRoughnessFactor=roughnessFactor;float oldMetalnessFactor=metalnessFactor;roughnessFactor=mix(roughnessFactor,flakeParams.x,1.-voronoiDist);metalnessFactor=mix(metalnessFactor,flakeParams.y,1.-voronoiDist);
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
vec3 sparkleRadiance=getIBLRadiance(normalize(vViewPosition),normal,roughnessFactor);float sparkleIntensity=length(sparkleRadiance);float sparkleIntensityMultiplier=sparkleIntensity>1.3 ? flakeParams.z : 1.;vec3 oldDiffuseColor=diffuseColor.rgb;vec2 cellPosition_=floor(uvMod);vec3 colorRGB=useColorFlakes ? hash3(cellPosition_): vec3(1.);float fallOff_=mix(1.,1./(1.+flakeFallOffParams.y*distFac+flakeFallOffParams.z*distFac*distFac),flakeFallOffParams.x);diffuseColor.rgb*=mix(vec3(1.),sparkleIntensityMultiplier*colorRGB*fallOff_,vec3(1.-voronoiDist));if(sparkleIntensity<flakeParams.w){float mixFactor=1.;roughnessFactor=mix(roughnessFactor,oldRoughnessFactor,mixFactor);metalnessFactor=mix(metalnessFactor,oldMetalnessFactor,mixFactor);normal=normalize(mix(normal,oldNormal,mixFactor));diffuseColor.rgb=mix(diffuseColor.rgb,oldDiffuseColor,mixFactor);}
#endif
`;var t8=Object.defineProperty,i8=Object.getOwnPropertyDescriptor,mP=(r,e,t,i)=>{for(var n=i>1?void 0:i?i8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&t8(e,t,n),n};f.NoiseBumpMaterialPlugin=class extends mt{constructor(){super(),this.enabled=!0,this._uniforms={noiseBumpParams:{value:new K},noiseBumpScale:{value:.05},noiseBumpFlakeScale:{value:1e3},noiseFlakeClamp:{value:1},noiseFlakeRadius:{value:.5},flakeParams:{value:new et(0,1,3,0)},flakeFallOffParams:{value:new S(0,1,0)},useColorFlakes:{value:!1}},this.materialExtension={parsFragmentSnippet:(e,t)=>this.isDisabled()||!t?.userData._noiseBumpMat?.hasBump?"":ZW,shaderExtender:(e,t)=>{this.isDisabled()||!t?.userData._noiseBumpMat?.hasBump||(e.fragmentShader=bt(e.fragmentShader,"#glMarker beforeAccumulation",e8,{prepend:!0}),e.defines&&(e.defines.USE_UV=""),e.extensionDerivatives=!0)},onObjectRender:(e,t)=>{const i=t.userData._noiseBumpMat;i?.hasBump&&(Array.isArray(i.bumpNoiseParams)?this._uniforms.noiseBumpParams.value.fromArray(i.bumpNoiseParams):this._uniforms.noiseBumpParams.value.copy(i.bumpNoiseParams),this._uniforms.noiseBumpScale.value=i.bumpScale,this._uniforms.noiseBumpFlakeScale.value=i.flakeScale,this._uniforms.noiseFlakeClamp.value=i.flakeClamp,this._uniforms.noiseFlakeRadius.value=i.flakeRadius,Array.isArray(i.flakeParams)?this._uniforms.flakeParams.value.fromArray(i.flakeParams):this._uniforms.flakeParams.value.copy(i.flakeParams),Array.isArray(i.flakeFallOffParams)?this._uniforms.flakeFallOffParams.value.fromArray(i.flakeFallOffParams):this._uniforms.flakeFallOffParams.value.copy(i.flakeFallOffParams),this._uniforms.useColorFlakes.value=i.useColorFlakes,ba({NOISE_BUMP_MATERIAL_ENABLED:+!this.isDisabled()},t))},extraUniforms:{},computeCacheKey:e=>(this.isDisabled()?"0":"1")+(e.userData._noiseBumpMat?.hasBump?"1":"0"),isCompatible:e=>e.isPhysicalMaterial,getUiConfig:e=>{const t=this._viewer;e.userData._noiseBumpMat===void 0&&(e.userData._noiseBumpMat={});const i=e.userData._noiseBumpMat,n={type:"folder",label:"SparkleBump (NoiseBump)",onChange:s=>{s.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return i.hasBump||!1},set value(s){s!==i.hasBump&&(s?f.NoiseBumpMaterialPlugin.AddNoiseBumpMaterial(e)||t.dialog.alert("Cannot add NoiseBumpMaterial."):(i.hasBump=!1,e.setDirty&&e.setDirty()),n.uiRefresh?.(!0,"postFrame"))}},{type:"vec4",label:"Bump Noise Params",bounds:[0,1],hidden:()=>!i.hasBump,property:[i,"bumpNoiseParams"]},{type:"slider",label:"Bump Scale",bounds:[0,.001],stepSize:1e-5,hidden:()=>!i.hasBump,property:[i,"bumpScale"]},{type:"slider",label:"Flake Scale",bounds:[100,1e4],stepSize:1e-4,hidden:()=>!i.hasBump,property:[i,"flakeScale"]},{type:"slider",label:"Flake Clamp",bounds:[0,1],stepSize:1,hidden:()=>!i.hasBump,property:[i,"flakeClamp"]},{type:"slider",label:"Flake Radius",bounds:[.01,1],stepSize:.001,hidden:()=>!i.hasBump,property:[i,"flakeRadius"]},{type:"slider",label:"Flake Roughness",bounds:[0,1],stepSize:.01,hidden:()=>!i.hasBump,property:[i.flakeParams,"x"]},{type:"slider",label:"Flake Metalness",bounds:[0,1],stepSize:.01,hidden:()=>!i.hasBump,property:[i.flakeParams,"y"]},{type:"slider",label:"Flake Strength",bounds:[0,100],stepSize:.001,hidden:()=>!i.hasBump,property:[i.flakeParams,"z"]},{type:"slider",label:"Flake Threshold",bounds:[.1,10],stepSize:.001,hidden:()=>!i.hasBump,property:[i.flakeParams,"w"]},{type:"slider",label:"Falloff",stepSize:1,bounds:[0,1],hidden:()=>!i.hasBump,property:[i.flakeFallOffParams,"x"]},{type:"slider",label:"Linear falloff factor",bounds:[0,10],stepSize:.001,hidden:()=>!i.hasBump,property:[i.flakeFallOffParams,"y"]},{type:"slider",label:"Quadratic falloff factor",bounds:[0,10],stepSize:.001,hidden:()=>!i.hasBump,property:[i.flakeFallOffParams,"z"]},{type:"checkbox",label:"Colored Flakes",hidden:()=>!i.hasBump,property:[i,"useColorFlakes"]}]};return n}},this.setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()},Object.assign(this.materialExtension.extraUniforms,this._uniforms)}static AddNoiseBumpMaterial(e,t){const i=e?.userData;if(!i)return!1;i._noiseBumpMat||(i._noiseBumpMat={});const n=i._noiseBumpMat;return n.hasBump=!0,n.bumpNoiseParams===void 0&&(n.bumpNoiseParams=new K(.5,.5)),n.bumpScale===void 0&&(n.bumpScale=.05),n.flakeScale===void 0&&(n.flakeScale=.05),n.flakeClamp===void 0&&(n.flakeClamp=1),n.flakeRadius===void 0&&(n.flakeRadius=.3),n.useColorFlakes===void 0&&(n.useColorFlakes=!1),n.flakeParams===void 0&&(n.flakeParams=new et(0,1,3,0)),n.flakeFallOffParams===void 0&&(n.flakeFallOffParams=new S(0,1,0)),t&&Object.assign(n,t),e.setDirty&&e.setDirty(),!0}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Eh)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Eh.name),super.onRemove(e)}},f.NoiseBumpMaterialPlugin.PluginType="NoiseBumpMaterialPlugin",f.NoiseBumpMaterialPlugin.NOISE_BUMP_MATERIAL_GLTF_EXTENSION="WEBGI_materials_noise_bump",mP([se("Enabled",r=>({onChange:r.setDirty})),G()],f.NoiseBumpMaterialPlugin.prototype,"enabled",2),f.NoiseBumpMaterialPlugin=mP([vt("Noise/Sparkle Bump (MatExt)")],f.NoiseBumpMaterialPlugin);class n8{constructor(e){this.parser=e,this.name=Eh.name}async extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return;const s=n.extensions[this.name];t.userData||(t.userData={}),f.NoiseBumpMaterialPlugin.AddNoiseBumpMaterial(t),We.Deserialize(s,t.userData._noiseBumpMat)}}const Eh={name:"WEBGI_materials_noise_bump",import:r=>new n8(r),export:r=>({writeMaterial:(e,t)=>{if(!e.isMeshStandardMaterial||!e.userData._noiseBumpMat?.hasBump)return;t.extensions=t.extensions||{};const i=We.Serialize(e.userData._noiseBumpMat);t.extensions[Eh.name]=i,r.extensionsUsed[Eh.name]=!0}}),textures:void 0},s8=`#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0
#if CUSTOM_BUMP_MAP_BICUBIC > 0
vec4 cubic_cb(float v){vec4 n=vec4(1.0,2.0,3.0,4.0)-v;vec4 s=n*n*n;float x=s.x;float y=s.y-4.0*s.x;float z=s.z-4.0*s.y+6.0*s.x;float w=6.0-x-y-z;return vec4(x,y,z,w)*(1.0/6.0);}vec4 textureBicubic_cb(sampler2D sampler,vec2 texCoords){vec2 texSize=vec2(textureSize(sampler,0));vec2 invTexSize=1.0/texSize;texCoords=texCoords*texSize-0.5;vec2 fxy=fract(texCoords);texCoords-=fxy;vec4 xcubic=cubic_cb(fxy.x);vec4 ycubic=cubic_cb(fxy.y);vec4 c=texCoords.xxyy+vec2(-0.5,+1.5).xyxy;vec4 s=vec4(xcubic.xz+xcubic.yw,ycubic.xz+ycubic.yw);vec4 offset=c+vec4(xcubic.yw,ycubic.yw)/s;offset*=invTexSize.xxyy;vec4 sample0=texture(sampler,offset.xz);vec4 sample1=texture(sampler,offset.yz);vec4 sample2=texture(sampler,offset.xw);vec4 sample3=texture(sampler,offset.yw);float sx=s.x/(s.x+s.y);float sy=s.z/(s.z+s.w);return mix(mix(sample3,sample2,sx),mix(sample1,sample0,sx),sy);}
#endif
varying vec2 vCustomBumpUv;uniform sampler2D customBumpMap;uniform float customBumpScale;vec2 dHdxy_fwd_cb(){vec2 dSTdx=dFdx(vCustomBumpUv);vec2 dSTdy=dFdy(vCustomBumpUv);
#if CUSTOM_BUMP_MAP_BICUBIC > 0
float Hll=customBumpScale*textureBicubic_cb(customBumpMap,vCustomBumpUv).x;float dBx=customBumpScale*textureBicubic_cb(customBumpMap,vCustomBumpUv+dSTdx).x-Hll;float dBy=customBumpScale*textureBicubic_cb(customBumpMap,vCustomBumpUv+dSTdy).x-Hll;
#else
float Hll=customBumpScale*texture2D(customBumpMap,vCustomBumpUv).x;float dBx=customBumpScale*texture2D(customBumpMap,vCustomBumpUv+dSTdx).x-Hll;float dBy=customBumpScale*texture2D(customBumpMap,vCustomBumpUv+dSTdy).x-Hll;
#endif
return vec2(dBx,dBy);}
#ifndef USE_BUMPMAP
vec3 perturbNormalArb(vec3 surf_pos,vec3 surf_norm,vec2 dHdxy,float faceDirection){
#ifdef BUMP_MAP_SCALE_LEGACY
vec3 vSigmaX=(dFdx(surf_pos.xyz));vec3 vSigmaY=(dFdy(surf_pos.xyz));
#else
vec3 vSigmaX=normalize(dFdx(surf_pos.xyz));vec3 vSigmaY=normalize(dFdy(surf_pos.xyz));
#endif
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
#endif
`;var r8=Object.defineProperty,a8=Object.getOwnPropertyDescriptor,Eb=(r,e,t,i)=>{for(var n=i>1?void 0:i?a8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&r8(e,t,n),n};f.CustomBumpMapPlugin=class extends mt{constructor(){super(),this.enabled=!0,this.bicubicFiltering=!0,this._defines={CUSTOM_BUMP_MAP_DEBUG:!1,CUSTOM_BUMP_MAP_BICUBIC:!0},this._uniforms={customBumpUvTransform:{value:new At},customBumpScale:{value:.001},customBumpMap:{value:null}},this.materialExtension={parsFragmentSnippet:(e,t)=>this.isDisabled()||!t?.userData._hasCustomBump?"":s8,shaderExtender:(e,t)=>{this.isDisabled()||!t?.userData._hasCustomBump||!t.userData._customBumpMap||(e.fragmentShader=bt(e.fragmentShader,"#glMarker beforeAccumulation",`
#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0
    normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd_cb(), faceDirection );
#endif
                `,{prepend:!0}),e.vertexShader=bt(e.vertexShader,"#include <uv_pars_vertex>",`
#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0
    varying vec2 vCustomBumpUv;
    uniform mat3 customBumpUvTransform;
#endif
                `,{prepend:!0}),e.vertexShader=bt(e.vertexShader,"#include <uv_vertex>",`
#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0
    vCustomBumpUv = ( customBumpUvTransform * vec3( uv, 1 ) ).xy;
#endif
                `,{prepend:!0}),e.defines&&(e.defines.USE_UV=""))},onObjectRender:(e,t)=>{const i=t.userData;if(!i?._hasCustomBump||!e.isMesh||!e.geometry)return;const n=i._customBumpMap?.isTexture?i._customBumpMap:null;this._uniforms.customBumpMap.value=n,this._uniforms.customBumpScale.value=n?i._customBumpScale??0:0,n&&(n.updateMatrix(),this._uniforms.customBumpUvTransform.value.copy(n.matrix)),ba({...this._defines,CUSTOM_BUMP_MAP_ENABLED:+this.enabled},t)},extraUniforms:{},computeCacheKey:e=>(this.enabled?"1":"0")+(e.userData._hasCustomBump?"1":"0")+e.userData?._customBumpMap?.uuid,isCompatible:e=>e.isPhysicalMaterial,getUiConfig:e=>{const t=this._viewer,i=this.enableCustomBump.bind(this),n=e.userData,s={type:"folder",label:"CustomBumpMap",onChange:a=>{a.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return n._hasCustomBump||!1},set value(a){a!==n._hasCustomBump&&(a?i(e)||t.dialog.alert("CustomBumpMapPlugin - Cannot add CustomBumpMap."):(n._hasCustomBump=!1,e.setDirty&&e.setDirty()),s.uiRefresh?.(!0,"postFrame"))}},{type:"slider",label:"Bump Scale",bounds:[-20,20],stepSize:.001,hidden:()=>!n._hasCustomBump,property:[n,"_customBumpScale"]},{type:"image",label:"Bump Map",hidden:()=>!n._hasCustomBump,property:[n,"_customBumpMap"],onChange:()=>{e.setDirty&&e.setDirty()}},Ii(n,"_customBumpMap","Sampler",()=>!n._hasCustomBump,()=>e.setDirty&&e.setDirty())]};return s}},this.setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()},Object.assign(this.materialExtension.extraUniforms,this._uniforms)}enableCustomBump(e,t,i){const n=e?.userData;if(!n)return!1;if(n._hasCustomBump===void 0){const s=e.appliedMeshes;let a=!0;if(s)for(const{geometry:o}of s)o&&(!o.attributes.position||!o.attributes.normal||!o.attributes.uv)&&(a=!1);if(!a)return!1}return n._hasCustomBump=!0,n._customBumpScale=i??n._customBumpScale??.001,n._customBumpMap=t??n._customBumpMap??null,e.setDirty&&e.setDirty(),!0}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Mh)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Mh.name),super.onRemove(e)}},f.CustomBumpMapPlugin.PluginType="CustomBumpMapPlugin",f.CustomBumpMapPlugin.CUSTOM_BUMP_MAP_GLTF_EXTENSION="WEBGI_materials_custom_bump_map",Eb([se("Enabled",r=>({onChange:r.setDirty})),G()],f.CustomBumpMapPlugin.prototype,"enabled",2),Eb([se("Bicubic",r=>({onChange:r.setDirty})),Tm("CUSTOM_BUMP_MAP_BICUBIC",void 0,!0,f.CustomBumpMapPlugin.prototype.setDirty),G()],f.CustomBumpMapPlugin.prototype,"bicubicFiltering",2),f.CustomBumpMapPlugin=Eb([vt("Custom BumpMap (MatExt)")],f.CustomBumpMapPlugin);class o8{constructor(e,t){this._viewer=t,this.parser=e,this.name=Mh.name}async extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return;const s=n.extensions[this.name];t.userData||(t.userData={}),t.userData._hasCustomBump=!0,t.userData._customBumpScale=s.customBumpScale??0;const a=s.resources?await this._viewer?.loadConfigResources(s.resources):void 0,o=[],l=s.customBumpMap;return l&&(l&&l.resource&&typeof l.resource=="string"?t.userData._customBumpMap=We.Deserialize(l,null,a,!1):l&&l.index!==void 0?o.push(i.assignTexture(t.userData,"_customBumpMap",l).then(c=>{c.colorSpace=Ct})):(console.warn("CustomBumpMapPlugin: Invalid Texture Map in extension",l,n.name),t.userData._customBumpMap=null)),Promise.all(o)}}const Mh={name:"WEBGI_materials_custom_bump_map",import:(r,e)=>new o8(r,e),export:r=>({writeMaterial:(e,t)=>{if(!e.isMeshStandardMaterial||!e.userData._hasCustomBump||(e.userData._customBumpScale||0)<.001)return;t.extensions=t.extensions||{};const i={images:{},textures:{}},n={};n.customBumpScale=e.userData._customBumpScale||1;const s=e.userData._customBumpMap?.userData.rootPath;if(s&&Hc(s)&&(n.customBumpMap=We.Serialize(e.userData._customBumpMap,i,!1)),r.checkEmptyMap(e.userData._customBumpMap)&&n.customBumpMap===void 0){const a={index:r.processTexture(e.userData._customBumpMap)};r.applyTextureTransform(a,e.userData._customBumpMap),n.customBumpMap=a}(Object.keys(i.textures).length||Object.keys(i.images).length)&&(n.resources=i),t.extensions[Mh.name]=n,r.extensionsUsed[Mh.name]=!0}}),textures:{customBumpMap:"RGB"}},l8=`
#ifdef USE_BUMPMAP
mat3 mat3_inverse(mat3 A){mat3 M_t=mat3(vec3(A[0][0],A[1][0],A[2][0]),vec3(A[0][1],A[1][1],A[2][1]),vec3(A[0][2],A[1][2],A[2][2]));float det=dot(cross(M_t[0],M_t[1]),M_t[2]);mat3 adjugate=mat3(cross(M_t[1],M_t[2]),cross(M_t[2],M_t[0]),cross(M_t[0],M_t[1]));return adjugate/det;}float CalculateHeight(in vec2 texCoords){float height=texture2D(bumpMap,texCoords).x;return clamp(height,0.0,1.0);}const vec2 bumpMapSize=vec2(512,512);vec3 CalculateNormal(in vec2 texCoords){
#if defined( TANGENTSPACE_NORMALMAP ) && 0
vec3 mapN=texture2D(normalMap,texCoords).xyz;mapN.xy*=normalScale;return normalize(mapN);
#else
vec2 texOffs=1.0/bumpMapSize;
#if PARALLAX_NORMAL_MAP_QUALITY > 0
float hx[9];hx[0]=texture2D(bumpMap,texCoords.st+texOffs*vec2(-1.0,-1.0)).r;hx[1]=texture2D(bumpMap,texCoords.st+texOffs*vec2(0.0,-1.0)).r;hx[2]=texture2D(bumpMap,texCoords.st+texOffs*vec2(1.0,-1.0)).r;hx[3]=texture2D(bumpMap,texCoords.st+texOffs*vec2(-1.0,0.0)).r;hx[4]=texture2D(bumpMap,texCoords.st).r;hx[5]=texture2D(bumpMap,texCoords.st+texOffs*vec2(1.0,0.0)).r;hx[6]=texture2D(bumpMap,texCoords.st+texOffs*vec2(-1.0,1.0)).r;hx[7]=texture2D(bumpMap,texCoords.st+texOffs*vec2(0.0,1.0)).r;hx[8]=texture2D(bumpMap,texCoords.st+texOffs*vec2(1.0,1.0)).r;vec2 deltaH=vec2(hx[0]-hx[2]+2.0*(hx[3]-hx[5])+hx[6]-hx[8],hx[0]-hx[6]+2.0*(hx[1]-hx[7])+hx[2]-hx[8]);
#else
float h_xa=texture2D(bumpMap,texCoords.st+texOffs*vec2(-1.0,0.0)).r;float h_xb=texture2D(bumpMap,texCoords.st+texOffs*vec2(1.0,0.0)).r;float h_ya=texture2D(bumpMap,texCoords.st+texOffs*vec2(0.0,-1.0)).r;float h_yb=texture2D(bumpMap,texCoords.st+texOffs*vec2(0.0,1.0)).r;vec2 deltaH=vec2(h_xa-h_xb,h_ya-h_yb);
#endif
return normalize(vec3(deltaH/texOffs,1.0));
#endif
}vec3 ReliefParallax(in float frontFace,in vec3 texDir3D,in vec2 texCoord){float surf_sign=frontFace;float back_face=step(0.0,-surf_sign);vec2 texStep=surf_sign*texDir3D.xy/abs(texDir3D.z);vec2 texC=texCoord.st+surf_sign*texStep+back_face*texStep.xy;float mapHeight=1.0;float bumpHeightStep=1.0/float(PARALLAX_MAP_STEPS);float bestBumpHeight=mapHeight+bumpHeightStep;
#pragma unroll_loop_start
for(int i=0;i<PARALLAX_MAP_STEPS;i++){if(mapHeight<bestBumpHeight){bestBumpHeight-=bumpHeightStep;mapHeight=back_face+surf_sign*CalculateHeight(texC.xy-bestBumpHeight*texStep.xy);}}
#pragma unroll_loop_end
bestBumpHeight+=bumpHeightStep;
#pragma unroll_loop_start
for(int i=0;i<PARALLAX_MAP_B_STEPS;i++){bumpHeightStep*=0.5;bestBumpHeight-=bumpHeightStep;mapHeight=back_face+surf_sign*CalculateHeight(texC.xy-bestBumpHeight*texStep.xy);bestBumpHeight+=(bestBumpHeight<mapHeight)? bumpHeightStep : 0.0;}
#pragma unroll_loop_end
bestBumpHeight-=bumpHeightStep*clamp((bestBumpHeight-mapHeight)/bumpHeightStep,0.0,1.0);mapHeight=bestBumpHeight;texC-=mapHeight*texStep;return vec3(texC.xy,mapHeight);}vec3 reliefParallaxPerturbNormal(in float faceDirection,inout vec3 normal){if(abs(bumpScale)<0.001)return vec3(vBumpMapUv,0.);float parallaxHeight;vec2 texCoords=vBumpMapUv;float face_sign=sign(dot(normal,vViewPosition));vec3 N=normalize(normal);vec3 dp1=dFdx(-vViewPosition);vec3 dp2=dFdy(-vViewPosition);vec2 duv1=dFdx(vBumpMapUv);vec2 duv2=dFdy(vBumpMapUv);vec3 dp2perp=cross(dp2,N);vec3 dp1perp=cross(N,dp1);vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;vec3 B=dp2perp*duv1.y+dp1perp*duv2.y;float invmax=inversesqrt(max(dot(T,T),dot(B,B)));mat3 tbnMat=mat3(T*invmax,B*invmax,N*bumpScale);vec3 tangentPos=normalize(mat3_inverse(tbnMat)*-vViewPosition);vec3 parallaxUv=ReliefParallax(face_sign,tangentPos,vBumpMapUv);tbnMat[2]=face_sign*N/bumpScale;normal=normalize(tbnMat*CalculateNormal(parallaxUv.xy).xyz);
#ifdef FLIP_SIDED
normal=-normal;
#endif
return parallaxUv;}
#endif
`;var c8=Object.defineProperty,h8=Object.getOwnPropertyDescriptor,Th=(r,e,t,i)=>{for(var n=i>1?void 0:i?h8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&c8(e,t,n),n};f.ParallaxMappingPlugin=class extends mt{constructor(e=!0){super(),this.enabled=!0,this.stepCount=12,this.binaryStepCount=3,this.debugNormals=!1,this.debugHitHeight=!1,this._defines={PARALLAX_NORMAL_MAP_QUALITY:0},this._bumpMapExtension={shaderExtender:(t,i,n)=>{if(!(!i.bumpMap||this.isDisabled())){t.fragmentShader=t.fragmentShader.replace("#include <normal_fragment_begin>",""),t.fragmentShader=t.fragmentShader.replace("#include <normal_fragment_maps>",""),t.fragmentShader=t.fragmentShader.replace("#include <map_fragment>",`#include <normal_fragment_begin>
#include <normal_fragment_maps>
#include <map_fragment>`);for(const s of["map_fragment","alphamap_fragment","roughnessmap_fragment","metalnessmap_fragment","emissivemap_fragment","transmission_fragment"])t.fragmentShader=bt(t.fragmentShader,`#include <${s}>`,lt[s].replace(/\bv\w+Uv\b/g,"parallaxUv.xy",{replaceAll:!0}));(this.debugNormals||this.debugHitHeight)&&(t.fragmentShader=bt(t.fragmentShader,"texture2D( map, parallaxUv.xy )",this.debugNormals?"vec4(normal, 1.); normal = nonPerturbedNormal":"vec4(parallaxUv.z,0., 0., 1.)")),t.fragmentShader=bt(t.fragmentShader,"#include <normal_fragment_maps>",bt(bt(lt.normal_fragment_maps,"#elif defined( USE_NORMALMAP_TANGENTSPACE )","#elif defined( USE_NORMALMAP_TANGENTSPACE ) && !defined( USE_BUMPMAP )"),"normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );","vec3 parallaxUv = reliefParallaxPerturbNormal(faceDirection, normal);"))}},parsFragmentSnippet:()=>this.isDisabled()?"":(l8+`
`).replaceAll("PARALLAX_MAP_STEPS",this.stepCount.toString()).replaceAll("PARALLAX_MAP_B_STEPS",this.binaryStepCount.toString()),isCompatible:t=>t.isPhysicalMaterial,computeCacheKey:t=>""+!this.isDisabled()+t.bumpMap?.uuid+this.debugNormals+this.debugHitHeight+this.stepCount.toString()+this.binaryStepCount.toString(),onObjectRender:(t,i,n)=>{this.isDisabled()||ba({...this._defines},i)}},this.enabled=e,this._updateExtension=this._updateExtension.bind(this)}_updateExtension(){this._bumpMapExtension?.setDirty?.(),this._viewer?.setDirty()}onAdded(e){return e.materialManager.registerMaterialExtension(this._bumpMapExtension),super.onAdded(e)}onRemove(e){return e.materialManager.unregisterMaterialExtension(this._bumpMapExtension),super.onRemove(e)}},f.ParallaxMappingPlugin.PluginType="ReliefParallaxMapping",Th([he(f.ParallaxMappingPlugin.prototype._updateExtension),G(),se("Enabled")],f.ParallaxMappingPlugin.prototype,"enabled",2),Th([Fe("Step count",[1,32],1),he(f.ParallaxMappingPlugin.prototype._updateExtension),G()],f.ParallaxMappingPlugin.prototype,"stepCount",2),Th([Fe("Binary search steps",[1,8],1),he(f.ParallaxMappingPlugin.prototype._updateExtension),G()],f.ParallaxMappingPlugin.prototype,"binaryStepCount",2),Th([he(f.ParallaxMappingPlugin.prototype._updateExtension),se("Debug Normals")],f.ParallaxMappingPlugin.prototype,"debugNormals",2),Th([he(f.ParallaxMappingPlugin.prototype._updateExtension),se("Debug Hit Height")],f.ParallaxMappingPlugin.prototype,"debugHitHeight",2),f.ParallaxMappingPlugin=Th([vt("Parallax Bump Mapping (MatExt)")],f.ParallaxMappingPlugin);const u8=`#include <simpleCameraHelpers>
uniform vec4 fragClippingPosition;uniform vec4 fragClippingParams;uniform float fragClippingCamAspect;
#if FRAG_CLIPPING_MODE == FragmentClippingMode.Circle
float fragClippingCircle(){vec2 pos=viewToScreen(vViewPosition.xyz).xy;float radius=fragClippingParams.x;vec2 center=fragClippingPosition.xy;pos.y/=fragClippingCamAspect;center.y/=fragClippingCamAspect;return length(pos-center)-radius;}
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Ellipse
float fragClippingEllipse(){vec2 pos=viewToScreen(vViewPosition.xyz).xy;vec2 radius=fragClippingParams.xy;vec2 center=fragClippingPosition.xy;pos.y/=fragClippingCamAspect;center.y/=fragClippingCamAspect;return length((pos-center)/radius)-1.0;}
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Rectangle
float fragClippingRectangle(){vec2 pos=viewToScreen(vViewPosition.xyz).xy;vec2 radius=fragClippingParams.xy;vec2 center=fragClippingPosition.xy;pos.y/=fragClippingCamAspect;center.y/=fragClippingCamAspect;vec2 d=abs(pos-center)-radius;return min(max(d.x,d.y),0.0)+length(max(d,0.0));}
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Plane
float fragClippingPlane(){vec3 pos=vViewPosition.xyz;vec3 normal=fragClippingParams.xyz;float d=dot(pos,normal)-fragClippingParams.w;return d;}
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Sphere
float fragClippingSphere(){vec3 pos=vViewPosition.xyz;vec3 center=fragClippingPosition.xyz;float radius=fragClippingParams.x;pos.y/=fragClippingCamAspect;center.y/=fragClippingCamAspect;return length(pos-center)-radius;}
#endif
`,d8=`float fragClippingDist=0.0;
#if FRAG_CLIPPING_MODE == FragmentClippingMode.Circle
fragClippingDist=fragClippingCircle();
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Ellipse
fragClippingDist=fragClippingEllipse();
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Rectangle
fragClippingDist=fragClippingRectangle();
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Plane
fragClippingDist=fragClippingPlane();
#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Sphere
fragClippingDist=fragClippingSphere();
#endif
#if FRAG_CLIPPING_DEBUG
gl_FragColor=vec4(max(fragClippingDist,0.0),0.0,0.0,1.0);
#include <colorspace_fragment>
return;
#endif
#if FRAG_CLIPPING_INVERSE == 1
if(fragClippingDist>0.0)discard;
#else
if(fragClippingDist<0.0)discard;
#endif
`;var f8=Object.defineProperty,p8=Object.getOwnPropertyDescriptor,gP=(r,e,t,i)=>{for(var n=i>1?void 0:i?p8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&f8(e,t,n),n};f.FragmentClippingExtensionPlugin=class extends mt{constructor(){super(),this.enabled=!0,this._defines={FRAG_CLIPPING_DEBUG:0},this._uniforms={fragClippingPosition:{value:new et},fragClippingParams:{value:new et},fragClippingCamAspect:{value:1}},this._plane=new Es,this._viewNormalMatrix=new At,this._v4=new et,this.materialExtension={parsFragmentSnippet:(e,t)=>!this.enabled||!t?.userData._fragmentClippingExt?.clipEnabled?"":Object.entries(nf).map(i=>["FragmentClippingMode."+i[0],""+i[1]]).reduce((i,n)=>i.replace(n[0],n[1]),u8),shaderExtender:(e,t)=>{!this.enabled||!t?.userData._fragmentClippingExt?.clipEnabled||(e.fragmentShader=bt(e.fragmentShader,"#glMarker mainStart",Object.entries(nf).map(i=>["FragmentClippingMode."+i[0],""+i[1]]).reduce((i,n)=>i.replace(n[0],n[1]),`
`+d8),{append:!0}))},onObjectRender:(e,t)=>{let i=t.userData._fragmentClippingExt;if(t.userData.isGBufferMaterial&&e&&e.material&&!Array.isArray(e.material)&&(i=e.material?.userData._fragmentClippingExt),!!i?.clipEnabled){if(Array.isArray(i.clipPosition)?this._uniforms.fragClippingPosition.value.fromArray(i.clipPosition):this._uniforms.fragClippingPosition.value.copy(i.clipPosition),i.clipMode===3&&i.clipParams){const n=Array.isArray(i.clipParams)?this._v4.fromArray(i.clipParams):this._v4.copy(i.clipParams),s=this._viewer.scene.mainCamera.matrixWorldInverse;this._plane.normal.set(n.x,n.y,n.z),this._plane.constant=n.w,this._viewNormalMatrix.getNormalMatrix(s),this._plane.applyMatrix4(s,this._viewNormalMatrix),this._uniforms.fragClippingParams.value.set(this._plane.normal.x,this._plane.normal.y,this._plane.normal.z,this._plane.constant)}else Array.isArray(i.clipPosition)?this._uniforms.fragClippingParams.value.fromArray(i.clipParams):this._uniforms.fragClippingParams.value.copy(i.clipParams);this._viewer?.scene.mainCamera.isPerspectiveCamera?this._uniforms.fragClippingCamAspect.value=this._viewer?.scene.mainCamera.aspect:this._uniforms.fragClippingCamAspect.value=1,ba({...this._defines,FRAG_CLIPPING_MODE:+(i.clipMode??0),FRAG_CLIPPING_INVERSE:+(i.clipInvert??!1)},t)}},extraUniforms:{},computeCacheKey:e=>(this.enabled?"1":"0")+(e.userData._fragmentClippingExt?.clipEnabled?"1":"0"),isCompatible:e=>e.isPhysicalMaterial||e.userData.isGBufferMaterial,getUiConfig:e=>{const t=this._viewer;e.userData._fragmentClippingExt===void 0&&(e.userData._fragmentClippingExt={});const i=e.userData._fragmentClippingExt,n={type:"folder",label:"Fragment Clipping",onChange:s=>{s.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return i.clipEnabled||!1},set value(s){s!==i.clipEnabled&&(s?f.FragmentClippingExtensionPlugin.AddFragmentClipping(e)||t.dialog.alert("Cannot add FragmentClippingExtension."):(i.clipEnabled=!1,e.setDirty&&e.setDirty()),n.uiRefresh?.(!0,"postFrame"))}},{type:"dropdown",label:"Mode",children:Object.entries(nf).map(s=>({label:s[0],value:s[1]})),hidden:()=>!i.clipEnabled,property:[i,"clipMode"]},{type:"vec4",label:"Position",bounds:[-1,1],hidden:()=>!i.clipEnabled,property:[i,"clipPosition"]},{type:"vec4",label:"Params",bounds:[0,1],hidden:()=>!i.clipEnabled,property:[i,"clipParams"]},{type:"toggle",label:"Invert",hidden:()=>!i.clipEnabled,property:[i,"clipInvert"]}]};return n}},this.setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()},Object.assign(this.materialExtension.extraUniforms,this._uniforms)}static AddFragmentClipping(e,t){const i=e?.userData;if(!i)return!1;i._fragmentClippingExt||(i._fragmentClippingExt={});const n=i._fragmentClippingExt;return n.clipEnabled=!0,n.clipPosition===void 0&&(n.clipPosition=[0,0,0,0]),n.clipParams===void 0&&(n.clipParams=[0,0,0,0]),n.clipMode===void 0!==void 0&&(n.clipMode=0),n.clipInvert===void 0!==void 0&&(n.clipInvert=!1),t&&Object.assign(n,t),e.setDirty&&e.setDirty(),!0}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Ih)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Ih.name),super.onRemove(e)}},f.FragmentClippingExtensionPlugin.PluginType="FragmentClippingExtensionPlugin1",f.FragmentClippingExtensionPlugin.FRAGMENT_CLIPPING_EXTENSION_GLTF_EXTENSION="WEBGI_materials_fragment_clipping_extension",gP([se("Enabled",r=>({onChange:r.setDirty})),G()],f.FragmentClippingExtensionPlugin.prototype,"enabled",2),f.FragmentClippingExtensionPlugin=gP([vt("Fragment Clipping (MatExt)")],f.FragmentClippingExtensionPlugin);var nf=(r=>(r[r.Circle=0]="Circle",r[r.Ellipse=1]="Ellipse",r[r.Rectangle=2]="Rectangle",r[r.Plane=3]="Plane",r[r.Sphere=4]="Sphere",r))(nf||{});class m8{constructor(e){this.parser=e,this.name=Ih.name}async extendMaterialParams(e,t){const n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return;const s=n.extensions[this.name];t.userData||(t.userData={}),f.FragmentClippingExtensionPlugin.AddFragmentClipping(t),We.Deserialize(s,t.userData._fragmentClippingExt)}}const Ih={name:"WEBGI_materials_fragment_clipping",import:r=>new m8(r),export:r=>({writeMaterial:(e,t)=>{if(!e.isMeshStandardMaterial||!e.userData._fragmentClippingExt?.clipEnabled)return;t.extensions=t.extensions||{};const i=We.Serialize(e.userData._fragmentClippingExt);t.extensions[Ih.name]=i,r.extensionsUsed[Ih.name]=!0}}),textures:void 0};var g8=Object.defineProperty,A8=Object.getOwnPropertyDescriptor,AP=(r,e,t,i)=>{for(var n=i>1?void 0:i?A8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&g8(e,t,n),n};f.VirtualCamerasPlugin=class extends mt{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.cameras=[],this._viewerListeners={preRender:()=>{if(this.isDisabled()||!this._viewer)return;const t=this._viewer;for(const i of this.cameras){if(!i.enabled)continue;const n=i.camera;try{this.dispatchEvent({type:"preRenderCamera",camera:i}),t.scene.renderCamera=n,t.renderManager.render(t.scene,!1);const s=t.renderManager.composer.readBuffer.texture;this.dispatchEvent({type:"preBlitCamera",camera:i,readBuffer:s}),t.renderManager.blit(i.target,{source:s}),this.dispatchEvent({type:"postRenderCamera",camera:i})}catch(s){if(t.console.error(s),i.enabled=!1,t.debug)throw s}}}},this._objectExtension={uuid:"VirtualCameraPluginExt",isCompatible:t=>t.isCamera,getUiConfig:t=>{if(t.isCamera)return[{type:"button",label:"Add Virtual Camera",hidden:()=>!!this.cameras.find(i=>i.camera===t),onClick:()=>{if(this._viewer)return this.addCamera(t,void 0,!0),t.setDirty&&t.setDirty(),()=>{this.removeCamera(t),t.setDirty&&t.setDirty()}}},{type:"button",label:"Virtual Camera Enabled",hidden:()=>!this.cameras.find(i=>i.camera===t),getValue:()=>{const i=this.cameras.find(n=>n.camera===t);return i?i.enabled:!1},setValue:()=>{const i=this.cameras.find(n=>n.camera===t);return i?(i.enabled=!i.enabled,i.enabled):!1}},{type:"button",label:"Remove Virtual Camera",hidden:()=>!this.cameras.find(i=>i.camera===t),onClick:()=>{if(this._viewer)return this.removeCamera(t),t.setDirty&&t.setDirty(),()=>{this.addCamera(t,void 0,!0),t.setDirty&&t.setDirty()}}}]}},this.enabled=e}onAdded(e){super.onAdded(e),e.object3dManager.registerObjectExtension(this._objectExtension)}onRemove(e){e.object3dManager.unregisterObjectExtension(this._objectExtension),super.onRemove(e)}addCamera(e,t,i=!1){if(!this._viewer)throw"Plugin not added to viewer";t=t??this._viewer.renderManager.composerTarget.clone(!0),t.name=e.name+"_virtualCamTarget";const n={camera:e,target:t,enabled:!0};return this.cameras.push(n),i&&this._viewer.getPlugin("RenderTargetPreviewPlugin")?.addTarget(t,e.name,!1,!1,!0),n}removeCamera(e){if(!this._viewer)throw"Plugin not added to viewer";const t=this.cameras.findIndex(i=>i.camera===e);if(t>=0){const i=this.cameras[t];return this.cameras.splice(t,1),this._viewer.getPlugin("RenderTargetPreviewPlugin")?.removeTarget(i.target),i.target.dispose(),!0}return!1}},f.VirtualCamerasPlugin.PluginType="VirtualCamerasPlugin",AP([se()],f.VirtualCamerasPlugin.prototype,"enabled",2),f.VirtualCamerasPlugin=AP([vt("Virtual Cameras")],f.VirtualCamerasPlugin);var y8=Object.defineProperty,vo=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&y8(e,t,n),n};const eA={cascades:3,shadowMapSize:2048,shadowBias:void 0,lightNear:void 0,lightFar:void 0,lightMargin:200},Ra=(Js=class extends mt{constructor(e=!0){super(),this.enabled=!0,this.parent=new Vi,this.maxFar=1e5,this.mode="practical",this.attachToFirstLight=!0,this.frustums=[],this.breaks=[],this.extendedBreaks=[],this.lights=[],this._lightRef=void 0,this._lightUpdate=t=>{t?.object===this.light&&this.refreshLights(t)},this._refreshingLights=!1,this.refreshLights=t=>{if(!this._refreshingLights){this._refreshingLights=!0;try{this._refreshLightsInner(t)}finally{this._refreshingLights=!1}}},this._refreshLightsInner=t=>{if(this._lightRef&&this._lightRef!==this.light&&(this._lightRef.removeEventListener("objectUpdate",this._lightUpdate),this._lightAutoAttached&&(this._lightAutoAttached=!1),this._lightRef=void 0),!this.light||(this._lightRef||(this.light.addEventListener("objectUpdate",this._lightUpdate),this._lightRef=this.light),this.isDisabled()))return;this.light.castShadow=!1,this.light.visible=!1,this.parent.visible=!0;let i=this.light.userData[Js.PluginType];i||(i={},this.light.userData[Js.PluginType]=i);const n={...eA,...i};for(let a=0;a<n.cascades;a++){if(!this.lights[a]){const l=new sl(16777215,1);l.name="CSM Light "+a,this.lights.push(l),this.parent.add(l),this.parent.add(l.target)}const o=this.lights[a];o.intensity=this.light.intensity,o.color.set(this.light.color),o.castShadow=!0,o.shadow.mapSize.width=n.shadowMapSize,o.shadow.mapSize.height=n.shadowMapSize,o.shadow.camera.near=n.lightNear??this.light.shadow.camera.near,o.shadow.camera.far=n.lightFar??this.light.shadow.camera.far,o.shadow.bias=n.shadowBias??this.light.shadow.bias,o.shadow.normalBias=this.light.shadow.normalBias,o.shadow.radius=this.light.shadow.radius}if(this.lights.length>n.cascades){const a=this.lights.splice(n.cascades,this.lights.length-n.cascades);for(const o of a)this.parent.remove(o.target),this.parent.remove(o)}const s=t?.change??t?.key;!s&&!["intensity","castShadow","mapSize","bias","radius","shadow","deserialize"].includes(s)&&this.cameraNeedsUpdate()},this._mainCameraChange=t=>{this.camera=t.camera,this.cameraNeedsUpdate()},this._cameraUpdated=!1,this._mainCameraUpdate=t=>{t.projectionUpdated!==!1?this.cameraNeedsUpdate():this.setDirty()},this.cameraNeedsUpdate=()=>{this._cameraUpdated=!0,this._viewer?.setDirty()},this._needsUpdate=!1,this.setDirty=()=>{const t=!this.isDisabled();t!==this._lastEnabled&&(this._lastEnabled=t,this.refreshLights(),t||(this.light&&(this.light.castShadow=!0,this.light.visible=!0,this.parent.visible=!1,this.light.setDirty&&this.light.setDirty()),this.extendedBreaks.length=0,this._sversion++,this.materialExtension.setDirty&&this.materialExtension.setDirty(),this._viewer?.setDirty())),t&&(this._needsUpdate=!0,this._viewer?.setDirty())},this._viewerListeners={preRender:()=>{if(this.isDisabled()||!this.light)return;let t=!1;this._cameraUpdated&&(this._updateFrustums(),t=!0),this._needsUpdate&&!this.update()&&(t=!0),t&&this._viewer?.renderManager.resetShadows()}},this._lastCenters=[],this._lightAutoAttached=!1,this.refreshAttachedLight=()=>{if(this.light&&this._lightAutoAttached){this.light.parent||(this.light=void 0,this._lightAutoAttached=!1);return}if(!this.attachToFirstLight)return;const t=this._viewer?.object3dManager.getLights()||[];for(const i of t)if(i.isDirectionalLight&&i.castShadow){if(i===this.light)return;this._lightAutoAttached=!0,this.light=i;return}},this._sversion=0,this._updateFrustums=()=>{if(!this.light)return;const{cascades:t=eA.cascades}=this.light.userData[Js.PluginType]||{},i=this._getBreaks(t);this._initCascades(i),this._updateShadowBounds(),this.extendedBreaks.length=0;for(let n=0;n<i.length;n++){const s=i[n];this.extendedBreaks.push(new K(i[n-1]||0,s))}this._sversion++,this.materialExtension.setDirty&&this.materialExtension.setDirty(),this._cameraUpdated=!1,this.setDirty()},this.materialExtension={extraDefines:{CSM_CASCADES:()=>this.cascades.toString(),USE_CSM:()=>this.light&&!this.isDisabled()?"1":void 0,CSM_FADE:()=>this.fade?"1":void 0},extraUniforms:{},computeCacheKey:()=>(this.isDisabled()?"1":"0")+this.lights.length+(this.fade?"1":"0")+this.light?.uuid,onObjectRender:(t,i)=>{if(this.isDisabled()||!this.light){i.extraUniformsToUpload.CSM_cascades&&(i.extraUniformsToUpload.CSM_cascades.needsUpdate=!1),i.extraUniformsToUpload.cameraNear&&(i.extraUniformsToUpload.cameraNear.needsUpdate=!1),i.extraUniformsToUpload.shadowFar&&(i.extraUniformsToUpload.shadowFar.needsUpdate=!1);return}i.extraUniformsToUpload||(i.extraUniformsToUpload={}),i.extraUniformsToUpload.CSM_cascades||(i.extraUniformsToUpload.CSM_cascades={value:[]}),i.extraUniformsToUpload.cameraNear||(i.extraUniformsToUpload.cameraNear={value:0}),i.extraUniformsToUpload.shadowFar||(i.extraUniformsToUpload.shadowFar={value:0}),i.__csmVersion||(i.__csmVersion=0),i.extraUniformsToUpload.cameraNear.needsUpdate=!0,i.extraUniformsToUpload.shadowFar.needsUpdate=!0,i.extraUniformsToUpload.CSM_cascades.needsUpdate=!0,i.__csmVersion!==this._sversion&&(i.__csmVersion=this._sversion,i.extraUniformsToUpload.cameraNear.value=this.camera?.near??.01,i.extraUniformsToUpload.shadowFar.value=Math.min(this.camera?.far??1e3,this.maxFar),i.extraUniformsToUpload.CSM_cascades.value=this.extendedBreaks)},isCompatible:t=>t.isMeshStandardMaterial||t.isMeshPhysicalMaterial||t.isMeshLambertMaterial||t.isMeshPhongMaterial},this.uiConfig={type:"folder",label:"Cascaded Shadows (CSM)",children:[...bi(this),{type:"button",label:()=>this.light?"Select Light":"No Light Attached",disabled:()=>!this.light,onClick:()=>{this.light&&this.light.dispatchEvent({type:"select",ui:!0,value:this.light,object:this.light})}}]},this._lightDirection=new S,this._cameraToLightMatrix=new fe,this._lightSpaceFrustum=new sf,this._center=new S,this._bbox=new en,this._uniformArray=[],this._logArray=[],this._lightOrientationMatrix=new fe,this._lightOrientationMatrixInverse=new fe,this._up=new S(0,1,0),this.injectInclude(),this._lastEnabled=e,this.enabled=e,this.mainFrustum=new sf}setLightParams(e,t){if(t=t||this.light,!t){this._viewer?.console.warn("CascadedShadowsPlugin: No light attached to CascadedShadowsPlugin");return}let i=t.userData[Js.PluginType];i||(i={},t.userData[Js.PluginType]=i),Object.assign(i,e),t===this.light&&this.refreshLights()}onAdded(e){super.onAdded(e),e.scene.addEventListener("mainCameraChange",this._mainCameraChange),e.scene.addEventListener("mainCameraUpdate",this._mainCameraUpdate),e.renderManager.addEventListener("resize",this.cameraNeedsUpdate),this.camera=e.scene.mainCamera,e.materialManager.registerMaterialExtension(this.materialExtension),e.object3dManager.addEventListener("lightAdd",this.refreshAttachedLight),e.object3dManager.addEventListener("lightRemove",this.refreshAttachedLight),this.refreshAttachedLight(),e.scene.addObject(this.parent,{addToRoot:!0,indexInParent:0}),this.refreshLights()}onRemove(e){e.scene.removeEventListener("mainCameraChange",this._mainCameraChange),e.scene.removeEventListener("mainCameraUpdate",this._mainCameraUpdate),e.renderManager.removeEventListener("resize",this.cameraNeedsUpdate),e.materialManager.unregisterMaterialExtension(this.materialExtension),e.object3dManager.removeEventListener("lightAdd",this.refreshAttachedLight),e.object3dManager.removeEventListener("lightRemove",this.refreshAttachedLight),this.refreshAttachedLight(),this.light&&this._lightAutoAttached&&(this.light=void 0,this._lightAutoAttached=!1);for(const t of this.lights)this.parent.remove(t.target),this.parent.remove(t);this.parent.clear(),this.parent.removeFromParent(),this.camera=void 0,super.onRemove(e)}_initCascades(e){const t=this.camera;return t?(t.updateProjectionMatrix&&t.updateProjectionMatrix(),this.mainFrustum.setFromProjectionMatrix(t.projectionMatrix,this.maxFar),this.mainFrustum.split(e,this.frustums),this.frustums):this.frustums}_updateShadowBounds(){for(let e=0;e<this.frustums.length;e++){const i=this.lights[e].shadow.camera,n=this.frustums[e],s=n.vertices.near,a=n.vertices.far,o=a[0];let l;o.distanceTo(a[2])>o.distanceTo(s[2])?l=a[2]:l=s[2];let c=o.distanceTo(l);if(this.fade&&this.camera){const h=this.camera,u=Math.max(h.far,this.maxFar),d=n.vertices.far[0].z/(u-h.near),p=.25*Math.pow(d,2)*(u-h.near);c+=p}i.left=-c/2,i.right=c/2,i.top=c/2,i.bottom=-c/2,i.updateProjectionMatrix()}}_getBreaks(e){this.breaks.length=0;const t=this.camera;if(!t)return this.breaks;const i=Math.min(t.far,this.maxFar);let n=this.mode;switch(n==="custom"&&this.customSplitsCallback===void 0&&(console.error("CSM: Custom split scheme callback not defined."),n="practical"),n){case"uniform":this._uniformSplit(e,t.near,i,this.breaks);break;case"logarithmic":this._logarithmicSplit(e,t.near,i,this.breaks);break;case"practical":default:this._practicalSplit(e,t.near,i,.5,this.breaks);break;case"custom":this.customSplitsCallback&&this.customSplitsCallback(e,t.near,i,this.breaks);break}return this.breaks}_uniformSplit(e,t,i,n){for(let s=1;s<e;s++)n.push((t+(i-t)*s/e)/i);n.push(1)}_logarithmicSplit(e,t,i,n){for(let s=1;s<e;s++)n.push(t*(i/t)**(s/e)/i);n.push(1)}_practicalSplit(e,t,i,n,s){this._uniformArray.length=0,this._logArray.length=0,this._logarithmicSplit(e,t,i,this._logArray),this._uniformSplit(e,t,i,this._uniformArray);for(let a=1;a<e;a++)s.push(Ft.lerp(this._uniformArray[a-1],this._logArray[a-1],n));s.push(1)}update(){this._needsUpdate=!1;const e=this.camera;if(!e||!this.light)return!0;const t=this.frustums,{shadowMapSize:i=eA.shadowMapSize,lightMargin:n=eA.lightMargin}=this.light.userData[Js.PluginType]||{};{this.light.updateMatrixWorld();const o=this.light.getWorldPosition(this._center);this.light.target.updateMatrixWorld(),this.light.target.getWorldPosition(this._lightDirection),this._lightOrientationMatrix.lookAt(o,this._lightDirection,this._up),this._lightOrientationMatrixInverse.copy(this._lightOrientationMatrix).invert(),this._lightDirection.sub(o).normalize()}const s=[];for(let o=0;o<t.length;o++){const l=this.lights[o],c=l.shadow.camera,h=(c.right-c.left)/i,u=(c.top-c.bottom)/i;this._cameraToLightMatrix.multiplyMatrices(this._lightOrientationMatrixInverse,e.matrixWorld),t[o].toSpace(this._cameraToLightMatrix,this._lightSpaceFrustum);const d=this._lightSpaceFrustum.vertices.near,p=this._lightSpaceFrustum.vertices.far;this._bbox.makeEmpty();for(let m=0;m<4;m++)this._bbox.expandByPoint(d[m]),this._bbox.expandByPoint(p[m]);this._bbox.getCenter(this._center),this._center.z=this._bbox.max.z+n,this._center.x=Math.floor(this._center.x/h)*h,this._center.y=Math.floor(this._center.y/u)*u,this._center.applyMatrix4(this._lightOrientationMatrix),s.push(this._center.clone()),l.position.copy(this._center),l.target.position.copy(this._center).add(this._lightDirection)}let a=!0;if(s.length===this._lastCenters.length){for(let o=0;o<s.length;o++)if(Math.abs(s[o].x-this._lastCenters[o].x)+Math.abs(s[o].y-this._lastCenters[o].y)+Math.abs(s[o].z-this._lastCenters[o].z)>.001){a=!1;break}}else a=!1;return this._lastCenters=s,a}get cascades(){return this.isDisabled()||!this.light?0:this.frustums.length}injectInclude(){lt.lights_fragment_begin.includes("defined( USE_CSM ) && defined( CSM_CASCADES )")||(lt.lights_fragment_begin=bt(lt.lights_fragment_begin,`#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
`,`
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES )

	DirectionalLight directionalLight;
	float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear);
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif

	#if defined( USE_SHADOWMAP ) && defined( CSM_FADE )
		vec2 cascade;
		float cascadeCenter;
		float closestEdge;
		float margin;
		float csmx;
		float csmy;

		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {

			directionalLight = directionalLights[ i ];
			getDirectionalLightInfo( directionalLight, directLight );

			#if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
			
            #if ( UNROLLED_LOOP_INDEX < CSM_CASCADES )

				// NOTE: Depth gets larger away from the camera.
				// cascade.x is closer, cascade.y is further
				cascade = CSM_cascades[ UNROLLED_LOOP_INDEX ];
				cascadeCenter = ( cascade.x + cascade.y ) / 2.0;
				closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y;
				margin = 0.25 * pow( closestEdge, 2.0 );
				csmx = cascade.x - margin / 2.0;
				csmy = cascade.y + margin / 2.0;
				if( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) {

					float dist = min( linearDepth - csmx, csmy - linearDepth );
					float ratio = clamp( dist / margin, 0.0, 1.0 );

					vec3 prevColor = directLight.color;
					directionalLightShadow = directionalLightShadows[ i ];
					directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;

					bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter;
					directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 );

					ReflectedLight prevLight = reflectedLight;
					RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

					bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter;
					float blendRatio = shouldBlend ? ratio : 1.0;

					reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio );
					reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio );
					reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio );
					reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio );

				}
				
				
            #else 
            
                directionalLightShadow = directionalLightShadows[ i ];
                directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
    
                RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

			#endif
			
			#endif

		}
		#pragma unroll_loop_end
	#elif defined (USE_SHADOWMAP)

		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {

			directionalLight = directionalLights[ i ];
			getDirectionalLightInfo( directionalLight, directLight );

			#if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )

                directionalLightShadow = directionalLightShadows[ i ];
				
				#if ( UNROLLED_LOOP_INDEX < CSM_CASCADES )

					if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;

					if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

				#else

					directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;

					RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

				#endif
				
			#endif

		}
		#pragma unroll_loop_end

	#elif ( NUM_DIR_LIGHT_SHADOWS > 0 )
		// note: no loop here - all CSM lights are in fact one light only
		getDirectionalLightInfo( directionalLights[0], directLight );
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

	#endif

	#if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS)
		// compute the lights not casting shadows (if any)

		#pragma unroll_loop_start
		for ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) {

			directionalLight = directionalLights[ i ];

			getDirectionalLightInfo( directionalLight, directLight );

			RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

		}
		#pragma unroll_loop_end

	#endif

#endif


#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !( defined( USE_CSM ) && defined( CSM_CASCADES ) )
`),lt.lights_pars_begin=`
#if defined( USE_CSM ) && defined( CSM_CASCADES )
uniform vec2 CSM_cascades[CSM_CASCADES];
uniform float cameraNear;
uniform float shadowFar;
#endif
	`+lt.lights_pars_begin)}},Js.PluginType="CascadedShadowsPlugin",Js);vo([se(),G(),he("setDirty")],Ra.prototype,"enabled"),vo([he("cameraNeedsUpdate"),G(),He()],Ra.prototype,"maxFar"),vo([he("cameraNeedsUpdate"),G(),Li(void 0,["uniform","logarithmic","practical"])],Ra.prototype,"mode"),vo([se(),G()],Ra.prototype,"attachToFirstLight"),vo([he("cameraNeedsUpdate"),G(),se()],Ra.prototype,"fade"),vo([he("refreshLights")],Ra.prototype,"light"),vo([he("cameraNeedsUpdate")],Ra.prototype,"customSplitsCallback"),vo([ct()],Ra.prototype,"refreshAttachedLight");let _8=Ra;class sf{constructor(e={}){this._inverseProjectionMatrix=new fe,this.vertices={near:[new S,new S,new S,new S],far:[new S,new S,new S,new S]},e.projectionMatrix!==void 0&&this.setFromProjectionMatrix(e.projectionMatrix,e.maxFar||1e4)}setFromProjectionMatrix(e,t){const i=e.elements[11]===0;return this._inverseProjectionMatrix.copy(e).invert(),this.vertices.near[0].set(1,1,-1),this.vertices.near[1].set(1,-1,-1),this.vertices.near[2].set(-1,-1,-1),this.vertices.near[3].set(-1,1,-1),this.vertices.near.forEach(n=>{n.applyMatrix4(this._inverseProjectionMatrix)}),this.vertices.far[0].set(1,1,1),this.vertices.far[1].set(1,-1,1),this.vertices.far[2].set(-1,-1,1),this.vertices.far[3].set(-1,1,1),this.vertices.far.forEach(n=>{n.applyMatrix4(this._inverseProjectionMatrix);const s=Math.abs(n.z);i?n.z*=Math.min(t/s,1):n.multiplyScalar(Math.min(t/s,1))}),this.vertices}split(e,t){for(;e.length>t.length;)t.push(new sf);t.length=e.length;for(let i=0;i<e.length;i++){const n=t[i];if(i===0)for(let s=0;s<4;s++)n.vertices.near[s].copy(this.vertices.near[s]);else for(let s=0;s<4;s++)n.vertices.near[s].lerpVectors(this.vertices.near[s],this.vertices.far[s],e[i-1]);if(i===e.length-1)for(let s=0;s<4;s++)n.vertices.far[s].copy(this.vertices.far[s]);else for(let s=0;s<4;s++)n.vertices.far[s].lerpVectors(this.vertices.near[s],this.vertices.far[s],e[i])}}toSpace(e,t){for(let i=0;i<4;i++)t.vertices.near[i].copy(this.vertices.near[i]).applyMatrix4(e),t.vertices.far[i].copy(this.vertices.far[i]).applyMatrix4(e)}}var v8=Object.defineProperty,yP=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&v8(e,t,n),n};const Mb=(So=class extends mt{constructor(){super(),this.enabled=!0,this._uiNeedRefresh=!1,this.applyOnLoad=!0,this.applyOnLoadForce=!1,this.variations=[],this._selectedMaterial=()=>{const e=this._picking?.getSelectedObject();if(e){if(e.isMaterial)return e;{const t=e?.material||void 0;return Array.isArray(t)?t[0]:t}}},this._uicShowAllVariations=!1,this.uiConfig={label:"Material Configurator",type:"folder",children:[()=>[{type:"input",label:"uuid",property:[this._selectedMaterial(),"uuid"],hidden:()=>!this._selectedMaterial(),disabled:!0},this.createVariationsUiConfig(this.getSelectedVariation())??(this._uicShowAllVariations?{}:{type:"button",label:"Select a material to see or add variations",readOnly:!0}),this._uicShowAllVariations&&!this._selectedMaterial()?this.variations.map(e=>this.createVariationsUiConfig(e)):[],{type:"button",label:"Clear variations",hidden:()=>!this.getSelectedVariation(),value:async()=>{const e=this.getSelectedVariation();e&&await this._viewer.dialog.confirm("Material configurator: Remove all variations for this material?")&&(e.materials=[]),this.refreshUi()}},{type:"button",label:"Remove completely",hidden:()=>!this.getSelectedVariation(),value:async()=>{const e=this.getSelectedVariation();e&&await this._viewer.dialog.confirm("Material configurator: Remove this variation?")&&this.removeVariation(e)}},{type:"button",label:"Add Variation",hidden:()=>!this._selectedMaterial(),value:async()=>{const e=this._selectedMaterial();e&&(!e.name&&!await this._viewer?.dialog.confirm("Material configurator: Material has no name. Use uuid instead?")||this.addVariation(e))}},{type:"button",label:"Refresh Ui",value:()=>this.refreshUi()},{type:"button",label:"Apply All",value:()=>{this.variations.forEach(e=>this.applyVariation(e,e.materials[0].uuid))}},{type:"checkbox",label:"Show All",hidden:()=>this._selectedMaterial(),property:()=>[this,"_uicShowAllVariations"],onChange:async()=>this.uiConfig?.uiRefresh?.()}]]},this.addEventListener("deserialize",this.refreshUi),this.refreshUi=this.refreshUi.bind(this),this._preFrame=this._preFrame.bind(this),this._refreshUi=this._refreshUi.bind(this),this._refreshUiConfig=this._refreshUiConfig.bind(this)}onAdded(e){super.onAdded(e),e.forPlugin(vs,t=>{this._picking=t,this._picking?.addEventListener("selectedObjectChanged",this._refreshUiConfig)},()=>{this._picking?.removeEventListener("selectedObjectChanged",this._refreshUiConfig),this._picking=void 0},this),this._previewGenerator=new ME,e.addEventListener("preFrame",this._refreshUi),e.addEventListener("preFrame",this._preFrame)}reapplyAll(){this.variations.forEach(async e=>{e.selectedIndex!==void 0&&this.applyVariation(e,e.selectedIndex)})}fromJSON(e,t){return this.variations=[],super.fromJSON(e,t)?((this.applyOnLoadForce&&e.applyOnLoad!==!1||e.applyOnLoad!==void 0&&this.applyOnLoad)&&this.reapplyAll(),this):null}onRemove(e){return this._previewGenerator?.dispose(),this._previewGenerator=void 0,this._picking?.removeEventListener("selectedObjectChanged",this._refreshUiConfig),this.removeEventListener("deserialize",this.refreshUi),e.removeEventListener("preFrame",this._refreshUi),e.removeEventListener("preFrame",this._preFrame),this._picking=void 0,super.onRemove(e)}findVariation(e){return e?this.variations.find(t=>t.regex??!0?e.match(typeof t.uuid=="string"?"^"+t.uuid+"$":t.uuid)!==null:t.uuid===e):void 0}getSelectedVariation(){const e=this._selectedMaterial();if(!e)return;const t=this.findVariation(e.uuid)||this.findVariation(e.name);return t&&t.regex===void 0&&(t.regex=!0),t}applyVariation(e,t,i,n){const s=this._viewer?.materialManager;if(!s)return!1;const a=this.findMaterialVariation(t,e);if(!a)return!1;i&&(e.selectedIndex=e.materials.indexOf(a));const o=n?.from!==void 0?this.findMaterialVariation(n.from,e):void 0;return s.applyMaterial(a,e.uuid,e.regex??!0,n?.from!==void 0?{...n,from:o}:n)}findMaterialVariation(e,t){return typeof e=="string"?t.materials.find(i=>i.uuid===e):t.materials[e]}async applyVariationAnimate(e,t,i=500){e._animation&&e._animation.stop();const n=this._viewer?.getPlugin(Gr);if(!n)throw new Error("MaterialConfiguratorBasePlugin - PopmotionPlugin is required for animation, please add it to the viewer.");this._viewer?.getPlugin(f.FrameFadePlugin)?.disable(So.PluginType);const s=n.animateNumber({duration:i,onUpdate:(a,o)=>{this.applyVariation(e,t,!0,{t:a,dt:o})},onComplete:()=>{this.applyVariation(e,t,!0,{t:1,dt:0})},onEnd:()=>{e._animation===s&&(e._animation=void 0)}});e._animation=s,await e._animation?.promise,this._viewer?.getPlugin(f.FrameFadePlugin)?.enable(So.PluginType)}getPreview(e,t,i=!0){if(!this._viewer)return"";const n=e;if(!n)return"";let s="";if(t.startsWith("generate:"))s=this._previewGenerator.generate(n,this._viewer.renderManager.renderer,this._viewer.scene.environment,t.split(":")[1]);else{const a=n[t]||"#ff00ff";s=a.image?PS(a.image,100):"",s.length||(s=BS(a.isColor?a.getHexString():a))}return i&&this._viewer.setDirty(),s}refreshUi(){this.isDisabled()||!this._viewer||tt(this.uiConfig.hidden)||(this.dispatchEvent({type:"refreshUi"}),this._uiNeedRefresh=!0)}_refreshUiConfig(){this.isDisabled()||this.uiConfig.uiRefresh?.(!0,"postFrame",500)}async _refreshUi(){return this.isDisabled()||!this._viewer||!this._uiNeedRefresh?!1:(this._uiNeedRefresh=!1,this._refreshUiConfig(),!0)}_preFrame(){if(this.isDisabled()||!this._viewer?.timeline.shouldRun()||!this.variations.length)return!1;const e=this._viewer?.timeline.time,t=this._viewer?.timeline.delta||0,i=this._viewer?.timeline.resetOnEnd??!1;let n=!1;for(const s of this.variations){if(!s.timeline?.length)continue;const a=s.selectedIndex,o=s.timeline.sort((d,p)=>-d.time+p.time),l=o.find(d=>d.time<=e),c=l?o.indexOf(l):-1,h=c<o.length-1&&c>=0?o[c+1]:i&&c>0?o[0]:void 0,u=!this._viewer?.timeline.running;if(l){const d=typeof a>"u"||l.index!==a&&(typeof a!="number"||l.index!==s.materials[a]?.uuid);if(u||d){const p=l.time,m=l.duration??.5;let A=m<1e-6?1:(e-p)/m,g=m<1e-6?0:t/m;A>1&&(A=1),g<1e-6&&(g=1/60),this.applyVariation(s,l.index,A>=1-1e-5,{t:A,dt:g,from:u?h?.index:void 0,rm:this._viewer?.renderManager}),n=!0}}}return n}createVariationsUiConfig(e){if(e)return{type:"folder",label:e.title,uuid:e.uuid,children:[{type:"input",label:"mapping",property:()=>[e,"uuid"],onChange:async()=>this.refreshUi()},{type:"input",label:"title",property:()=>[e,"title"],onChange:async()=>this.refreshUi()},{type:"dropdown",label:"Preview Type",property:()=>[e,"preview"],onChange:async()=>this.refreshUi(),children:["generate:sphere","generate:cube","color","map","emissive",...Object.keys(si.MaterialProperties).filter(t=>t.endsWith("Map"))].map(t=>({label:t,value:t}))},{type:"checkbox",label:"regex mapping",property:()=>[e,"regex"],onChange:async()=>this.refreshUi()},...e.materials.map(t=>t.uiConfig?Object.assign(t.uiConfig,{expanded:!1}):{})]}}removeVariationForMaterial(e){let t=this.findVariation(e.uuid);!t&&e.name.length>0&&(t=this.findVariation(e.name)),t&&this.removeVariation(t)}removeVariation(e){e&&(this.variations.splice(this.variations.indexOf(e),1),this.refreshUi())}addVariation(e,t,i=!0){const n=i&&e?.clone?e.clone():e;if(e&&n){let s=this.findVariation(t??e.uuid);!s&&!t&&e.name.length>0&&(s=this.findVariation(e.name)),s||(s=this.createVariation(e,t)),s.materials.push(n),this.refreshUi()}}createVariation(e,t){return this.variations.push({uuid:t??e.name.length>0?Hu(e.name):e.uuid,title:e.name.length>0?e.name:"No Name",preview:"generate:sphere",materials:[],regex:!0}),this.variations[this.variations.length-1]}},So.PluginType="MaterialConfiguratorPlugin",So);yP([G()],Mb.prototype,"applyOnLoad"),yP([G()],Mb.prototype,"variations");let b8=Mb;var w8=Object.defineProperty,_P=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&w8(e,t,n),n};const iw=class iw extends mt{constructor(){super(),this.enabled=!0,this._uiNeedRefresh=!1,this.refreshScene=!0,this.applyOnLoad=!0,this.variations=[],this._selectedSwitchNode=()=>{const e=this._picking?.getSelectedObject();if(!e?.isObject3D)return;const t=this.variations.map(n=>n.name);let i;return e.traverseAncestors(n=>{i||n.name&&t.includes(n.name)&&(i=n)}),i},this.autoSnapIcons=!1,this.uiConfig={label:"Switch Node Plugin",type:"folder",children:[{type:"checkbox",label:"Enabled",property:[this,"enabled"]},()=>[{type:"folder",label:"All nodes",expanded:!0,children:[this.variations.map(e=>({type:"input",label:e.title,property:[e,"name"],onChange:()=>this.refreshUi()}))]},{type:"button",label:"Add Node",value:()=>{this.addNode({name:"switch_node",selected:"",title:"Switch Node",camView:"front",camDistance:1})}},{type:"button",label:"Refresh UI",value:()=>this.refreshUi()},{type:"input",label:"Selected node title",hidden:()=>!this._selectedSwitchNode(),property:()=>{const e=this._selectedSwitchNode();return e?[this.variations.find(t=>t.name===e.name),"title"]:[]},onChange:()=>this.refreshUi()},{type:"slider",bounds:[.01,2],stepSize:.01,label:"Cam Distance",hidden:()=>!this._selectedSwitchNode(),property:()=>{const e=this._selectedSwitchNode();return e?[this.variations.find(t=>t.name===e.name),"camDistance"]:[]}},{type:"dropdown",label:"Cam View",hidden:()=>!this._selectedSwitchNode(),property:()=>{const e=this._selectedSwitchNode();return e?[this.variations.find(t=>t.name===e.name),"camView"]:[]},onChange:()=>this.refreshUi(),children:["top","bottom","front","back","left","right"].map(e=>({label:e,value:e}))}]]},this._postFrame=this._postFrame.bind(this),this.refreshUiConfig=this.refreshUiConfig.bind(this),this.addEventListener("deserialize",async()=>{this.refreshUi()})}onAdded(e){super.onAdded(e),e.forPlugin(vs,t=>{this._picking=t,this._picking?.addEventListener("selectedObjectChanged",this.refreshUiConfig)},()=>{this._picking?.removeEventListener("selectedObjectChanged",this.refreshUiConfig),this._picking=void 0},this),e.addEventListener("postFrame",this._postFrame)}onRemove(e){this._picking?.removeEventListener("selectedObjectChanged",this.refreshUiConfig),this._picking=void 0,e.removeEventListener("postFrame",this._postFrame),super.onRemove(e)}_postFrame(){this._uiNeedRefresh&&this._refreshUi()}selectNode(e,t,i=!0){const n=this._viewer?.scene.getObjectByName(e.name);if(!n||n.children.length<1)return;const s=typeof t=="number"?n.children[t]:n.children.find(o=>o.name===t||o.uuid===t);if(!s)return this._viewer?.console.warn("SwitchNodePlugin: child not found",t),!1;e.selected=s.name||s.uuid;let a=!1;for(const o of n.children){const l=o.visible;o.visible=(o.name||o.uuid)===e.selected,a=a||l!==o.visible}return a&&i&&this._viewer.scene.setDirty({refreshScene:this.refreshScene,frameFade:!0}),a}reapplyAll(){this.variations.forEach(e=>this.selectNode(e,e.selected||0,!1)),this._viewer.scene.setDirty({refreshScene:!0,frameFade:!0})}fromJSON(e,t){return this.variations=[],super.fromJSON(e,t)?(e.applyOnLoad===void 0&&(this.applyOnLoad=!0),this.applyOnLoad&&this.reapplyAll(),this):null}refreshUi(){this.enabled&&(this._uiNeedRefresh=!0)}_refreshUi(){return!this.enabled||!this._viewer?!1:(this._uiNeedRefresh=!1,this.autoSnapIcons&&this.snapIcons(),this.refreshUiConfig(),!0)}refreshUiConfig(){this.enabled&&this.uiConfig.uiRefresh?.()}getPreview(e,t,i=!0){if(!this._viewer||!e)return"";const n=e.camView,s=new S((n.includes("right")?1:0)-(n.includes("left")?1:0),(n.includes("top")?1:0)-(n.includes("bottom")?1:0),(n.includes("front")?1:0)-(n.includes("back")?1:0));e.camDistance||(e.camDistance=1);const a=mv(this._viewer.renderManager.renderer,t,this._viewer?.scene,7,s.multiplyScalar(e.camDistance*2));return i&&this._viewer.setDirty(),a}addNode(e,t=!0){this.variations.push(e),t&&this.refreshUi()}snapIcons(){for(const e of this.variations){const t=this._viewer.scene.getObjectByName(e.name);if(!t){console.warn("no object found for variation, skipping",e);continue}t.children.length<1&&console.warn("SwitchNode does not have enough children",e);for(const i of t.children){if(i.userData.__icon)continue;const n=this.getPreview(e,i,!1);n&&(i.userData.__icon=n)}}}};iw.PluginType="SwitchNodePlugin";let rf=iw;_P([G()],rf.prototype,"refreshScene"),_P([G()],rf.prototype,"variations");function Tb(r,e,t,i,n){const s=r.getAttribute(e),a=Array.isArray(i)?i.length/t:i.count;return s&&s.count===a?(s.set(Array.isArray(i)?i:i.array),s.needsUpdate=!0):r.setAttribute(e,Array.isArray(i)?new Ee(i,t):i),s}function C8(r,e){const t=r.index;t&&t.count===(Array.isArray(e)?e.length:e.count)?(t.set(Array.isArray(e)?e:e.array),t.needsUpdate=!0):r.setIndex(e)}function Ib(r,e){const t=r.uiConfig;if(!t)return;let i=t.children?.find(n=>typeof n=="object"&&n.tags?.includes("generatedGeometry"));if(!i){i={type:"folder",label:"Generation Params",expanded:!0,tags:["generatedGeometry"],children:[]};const n=t.children?.findIndex(s=>typeof s=="object"&&(s.type==="divider"||s.type==="separator"))??-1;n>=0?t.children?.splice(n,0,i):t.children?.push(i)}r.userData.__generationParamsUiType!==r.userData.generationParams.type&&(i.children=e(),r.userData.__generationParamsUiType=r.userData.generationParams.type,i.uiRefresh?.(!0,"postFrame"))}function x8(r){const e=r.uiConfig;if(!e)return;const t=e.children?.findIndex(i=>typeof i=="object"&&i.tags?.includes("generatedGeometry"))??-1;t>=0&&(e.children?.splice(t,1),e.uiRefresh?.(!0,"postFrame"))}class gr{constructor(e){this.type=e,this.defaultMeshClass=()=>rg,this.defaultMaterialClass=()=>si,this.defaultGeometryClass=()=>Md}createUiConfig(e){if(!e.userData.generationParams)return[];const t=bi(e.userData.generationParams)?.flatMap(i=>tt(i)).filter(i=>tt(i.property)?.[1]!=="type")||[];return t.forEach(i=>{i.onChange=()=>this.generate(e)}),t}generate(e,t={}){const i=e??new Md;if(t.type&&t.type!==this.type)return console.error("Cannot change type of generated geometry here, use the plugin instead"),i;i.userData.generationParams||(i.userData.generationParams={type:this.type}),i.userData.generationParams.type=this.type;const n={...this.defaultParams,...i.userData.generationParams,...t,type:this.type},{indices:s,vertices:a,normals:o,uvs:l,groups:c,positions:h}=this._generateData(n);if(h!==void 0&&i.setPositions?i.setPositions(h):(s&&C8(i,s),a&&Tb(i,"position",3,a),o&&Tb(i,"normal",3,o),l&&Tb(i,"uv",2,l)),c){i.clearGroups();for(const d of c)i.addGroup(d.start,d.count,d.materialIndex)}return i.computeBoundingBox&&i.computeBoundingBox(),i.computeBoundingSphere&&i.computeBoundingSphere(),Object.assign(i.userData.generationParams,n),Ib(i,()=>this.createUiConfig(i)),i.setDirty(),i}setDefaultParams(e){return Object.assign(this.defaultParams,e),this}}class vP extends gr{constructor(e="torus",t){super(e),this.defaultParams={radius:1,tube:.4,radialSegments:12,tubularSegments:48,arc:Math.PI*2},t&&Object.assign(this.defaultParams,t)}_generateData(e){const{radius:t,tube:i,arc:n}=e;let{radialSegments:s,tubularSegments:a}=e;s=Math.floor(s),a=Math.floor(a);const o=[],l=[],c=[],h=[],u=new S,d=new S,p=new S;for(let m=0;m<=s;m++)for(let A=0;A<=a;A++){const g=A/a*n,y=m/s*Math.PI*2;d.x=(t+i*Math.cos(y))*Math.cos(g),d.y=(t+i*Math.cos(y))*Math.sin(g),d.z=i*Math.sin(y),l.push(d.x,d.y,d.z),u.x=t*Math.cos(g),u.y=t*Math.sin(g),p.subVectors(d,u).normalize(),c.push(p.x,p.y,p.z),h.push(A/a),h.push(m/s)}for(let m=1;m<=s;m++)for(let A=1;A<=a;A++){const g=(a+1)*m+A-1,y=(a+1)*(m-1)+A-1,v=(a+1)*(m-1)+A,_=(a+1)*m+A;o.push(g,y,_),o.push(y,v,_)}return{indices:o,vertices:l,normals:c,uvs:h}}}class bP extends gr{constructor(e="circle",t){super(e),this.defaultParams={radius:1,segments:32,thetaStart:0,thetaLength:Math.PI*2},t&&Object.assign(this.defaultParams,t)}_generateData(e){const{radius:t,thetaStart:i,thetaLength:n}=e,s=Math.max(3,e.segments),a=[],o=[],l=[],c=[],h=new S,u=new K;o.push(0,0,0),l.push(0,0,1),c.push(.5,.5);for(let d=0,p=3;d<=s;d++,p+=3){const m=i+d/s*n;h.x=t*Math.cos(m),h.y=t*Math.sin(m),o.push(h.x,h.y,h.z),l.push(0,0,1),u.x=(o[p]/t+1)/2,u.y=(o[p+1]/t+1)/2,c.push(u.x,u.y)}for(let d=1;d<=s;d++)a.push(d,d+1,0);return{indices:a,vertices:o,normals:l,uvs:c}}}class wP extends gr{constructor(e="box",t){super(e),this.defaultParams={width:1,height:1,depth:1,widthSegments:1,heightSegments:1,depthSegments:1},t&&Object.assign(this.defaultParams,t)}_buildPlane(e,t,i,n,s,a,o,l,c,h,u,d){const{indices:p,vertices:m,normals:A,uvs:g,numberOfVertices:y,groupStart:v,groups:_}=e,b=o/h,T=l/u,E=o/2,M=l/2,I=c/2,C=h+1,x=u+1;let D=0,U=0;const O=new S;for(let N=0;N<x;N++){const H=N*T-M;for(let V=0;V<C;V++){const X=V*b-E;O[t]=X*s,O[i]=H*a,O[n]=I,m.push(O.x,O.y,O.z),O[t]=0,O[i]=0,O[n]=c>0?1:-1,A.push(O.x,O.y,O.z),g.push(V/h),g.push(1-N/u),D+=1}}for(let N=0;N<u;N++)for(let H=0;H<h;H++){const V=y+H+C*N,X=y+H+C*(N+1),W=y+(H+1)+C*(N+1),ce=y+(H+1)+C*N;p.push(V,X,ce),p.push(X,W,ce),U+=6}_.push({start:v,count:U,materialIndex:d}),e.groupStart+=U,e.numberOfVertices+=D}_generateData(e){const{width:t,height:i,depth:n}=e;let{widthSegments:s,heightSegments:a,depthSegments:o}=e;s=Math.floor(s),a=Math.floor(a),o=Math.floor(o);const l={indices:[],vertices:[],normals:[],uvs:[],numberOfVertices:0,groupStart:0,groups:[]};return this._buildPlane(l,"z","y","x",-1,-1,n,i,t,o,a,0),this._buildPlane(l,"z","y","x",1,-1,n,i,-t,o,a,1),this._buildPlane(l,"x","z","y",1,1,t,n,i,s,o,2),this._buildPlane(l,"x","z","y",1,-1,t,n,-i,s,o,3),this._buildPlane(l,"x","y","z",1,-1,t,i,n,s,a,4),this._buildPlane(l,"x","y","z",-1,-1,t,i,-n,s,a,5),l}}class CP extends gr{constructor(e="sphere",t){super(e),this.defaultParams={radius:1,widthSegments:32,heightSegments:16,phiStart:0,phiLength:Math.PI*2,thetaStart:0,thetaLength:Math.PI},t&&Object.assign(this.defaultParams,t)}_generateData(e){const{radius:t,phiStart:i,phiLength:n,thetaStart:s,thetaLength:a}=e;let{widthSegments:o,heightSegments:l}=e;o=Math.max(3,Math.floor(o)),l=Math.max(2,Math.floor(l));const c=Math.min(s+a,Math.PI);let h=0;const u=[],d=new S,p=new S,m=[],A=[],g=[],y=[];for(let v=0;v<=l;v++){const _=[],b=v/l;let T=0;v===0&&s===0?T=.5/o:v===l&&c===Math.PI&&(T=-.5/o);for(let E=0;E<=o;E++){const M=E/o;d.x=-t*Math.cos(i+M*n)*Math.sin(s+b*a),d.y=t*Math.cos(s+b*a),d.z=t*Math.sin(i+M*n)*Math.sin(s+b*a),A.push(d.x,d.y,d.z),p.copy(d).normalize(),g.push(p.x,p.y,p.z),y.push(M+T,1-b),_.push(h++)}u.push(_)}for(let v=0;v<l;v++)for(let _=0;_<o;_++){const b=u[v][_+1],T=u[v][_],E=u[v+1][_],M=u[v+1][_+1];(v!==0||s>0)&&m.push(b,T,M),(v!==l-1||c<Math.PI)&&m.push(T,E,M)}return{indices:m,vertices:A,normals:g,uvs:y}}}class xP extends gr{constructor(e="plane",t){super(e),this.defaultParams={width:1,height:1,widthSegments:2,heightSegments:2},t&&Object.assign(this.defaultParams,t)}_generateData(e){const t=e.width/2,i=e.height/2,n=Math.floor(e.widthSegments),s=Math.floor(e.heightSegments),a=n+1,o=s+1,l=e.width/n,c=e.height/s,h=[],u=[],d=[],p=[];for(let m=0;m<o;m++){const A=m*c-i;for(let g=0;g<a;g++){const y=g*l-t;u.push(y,-A,0),d.push(0,0,1),p.push(g/n),p.push(1-m/s)}}for(let m=0;m<s;m++)for(let A=0;A<n;A++){const g=A+a*m,y=A+a*(m+1),v=A+1+a*(m+1),_=A+1+a*m;h.push(g,y,_),h.push(y,v,_)}return{indices:h,vertices:u,normals:d,uvs:p}}}class SP extends gr{constructor(e="cylinder",t){super(e),this.defaultParams={radiusTop:1,radiusBottom:1,height:1,radialSegments:32,heightSegments:1,openEnded:!1,thetaStart:0,thetaLength:Math.PI*2},t&&Object.assign(this.defaultParams,t)}_generateTorso(e){const{radiusTop:t,radiusBottom:i,height:n,radialSegments:s,heightSegments:a,thetaStart:o,thetaLength:l,indexArray:c,indices:h,groups:u,vertices:d,normals:p,uvs:m,groupStart:A,halfHeight:g}=e,y=new S,v=new S;let _=0;const b=(i-t)/n;for(let T=0;T<=a;T++){const E=[],M=T/a,I=M*(i-t)+t;for(let C=0;C<=s;C++){const x=C/s,D=x*l+o,U=Math.sin(D),O=Math.cos(D);v.x=I*U,v.y=-M*n+g,v.z=I*O,d.push(v.x,v.y,v.z),y.set(U,b,O).normalize(),p.push(y.x,y.y,y.z),m.push(x,1-M),E.push(e.index++)}c.push(E)}for(let T=0;T<s;T++)for(let E=0;E<a;E++){const M=c[E][T],I=c[E+1][T],C=c[E+1][T+1],x=c[E][T+1];h.push(M,I,x),h.push(I,C,x),_+=6}u.push({start:A,count:_,materialIndex:0}),e.groupStart+=_}_generateCap(e,t){const{radiusTop:i,radiusBottom:n,radialSegments:s,thetaStart:a,thetaLength:o,indices:l,groups:c,vertices:h,normals:u,uvs:d,groupStart:p,halfHeight:m}=e,A=e.index,g=new K,y=new S;let v=0;const _=t===!0?i:n,b=t===!0?1:-1;for(let E=1;E<=s;E++)h.push(0,m*b,0),u.push(0,b,0),d.push(.5,.5),e.index++;const T=e.index;for(let E=0;E<=s;E++){const I=E/s*o+a,C=Math.cos(I),x=Math.sin(I);y.x=_*x,y.y=m*b,y.z=_*C,h.push(y.x,y.y,y.z),u.push(0,b,0),g.x=C*.5+.5,g.y=x*.5*b+.5,d.push(g.x,g.y),e.index++}for(let E=0;E<s;E++){const M=A+E,I=T+E;t===!0?l.push(I,I+1,M):l.push(I+1,I,M),v+=3}c.push({start:p,count:v,materialIndex:t===!0?1:2}),e.groupStart+=v}_generateData(e){let{radialSegments:t,heightSegments:i}=e;t=Math.floor(t),i=Math.floor(i);const n={indices:[],vertices:[],normals:[],uvs:[],numberOfVertices:0,groupStart:0,groups:[],index:0,indexArray:[],halfHeight:e.height/2,...e,radialSegments:t,heightSegments:i};return this._generateTorso(n),e.openEnded===!1&&(e.radiusTop>0&&this._generateCap(n,!0),e.radiusBottom>0&&this._generateCap(n,!1)),n}}const Ki={};Ki.LineCurve={ctor:Yo,vals:{start:"v1",end:"v2"},getUiConfig:r=>[ii(r,"v1","Start Point"),ii(r,"v2","End Point")]},Ki.CubicBezierCurve={ctor:Eu,vals:{start:"v0",end:"v3",control1:"v1",control2:"v2"},getUiConfig:r=>[ii(r,"v0","Start Point"),ii(r,"v1","Control Point 1"),ii(r,"v2","Control Point 2"),ii(r,"v3","End Point")]},Ki.QuadraticBezierCurve={ctor:Mu,vals:{start:"v0",end:"v2",control1:"v1"},getUiConfig:r=>[ii(r,"v0","Start Point"),ii(r,"v1","Control Point"),ii(r,"v2","End Point")]},Ki.EllipseCurve={ctor:Xo,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise",rotation:"aRotation"},getUiConfig:r=>[ii(r,"aX","X Center"),ii(r,"aY","Y Center"),ii(r,"xRadius","X Radius"),ii(r,"yRadius","Y Radius"),ii(r,"aStartAngle","Start Angle"),ii(r,"aEndAngle","End Angle"),ii(r,"aClockwise","Clockwise"),ii(r,"aRotation","Rotation")]},Ki.ArcCurve={ctor:Ip,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise"},getUiConfig:r=>{const e=ii(r,"xRadius","Radius");if(e){const t=e.onChange;e.onChange=(...i)=>{r.yRadius=r.xRadius,t?.(...i)}}return[ii(r,"aX","X Center"),ii(r,"aY","Y Center"),e,ii(r,"aStartAngle","Start Angle"),ii(r,"aEndAngle","End Angle"),ii(r,"aClockwise","Clockwise")]}},Ki.SplineCurve={ctor:Iu,vals:{points:"points"},getUiConfig:r=>[()=>r.points.map((e,t)=>ii(r.points,t.toString(),`Point ${t}`)),{type:"button",label:"Add Point",value:()=>{const e=r.points,t=e[e.length-1]||new K(0,0),i=e[e.length-2]||new K(1,1);e.push(t.clone().add(t.clone().sub(i))),r.points=e,r.updateArcLengths(),r.uiConfig?.uiRefresh?.(!0,"postFrame")}}]},Ki.LineCurve3={...Ki.LineCurve,ctor:$o},Ki.CubicBezierCurve3={...Ki.CubicBezierCurve,ctor:Dp},Ki.QuadraticBezierCurve3={...Ki.QuadraticBezierCurve,ctor:Tu},Ki.CatmullRomCurve3={ctor:Uc,vals:{points:"points",closed:"closed",curveType:"curveType",tension:"tension"},getUiConfig:r=>[()=>r.points.map((e,t)=>ii(r.points,t.toString(),`Point ${t}`)),{type:"button",label:"Add Point",value:()=>{const e=r.points,t=e[e.length-1]||new S(0,0,0),i=e[e.length-2]||new S(1,1,0);e.push(t.clone().add(t.clone().sub(i))),r.points=e,r.updateArcLengths(),r.uiConfig?.uiRefresh?.(!0,"postFrame")}},ii(r,"closed","Closed Loop"),{type:"dropdown",property:[r,"curveType"],label:"Curve Type",children:["centripetal","chordal","catmullrom"].map(e=>({label:e,value:e}))},ii(r,"tension","Tension")]},Ki.EllipseCurve3D={ctor:vl,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise",rotation:"aRotation"},getUiConfig:Ki.EllipseCurve.getUiConfig},Ki.CurvePath={ctor:Pu,vals:{},getUiConfig:r=>[()=>r.curves.map((e,t)=>{if(e.uiConfig)return e.uiConfig;const i=e.type,n=Ki[i];if(n){const s=n.getUiConfig(e)||[],a={type:"folder",label:i.replace(/([A-Z])/g," $1").trim(),children:[af(e,o=>{r.curves[t]=o,r.updateArcLengths(),r.uiConfig?.uiRefresh?.(!0,"postFrame")}),...s,{type:"button",label:"Remove Curve",value:()=>(r.curves.splice(t,1),r.updateArcLengths(),r.uiConfig?.uiRefresh?.(!0,"postFrame"),!0)}]};return e.uiConfig=a,a}}),{type:"button",label:"Add Curve",value:()=>{const e=r.type.endsWith("3")?new $o(new S(0,0,0),new S(1,1,0)):new Yo(new K(0,0),new K(1,1));return r.add(e),r.updateArcLengths(),r.uiConfig?.uiRefresh?.(!0,"postFrame"),!0}}]},Ki.CurvePath3={...Ki.CurvePath,ctor:zm};function af(r,e,t=Ki){return{type:"dropdown",label:"Curve Type",children:Object.keys(t).map(i=>({label:i.replace(/([A-Z])/g," $1").trim(),value:i})),getValue:()=>r&&r.type||"LineCurve3",setValue:i=>{const n=r.type?t[r.type]:null,s=t[i];if(!(r&&s&&r.type!==i))return!0;const a=s.ctor;if(!a)return!1;const o=new a;if(Array.isArray(o.points)&&o.points.length===0){const l=o.type.endsWith("3")?new S:new K,c=o.type.endsWith("3")?new S(1,1,1):new K(1,1);o.points.push(l,c)}if(Array.isArray(o.curves)&&o.curves.length===0){const l=o.type.endsWith("3")?new $o(new S(0,0,0),new S(1,1,0)):new Yo(new K(0,0),new K(1,1));o.curves.push(l)}if(n){const l=Object.entries(n.vals).map(([c,h])=>[c,r[h],s.vals[c]]).filter(([c,h,u])=>h!=null&&!!u);for(const[,c,h]of l){const u=o[h];u!==void 0&&(typeof u=="object"&&typeof u.copy=="function"?o[h].copy(c):Array.isArray(u)&&Array.isArray(c)?o[h]=[...c]:typeof u=="object"&&typeof c=="object"&&c!==null?o[h]={...c}:o[h]=c)}}return e(o),!0}}}function tA(r,e=Ki){const t=r.type,i=e[t];if(!i)return[];const n={type:"folder",label:t.replace(/([A-Z])/g," $1").trim(),children:i.getUiConfig(r)||[]};return r.uiConfig=n,[n]}class EP extends gr{constructor(e="tube",t){super(e),this.defaultParams={path:new vl(0,0,1,1,0,2*Math.PI,!1,0),tubularSegments:64,radius:.1,radialSegments:8,closed:!1},t&&Object.assign(this.defaultParams,t)}_generateData(e){const t=new Uu(e.path,e.tubularSegments,e.radius,e.radialSegments,e.closed),i=t.getAttribute("position"),n=t.getAttribute("normal"),s=t.getAttribute("uv"),o={indices:t.index?Array.from(t.index.array):[],vertices:i,normals:n,uvs:s};return t.dispose(),o}createUiConfig(e){const t=e.userData.generationParams;if(!t)return[];const n=super.createUiConfig(e).filter(a=>a.label!=="path"),s=a=>{t.path=a,e.userData.__generationParamsUiType="",this.generate(e)};return[af(t.path,s),...tA(t.path),...n]}}function Pb(r,e){const t=new rr;switch(r){case"rectangle":{const i=(e.width??1)/2,n=(e.height??1)/2;return t.moveTo(-i,-n),t.lineTo(i,-n),t.lineTo(i,n),t.lineTo(-i,n),t.closePath(),t}case"circle":{const i=e.circleRadius??1,n=e.circleSegments??32;for(let s=0;s<n;s++){const a=s/n*Math.PI*2,o=i*Math.cos(a),l=i*Math.sin(a);s===0?t.moveTo(o,l):t.lineTo(o,l)}return t.closePath(),t}case"polygon":{const i=Math.max(3,e.sides??6),n=e.polygonRadius??1;for(let s=0;s<i;s++){const a=s/i*Math.PI*2-Math.PI/2,o=n*Math.cos(a),l=n*Math.sin(a);s===0?t.moveTo(o,l):t.lineTo(o,l)}return t.closePath(),t}default:throw new Error("Unknown shape preset type: "+r)}}function MP(r){const e=r.getPoints();return e.reverse(),new rr(e)}class TP extends gr{constructor(e="shape",t){super(e),this.defaultParams={shapeType:"rectangle",width:1,height:1,circleRadius:1,circleSegments:32,sides:6,polygonRadius:1,curveSegments:12},t&&Object.assign(this.defaultParams,t)}_generateData(e){const t=Pb(e.shapeType,e),i=new Ou(t,e.curveSegments);i.computeVertexNormals();const n=i.getAttribute("position"),s=i.getAttribute("normal"),a=i.getAttribute("uv"),l={indices:i.index?Array.from(i.index.array):[],vertices:n,normals:s,uvs:a};return i.dispose(),l}createUiConfig(e){const t=e.userData.generationParams;if(!t)return[];const i=super.createUiConfig(e);for(const n of i){const s=n.label;s==="width"||s==="height"?n.hidden=()=>t.shapeType!=="rectangle":s==="circleRadius"||s==="circleSegments"?n.hidden=()=>t.shapeType!=="circle":(s==="sides"||s==="polygonRadius")&&(n.hidden=()=>t.shapeType!=="polygon")}return i}}class IP extends gr{constructor(e="tubeShape",t){super(e),this.defaultParams={path:new vl(0,0,2,2,0,2*Math.PI,!1,0),shapeType:"rectangle",width:.5,height:.3,circleRadius:.2,circleSegments:16,sides:6,polygonRadius:.2,shapeSegments:16,tubularSegments:64,closed:!1,shapeScaleX:1,shapeScaleY:1,primary:"shape",materialSplits:""},t&&Object.assign(this.defaultParams,t)}_generateData(e){const t=e.shapeType==="custom"&&e.shape?e.shape:Pb(e.shapeType,e),i=MP(t),n=new dT(i,e.path,e.shapeSegments,e.tubularSegments,e.closed,new K(e.shapeScaleX,e.shapeScaleY),e.primary);if(e.materialSplits){const h=e.materialSplits.split(",").map(u=>parseFloat(u.trim())).filter(u=>!isNaN(u));h.length>0&&n.createSplits(h)}const s=n.getAttribute("position"),a=n.getAttribute("normal"),o=n.getAttribute("uv"),c={indices:n.index?Array.from(n.index.array):[],vertices:s,normals:a,uvs:o};return n.groups.length>0&&(c.groups=n.groups.map(h=>({start:h.start,count:h.count,materialIndex:h.materialIndex}))),n.dispose(),c}createUiConfig(e){const t=e.userData.generationParams;if(!t)return[];const n=super.createUiConfig(e).filter(a=>{const o=a.label;return o!=="path"&&o!=="shape"});for(const a of n){const o=a.label;o==="width"||o==="height"?a.hidden=()=>t.shapeType!=="rectangle":o==="circleRadius"||o==="circleSegments"?a.hidden=()=>t.shapeType!=="circle":(o==="sides"||o==="polygonRadius")&&(a.hidden=()=>t.shapeType!=="polygon")}const s=a=>{t.path=a,e.userData.__generationParamsUiType="",this.generate(e)};return[af(t.path,s),...tA(t.path),...n]}}const jh=class jh extends gr{constructor(e="line",t){super(e),this.defaultParams={curve:new $o(new S(0,0,0),new S(1,1,0)),segments:50,closePath:!1},this.defaultMeshClass=()=>jh.UseMeshLines?Kv:fn,this.defaultMaterialClass=()=>jh.UseMeshLines?ji:Yn,this.defaultGeometryClass=()=>jh.UseMeshLines?Jv:Md,t&&Object.assign(this.defaultParams,t)}_generateData(e){const t=[];let i=e.curve;if(!i&&this.defaultParams.curve&&(i=this.defaultParams.curve),!i)throw new Error("No curve specified for line generation");const n=Math.max(2,e.segments||50),s=e.closePath||!1;i.updateArcLengths();const a=i.getSpacedPoints(n-1);a.length!==n&&console.error(`LineGeometryGenerator: Curve points length (${a.length}) does not match segments (${n}).`);for(const o of a)"z"in o?t.push(o.x,o.y,o.z):t.push(o.x,o.y,0);if(s&&a.length>0){const o=a[0];"z"in o?t.push(o.x,o.y,o.z):t.push(o.x,o.y,0)}return{vertices:t,normals:[],uvs:[],positions:t}}createUiConfig(e){const t=super.createUiConfig(e),i=t.find(o=>o.label==="curve"&&o.type==="folder"),n=e.userData.generationParams?.curve;if(!n)return[];if(n?.uiConfig){const o=i?t.indexOf(i):-1;o>=0?t.splice(o,1,n.uiConfig):t.push(n.uiConfig)}else if(i){const o=tA(n);if(o.length>0){const l=t.indexOf(i);t.splice(l,1,...o)}}return[af(n,o=>{e.userData.generationParams.curve=o,e.userData.__generationParamsUiType="",this.generate(e)}),...t]}};jh.UseMeshLines=!0;let iA=jh;const nw=class nw extends mt{constructor(){super(...arguments),this.enabled=!0,this.toJSON=void 0,this.generators={plane:new xP("plane"),sphere:new CP("sphere"),box:new wP("box"),circle:new bP("circle"),torus:new vP("torus"),cylinder:new SP("cylinder"),tube:new EP("tube"),shape:new TP("shape"),tubeShape:new IP("tubeShape"),line:new iA("line")},this.defaultMeshClass=rg,this.defaultMaterialClass=si,this.defaultGeometryClass=Md,this._objectAdd=e=>{const t=e.object,i=t?.geometry?.userData?.generationParams?.type;i&&Ib(t.geometry,()=>{const n=t.geometry;if(!n)return[];const s=this.generators[i];return s?.createUiConfig?s.createUiConfig(n)??[]:[]})},this._objectRemove=e=>{const t=e.object?.geometry;t?.userData?.generationParams?.type&&x8(t)},this._geometryUpdate=e=>{e.regenerate&&e.geometry?.userData?.generationParams&&this.updateGeometry(e.geometry)},this.uiConfig={type:"folder",label:"Generate Geometry",children:[()=>Object.keys(this.generators).map(e=>({type:"button",uuid:"generate_"+e,label:"Generate "+e,value:async()=>{const t=this.generateObject(e);t.name=e,this._viewer?.scene.addObject(t)}}))]}}generateObject(e,{mesh:t,geometry:i,material:n,...s}={}){const a=this.generators[e];if(!a)throw new Error("Unknown generator type: "+e);let o=t;const l=o?.geometry||i||(a.defaultGeometryClass?new(a.defaultGeometryClass()):new this.defaultGeometryClass),c=o?.material||n||(a.defaultMaterialClass?new(a.defaultMaterialClass()):new this.defaultMaterialClass);return o=o||(a.defaultMeshClass?new(a.defaultMeshClass())(l,c):new this.defaultMeshClass(l,c)),o&&(o.geometry!==l&&(o.geometry=l),o.material!==c&&(o.material=c),a.generate(o.geometry,s),o.name=e,l.name||(l.name="Generated "+mS(e)),c.name||(c.name="Material for "+l.name),o)}generateGeometry(e,t,i){const n=this.generators[e];if(!n)throw new Error("Unknown generator type: "+e);const s=n.generate(i,t);return s.name="Generated "+e,s}updateGeometry(e,t){if(!e.userData.generationParams?.type)throw new Error("Geometry is not generated");const i=this.generators[e.userData.generationParams.type];if(!i)throw new Error("Unknown generator type: "+e.userData.generationParams.type);i.generate(e,t)}onAdded(e){super.onAdded(e),e.scene.addEventListener("geometryUpdate",this._geometryUpdate),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.forPlugin("Object3DGeneratorPlugin",t=>{t.addObject3DGenerators("geometry-",Object.fromEntries(Object.keys(this.generators).map(i=>[i,n=>{const s=this.generateObject(i,n);return s.name=i,s}])))},t=>{t.removeObject3DGenerators("geometry-")},this)}onRemove(e){e.scene.removeEventListener("geometryUpdate",this._geometryUpdate),e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),super.onRemove(e)}};nw.PluginType="GeometryGeneratorPlugin";let Ph=nw;var S8=Object.defineProperty,E8=Object.getOwnPropertyDescriptor,bo=(r,e,t,i)=>{for(var n=i>1?void 0:i?E8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&S8(e,t,n),n};f.ShapeTubeExtrudePlugin=class extends mt{constructor(){super(...arguments),this.dependencies=[vs,Ph],this.enabled=!0,this.toJSON=void 0,this.shapeSegments=32,this.tubularSegments=32,this.shapeScaleX=1,this.shapeScaleY=1,this.materialSplits="0.3, 0.6",this.horizontalSplits=!0,this.extrudeCircleTube=async()=>{const t=this._viewer?.getPlugin(vs)?.getSelectedObject();if(!t||!t.geometry)return;const i=1,n=new vl(0,0,i,i,0,2*Math.PI,!1,0);this.extrudeObject(t,n)}}extrudeObject(e,t,i=this.shapeSegments,n=this.tubularSegments,s=this.shapeScaleX,a=this.shapeScaleY,o=this.materialSplits,l=this.horizontalSplits){if(!this._viewer)return;if(e.userData._extrudeSource){const m=e.userData._extrudeSource,A=e.parent?.children.find(g=>m===g.uuid);if(!A){console.warn("Could not find extrude source with uuid",m);return}e=A}if(e.userData.extrudedObject){const m=e.userData.extrudedObject,A=e.parent?.children.find(g=>m===g.uuid);A&&A.dispose?.(!0),delete e.userData.extrudedObject}const c=e.geometry;if(!c){console.warn("ShapeTubeExtrudePlugin: No geometry to extrude");return}let h;try{h=f.ShapeTubeExtrudePlugin.ConvertGeometryToFlatShape(c)}catch(m){console.warn("ShapeTubeExtrudePlugin:",typeof m=="string"?m:m?.message);return}const u=this._viewer.getPlugin(Ph);if(!u)return;const d=o?o.split(",").map(m=>parseFloat(m.trim())).filter(m=>!isNaN(m)).join(", "):"",p=u.generateObject("tubeShape",{path:t,shapeType:"custom",shape:h,shapeSegments:i,tubularSegments:n,closed:!0,shapeScaleX:s,shapeScaleY:a,primary:l?"shape":"path",materialSplits:d});p.userData._extrudeSource=e.uuid,p.userData.isExtrudedTube=!0,p.name=e.name+"_extruded",e.visible=!1,e.userData.extrudedObject=p.uuid,e.parent?e.parent.add(p):this._viewer.scene.addObject(p)}static ExtrudeShape(e,t,i,n=32,s=64,a=1,o=1,l="",c=!0){const h=e.getPlugin(Ph);if(h)return h.generateObject("tubeShape",{path:i,shapeType:"custom",shape:t,shapeSegments:n,tubularSegments:s,closed:!0,shapeScaleX:a,shapeScaleY:o,primary:c?"shape":"path",materialSplits:l})}static ConvertGeometryToFlatShape(e,t=!0){if(e.userData.__planarShape)return e.userData.__planarShape;const i=e.attributes.position;if(!i)throw new Error("No position attribute");if(i.count>500)throw new Error("Too many vertices to extrude (max 500)");e.boundingBox||e.computeBoundingBox();const n=e.boundingBox.getSize(new S),s=n.x<.001?"x":n.y<.001?"y":n.z<.001?"z":null;if(!s)throw new Error("Geometry is not axis-aligned planar");let a=[];for(let l=0;l<i.count;l++){const c=new K;s==="x"?c.set(i.getY(l),i.getZ(l)):s==="y"?c.set(i.getX(l),i.getZ(l)):c.set(i.getX(l),i.getY(l)),a.push(c)}if(t){let l=0;for(let c=0;c<a.length;c++)(a[c].x<a[l].x||a[c].x===a[l].x&&a[c].y<a[l].y)&&(l=c);l!==0&&(a=a.slice(l).concat(a.slice(0,l)))}const o=new rr(a);return e.userData.__planarShape=o,o}},f.ShapeTubeExtrudePlugin.PluginType="ShapeTubeExtrudePlugin",bo([Fe("Shape Segments",[1,100],1)],f.ShapeTubeExtrudePlugin.prototype,"shapeSegments",2),bo([Fe("Tube Segments",[1,100],1)],f.ShapeTubeExtrudePlugin.prototype,"tubularSegments",2),bo([Fe("Shape Scale X",[.01,10],.01)],f.ShapeTubeExtrudePlugin.prototype,"shapeScaleX",2),bo([Fe("Shape Scale Y",[.01,10],.01)],f.ShapeTubeExtrudePlugin.prototype,"shapeScaleY",2),bo([He("Material Splits")],f.ShapeTubeExtrudePlugin.prototype,"materialSplits",2),bo([se("Horizontal Splits")],f.ShapeTubeExtrudePlugin.prototype,"horizontalSplits",2),bo([ct("Extrude Circle Tube")],f.ShapeTubeExtrudePlugin.prototype,"extrudeCircleTube",2),f.ShapeTubeExtrudePlugin=bo([vt("Extrude Tube Shapes")],f.ShapeTubeExtrudePlugin);const M8=`
#ifdef HDRi_GROUND_PROJ
float intersectPlane1(const in vec3 r0,const in vec3 rd,const in vec3 n,const in vec3 p0){float t=dot(p0-r0,n)/(dot(n,rd)+1e-6);return t<0. ? 1000. : t;}float intersectSphere1(in vec3 ro,in vec3 rd,in vec3 sph,in float rad){vec3 oc=ro-sph;float b=dot(oc,rd);float c=dot(oc,oc)-rad*rad;float t=b*b-c;return t<0.0 ? t :-b+sqrt(t);}
#define PI_HALF 1.5707963267948966
uniform float worldRadius;uniform float tripodHeight;uniform vec3 originPosition;vec3 hdriProject(){vec3 p=normalize(vWorldDirection);vec3 camPos=cameraPosition;camPos.y-=tripodHeight;float t=intersectSphere1(camPos,p,originPosition,worldRadius);if(t>0.0){float t2=intersectPlane1(camPos,p,vec3(0,-1,0),originPosition+vec3(0.0,-tripodHeight,0.0));p=(camPos+min(t,t2)*p)/worldRadius;/*if(t2<t&&tripodHeight<0.001){float phi=atan(p.z,p.x);float p1=0.4;float l=length(p.xz);p1=(1.-p1*l)/(1.-p1);float theta=sin(l*PI_HALF)*PI_HALF;p.x=sin(theta)*cos(phi)*p1;p.y=-cos(theta);p.z=sin(theta)*sin(phi)*p1;}*/}else p=vec3(0.0,1.0,0.0);return p;}
#endif
`;var T8=Object.defineProperty,I8=Object.getOwnPropertyDescriptor,Dh=(r,e,t,i)=>{for(var n=i>1?void 0:i?I8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&T8(e,t,n),n};f.HDRiGroundPlugin=class extends mt{constructor(e=!1,t=!0){super(),this.enabled=!1,this.worldRadius=100,this.tripodHeight=10,this.originPosition=new S(0,0,0),this.promptOnBackgroundMismatch=!0,this.setDirty=this.setDirty.bind(this),this.enabled=e,this.promptOnBackgroundMismatch=t,this.addEventListener("deserialize",this.setDirty)}setDirty(){if(!this._viewer)return;const e=this._viewer.scene.background;this.enabled&&e!==this._viewer.scene.environment&&e!=="environment"&&(e&&e.isDataTexture?e.mapping=$r:(this.promptOnBackgroundMismatch?this._viewer.dialog.confirmSync("Background must be same as environment, do you want to change it?"):!0)?this._viewer.scene.background="environment":this.enabled=!1);const t=this._viewer.renderManager.renderer.background.getBoxMesh2()?.material,i=t?.uniforms??Di.backgroundCube.uniforms;i.tripodHeight||(i.tripodHeight={value:1}),i.worldRadius||(i.worldRadius={value:1}),i.originPosition||(i.originPosition={value:new S}),i.tripodHeight.value=this.tripodHeight,i.worldRadius.value=this.worldRadius,i.originPosition.value.copy(this.originPosition),t&&(this.isDisabled()&&t.defines.HDRi_GROUND_PROJ?delete t.defines.HDRi_GROUND_PROJ:this.isDisabled()||(t.defines.HDRi_GROUND_PROJ="1"),t.needsUpdate=!0),this._viewer.setDirty()}onAdded(e){if(super.onAdded(e),this._viewer?.renderManager.webglRenderer?.background.getBoxMesh()&&e.console.error("HDRi Ground Plugin must be added before setting any cube or env map"),!Di.backgroundCube.fragmentShader.includes("#ifdef HDRi_GROUND_PROJ")){const t="void main() {",i=Di.backgroundCube.fragmentShader.split(t);i.length!==2?e.console.error("HDRi Ground Plugin: Could not parse backgroundCube shader"):Di.backgroundCube.fragmentShader=i[0]+`
${M8}
${t}
vec3 worldDirection = 
#ifdef HDRi_GROUND_PROJ
hdriProject()
#else
vWorldDirection
#endif
;
${bt(i[1],"vWorldDirection","worldDirection",{replaceAll:!0})}
`}e.scene.addEventListener("environmentChanged",this.setDirty)}},f.HDRiGroundPlugin.PluginType="HDRiGroundPlugin",Dh([G(),he(f.HDRiGroundPlugin.prototype.setDirty),se("Enabled")],f.HDRiGroundPlugin.prototype,"enabled",2),Dh([G(),he(f.HDRiGroundPlugin.prototype.setDirty),Fe("World Radius",[1,1e3],.01)],f.HDRiGroundPlugin.prototype,"worldRadius",2),Dh([G(),he(f.HDRiGroundPlugin.prototype.setDirty),Fe("Tripod height",[0,50],.01)],f.HDRiGroundPlugin.prototype,"tripodHeight",2),Dh([G(),he(f.HDRiGroundPlugin.prototype.setDirty),yi("Origin Position",void 0,.001,r=>({onChange:r.setDirty}))],f.HDRiGroundPlugin.prototype,"originPosition",2),Dh([G(),he(f.HDRiGroundPlugin.prototype.setDirty)],f.HDRiGroundPlugin.prototype,"promptOnBackgroundMismatch",2),f.HDRiGroundPlugin=Dh([vt("HDRi Ground")],f.HDRiGroundPlugin);var P8=Object.defineProperty,D8=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&P8(e,t,n),n};const Db=(Wh=class extends mt{constructor(e=!0,t=!1){super(),this.enabled=!0,this.helpers=[KI,nP,eP,$I,JI,tP],this.toJSON=null,this.inSceneRoot=!1,this._widgetRoot=new _l,this.refreshObject=i=>{this._createWidget(i)||this._removeWidget(i)},this._viewerListeners={preRender:()=>{this.widgets.forEach(i=>i.preRender&&i.preRender())}},this.widgets=[],this._widgetDisposed=i=>this._unregisterWidget(i.target),this._objectAdd=i=>{const n=i.object;this._createWidget(n)},this._objectRemove=i=>{const n=i.object;this._removeWidget(n)},this.uiConfig={type:"folder",label:"Widgets",children:[{type:"checkbox",label:"Enabled",property:[this,"enabled"]}]},this.enabled=e,this.inSceneRoot=t}setDirty(){this.widgets?.forEach(e=>e.visible=!this.isDisabled()),this._viewer?.setDirty()}onAdded(e){super.onAdded(e),this._widgetRoot.userData.isWidgetRoot=!0,this._widgetRoot.name="Widgets Root",this._modelRoot=this.inSceneRoot?e.scene:e.scene.modelRoot,e.scene.addObject(this._widgetRoot,{addToRoot:!0,autoScale:!1,autoCenter:!1}),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove)}onRemove(e){e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),this.widgets.forEach(t=>t.dispose&&t.dispose()),this.widgets=[],this._widgetRoot.removeFromParent(),this._widgetRoot.clear(),super.onRemove(e)}_registerWidget(e){this.widgets.push(e),e.addEventListener("dispose",this._widgetDisposed)}_unregisterWidget(e){e.removeEventListener("dispose",this._widgetDisposed);const t=this.widgets.indexOf(e);t>=0&&this.widgets.splice(t,1)}_createWidget(e){if(!e||e.assetType==="widget"||e===this._widgetRoot||e.isWidget||e.userData.disableWidgets)return!1;let t=!1,i=!1;if(e.traverseAncestors(a=>{t=t||a===this._widgetRoot||!!a.isWidget||a.assetType==="widget"||!!a.userData.disableWidgets,i=i||a===this._modelRoot}),t||!i)return!1;const n=this.widgets.find(a=>a.object===e);if(n)return n.update&&n.update(),!0;const s=this.helpers.filter(a=>a.Check(e));for(const a of s){const o=a.Create(e);o.visible=!this.isDisabled(),this._widgetRoot.add(o),this._registerWidget(o)}return!0}_removeWidget(e){if(!e)return;const t=this.widgets.filter(i=>i.object===e);for(const i of t)i.dispose&&i.dispose(!0),i.parent&&i.removeFromParent(),this._unregisterWidget(i)}},Wh.PluginType="Object3DWidgetsPlugin",Wh);D8([he(Db.prototype.setDirty)],Db.prototype,"enabled");let R8=Db;var B8=Object.defineProperty,L8=Object.getOwnPropertyDescriptor,Rb=(r,e,t,i)=>{for(var n=i>1?void 0:i?L8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&B8(e,t,n),n};f.Object3DGeneratorPlugin=class extends mt{constructor(){super(),this.enabled=!0,this.toJSON=void 0,this._selectedType="",this.generators={"object-empty":(e={})=>{const t=new lT;return e.position?t.position.copy(e.position):t.position.set(0,0,0),t.name=e.name??"New Object",t},"object-group":(e={})=>{const t=new _l;return e.position?t.position.copy(e.position):t.position.set(0,0,0),t.name=e.name??"New Object",t},"camera-perspective":(e={})=>{const t=new th(e.controlsMode??"",this._viewer?.canvas,e.autoAspect,e.fov,e.aspect);return e.position?t.position.copy(e.position):t.position.set(0,0,5),e.target?t.target.copy(e.target):t.target.set(0,0,0),t.autoLookAtTarget=e.autoLookAtTarget??!0,t.setDirty(),t.name=e.name??"Perspective Camera",t},"camera-orthographic":(e={})=>{const t=new Sd(e.controlsMode??"",this._viewer?.canvas,e.autoAspect,e.frustumSize);return e.position?t.position.copy(e.position):t.position.set(0,0,5),e.target?t.target.copy(e.target):t.target.set(0,0,0),t.autoLookAtTarget=e.autoLookAtTarget??!0,t.setDirty(),t.name=e.name??"Orthographic Camera",t},"light-directional":(e={})=>{const t=new lg(e.color??16711680,e.intensity??3);return e.position?t.position.copy(e.position):t.position.set(5,5,5),t.lookAt(e.target??new S(0,0,0)),t.name="Directional Light",t},"light-ambient":(e={})=>{const t=new bl(e.color??16777215,e.intensity??1);return t.name="Ambient Light",t},"light-point":(e={})=>{const t=new cg(e.color??16711680,e.intensity??3);return e.position?t.position.copy(e.position):t.position.set(5,5,5),t.name="Point Light",t},"light-spot":(e={})=>{const t=new hg(e.color??16711680,e.intensity??3);return e.position?t.position.copy(e.position):t.position.set(5,5,5),t.lookAt(e.target??new S(0,0,0)),t.name="Spot Light",t},"light-hemisphere":(e={})=>{const t=new Ca(e.color??11184895,5592131,e.intensity??1);return t.name="Hemisphere Light",t},"light-rect-area":(e={})=>{const t=new Nr(e.color??255,e.intensity??3,2,2);return e.position?t.position.copy(e.position):t.position.set(5,5,5),t.lookAt(e.target??new S(0,0,0)),t.name="Rect Area Light",t}},this._selectedType=Object.keys(this.generators)[0]}generate(e,t,i=!0,n=!0,s=!0){if(!this._viewer)throw new Error("No viewer");const a=this.generators[e??this._selectedType]?.(t);if(i&&a){const o={redo:()=>this._viewer?.scene.addObject(a),undo:()=>a.dispose?a.dispose(!0):a.removeFromParent()};s&&this._viewer?.getPlugin("UndoManagerPlugin")?.undoManager?.record(o),o.redo(),n&&a.dispatchEvent({type:"select",value:a,object:a,ui:!0,bubbleToParent:!0,trackUndo:!1})}return a||void 0}removeObject3DGenerators(e,t=!0){return this.generators=Object.fromEntries(Object.entries(this.generators).filter(([i,n])=>!i.startsWith(e))),t&&this.uiConfig?.uiRefresh?.(!0),this}removeObject3DGenerator(e,t=!0){return delete this.generators[e],t&&this.uiConfig?.uiRefresh?.(!0),this}addObject3DGenerators(e,t,i=!0){this.removeObject3DGenerators(e,!1),Object.entries(t).forEach(([n,s])=>{this.generators[e+n]=s}),i&&this.uiConfig?.uiRefresh?.(!0)}addObject3DGenerator(e,t,i=!0){this.removeObject3DGenerator(e,!1),this.generators[e]=t,i&&this.uiConfig?.uiRefresh?.(!0)}},f.Object3DGeneratorPlugin.PluginType="Object3DGeneratorPlugin",Rb([Li("Type",void 0,r=>({children:[()=>Object.keys(r.generators).map(e=>({label:e}))]}))],f.Object3DGeneratorPlugin.prototype,"_selectedType",2),Rb([ct("Generate",{sendArgs:!1})],f.Object3DGeneratorPlugin.prototype,"generate",1),f.Object3DGeneratorPlugin=Rb([Aa("Generate Scene Objects")],f.Object3DGeneratorPlugin);var O8=Object.defineProperty,U8=Object.getOwnPropertyDescriptor,Rh=(r,e,t,i)=>{for(var n=i>1?void 0:i?U8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&O8(e,t,n),n};f.ContactShadowGroundPlugin=class extends f.BaseGroundPlugin{constructor(){super(),this.contactShadows=!0,this.shadowScale=1,this.shadowHeight=5,this.blurAmount=1,this.mapMode="aoMap",this.shadowCamera=new Mr(-1,1,1,-1,.001,this.shadowHeight),this._depthTex=null,this._refreshShadowCameraFrustum=this._refreshShadowCameraFrustum.bind(this),this.refresh=this.refresh.bind(this)}onAdded(e){const t=e.renderManager.createTarget({type:Qt,format:qt,colorSpace:ai,size:{width:512,height:512},generateMipmaps:!1,depthBuffer:!0,minFilter:at,magFilter:at});t.texture.name="groundContactDepthTexture";const i=new Ec({depthPacking:If,transparent:!1,blending:gn});i.opacity=-1,i.onBeforeCompile=n=>{n.fragmentShader=bt(n.fragmentShader,"gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( opacity > 0. ? vec3( 1.0 - fragCoordZ ) : vec3( fragCoordZ ), 1.0 );")},this._depthPass=new f.GBufferRenderPass("contactShadowGround",t,i,new ee(1,1,1),1),this._blurHelper=new EE(e),super.onAdded(e)}onRemove(e){const t=tt(this._depthPass?.target);return t&&this._viewer?.renderManager.disposeTarget(t),this._depthPass?.dispose(),this._depthPass=void 0,this._blurHelper?.dispose(),this._blurHelper=void 0,super.onRemove(e)}_postFrame(){super._postFrame(),this._viewer}_preRender(){if(super._preRender(),!this._viewer||!this._depthPass||!this._blurHelper||!this.contactShadows||!this.visible)return;this._depthPass.scene=this._viewer.scene,this._depthPass.camera=this.shadowCamera,this._depthPass.render(this._viewer.renderManager.renderer,null);const e=tt(this._depthPass.target);if(!e)return;const t=this._viewer.renderManager.getTempTarget({type:Qt,format:qt,colorSpace:ai,size:{width:1024,height:1024},generateMipmaps:!1,depthBuffer:!1,minFilter:at,magFilter:at});this._blurHelper.blur(e.texture,e,t,this.blurAmount/256),this._blurHelper.blur(e.texture,e,t,.4*this.blurAmount/256),this._viewer.renderManager.releaseTempTarget(t)}_refreshTransform(){return!super._refreshTransform()||!this._mesh||!this._viewer?!1:(this.shadowCamera.position.copy(this._mesh.getWorldPosition(new S)),this.shadowCamera.setRotationFromEuler(new Pt(Math.PI/2,0,0)),this.shadowCamera.updateMatrixWorld(),this._refreshShadowCameraFrustum(),this._mesh.scale.y=-this.size,!0)}_refreshShadowCameraFrustum(){this.shadowCamera&&(this.shadowCamera.left=-this.size/(2*this.shadowScale),this.shadowCamera.right=this.size/(2*this.shadowScale),this.shadowCamera.top=this.size/(2*this.shadowScale),this.shadowCamera.bottom=-this.size/(2*this.shadowScale),this.shadowCamera.far=this.shadowHeight,this.shadowCamera.updateProjectionMatrix(),this._setDirty())}_setDirty(){this._viewer?.setDirty()}_removeMaterial(){this._material&&(this._material.alphaMap=null,this._material.aoMap=null,this._material.map=null,this._material.userData.ssaoDisabled&&delete this._material.userData.ssaoDisabled,this._material.userData.ssreflDisabled&&delete this._material.userData.ssreflDisabled,this._material.userData.ssreflNonPhysical&&delete this._material.userData.ssreflNonPhysical,super._removeMaterial())}refresh(){this._viewer&&(this.contactShadows?this._depthTex=tt(this._depthPass?.target)?.texture||null:(this._material?.alphaMap===this._depthTex&&(this._material.alphaMap=null,this._material.setDirty()),this._material?.aoMap===this._depthTex&&(this._material.aoMap=null,this._material.setDirty()),this._material?.map===this._depthTex&&(this._material.map=null,this._material.setDirty()),this._material?.userData.__csgpParamsSet&&(delete this._material.userData.__csgpParamsSet,delete this._material.userData.ssaoDisabled,delete this._material.userData.ssreflDisabled,delete this._material.userData.ssreflNonPhysical),this._depthTex=null),super.refresh())}_createMaterial(e){const t=super._createMaterial(e);return t.roughness=1,t.metalness=0,t.color.set(16777215),t.transparent=!0,t}_refreshMaterial(){if(!this._viewer)return!1;const e=super._refreshMaterial();return this._material&&this.contactShadows&&(this._material.userData.ssaoDisabled=this.mapMode==="aoMap",this._material.userData.ssreflDisabled=this.mapMode==="alphaMap",this._material.userData.ssreflNonPhysical=!1,this._material.userData.__csgpParamsSet=!0,this._material.alphaMap===this._depthTex&&(this._material.alphaMap=null),this._material.aoMap===this._depthTex&&(this._material.aoMap=null),this._material.map===this._depthTex&&(this._material.map=null),this._material[this.mapMode]=this._depthTex,this._material.setDirty(),this._depthPass&&(this._depthPass.clearColor.set(this.mapMode==="aoMap"?new ee(1,1,1):new ee(0,0,0)),this._depthPass.clearAlpha=this.mapMode==="aoMap"?1:0,this._depthPass.overrideMaterial.opacity=this.mapMode==="aoMap"?-1:1)),e}},f.ContactShadowGroundPlugin.PluginType="ContactShadowGroundPlugin",Rh([se("Contact Shadows"),he(f.ContactShadowGroundPlugin.prototype.refresh),G()],f.ContactShadowGroundPlugin.prototype,"contactShadows",2),Rh([Fe("Shadow Scale",[0,2]),G(),he(f.ContactShadowGroundPlugin.prototype._refreshShadowCameraFrustum)],f.ContactShadowGroundPlugin.prototype,"shadowScale",2),Rh([Fe("Shadow Height",[0,20]),G(),he(f.ContactShadowGroundPlugin.prototype._refreshShadowCameraFrustum)],f.ContactShadowGroundPlugin.prototype,"shadowHeight",2),Rh([Fe("Blur Amount",[0,10]),G(),he(f.ContactShadowGroundPlugin.prototype._setDirty)],f.ContactShadowGroundPlugin.prototype,"blurAmount",2),Rh([he(f.ContactShadowGroundPlugin.prototype._refreshMaterial),Li("Map Mode",["aoMap","map","alphaMap"]),G()],f.ContactShadowGroundPlugin.prototype,"mapMode",2),f.ContactShadowGroundPlugin=Rh([Aa("Ground Plane (Contact Shadows)")],f.ContactShadowGroundPlugin);var F8=Object.defineProperty,N8=Object.getOwnPropertyDescriptor,Bb=(r,e,t,i)=>{for(var n=i>1?void 0:i?N8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&F8(e,t,n),n};const sw=class sw extends mt{constructor(){super(),this.enabled=!0,this.toJSON=void 0,this.simplifyFactor=.5}get initialized(){return!0}async initialize(){}onAdded(e){super.onAdded(e),this._pickingPlugin=e.getPlugin(vs)}simplifyGeometries(e,t){if(!e){const n=this._pickingPlugin?.getSelectedObject();if(!n?.isObject3D)return;const s=[];if(n?.traverse(a=>{a.geometry&&!s.includes(a.geometry)&&s.push(a.geometry)}),e=s,!e||!e.length)return}Array.isArray(e)||(e=[e]);const i=[];for(const n of e)i.push(this.simplifyGeometry(n,t));return i}simplifyGeometry(e,{factor:t,count:i,replace:n=!0,disposeOnReplace:s=!1}={}){if(!e&&(e=this._pickingPlugin?.getSelectedObject()?.geometry,!e))return;if(!e.attributes.position)return this._viewer?.console.error("SimplifyModifierPlugin: Geometry does not have position attribute",e),e;t=t||this.simplifyFactor,i=i||e.attributes.position.count*t,e.boundingBox||e.computeBoundingBox();const a=this._simplify(e,i);a.computeBoundingBox(),a.computeBoundingSphere(),a.computeVertexNormals();const o=a.boundingBox,l=o.getSize(new S);if(!isFinite(l.x)||!isFinite(l.y)||!isFinite(l.z))return this._viewer?.console.error("SimplifyModifierPlugin: Unable to simplify",e,a,l),e;const c=e.boundingBox,h=c.getSize(new S),u=l.clone().sub(h),d=u.clone().divide(h);if(d.lengthSq()>.001&&console.warn("Simplify",e,a,o,c,l,h,u,d),!n)return a;const p=e.appliedMeshes;if(!p)return console.error("No meshes found for geometry, cannot replace",e),a;for(const m of p)m.geometry=a;return s&&e.dispose(!0),a}async simplifyAll(e,t){if(!e&&this._viewer&&(e=this._viewer.scene.modelRoot),!e){console.error("SimplifyModifierPlugin: No root found");return}if(!this.initialized&&(await this.initialize(),!this.initialized)){this._viewer?.console.error("SimplifyModifierPlugin cannot be initialized");return}const i=[];if(e.traverse(n=>{n.geometry&&!i.includes(n.geometry)&&i.push(n.geometry)}),!i.length){console.error("SimplifyModifierPlugin: No geometries found");return}return this.simplifyGeometries(i,t)}async simplifySelected(){if(!this._viewer)return;if(!this.initialized&&(await this.initialize(),!this.initialized)){await this._viewer.dialog.alert("Simplify: SimplifyModifierPlugin cannot be initialized");return}const e=this._pickingPlugin?.getSelectedObject();if(!e?.isObject3D){await this._viewer.dialog.alert("Simplify: No Object Selected");return}let t=!1;e.geometry?e.children.length===0&&(t=!0):t=!0,t||await this._viewer.dialog.confirm("Simplify: Simplify all in hierarchy?")&&(t=!0),t?this.simplifyGeometries():this.simplifyGeometry(e.geometry)}};sw.PluginType="SimplifyModifierPlugin";let Ul=sw;Bb([Fe("Simplify Factor",[0,1])],Ul.prototype,"simplifyFactor",2),Bb([ct("Simplify All",{sendArgs:!1})],Ul.prototype,"simplifyAll",1),Bb([ct("Simplify Selected")],Ul.prototype,"simplifySelected",1);var k8=Object.defineProperty,G8=Object.getOwnPropertyDescriptor,Lb=(r,e,t,i)=>{for(var n=i>1?void 0:i?G8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&k8(e,t,n),n};f.MeshOptSimplifyModifierPlugin=class extends Ul{constructor(e=!0,t=document.head){super(),this.rootNode=t,this._initializing=void 0,this.errorThreshold=.5,this.lockBorder=!1,e&&this.initialize()}get initialized(){return!!window.MeshoptSimplifier}onAdded(e){super.onAdded(e)}async initialize(){if(this.initialized)return;if(this._initializing)return await this._initializing;const e=document.createElement("script");e.type="module";const t=Math.random().toString(36).substring(7);return e.innerHTML=`
import { MeshoptSimplifier } from ${JSON.stringify(f.MeshOptSimplifyModifierPlugin.SIMPLIFIER_URL)};
MeshoptSimplifier.ready.then(() => {
window.MeshoptSimplifier = MeshoptSimplifier;
window.dispatchEvent(new CustomEvent('${t}'))
});
`,this._initializing=new Promise(i=>{window.addEventListener(t,()=>i(),{once:!0}),this.rootNode.appendChild(e),this._script=e}),await this._initializing}dispose(){this._script&&(this._script.remove(),delete window.MeshoptSimplifier),this._script=void 0}_simplify(e,t){if(!this.initialized)throw new Error("MeshOptSimplifyModifierPlugin not initialized");e.index?e=e.clone():e=lv(e);const i=e.index.array,n=e.attributes.position.array,s=t/e.attributes.position.count,a=3*Math.floor(s*i.length/3),[o,l]=window.MeshoptSimplifier.simplify(i,n,3,a,this.errorThreshold,this.lockBorder?["LockBorder"]:[]);return console.log("srcCount",i.length/3,"destCount",o.length/3),l&&console.warn("Simplify error",l),e.setIndex(new Ze(new Uint32Array(o),1)),ni.upgradeGeometry.call(e.toNonIndexed())}},f.MeshOptSimplifyModifierPlugin.PluginType="MeshOptSimplifyModifierPlugin",f.MeshOptSimplifyModifierPlugin.SIMPLIFIER_URL="https://unpkg.com/meshoptimizer@0.20.0/meshopt_simplifier.module.js",Lb([Ot()],f.MeshOptSimplifyModifierPlugin.prototype,"errorThreshold",2),Lb([se()],f.MeshOptSimplifyModifierPlugin.prototype,"lockBorder",2),f.MeshOptSimplifyModifierPlugin=Lb([vt("Simplify Modifier (meshopt)")],f.MeshOptSimplifyModifierPlugin);const z8=r=>{const e=[],t=new Set;for(const i of r){let n=i,s=0;for(;t.has(n);)n=i+"."+ ++s;t.add(n),e.push(n)}return e},V8=(r,e)=>{const t={};for(const i of r.mappings)for(const n of i.variants)t[e[n]]={material:null,gltfMaterialIndex:i.material};return t},H8=r=>r.material!==void 0&&r.userData&&r.userData._variantMaterials,Bh="KHR_materials_variants";class Q8{constructor(e){this.parser=e,this.name=Bh}async afterRoot(e){const t=this.parser,i=t.json;if(!i.extensions||!i.extensions[this.name])return;const s=i.extensions[this.name].variants||[],a=z8(s.map(l=>l.name));for(const l of e.scenes)l.traverse(c=>{const h=t.associations.get(c);if(!h||h.meshes===void 0||h.primitives===void 0)return;const p=i.meshes[h.meshes].primitives[h.primitives].extensions;!p||!p[this.name]||(c.userData._variantMaterials=V8(p[this.name],a))});const o=async l=>{const c=l.material,h=l.userData._variantMaterials,u=[];for(const d in h){const p=h[d];if(p.material)continue;const m=p.gltfMaterialIndex;u.push(t.getDependency("material",m).then(A=>{l.material=A,t.assignFinalMaterial(l),h[d].material=l.material}))}return Promise.all(u).then(()=>{l.material=c})};await Promise.all(e.scenes.map(async l=>{const c=[];return l.traverse(h=>H8(h)&&c.push(o(h))),l.userData.__importData||(l.userData.__importData={}),l.userData.__importData[Bh]={names:a},Promise.all(c)}))}}const PP=r=>r.material!==void 0&&r.userData&&r.userData._variantMaterials&&!!Object.values(r.userData._variantMaterials).filter(e=>nA(e?.material)),nA=r=>r&&r.isMaterial&&!Array.isArray(r);class j8{constructor(e){this.writer=e,this.name=Bh,this.variantNames=[]}beforeParse(e){const t=new Set;for(const i of e)i.traverse(n=>{if(!PP(n))return;const s=n.userData._variantMaterials;for(const a in s){const o=s[a];nA(o.material)&&t.add(a)}});t.forEach(i=>this.variantNames.push(i))}writeMesh(e,t){if(!PP(e))return;const i=e.userData,n=i._variantMaterials,s={};for(const l in n){const c=n[l].material;if(!nA(c))continue;const h=this.variantNames.indexOf(l),u=this.writer.processMaterial(c);s[u]||(s[u]={material:u,variants:[]}),s[u].variants.push(h)}const a=Object.values(s).map(l=>l.variants.sort((c,h)=>c-h)&&l).sort((l,c)=>l.material-c.material);if(a.length===0)return;const o=nA(i._originalMaterial)?this.writer.processMaterial(i._originalMaterial)??-1:-1;for(const l of t.primitives)o>=0&&(l.material=o),l.extensions=l.extensions||{},l.extensions[this.name]={mappings:a}}afterParse(e){if(this.variantNames.length===0)return;const t=this.writer.json;t.extensions=t.extensions||{};const i=this.variantNames.map(n=>({name:n}));t.extensions[this.name]={variants:i},this.writer.extensionsUsed[this.name]=!0}}function W8(r){return new j8(r)}var q8=Object.defineProperty,DP=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&q8(e,t,n),n};const sA=(qh=class extends mt{constructor(){super(),this.enabled=!0,this.variants={},this.selectedVariant="",this.applyFirstVariantOnLoad=!0,this._objectAdded=e=>{const t=e.object;t?.isObject3D&&this._viewer&&(t.traverse(i=>{if(i.userData._variantMaterials)for(const a of Object.values(i.userData._variantMaterials))a?.material&&(a.material=this._viewer?.materialManager.convertToIMaterial(a.material,{})||a.material);const n=i.userData?.__importData?.[Bh];if(!n)return;const s=n.names||[];for(const a of s)this.variants[a]||(this.variants[a]=[]),this.variants[a].push(i);delete i.userData.__importData[Bh]}),!this.selectedVariant&&this.applyFirstVariantOnLoad&&(this.selectedVariant=Object.keys(this.variants)[0]||""),this.uiConfig.uiRefresh?.())},this.uiConfig={type:"folder",label:"KHR Material Variants",children:[()=>({children:[null,...Object.keys(this.variants)].map(e=>e?{label:e}:{label:"none",value:""}),type:"dropdown",label:"Variant",property:[this,"selectedVariant"]})]}}onAdded(e){super.onAdded(e),e.scene.addEventListener("addSceneObject",this._objectAdded),e.assetManager.registerGltfExtension(RP)}onRemove(e){return e.scene.removeEventListener("addSceneObject",this._objectAdded),e.assetManager.unregisterGltfExtension(RP.name),this.variants={},super.onRemove(e)}_variantChanged(){this.applyVariant(this.selectedVariant||"",!0)}applyVariant(e,t=!1,i,n=!0){if(!t&&!i&&this.selectedVariant===e||!e)return;i||(this.selectedVariant=e);const s=i?Array.isArray(i)?i:[i]:e?this.variants[e]||[]:Object.values(this.variants).flat();for(const a of s){const o=new Set,l=c=>{if(!c.userData._variantMaterials||o.has(c))return;const h=e?c.userData._variantMaterials[e]?.material:c.userData._originalMaterial;h&&(c.userData._originalMaterial||(c.userData._originalMaterial=c.material),c.material=h),o.add(c)};n?a.traverse(l):l(a)}}},qh.PluginType="GLTFKHRMaterialVariantsPlugin",qh);DP([he(sA.prototype._variantChanged),G()],sA.prototype,"selectedVariant"),DP([G()],sA.prototype,"applyFirstVariantOnLoad");let X8=sA;const RP={name:Bh,import:r=>new Q8(r),export:W8};var Y8=Object.getOwnPropertyDescriptor,$8=(r,e,t,i)=>{for(var n=i>1?void 0:i?Y8(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(n)||n);return n};f.TailwindCSSCDNPlugin=class extends mt{constructor(){super(...arguments),this.enabled=!0,this._tailwindScript=null,this.toJSON=null}async onAdded(e){super.onAdded(e),this._tailwindScript=document.createElement("script"),this._tailwindScript.src=f.TailwindCSSCDNPlugin.CDN_URL,this._tailwindScript.type="text/javascript",document.head.appendChild(this._tailwindScript)}onRemove(e){this._tailwindScript&&this._tailwindScript.parentNode&&(this._tailwindScript.parentNode.removeChild(this._tailwindScript),this._tailwindScript=null),super.onRemove(e)}},f.TailwindCSSCDNPlugin.PluginType="TailwindCDNPlugin",f.TailwindCSSCDNPlugin.CDN_URL="https://cdn.tailwindcss.com",f.TailwindCSSCDNPlugin=$8([vt("Tailwind CSS")],f.TailwindCSSCDNPlugin);const rw=class rw extends mt{constructor(){super(),this.enabled=!0,this.plugins=new Map,this._path="./TestPlugin.ts",this.uiConfig={type:"folder",label:"Viewer Scripts",expanded:!0,children:[{type:"input",label:"Path",property:[this,"_path"]},{type:"button",label:"Load Plugin",value:async()=>{await this.loadPlugin(this._path),this.uiConfig.uiRefresh?.(!0,"postFrame")}},{type:"button",label:"Unload Plugin",value:async()=>{await this.unloadPlugin(this._path),this.uiConfig.uiRefresh?.(!0,"postFrame")}},{type:"button",label:"Refresh UI",value:async()=>{this.uiConfig.uiRefresh?.(!0,"postFrame")}},{type:"folder",label:"Loaded Plugins",expanded:!0,children:[()=>[...this.plugins.values()].map(e=>this._viewer?.getPlugin(e)?.uiConfig)]}]}}onAdded(e){super.onAdded(e)}async loadPlugin(e){const t=this._viewer;if(!t)throw new Error("Plugin not added to viewer.");typeof e=="object"&&typeof e.then=="function"&&(e=await e),e=e;const i=typeof e=="string"?e:e.__tpPluginPath||"";if(i?.length&&this.plugins.has(i))throw new Error("Plugin already loaded: "+i);const n=typeof e=="object"?e:typeof i=="string"&&i?await import(i+"?t="+Date.now()):null;if(!n)throw new Error("Could not find/load module: "+i);const s=n.default||Object.values(n)[0];if(!s)throw new Error("No plugin found in module: "+i);if(typeof s!="function")throw new Error("Plugin is not a class or function in module: "+e);if(!(s.prototype&&s.prototype instanceof Zc))throw new Error("Plugin is not a subclass of AViewerPlugin in module: "+e);const a=s.PluginType;if(console.log(a),console.log(n),t.getPlugin(a))throw new Error("Plugin of type "+a+" already added to viewer");return i?.length&&this.plugins.set(i,s),await t.addPlugin(s)}async unloadPlugin(e){const t=this._viewer;if(!t)throw new Error("Plugin not added to viewer.");const i=this.plugins.get(e);if(!i)throw new Error("Plugin not loaded: "+e);const n=t.getPlugin(i);if(!n)throw new Error("Plugin not found in viewer: "+e);await t.removePlugin(n),this.plugins.delete(e)}};rw.PluginType="DynamicImportPlugin";let Ob=rw;const K8={handleHotUpdate({server:r,modules:e,timestamp:t}){const i=new Set,n=[];for(const s of e)console.log(s.id,s.url),s.url.endsWith(".plugin.ts")?(r.moduleGraph.invalidateModule(s,i,t,!0),r.ws.send({type:"custom",event:"custom-tp-plugin-update",data:{url:s.url,id:s.id}})):n.push(s);return n},transform(r,e){if(e.endsWith(".plugin.ts")){const t=`
export const __tpPluginPath = "${e}";
`;return r+t}}},Fl={copy_position:{defaultProps:{axis:["x","y","z"],invert:[]},update:(r,e,t,i)=>{if(!e)return{changed:!1};const{axis:n=["x","y","z"],invert:s=[]}=t,a=e.getWorldPosition(new S);let o=!1,l=!0;return n.forEach(c=>{s.includes(c)&&(a[c]*=-1);const h=r.position[c];r.position[c]=a[c]*i+h*(1-i),o=o||Math.abs(r.position[c]-h)>1e-5,l=l&&Math.abs(r.position[c]-h)<1e-5}),{changed:o,end:l,change:"position"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="position"||t==="transform"}},copy_rotation:{defaultProps:{axis:["x","y","z"],invert:[],order:void 0},update:(r,e,t,i)=>{if(!e)return{changed:!1};const{axis:n=["x","y","z"],invert:s=[]}=t;let a=t.order;const o=new Pt().copy(r.rotation);a||(a=o.order),o.order=a;const l=new $e;e.getWorldQuaternion(l);const c=new Pt().setFromQuaternion(l,a);let h=!1,u=!0;return n.forEach(d=>{let p=c[d];s.includes(d)&&(p*=-1);const m=r.rotation[d],A=p*i+m*(1-i);o[d]=A,h=h||Math.abs(A-m)>1e-5,u=u&&Math.abs(A-m)<1e-5}),r.rotation.copy(o),{changed:h,end:u,change:"rotation"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="rotation"||t==="quaternion"||t==="transform"}},copy_scale:{defaultProps:{axis:["x","y","z"]},update:(r,e,t,i)=>{if(!e)return{changed:!1};const{axis:n=["x","y","z"],uniform:s=!1}=t,a=new S;e.getWorldScale(a);const o=r.scale.clone();let l=0;if(n.forEach(u=>{const d=a[u]*i+o[u]*(1-i);r.scale[u]=d,l=l+d}),s){const u=l/n.length;r.scale.set(u,u,u)}const c=!o.equals(r.scale),h=o.distanceTo(r.scale)<1e-5;return{changed:c,end:h,change:"scale"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="scale"||t==="transform"}},copy_transforms:{defaultProps:{},update:(r,e,t,i)=>{if(!e)return{changed:!1};const n=new fe;e.updateMatrixWorld(),n.copy(e.matrixWorld);const s=new S().copy(r.position),a=new $e().copy(r.quaternion),o=new S().copy(r.scale),l=new S,c=new $e,h=new S;n.decompose(l,c,h),r.position.lerpVectors(s,l,i),r.quaternion.slerpQuaternions(a,c,i),r.scale.lerpVectors(o,h,i);const u=!s.equals(r.position)||!a.equals(r.quaternion)||!o.equals(r.scale),d=s.distanceTo(r.position)<1e-5&&a.angleTo(r.quaternion)<1e-5&&o.distanceTo(r.scale)<1e-5;return{changed:u,end:d,change:"transform"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="position"||t==="rotation"||t==="quaternion"||t==="scale"||t==="transform"}},follow_path:{defaultProps:{offset:0,followCurve:!1},update:(r,e,t,i)=>{if(!e)return{changed:!1};const{offset:n=0,followCurve:s=!1}=t;if(!e.geometry)return{changed:!1};const a=e.geometry,o=a.getPositions?a.getPositions():a.attributes?.position?.array,l=J8(o,n);if(!l)return{changed:!1};const{targetPos:c,direction:h}=l,u=e.localToWorld(c.clone()),d=h?.lengthSq()>0?e.localToWorld(h.clone().add(c)).sub(u).normalize():null,p=new S().copy(r.position),m=new $e().copy(r.quaternion);r.position.copy(u);let A=!1;if(s&&d){const _=u.clone().add(d);if(r.lookAt(_),i!==1){const b=r.quaternion.clone();r.quaternion.slerpQuaternions(m,b,i)}A=!m.equals(r.quaternion)}i!==1&&r.position.lerpVectors(p,u,i);const y=!p.equals(r.position)||A,v=p.distanceTo(r.position)<1e-5&&(!A||m.angleTo(r.quaternion)<1e-5);return{changed:y,end:v,change:A?"transform":"position"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="position"||t==="transform"||t==="geometry"}},look_at:{defaultProps:{upAxis:"y"},update:(r,e,t,i)=>{if(!e)return{changed:!1};const{upAxis:n="y"}=t,a=e.getWorldPosition(new S).clone().sub(r.position).normalize(),o=new S(0,1,0);n==="x"?o.set(1,0,0):n==="-x"?o.set(-1,0,0):n==="y"?o.set(0,1,0):n==="-y"?o.set(0,-1,0):n==="z"?o.set(0,0,1):n==="-z"&&o.set(0,0,-1);const l=new S().crossVectors(o,a).normalize();o.crossVectors(a,l).normalize();const c=new fe;c.makeBasis(l,o,a);const h=new $e().setFromRotationMatrix(c);r.quaternion.slerp(h,i);const u=!r.quaternion.equals(h),d=r.quaternion.angleTo(h)<1e-5;return{changed:u,end:d,change:"rotation"}},setDirty(r,e){const t=r.change||r.key;return!t||t==="position"||t==="rotation"||t==="quaternion"||t==="scale"||t==="transform"}}};function J8(r,e){if(!r)return null;const t=r.length/3;if(t<2)return null;const i=[];let n=0;for(let b=0;b<t-1;b++){const T=r[b*3],E=r[b*3+1],M=r[b*3+2],I=r[(b+1)*3],C=r[(b+1)*3+1],x=r[(b+1)*3+2],D=Math.sqrt((I-T)**2+(C-E)**2+(x-M)**2);i.push(D),n+=D}if(n===0)return null;const a=Math.max(0,Math.min(1,e))*n;let o=0,l=0,c=0;for(let b=0;b<i.length;b++){if(o+i[b]>=a){l=b,c=(a-o)/i[b];break}o+=i[b]}const h=l*3,u=(l+1)*3,d=r[h],p=r[h+1],m=r[h+2],A=r[u],g=r[u+1],y=r[u+2],v=new S(d+(A-d)*c,p+(g-p)*c,m+(y-m)*c),_=new S(A-d,g-p,y-m);return _.normalize(),{targetPos:v,direction:_}}var Z8=Object.defineProperty,e6=Object.getOwnPropertyDescriptor,wo=(r,e,t,i)=>{for(var n=i>1?void 0:i?e6(e,t):e,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=(i?a(e,t,n):a(n))||n);return i&&n&&Z8(e,t,n),n};f.ObjectConstraintsPlugin=class extends mt{constructor(e=!0){super(),this.enabled=!0,this.dependencies=[],this._objectAdd=t=>{const i=t.object;i&&(i.isWidget||(Array.isArray(i.userData.constraints)&&i.userData.constraints.forEach(n=>this._registerConstraint(n,i)),this._setupUiConfig(i),Array.from(this._constraints.keys()).forEach(n=>{n?.target===i.uuid&&this._refreshConstraint(n,i)})))},this._objectRemove=t=>{const i=t.object;i&&(Array.isArray(i.userData.constraints)&&i.userData.constraints.forEach(n=>this._unregisterConstraint(n,i)),this._cleanUpUiConfig(i),this._constraintTargets.get(i)?.forEach(n=>this._refreshConstraint(n,null)))},this._constraints=new Map,this._constraintTargets=new Map,this._constraintObjects=new Map,this._objectUpdate=t=>{this._constraintTargets.get(t.object)?.forEach(i=>{i.setDirty(t,!0)}),this._constraintObjects.get(t.object)?.forEach(i=>{i.setDirty(t,!1)})},this._viewerListeners={preFrame:()=>{if(this.isDisabled()||this._viewer?.timeline.running&&this._viewer.timeline.delta===0)return;Array.from(this._constraints.keys()).filter(i=>i.needsUpdate).forEach(i=>{const n=this._constraints.get(i);n&&i.update(n)})}},this.enabled=e}addConstraint(e,t,i){const n=typeof t=="string"?new f.ObjectConstraint(t):t||new f.ObjectConstraint;return e.userData.constraints||(e.userData.constraints=[]),i&&(typeof i=="string"?n.target=i:n.target=i.uuid),e.userData.constraints.includes(n)||(e.userData.constraints.push(n),this._registerConstraint(n,e),e.setDirty&&e.setDirty({change:"userData.constraints",source:"ObjectConstraintsPlugin.addConstraint"})),n}removeConstraint(e,t){if(!e.userData.constraints)return;const i=e.userData.constraints.indexOf(t);i!==-1&&(e.userData.constraints.splice(i,1),this._unregisterConstraint(t,e),e.setDirty&&e.setDirty({change:"userData.constraints",source:"ObjectConstraintsPlugin.addConstraint"}))}_refreshConstraint(e,t){const i=this._constraints.get(e);if(!i)return;const n=t!==void 0?t??void 0:this._viewer?.object3dManager.findObject(e.target),s=i.target;n!==s&&(this._removeTarget(s,e),this._addTarget(n,e)),i.target=n}_registerConstraint(e,t){if(this._constraints.has(e)){this._refreshConstraint(e);return}this._constraints.set(e,{obj:t}),this._constraintObjects.has(t)||this._constraintObjects.set(t,new Set),this._constraintObjects.get(t).add(e),this._refreshConstraint(e),e.refresh=()=>this._refreshConstraint(e),e.remove=()=>(this.removeConstraint(t,e),()=>{this.addConstraint(t,e)});const i=e.uiConfig,n=t.userData.constraints?.indexOf(e)??-1;if(i&&n>=0){const s=this._viewer?.getPlugin("AnimationObjectPlugin");if(s){const a=this._animatableComponents(e);a.length&&a.forEach(o=>s.setupUiConfigButton(t,o,"userData.constraints."+n.toString()+".props."))}}}_unregisterConstraint(e,t){if(!this._constraints.has(e))return;const i=this._constraints.get(e);if(i?.obj===t){this._removeTarget(i.target,e);const n=this._constraintObjects.get(t);if(n&&(n.delete(e),n.size===0&&this._constraintObjects.delete(t)),this._constraints.delete(e),e.refresh=void 0,e.uiConfig){const a=this._viewer?.getPlugin("AnimationObjectPlugin");a&&this._animatableComponents(e).forEach(o=>a.cleanupUiConfigButton(o))}}}_animatableComponents(e){return e?.uiConfig?.children?.flatMap(t=>tt(t)).filter(t=>typeof t=="object"&&t.type==="number"&&t.property[1]==="offset"&&t.property[0]===e.props)||[]}_addTarget(e,t){if(!e)return;this._constraintTargets.has(e)||this._constraintTargets.set(e,new Set);const i=this._constraintTargets.get(e);i.has(t)||(i.add(t),t.setDirty())}_removeTarget(e,t){if(!e)return;const i=this._constraintTargets.get(e);i&&(i.has(t)&&(i.delete(t),t.setDirty()),i.size===0&&this._constraintTargets.delete(e))}_setupUiConfig(e){!(e.isObject3D||e.isMaterial)||!e.uiConfig||e.uiConfig?.children?.find(n=>typeof n=="object"&&n.tags?.includes(f.ObjectConstraintsPlugin.PluginType))||e.uiConfig?.children?.push({type:"folder",label:"Constraints",tags:["constraints",f.ObjectConstraintsPlugin.PluginType],children:[()=>e.userData.constraints?.map(n=>n.uiConfig),{type:"button",label:"Add Constraint",icon:"plus",tags:["context-menu","header-action"],onClick:()=>{const n=this.addConstraint(e);return()=>this.removeConstraint(e,n)}}]})}_cleanUpUiConfig(e){if(!e.uiConfig)return;const t=e.uiConfig?.children?.findIndex(i=>typeof i=="object"&&i.tags?.includes(f.ObjectConstraintsPlugin.PluginType));t!==void 0&&t>=0&&e.uiConfig.children?.splice(t,1)}onAdded(e){super.onAdded(e),e.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.scene.addEventListener("objectUpdate",this._objectUpdate)}onRemove(e){e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.scene.removeEventListener("objectUpdate",this._objectUpdate),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),super.onRemove(e)}},f.ObjectConstraintsPlugin.PluginType="ObjectConstraintsPlugin",f.ObjectConstraintsPlugin.ConstraintTypes=Fl,wo([se(),G()],f.ObjectConstraintsPlugin.prototype,"enabled",2),f.ObjectConstraintsPlugin=wo([vt("Object Constraints")],f.ObjectConstraintsPlugin),f.ObjectConstraint=class{constructor(e){this.uuid=Oi(),this.enabled=!0,this.target="",this.influence=1,this.props={},this.needsUpdate=!1,this.setDirty=(t,i)=>{if(!(this.needsUpdate||t?.source===this.uuid)){if(typeof t!="object"&&(t=void 0),t){const n=Fl[this.type];if(t.key&&/.props\..+$/.test(t.key))this._propsUi.forEach(s=>s?.uiRefresh?.());else if(n?.setDirty&&!n.setDirty(t,i))return!1}return this.needsUpdate=!0,!0}},this.refresh2=()=>{this.refresh&&this.refresh(),this.setDirty()},this._propsUi=[],this.uiConfig={type:"folder",label:()=>this.type||"Constraint",tags:["constraint",f.ObjectConstraintsPlugin.PluginType],onChange:this.setDirty,children:[...bi(this),()=>{if(this._propsUi.length)return this._propsUi.forEach(i=>i.uiRefresh?.(!0)),this._propsUi;const t=bi(this.props).map(i=>tt(i));return this._propsUi=t,t},{type:"button",tags:["context-menu"],label:"Remove Constraint",icon:"cross",property:[this,"remove"]}]},this.type=e??"copy_position",this.props=Fl[this.type]?.defaultProps||{},this.props||(this.props={})}update(e){const i=Fl[this.type]?.update(e.obj,e.target,this.props,this.influence);return i?.changed&&i.change&&e.obj.setDirty&&e.obj.setDirty({change:i.change,source:this.uuid}),this.needsUpdate=!(i.end??!0),i?.changed||!1}typeChanged(){const e=this.props;this.props=Fl[this.type]?.defaultProps||{};for(const t of Object.keys(this.props))if(e[t]!==void 0){const i=typeof this.props[t],n=typeof e[t];i===n&&(typeof i!="object"||i?.type&&i.type===n?.type)&&(this.props[t]=e[t])}this._propsUi=[],this.setDirty(),this.uiConfig?.uiRefresh?.(!0,"postFrame",1)}},wo([G(),se()],f.ObjectConstraint.prototype,"enabled",2),wo([G(),he("typeChanged"),Li(void 0,Object.keys(Fl).map(r=>({label:r})))],f.ObjectConstraint.prototype,"type",2),wo([G(),he("refresh2"),He()],f.ObjectConstraint.prototype,"target",2),wo([G(),Fe(void 0,[0,1],.01)],f.ObjectConstraint.prototype,"influence",2),wo([G()],f.ObjectConstraint.prototype,"props",2),f.ObjectConstraint=wo([Vc("ObjectConstraint")],f.ObjectConstraint);function t6(r){return{oneOf:r.map(e=>typeof e=="number"||typeof e=="boolean"?`${e}`:`"${e}"`),type:"Union"}}const aw=class aw{static AddClass(e){const t=e.ctor.prototype.serializableClassId;if(!t){console.error("Non Serializable class cannot be added to TypeSystem",e);return}t!==e.key&&console.warn(`TypeSystem: class serializableClassId "${t}" does not match registered className "${e.key}"`),this.Classes.set(e.key,e)}static GetClass(e){const t=typeof e=="string"?e:e.type;return this.Classes.get(t)}static GetClassType(e){for(const[t,i]of this.Classes)if(i.ctor===e)return t}static GetType(e,t=!0){if(e===void 0)return!1;if(e===null)return"null";if(typeof e=="function")return!1;if(typeof e=="number")return`${e}`;if(typeof e=="string")return`${JSON.stringify(e)}`;if(typeof e=="boolean")return`${e}`;if(Array.isArray(e)){const i=new Set;for(const s of e){const a=this.GetType(s);if(!a)return!1;i.add(a)}return{arrayOf:i.size===1?i.values().next().value:{oneOf:i,type:"Union"},type:"Array"}}if(typeof e=="object"){const i=e.constructor;if(i&&i!==Object){const s=this.GetClassType(i);if(s)return s;if(t){if(e.type&&Lt.SerializableClasses.has(e.type))return e.type;if(e.serializableClassId&&Lt.SerializableClasses.has(e.serializableClassId))return e.serializableClassId;const a=Lt.GetSerializer(e);return a&&typeof a.type=="string"&&!a.type.startsWith("_")?a.type:!1}}const n=new Map;for(const s in e){const a=e[s];if(typeof a=="function")continue;const o=this.GetType(a);if(!o)return!1;n.set(s,o)}return{recordOf:n,type:"Object"}}return!1}static NonLiteral(e){return typeof e!="string"?e:/^"(?:[^"\\]|\\.)*"$/.test(e)?"string":/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)?"number":e==="true"||e==="false"?"boolean":e==="Infinity"||e==="-Infinity"||e==="NaN"?"number":e}static TypeToString(e){return typeof e=="string"?e:"oneOf"in e?`(${Array.from(e.oneOf).map(t=>this.TypeToString(t)).join("|")})`:"arrayOf"in e?`Array<${this.TypeToString(e.arrayOf)}>`:"recordOf"in e?`{ ${Array.from(e.recordOf.entries()).map(([i,n])=>`${i}: ${this.TypeToString(n)}`).join("; ")} }`:e.type}static CanAssign(e,t){if(e===t)return!0;const i=this.GetClass(e),n=this.GetClass(t);if(i&&i===n)return!0;if(typeof t=="string"){if(typeof e=="string")return this.NonLiteral(e)===t;if("oneOf"in e){const s=e.oneOf;for(const a of s)if(!this.CanAssign(a,t))return!1;return!0}return"arrayOf"in e||"recordOf"in e,!1}if("oneOf"in t){const s=t.oneOf;for(const a of s)if(this.CanAssign(e,a))return!0;return!1}if("arrayOf"in t)return typeof e!="string"&&"arrayOf"in e?this.CanAssign(e.arrayOf,t.arrayOf):!1;if("recordOf"in t){if(typeof e!="string"&&"recordOf"in e){for(const[s,a]of t.recordOf){const o=e.recordOf.get(s);if(!o||!this.CanAssign(o,a))return!1}return!0}return!1}return!1}};aw.Classes=new Map;let zr=aw;class BP{constructor(e){this.isItemRef=!0,this.id=e||""}toJSON(e){if(!this.id)return{};if(e&&(e.typed||(e.typed={}),!e.typed[this.id])){const t=Ba.Get(this);t&&(t.__rootPath?e.typed[this.id]={external:!0,rootPath:t.__rootPath,rootPathOptions:t.__rootPathOptions}:e.typed[this.id]=We.Serialize(t,e))}return{id:this.id}}fromJSON(e,t){if(e&&typeof e.id=="string"&&(this.id=e.id,t?.typed)){const i=t.typed[this.id],n=t.__isLoadedResources,s=n&&i?i:We.Deserialize(i,t);s?.external&&s.rootPath?console.warn("ReferenceManager - External resources is expected to be loaded already in ImportMeta phase:",s):(this._itemObject=s,n&&(t.typed[this.id]=s))}return this}}const cf=class cf{static Get(e){const t=this.Objects.get(e.id);return t?t.object:null}static Add(e,t,i){let n=this.Objects.get(e);n||(n={id:e,refs:new Map,object:t},this.Objects.set(e,n));let s=n.refs.get(i);s||(s=new Set,n.refs.set(i,s));const a=new BP(e);return s.add(a),a}static Remove(e,t,i){const n=this.Objects.get(e);if(n){const s=n.refs.get(t);s&&s.has(i)&&(s.delete(i),s.size===0&&(n.refs.delete(t),n.refs.size===0&&this.Objects.delete(e)))}}static Delete(e){if(e)for(const[t,i]of[...this.Objects])i.refs.delete(e),i.refs.size===0&&this.Objects.delete(t),i.object===e&&this.Objects.delete(t)}static RemoveOp(e,t){if(e!==void 0&&e.isItemRef){const i=e;cf.Remove(i.id,t,i)}}static GetOp(e,t=!0){if(e.isItemRef){const i=cf.Get(e);return i||(t&&console.error("Object3DComponent: Reference not found",e),null)}}static GetCached(e){if(e&&e.isItemRef&&e._itemObject){const t=e._itemObject;return e._itemObject=void 0,t}}};We.MakeSerializable(BP,"ItemRef"),cf.Objects=new Map;let Ba=cf;function Lh(r){const e=new Set;let t=r;for(;t&&t!==La&&t!==Function.prototype;)t.ComponentType&&e.add(t.ComponentType),t=Object.getPrototypeOf(t);return e}function LP(r,e){if(!r.isObject3DComponent)throw new Error("EntityComponentPlugin: invalid component instance");r.ctx=e;const t=s6(r.constructor),i=r.uiConfig??{type:"folder",label:()=>r._sType?`Missing (${r._sType})`:r.constructor.ComponentType,expanded:!1,children:bi(r)},n=i.children,s=[];t.forEach(a=>{const o=a.key;if(!Wn(r,o)){console.error("Object3DComponent: state property not found on component",a,r);return}const l=a.default??r[o];if(l===void 0){console.error("Object3DComponent: state property default value must be set",a,r);return}const c=zr.GetType(l);if(!c){console.error("Object3DComponent: unsupported type for state property",a,l);return}const h=a.type??zr.NonLiteral(c);if(!zr.CanAssign(c,h)){console.error("Object3DComponent: default value type is not compatible with state property type",a,l,c,h);return}delete r[o],Object.defineProperty(r,o,{get:()=>Ub(r,o,l),set:d=>{OP(d,r,o,h,l)},enumerable:!0,configurable:!0}),UP(c,l,l,r,o);const u={config:a,propType:h,defaultValue:l,defaultValueType:c,propKey:o};if(s.push(u),n){const d=r6(r,u);d?.length&&n.push(...d)}}),Oh.InstanceProperties.set(r,s),n?.push({type:"button",label:"Reset to Default",uuid:"reset_to_default",tags:["context-menu"],value:()=>{const a={};return s.forEach(({propKey:o,defaultValue:l})=>{r[o]=l,a[o]=r[o]}),()=>{s.forEach(({propKey:o})=>{r[o]=a[o]})}}},{type:"button",label:"Remove Component",uuid:"remove_component",tags:["context-menu"],value:()=>e.ecp.removeComponent(r.object,r.uuid)}),r.uiConfig=i}function i6(r,e){if(!r.isObject3DComponent)throw new Error("EntityComponentPlugin: invalid component instance");const t=Oh.InstanceProperties.get(r);if(t)for(const{propKey:i,defaultValue:n,propType:s}of t){const a=e?e[i]:void 0,o=r.stateRef[i];let l;const c=Ba.GetCached(o);c!==void 0?l=c:l=Ub(r,i,n,o,!1),OP(l,r,i,s,n,a)}}function n6(r){if(!r.isObject3DComponent)throw new Error("EntityComponentPlugin: invalid component instance");Ba.Delete(r),Oh.InstanceProperties.delete(r)}const uA=class uA{};uA.TypeProperties=new Map,uA.InstanceProperties=new Map;let Oh=uA;function s6(r){const e=Oh.TypeProperties.get(r);if(e)return e;const t=new Map;let i=r,n=0;for(;i&&i!==Function.prototype;){if(i.StateProperties)for(const s of i.StateProperties){const a=typeof s=="string"?s:s.key,o=t.get(a);if(o){const l=o[1];l===i?console.error("Object3DComponent: duplicate state property in class",{key:a,base:i}):console.warn("Object3DComponent: state property overridden in derived class",{key:a,base:i,constructor:l});continue}t.set(a,[typeof s=="string"?{key:s}:s,i,n]),n+=.001}if(i===La)break;i=Object.getPrototypeOf(i),n-=1}return Array.from(t.values()).sort((s,a)=>s[2]-a[2]).map(s=>s[0])}function Ub(r,e,t,i,n=!0){if(i=i??r.stateRef[e],i===void 0)return t;const s=Ba.GetOp(i,n);return s!==void 0?s:i}function OP(r,e,t,i,n,s){if(r===void 0){console.error("Object3DComponent: state property cannot be set to undefined",t,r);return}const a=s!==void 0?Ub(e,t,n,s):e[t];if(a===r)return;const o=zr.GetType(r);if(!o){console.error("Object3DComponent: unsupported type for state property",t,r);return}if(!zr.CanAssign(o,i)){console.error("Object3DComponent: assigned value type is not compatible with state property type",t,r,o,i);return}s===void 0&&(s=e.stateRef[t]),Ba.RemoveOp(s,e),UP(o,r,n,e,t),a!==void 0&&a!==r&&e.stateChangeHandlers[t]?.forEach(l=>l(r,a,t))}function UP(r,e,t,i,n){let s;const a=zr.GetClass(r);if(a){const o=a.getId(e);if(o)s=Ba.Add(o,e,i);else{console.error("Object3DComponent: cannot get reference id for value of state property",n,e);return}}else e===t?s=void 0:s=e;s===void 0?delete i.stateRef[n]:i.stateRef[n]=s}function r6(r,e){const{config:t,propType:i,defaultValue:n,propKey:s}=e,a=typeof i=="string"?[i]:"oneOf"in i?Array.from(i.oneOf):["unknown"],o=a.includes("null"),l=a.map(d=>zr.GetClass(d)).filter(d=>d!==void 0),c=[];if(l.length===a.length&&!o||l.length===a.length-1&&o){const d={type:"reference",label:t.label??s+"",property:[r,s],classTypes:l,allowNull:o,defaultValue:n};c.push(d)}const h=a.map(d=>typeof d=="string"?d.startsWith('"')&&d.endsWith('"')?JSON.parse(d):isNaN(Number(d))?d==="true"?!0:d==="false"?!1:typeof d=="number"||typeof d=="boolean"?d:void 0:Number(d):void 0).filter(d=>d!==void 0),u=()=>{const d=ii(r,s,t.label,void 0,!1);if(d)return typeof d=="object"&&(d.uuid=s,d.dispatchMode="immediate"),h.length>0&&h.length===a.length&&(d.type==="input"||d.type==="number"||d.type==="string")&&(d.type="dropdown",d.children=h.map(p=>({label:typeof p=="string"?p:typeof p=="number"?p.toString():typeof p=="boolean"?p?"true":"false":p+"",value:p}))),e.config.uiConfig&&Object.assign(d,e.config.uiConfig),d};return c.push(u),c}const dA=class dA{constructor(){this.isObject3DComponent=!0,this._object=null,this.uuid=Math.random().toString(32).slice(2,10),this.stateChangeHandlers={},this._state={}}get object(){if(!this._object)throw new Error("Cannot access object at this point.");return this._object}set object(e){console.error("Object3DComponent: object is read-only")}get stateRef(){return this._state}setState(e){const t=this._state;if(e!==t){e&&typeof e=="object"?this._state=e:this._state={};for(const i in t)i in this._state||(this._state[i]=t[i]);return i6(this,t),this}}start(){}stop(){}update(e){}preFrame(e){}init(e,t){if(!e)throw new Error("Object3DComponent: no object");this._object=e,this.setState(t)}destroy(){this._object=null,this.stateChangeHandlers={};const e=this._state;return this._state={},e}onStateChange(e,t){this.stateChangeHandlers[e]||(this.stateChangeHandlers[e]=[]),this.stateChangeHandlers[e].push(t)}getComponent(e,t=!1){const i=this._object;return i?t?Uh.GetComponent(i,e):Uh.GetComponentInParent(i,e)||this.ctx.ecp.getComponentOfType(e):t?null:this.ctx.ecp.getComponentOfType(e)}};dA.StateProperties=[],dA.ComponentType="Object3DComponent";let La=dA;var a6=Object.defineProperty,rA=(r,e,t,i)=>{for(var n=void 0,s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&a6(e,t,n),n};const fA=class fA extends La{constructor(){super(...arguments),this.running=!0,this.mass=1,this.damping=.98,this.velocity=new S,this.acceleration=new S,this.MoveLeft=()=>{this.applyImpulse({x:-5})},this.MoveRight=()=>{this.applyImpulse({x:5})},this.PushForward=async()=>{for(let e=0;e<200;e++)this.addForce({z:10}),await Qn(32)},this.PushBackward=async()=>{for(let e=0;e<200;e++)this.addForce({z:-10}),await Qn(32)}}update({deltaTime:e}){if(!this.object||!this.running)return;const t=(e??16)/1e3;return this.velocity.x+=this.acceleration.x*t,this.velocity.y+=this.acceleration.y*t,this.velocity.z+=this.acceleration.z*t,this.velocity.multiplyScalar(this.damping),this.acceleration.set(0,0,0),Math.abs(this.velocity.x)+Math.abs(this.velocity.y)+Math.abs(this.velocity.z)<=1e-6?!1:(this.object.position.x+=this.velocity.x*t,this.object.position.y+=this.velocity.y*t,this.object.position.z+=this.velocity.z*t,!0)}addForce(e){e.x!==void 0&&(this.acceleration.x+=e.x/this.mass),e.y!==void 0&&(this.acceleration.y+=e.y/this.mass),e.z!==void 0&&(this.acceleration.z+=e.z/this.mass)}applyImpulse(e){e.x!==void 0&&(this.velocity.x+=e.x/this.mass),e.y!==void 0&&(this.velocity.y+=e.y/this.mass),e.z!==void 0&&(this.velocity.z+=e.z/this.mass)}setVelocity(e){this.velocity.copy(e)}stop(){this.reset()}start(){this.reset()}reset(){this.velocity.set(0,0,0),this.acceleration.set(0,0,0)}};fA.StateProperties=["running","mass","damping"],fA.ComponentType="SampleBodyComponent";let Nl=fA;rA([ct()],Nl.prototype,"MoveLeft"),rA([ct()],Nl.prototype,"MoveRight"),rA([ct()],Nl.prototype,"PushForward"),rA([ct()],Nl.prototype,"PushBackward");const Vt=class Vt extends mt{constructor(e=!0){super(),this.enabled=!0,this._components=new Map,this._typeToComponents=new Map,this.componentTypes=new Map,this._onRemove=[],this._preFrame=t=>{if(this.isDisabled()||!this._viewer?.renderEnabled||t.deltaTime<=0)return;const i=[t];let n=!1,s=this.componentsDispatch("preFrame",...i);!n&&s.find(a=>!!a[1])&&(n=!0),this._running&&t.timeline.delta>0&&(s=this.componentsDispatch("update",...i),!n&&s.find(a=>!!a[1])&&(n=!0)),n&&this._viewer?.setDirty(this)},this._objectAdd=t=>{const i=t.object;if(!i||i.isWidget)return;if(i.getComponent||(i.getComponent=(s,a=!1)=>a?Vt.GetComponent(i,s):Vt.GetComponentInParent(i,s)||this.getComponentOfType(s)),!i._compUiInit&&i.uiConfig?.children&&Vt.AddObjectUiConfig){i._compUiInit=!0;const s={type:"dropdown",label:"Add Component",value:"",children:[{label:"Select component type",value:""},()=>[...this.componentTypes.values()].map(a=>({label:a.ComponentType,value:a.ComponentType}))]};i.uiConfig.children.push({type:"folder",label:"Components",tags:[Vt.PluginType],children:[s,{type:"button",label:"Add Component",onClick:()=>{if(s.value)return this.addComponent(i,s.value)}},()=>{const a=Vt.GetObjectData(i);return a?Object.keys(a).map(l=>this._components.get(i.uuid+l)?.uiConfig).filter(l=>!!l):[]}]})}const n=Vt.GetObjectData(i);n&&Object.entries(n).forEach(([s,a])=>{if(t.componentType&&a.type!==t.componentType)return;const o=this.registerComponent(i,a,s);o&&(n[s].state=o.stateRef)})},this._objectRemove=t=>{const i=t.object;if(!i)return;const n=Vt.GetObjectData(i);i.getComponent&&delete i.getComponent,i._compUiInit&&i.uiConfig?.children&&(i._compUiInit=!1,i.uiConfig.children=i.uiConfig.children.filter(s=>{if(typeof s=="object"&&s.tags&&Array.isArray(s.tags)&&s.tags.includes(Vt.PluginType))return!1})),n&&Object.entries(n).forEach(([s,a])=>{if(t.componentType&&a.type!==t.componentType)return;const o=this._components.get(i.uuid+s);if(o){if(o.object!==i){console.warn(`EntityComponentPlugin: component with id ${s} exists on a different object`);return}const l=this.unregisterComponent(o);l&&(a.state=l)}})},this._objectUpdate=t=>{if(t.change==="deserialize"){if(!t.object)return;this._objectAdd(t)}},this.componentTypes.set(La.ComponentType,La),this._running=e}get running(){return this._running}start(){if(!this._running){this._running=!0;for(const e of this._components.values())try{e.start()}catch(t){console.error("EntityComponentPlugin: Error starting component",e),console.error(t)}this._viewer&&this._components.size&&this._viewer.setDirty(this)}}stop(){if(this._running){this._running=!1;for(const e of this._components.values())try{e.stop()}catch(t){console.error("EntityComponentPlugin: Error stopping component",e),console.error(t)}this._viewer&&this._components.size&&this._viewer.setDirty(this)}}componentsDispatch(e,...t){return Vt.ComponentsDispatch([...this._components.values()],e,t)}static ObjectDispatch(e,t,...i){const n=Vt.ObjectToComponents.get(e);return n?Vt.ComponentsDispatch(n,t,i):[]}static ComponentsDispatch(e,t,i){const n=[];for(const s of e){const a=s[t];if(typeof a=="function")try{n.push([s,a.apply(s,i)])}catch(o){console.error(`EntityComponentPlugin: Error in component ${s.constructor.ComponentType} handling ${t}`,s,o)}}return n}addComponentType(e){if(!e||typeof e!="function")throw new Error("EntityComponentPlugin: invalid component type");if(!e.ComponentType||typeof e.ComponentType!="string")throw new Error('EntityComponentPlugin: component type must have a valid string "ComponentType" property');return this.componentTypes.has(e.ComponentType)?(console.warn(`EntityComponentPlugin: component type "${e.ComponentType}" already registered`),!1):(this.componentTypes.set(e.ComponentType,e),this.dispatchEvent({type:"addComponentType",cls:e}),this._viewer?.object3dManager.getObjects().forEach(t=>this._objectAdd({object:t,componentType:e.ComponentType})),!0)}removeComponentType(e){if(!e||typeof e!="function")throw new Error("EntityComponentPlugin: invalid component type");if(!e.ComponentType||typeof e.ComponentType!="string")throw new Error('EntityComponentPlugin: component type must have a valid string "ComponentType" property');return this.componentTypes.has(e.ComponentType)?(this.dispatchEvent({type:"removeComponentType",cls:e}),this._viewer?.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t,componentType:e.ComponentType})),this.componentTypes.delete(e.ComponentType),!0):(console.warn(`EntityComponentPlugin: component type "${e.ComponentType}" not registered`),!1)}hasComponentType(e){const t=typeof e=="string"?e:e.ComponentType;return this.componentTypes.has(t)}onAdded(e){super.onAdded(e),e.object3dManager.getObjects().forEach(i=>this._objectAdd({object:i})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.scene.addEventListener("objectUpdate",this._objectUpdate);const t=e.on("preFrame",{order:1,callback:this._preFrame});t&&this._onRemove.push(t)}onRemove(e){e.object3dManager.removeEventListener("objectAdd",this._objectAdd),e.object3dManager.removeEventListener("objectRemove",this._objectRemove),e.object3dManager.getObjects().forEach(t=>this._objectRemove({object:t})),e.scene.removeEventListener("objectUpdate",this._objectUpdate),this._onRemove.forEach(t=>t()),super.onRemove(e)}static GetObjectData(e){let t=e.userData[Vt.UserDataKey];return t&&typeof t!="object"&&(console.warn(`EntityComponentPlugin: userData.${Vt.UserDataKey} is not an object`,e),t={},e.userData[Vt.UserDataKey]=t),t||null}addComponent(e,t,i){if(!this._viewer)throw new Error("EntityComponentPlugin: no viewer");const n=t?typeof t=="string"?{type:t,state:{}}:t.ComponentType?{type:t.ComponentType,state:{}}:t&&typeof t.type=="string"&&t.state?t:{type:"Object3DComponent",state:{}}:{type:"Object3DComponent",state:{}};t.ComponentType&&(this.hasComponentType(t)||this.addComponentType(t));const s=this.registerComponent(e,n,i);if(!s)throw new Error("EntityComponentPlugin: cannot create component of type "+n.type);let a=Vt.GetObjectData(e);a||(a={},e.userData[Vt.UserDataKey]=a),a[s.uuid]?(a[s.uuid].type=s.constructor.ComponentType,a[s.uuid].state=s.stateRef):a[s.uuid]={state:s.stateRef,type:s.constructor.ComponentType},e.setDirty&&e.setDirty({change:`userData.${Vt.UserDataKey}`,source:"EntityComponentPlugin.addComponent",refreshUi:!0});const o={undo:()=>{const l=this.removeComponent(e,o.component.uuid);l&&(o.redo=l.undo)},redo:()=>{this.addComponent(e,t)},component:s};return o}removeComponent(e,t){if(!this._viewer)return;const i=this._components.get(e.uuid+t);if(!i)return;const n=i.constructor.ComponentType,s=this.unregisterComponent(i),a=Vt.GetObjectData(e);a&&(delete a[t],Object.keys(a).length===0&&delete e.userData[Vt.UserDataKey],e.setDirty&&e.setDirty({change:`userData.${Vt.UserDataKey}`,source:"EntityComponentPlugin.removeComponent",refreshUi:!0}));const o={state:s,undo:()=>{o.state&&this.addComponent(e,{type:n,state:o.state},t)},redo:()=>{this.removeComponent(e,t)}};return o}static GetComponentData(e,t){if(!e)return null;const i=Vt.GetObjectData(e);if(!i)return null;const n=typeof t=="string"?[t]:[...Lh(t)];for(const[a,o]of Object.entries(i))for(const l of n)if(o.type===l)return{id:a,...o};const s=Vt.GetComponent(e,t);return s?{id:s.uuid,type:s.constructor.ComponentType,state:s.stateRef}:null}static GetComponents(e,t){if(!e)return[];const i=Vt.ObjectToComponents.get(e)||[];if(!t)return i;const n=typeof t=="string"?[t]:[...Lh(t)];return i.filter(s=>{const a=Lh(s.constructor);return n.some(o=>a.has(o))})}static GetComponent(e,t){if(!e)return null;const i=Vt.ObjectToComponents.get(e)||[],n=typeof t=="string"?[t]:[...Lh(t)];for(const s of i){const a=Lh(s.constructor);for(const o of n)if(a.has(o))return s}return null}static GetComponentInParent(e,t){if(!e)return null;let i=e,n=null;for(;!n&&i;)n=Vt.GetComponent(i,t),i=i.parent;return n}static GetComponentsInParent(e,t){if(!e)return[];let i=e;const n=[];for(;i;)n.push(...Vt.GetComponents(i,t)),i=i.parent;return n}getComponentsOfType(e){const t=typeof e=="string"?e:e.ComponentType,i=this._typeToComponents.get(t);return i?[...i]:[]}getComponentOfType(e){const t=typeof e=="string"?e:e.ComponentType,i=this._typeToComponents.get(t);return!i||i.size===0?null:i.values().next().value}registerComponent(e,t,i){if(!this._viewer)throw new Error("EntityComponentPlugin: no viewer");if(!e)throw new Error("EntityComponentPlugin: no object");if((!t||typeof t!="object")&&(console.warn("EntityComponentPlugin: invalid component state",t,e),t={type:"Object3DComponent",state:{}}),i){const l=this._components.get(e.uuid+i);if(l)return l.object!==e&&(console.error(`EntityComponentPlugin: component with id ${i} already exists on a different object`),l.object=e),l.constructor.ComponentType!==t.type?(console.warn(`EntityComponentPlugin: component with id ${i} type mismatch (${l.constructor.ComponentType} != ${t.type}), removing previous component and creating new one`),this.unregisterComponent(l)):l.setState(t.state),l}const n=this.componentTypes.get(t.type),s={viewer:this._viewer,ecp:this,plugin:l=>{const c=s.viewer?.getPlugin(l);if(!c)throw new Error(`EntityComponentPlugin: cannot find plugin ${typeof l=="string"?l:l.name}`);return c}};let a;try{a=n?new n:new La,n||(console.error("EntityComponentPlugin: unknown component type "+t.type,e),a._sType=t.type),i&&(a.uuid=i),LP(a,s)}catch(l){return console.error("EntityComponentPlugin: Error creating component of type "+t.type),console.error(l),null}this._components.set(e.uuid+a.uuid,a),Vt.ObjectToComponents.set(e,[...Vt.ObjectToComponents.get(e)||[],a]);const o=this._typeToComponents.get(a.constructor.ComponentType)||new Set;o.add(a),this._typeToComponents.set(a.constructor.ComponentType,o);try{a.init(e,t.state)}catch(l){console.error("EntityComponentPlugin: Error initializing component",a),console.error(l)}this.dispatchEvent({type:"registerComponent",component:a,object:e});try{this.running&&a.start()}catch(l){console.error("EntityComponentPlugin: Error starting component",a),console.error(l)}return a}unregisterComponent(e){if(!e)return;const t=e.object;let i=null;if(!t)console.warn("EntityComponentPlugin: component already destroyed",e);else{try{this.running&&e.stop()}catch(o){console.error("EntityComponentPlugin: Error stopping component",e),console.error(o)}try{i=e.destroy()}catch(o){console.error("EntityComponentPlugin: Error destroying component",e),console.error(o)}}this._components.delete(t.uuid+e.uuid);const n=this._typeToComponents.get(e.constructor.ComponentType);n&&(n.delete(e),n.size===0&&this._typeToComponents.delete(e.constructor.ComponentType)),n6(e);const s=Vt.ObjectToComponents.get(t)||[],a=s.indexOf(e);return a!==-1&&(s.splice(a,1),s.length===0&&Vt.ObjectToComponents.delete(t)),t&&this.dispatchEvent({type:"unregisterComponent",component:e,object:t}),i}};Vt.PluginType="EntityComponentPlugin",Vt.ObjectToComponents=new Map,Vt.UserDataKey=Vt.PluginType,Vt.AddObjectUiConfig=!0;let Uh=Vt;const o6=Uh;function l6(){window.dispatchEvent(new Event("threepipe-test-finished")),document.body.classList.add("_testFinish")}function c6(){window.dispatchEvent(new Event("threepipe-test-started")),document.body.classList.add("_testStarted")}function h6(r){return qe.autoCenter.call(r)}function u6(r,e,t,i){return qe.autoScale.call(r,e,t,i)}f.AAssetManagerProcessStatePlugin=kI,f.ACESFilmicToneMapping=p4,f.ACameraControlsPlugin=Vg,f.ACameraHelperWidget=XI,f.AGeometryGenerator=gr,f.AHelperWidget=Ch,f.ALightHelperWidget=qg,f.AScreenPassExtensionPlugin=qd,f.AViewerPlugin=Zc,f.AViewerPluginAsync=Mk,f.AViewerPluginSync=mt,f.AddEquation=BH,f.AddOperation=c4,f.AdditiveAnimationBlendMode=JQ,f.AdditiveBlending=IH,f.AgXToneMapping=g4,f.AlphaFormat=K4,f.AlwaysCompare=z5,f.AlwaysDepth=e4,f.AlwaysStencilFunc=B5,f.AmbientLight=Kp,f.AmbientLight2=bl,f.AnimationAction=$x,f.AnimationClip=Ja,f.AnimationLoader=qO,f.AnimationMixer=Kx,f.AnimationObjectGroup=mU,f.AnimationObjectPlugin=YW,f.AnimationUtils=HO,f.ArcCurve=Ip,f.ArrayCamera=HC,f.ArrowHelper=BU,f.AssetExporter=eI,f.AssetExporterPlugin=$g,f.AssetImporter=Ds,f.AssetManager=Lg,f.AsyncCompress=m1,f.AsyncDecompress=Nz,f.AsyncDeflate=f1,f.AsyncGunzip=A1,f.AsyncGzip=m1,f.AsyncInflate=I0,f.AsyncUnzipInflate=Xz,f.AsyncUnzlib=_1,f.AsyncZipDeflate=Qz,f.AsyncZlib=Uz,f.AttachedBindMode=y4,f.Audio=qx,f.AudioAnalyser=rU,f.AudioContext=__,f.AudioListener=iU,f.AudioLoader=ZO,f.AxesHelper=LU,f.BackSide=SH,f.BaseImporterPlugin=Rl,f.BasicDepthPacking=i5,f.BasicShadowMap=vH,f.BatchedMesh=rx,f.Bone=Rc,f.BoneHelper=cW,f.BooleanKeyframeTrack=tl,f.Box2=C_,f.Box3=en,f.Box3B=En,f.Box3Helper=DU,f.BoxGeometry=gi,f.BoxGeometryGenerator=wP,f.BoxHelper=PU,f.BoxSelectionWidget=YI,f.BufferAttribute=Ze,f.BufferGeometry=Je,f.BufferGeometry2=Md,f.BufferGeometryLoader=y_,f.ByteType=G4,f.CSMFrustum=sf,f.Cache=Ai,f.Camera=fu,f.CameraHelper=IU,f.CameraHelper2=$I,f.CameraViewPlugin=Q0,f.CanvasSnapshot=wd,f.CanvasSnipperPlugin=wb,f.CanvasTexture=qo,f.CapsuleGeometry=Bp,f.CascadedShadowsPlugin=_8,f.CatmullRomCurve3=Uc,f.CineonToneMapping=f4,f.CircleGeometry=Lp,f.CircleGeometryGenerator=bP,f.ClampToEdgeWrapping=M4,f.Clock=ku,f.Color=ee,f.ColorKeyframeTrack=u_,f.ColorManagement=Nt,f.Compress=wg,f.CompressedArrayTexture=dx,f.CompressedCubeTexture=fx,f.CompressedTexture=ua,f.CompressedTextureLoader=Lx,f.ConeGeometry=Op,f.ConstantAlphaFactor=KH,f.ConstantColorFactor=YH,f.ConvexHull=xj,f.CopyShader=Cl,f.CubeCamera=dC,f.CubeReflectionMapping=b4,f.CubeRefractionMapping=w4,f.CubeTexture=wc,f.CubeTextureLoader=XO,f.CubeUVReflectionMapping=S4,f.CubicBezierCurve=Eu,f.CubicBezierCurve3=Dp,f.CubicInterpolant=Dx,f.CullFaceBack=AH,f.CullFaceFront=yH,f.CullFaceFrontBack=_H,f.CullFaceNone=gH,f.Curve=Ts,f.CurvePath=Pu,f.CurvePath3=zm,f.CustomBlending=RH,f.CustomContextMenu=Zu,f.CustomToneMapping=m4,f.CylinderGeometry=sn,f.CylinderGeometryGenerator=SP,f.Cylindrical=vU,f.DRACOLoader=G1,f.DRACOLoader2=Dg,f.Damper=FU,f.Data3DTexture=Ff,f.DataArrayTexture=Uf,f.DataTexture=Vn,f.DataTextureLoader=f_,f.DataUtils=zn,f.DecodeUTF8=zz,f.Decompress=R0,f.DecrementStencilOp=w5,f.DecrementWrapStencilOp=x5,f.DefaultLoadingManager=d_,f.Deflate=Ys,f.DepthFormat=iQ,f.DepthNormalMaterial=Bk,f.DepthStencilFormat=nQ,f.DepthTexture=ap,f.DetachedBindMode=_4,f.DeviceOrientationControlsPlugin=fb,f.DirectionalLight=sl,f.DirectionalLight2=lg,f.DirectionalLightHelper=TU,f.DirectionalLightHelper2=KI,f.DiscreteInterpolant=Rx,f.DisplayP3ColorSpace=u5,f.DodecahedronGeometry=Up,f.DoubleSide=EH,f.Dropzone=gm,f.DstAlphaFactor=QH,f.DstColorFactor=WH,f.DuplicateTracker=Yg,f.DynamicCopyUsage=Y5,f.DynamicDrawUsage=H5,f.DynamicImportPlugin=Ob,f.DynamicReadUsage=W5,f.ECS=o6,f.EXRExporter=q1,f.EXRExporter2=H0,f.EXRLoader=G0,f.EasingFunctions=Kc,f.EdgesGeometry=mx,f.EffectComposer=_T,f.EffectComposer2=vT,f.EllipseCurve=Xo,f.EllipseCurve3D=vl,f.EncodeUTF8=Vz,f.EntityComponentPlugin=Uh,f.EqualCompare=U5,f.EqualDepth=n4,f.EqualStencilFunc=T5,f.EquirectangularReflectionMapping=C4,f.EquirectangularRefractionMapping=x4,f.Euler=Pt,f.EventDispatcher=xi,f.ExtendedCopyPass=r0,f.ExtendedRenderPass=s0,f.ExtendedShaderMaterial=oT,f.ExtendedShaderPass=nh,f.ExtrudeGeometry=Hp,f.FBXLoader=P1,f.FBXLoader2=F1,f.Face=$s,f.FileLoader=ti,f.FileTransferPlugin=Cb,f.FlateErrorCode=Lz,f.Float16BufferAttribute=XD,f.Float32BufferAttribute=Ee,f.FloatType=j4,f.FnCaller=Wu,f.Fog=dp,f.FogExp2=up,f.FragmentClippingMode=nf,f.FrameFadeBlendPass=QI,f.FramebufferTexture=fO,f.FrontSide=xH,f.Frustum=pu,f.FullScreenQuad=e0,f.GBufferMaterial=ng,f.GLBufferAttribute=_U,f.GLSL1=K5,f.GLSL3=J5,f.GLStatsJS=HS,f.GLTFAnimationPlugin=WW,f.GLTFBinaryExtension=c0,f.GLTFExporter=Dd,f.GLTFExporter2=Bg,f.GLTFKHRMaterialVariantsPlugin=X8,f.GLTFLightExtrasExtension=Bd,f.GLTFLoader=Mt,f.GLTFLoader2=Il,f.GLTFMaterialExtrasExtension=Ld,f.GLTFMaterialsAlphaMapExtension=xl,f.GLTFMaterialsBumpMapExtension=rh,f.GLTFMaterialsDisplacementMapExtension=Sl,f.GLTFMaterialsLightMapExtension=El,f.GLTFMeshOptDecodePlugin=bb,f.GLTFObject3DExtrasExtension=Od,f.GLTFParser=NT,f.GLTFViewerConfigExtension=ho,f.GLTFWriter2=DT,f.GPUComputationRenderer=vj,f.GenericBlendTexturePass=mT,f.GeometryGeneratorPlugin=Ph,f.GreaterCompare=N5,f.GreaterDepth=r4,f.GreaterEqualCompare=G5,f.GreaterEqualDepth=s4,f.GreaterEqualStencilFunc=R5,f.GreaterStencilFunc=P5,f.GridHelper=EU,f.Group=Vi,f.Group2=_l,f.Gunzip=xg,f.Gzip=wg,f.HVBlurHelper=EE,f.HalfEdge=zg,f.HalfFloatType=W4,f.HemisphereLight=$p,f.HemisphereLight2=Ca,f.HemisphereLightHelper=SU,f.HorizontalBlurShader=xE,f.IcosahedronGeometry=Qp,f.ImageBitmapLoader=Vx,f.ImageLoader=Gc,f.ImageUtils=fy,f.Importer=qi,f.IncrementStencilOp=b5,f.IncrementWrapStencilOp=C5,f.Inflate=ys,f.InstancedBufferAttribute=ha,f.InstancedBufferGeometry=A_,f.InstancedInterleavedBuffer=Gu,f.InstancedMesh=Oc,f.InstancedMesh2=Wk,f.Int16BufferAttribute=WD,f.Int32BufferAttribute=qD,f.Int8BufferAttribute=HD,f.IntType=H4,f.InterleavedBuffer=Mc,f.InterleavedBufferAttribute=Rn,f.Interpolant=kc,f.InterpolateDiscrete=jQ,f.InterpolateLinear=WQ,f.InterpolateSmooth=qQ,f.InvertStencilOp=S5,f.JSONMaterialLoader=oh,f.JSUndoManager=M_,f.KHR_TEXTURE_BASISU=vb,f.KTX2LoadPlugin=tf,f.KTX2Loader=dr,f.KTX2Loader2=uP,f.KTXLoadPlugin=_b,f.KTXLoader=II,f.KeepStencilOp=_5,f.KeyframeTrack=or,f.LOD=XC,f.LatheGeometry=Du,f.Layers=Qf,f.LegacyPhongMaterial=sg,f.LessCompare=O5,f.LessDepth=t4,f.LessEqualCompare=F5,f.LessEqualDepth=i4,f.LessEqualStencilFunc=I5,f.LessStencilFunc=M5,f.Light=eo,f.LightProbe=kx,f.Line=fn,f.Line2=ag,f.Line3=x_,f.LineBasicMaterial=Mi,f.LineBasicMaterial2=Hk,f.LineCurve=Yo,f.LineCurve3=$o,f.LineDashedMaterial=Tx,f.LineGeometry=Ed,f.LineGeometry2=Jv,f.LineGeometryGenerator=iA,f.LineHelper=JI,f.LineLoop=$y,f.LineMaterial=$c,f.LineMaterial2=ji,f.LineSegments=Ms,f.LineSegments2=va,f.LineSegmentsGeometry=Gs,f.LineSegmentsGeometry2=uT,f.LinearDisplayP3ColorSpace=d5,f.LinearEncoding=tj,f.LinearFilter=L4,f.LinearInterpolant=h_,f.LinearMipMapLinearFilter=N4,f.LinearMipMapNearestFilter=U4,f.LinearMipmapLinearFilter=F4,f.LinearMipmapNearestFilter=O4,f.LinearSRGBColorSpace=h5,f.LinearToSRGB=_S,f.LinearToneMapping=u4,f.LinearTransfer=p5,f.Loader=oi,f.LoaderUtils=Ps,f.LoadingManager=Yp,f.LoopOnce=VQ,f.LoopPingPong=QQ,f.LoopRepeat=HQ,f.LuminanceAlphaFormat=tQ,f.LuminanceFormat=eQ,f.MOUSE=pH,f.MTLLoader2=m0,f.Material=tn,f.MaterialConfiguratorBasePlugin=b8,f.MaterialExtender=yl,f.MaterialLoader=Nu,f.MaterialManager=tI,f.MaterialPreviewGenerator=ME,f.MathUtils=Ft,f.Matrix2=im,f.Matrix3=At,f.Matrix4=fe,f.MaxEquation=FH,f.Mesh=_e,f.Mesh2=rg,f.MeshBasicMaterial=is,f.MeshBasicMaterial2=Ik,f.MeshDepthMaterial=Ec,f.MeshDepthMaterialOverride=VI,f.MeshDistanceMaterial=zy,f.MeshLambertMaterial=o_,f.MeshLine=Kv,f.MeshLineMaterial=jk,f.MeshLineSegments=cT,f.MeshMatcapMaterial=Mx,f.MeshNormalMaterial=a_,f.MeshNormalMaterialOverride=HI,f.MeshPhongMaterial=Zo,f.MeshPhysicalMaterial=Jo,f.MeshStandardMaterial=Ya,f.MeshStandardMaterial2=Vk,f.MeshSurfaceSampler=bj,f.MeshToonMaterial=Ex,f.MetaImporter=Qm,f.MinEquation=UH,f.MirroredRepeatWrapping=T4,f.MixOperation=l4,f.MultiplyBlending=DH,f.MultiplyOperation=o4,f.NearestFilter=I4,f.NearestMipMapLinearFilter=B4,f.NearestMipMapNearestFilter=D4,f.NearestMipmapLinearFilter=R4,f.NearestMipmapNearestFilter=P4,f.NeutralToneMapping=A4,f.NeverCompare=L5,f.NeverDepth=ZH,f.NeverStencilFunc=E5,f.NoBlending=MH,f.NoColorSpace=l5,f.NoToneMapping=h4,f.NormalAnimationBlendMode=KQ,f.NormalBlending=TH,f.NotEqualCompare=k5,f.NotEqualDepth=a4,f.NotEqualStencilFunc=D5,f.NumberKeyframeTrack=$a,f.OBJLoader2=WT,f.Object3D=ft,f.Object3D2=lT,f.Object3DComponent=La,f.Object3DManager=Og,f.Object3DWidgetsPlugin=R8,f.ObjectClipboard=sP,f.ObjectLoader=Zp,f.ObjectPicker=CE,f.ObjectShaderMaterial=$v,f.ObjectSpaceNormalMap=o5,f.OctahedronGeometry=da,f.OneFactor=kH,f.OneMinusConstantAlphaFactor=JH,f.OneMinusConstantColorFactor=$H,f.OneMinusDstAlphaFactor=jH,f.OneMinusDstColorFactor=qH,f.OneMinusSrcAlphaFactor=HH,f.OneMinusSrcColorFactor=zH,f.OrbitControls=W_,f.OrbitControls2=_3,f.OrthographicCamera=Mr,f.OrthographicCamera0=aT,f.OrthographicCamera2=Sd,f.P3Primaries=A5,f.PCFShadowMap=bH,f.PCFSoftShadowMap=wH,f.PLYLoadPlugin=Ab,f.PLYLoader=DI,f.PMREMGenerator=Fy,f.Pass=Id,f.Path=Fc,f.PerspectiveCamera=zi,f.PerspectiveCamera0=rT,f.PerspectiveCamera2=th,f.PhysicalMaterial=si,f.PickingPlugin=vs,f.PipelinePassPlugin=Pl,f.PivotControls=Qc,f.Plane=Es,f.PlaneGeometry=ca,f.PlaneGeometryGenerator=xP,f.PlaneHelper=RU,f.PointLight=nl,f.PointLight2=cg,f.PointLightHelper=CU,f.PointLightHelper2=eP,f.PointerDragHelper=cS,f.PointerLockControlsPlugin=pb,f.Points=Wo,f.PointsMaterial=Tr,f.PolarGridHelper=MU,f.PolyhedronGeometry=qa,f.PopmotionPlugin=Gr,f.PositionalAudio=sU,f.ProgressiveBlendPass=zI,f.PropertyBinding=Et,f.PropertyMixer=Yx,f.QuadraticBezierCurve=Mu,f.QuadraticBezierCurve3=Tu,f.Quaternion=$e,f.QuaternionKeyframeTrack=fa,f.QuaternionLinearInterpolant=Bx,f.RED_GREEN_RGTC2_Format=GQ,f.RED_RGTC1_Format=NQ,f.REVISION=fH,f.RGBADepthPacking=n5,f.RGBAFormat=Z4,f.RGBAIntegerFormat=cQ,f.RGBA_ASTC_10x10_Format=RQ,f.RGBA_ASTC_10x5_Format=IQ,f.RGBA_ASTC_10x6_Format=PQ,f.RGBA_ASTC_10x8_Format=DQ,f.RGBA_ASTC_12x10_Format=BQ,f.RGBA_ASTC_12x12_Format=LQ,f.RGBA_ASTC_4x4_Format=bQ,f.RGBA_ASTC_5x4_Format=wQ,f.RGBA_ASTC_5x5_Format=CQ,f.RGBA_ASTC_6x5_Format=xQ,f.RGBA_ASTC_6x6_Format=SQ,f.RGBA_ASTC_8x5_Format=EQ,f.RGBA_ASTC_8x6_Format=MQ,f.RGBA_ASTC_8x8_Format=TQ,f.RGBA_BPTC_Format=OQ,f.RGBA_ETC2_EAC_Format=vQ,f.RGBA_PVRTC_2BPPV1_Format=AQ,f.RGBA_PVRTC_4BPPV1_Format=gQ,f.RGBA_S3TC_DXT1_Format=uQ,f.RGBA_S3TC_DXT3_Format=dQ,f.RGBA_S3TC_DXT5_Format=fQ,f.RGBDepthPacking=s5,f.RGBELoader=iI,f.RGBEPNGLoader=RT,f.RGBFormat=J4,f.RGBIntegerFormat=lQ,f.RGBM16ColorSpace=f5,f.RGB_BPTC_SIGNED_Format=UQ,f.RGB_BPTC_UNSIGNED_Format=FQ,f.RGB_ETC1_Format=yQ,f.RGB_ETC2_Format=_Q,f.RGB_PVRTC_2BPPV1_Format=mQ,f.RGB_PVRTC_4BPPV1_Format=pQ,f.RGB_S3TC_DXT1_Format=hQ,f.RGDepthPacking=r5,f.RGFormat=aQ,f.RGIntegerFormat=oQ,f.RawShaderMaterial=Sx,f.Ray=Va,f.Raycaster=zu,f.Rec709Primaries=g5,f.RectAreaLight=Jp,f.RectAreaLight2=Nr,f.RedFormat=sQ,f.RedIntegerFormat=rQ,f.ReferenceManager=Ba,f.ReinhardToneMapping=d4,f.RenderPass=t0,f.RenderTarget=Ww,f.RenderTargetManager=wT,f.RepeatWrapping=E4,f.ReplaceStencilOp=v5,f.ReverseSubtractEquation=OH,f.Rhino3dmLoader=z1,f.Rhino3dmLoader2=ur,f.RingGeometry=jp,f.SIGNED_RED_GREEN_RGTC2_Format=zQ,f.SIGNED_RED_RGTC1_Format=kQ,f.SRGBColorSpace=c5,f.SRGBToLinear=qU,f.SRGBTransfer=m5,f.STLLoadPlugin=yb,f.STLLoader=RI,f.SVGTextureLoader=Rg,f.SampleBodyComponent=Nl,f.Scene=Qo,f.SceneUiConfigPlugin=jg,f.SelectionWidget=qI,f.Serialization=Lt,f.ShaderChunk=lt,f.ShaderLib=Di,f.ShaderMaterial=nn,f.ShaderMaterial2=Cd,f.ShaderPass=i0,f.ShadowMaterial=xx,f.Shape=rr,f.ShapeGeometry=Ou,f.ShapeGeometryGenerator=TP,f.ShapePath=OU,f.ShapeUtils=ar,f.ShortType=z4,f.SimpleEventDispatcher=cm,f.SimpleJSONExporter=Q1,f.SimpleJSONLoader=Fd,f.SimpleTextExporter=j1,f.SimplifyModifierPlugin=Ul,f.Skeleton=Bc,f.SkeletonHelper=wU,f.SkeletonHelper2=tP,f.SkinnedMesh=_p,f.Source=ia,f.Sphere=un,f.SphereGeometry=Is,f.SphereGeometryGenerator=CP,f.Spherical=Ir,f.SphericalHarmonics3=Nx,f.SplineCurve=Iu,f.SpotLight=zc,f.SpotLight2=hg,f.SpotLightHelper=bU,f.SpotLightHelper2=nP,f.Sprite=mp,f.SpriteMaterial=gu,f.SrcAlphaFactor=VH,f.SrcAlphaSaturateFactor=XH,f.SrcColorFactor=GH,f.StaticCopyUsage=X5,f.StaticDrawUsage=V5,f.StaticReadUsage=j5,f.StereoCamera=eU,f.StreamCopyUsage=$5,f.StreamDrawUsage=Q5,f.StreamReadUsage=q5,f.StringKeyframeTrack=il,f.SubtractEquation=LH,f.SubtractiveBlending=PH,f.SwitchNodeBasePlugin=rf,f.TOUCH=mH,f.TYPED_ARRAYS=fS,f.TangentSpaceNormalMap=a5,f.TetrahedronGeometry=Wp,f.Texture=kt,f.TextureLoader=Za,f.ThreeFirstPersonControlsPlugin=mb,f.ThreeSerialization=We,f.TorusGeometry=Xa,f.TorusGeometryGenerator=vP,f.TorusKnotGeometry=qp,f.TransformAnimationPlugin=Sb,f.TransformControls=lr,f.TransformControlsGizmo=tE,f.TransformControlsPlane=iE,f.Triangle=ts,f.TriangleFanDrawMode=t5,f.TriangleStripDrawMode=e5,f.TrianglesDrawMode=ZQ,f.TubeGeometry=Uu,f.TubeGeometryGenerator=EP,f.TubeShapeGeometry=dT,f.TubeShapeGeometryGenerator=IP,f.TypeSystem=zr,f.USDZLoadPlugin=gb,f.USDZLoader=PI,f.UVMapping=v4,f.UVsDebug=cI,f.UiConfigMethods=GS,f.UiConfigRenderer=EF,f.UiConfigRendererBase=zS,f.UiConfigTypeMap=Ku,f.Uint16BufferAttribute=Xf,f.Uint32BufferAttribute=My,f.Uint8BufferAttribute=QD,f.Uint8ClampedBufferAttribute=jD,f.UndoManagerPlugin=TW,f.Uniform=tm,f.UniformsGroup=yU,f.UniformsLib=De,f.UniformsUtils=ko,f.UnlitLineMaterial=Yn,f.UnlitMaterial=gs,f.UnsignedByteType=k4,f.UnsignedInt248Type=Y4,f.UnsignedInt5999Type=$4,f.UnsignedIntType=Q4,f.UnsignedShort4444Type=q4,f.UnsignedShort5551Type=X4,f.UnsignedShortType=V4,f.Unzip=Yz,f.UnzipInflate=qz,f.UnzipPassThrough=T1,f.Unzlib=Mg,f.VSMShadowMap=CH,f.Vector2=K,f.Vector3=S,f.Vector4=et,f.VectorKeyframeTrack=Ka,f.VertexList=ib,f.VertexNode=NI,f.VerticalBlurShader=SE,f.VideoLoader=V1,f.VideoTexture=Jy,f.VideoTextureLoader=H1,f.ViewHelper2=wv,f.ViewerUiConfigPlugin=Qg,f.WebGL3DRenderTarget=BD,f.WebGLArrayRenderTarget=RD,f.WebGLCoordinateSystem=Z5,f.WebGLCubeRenderTarget=Py,f.WebGLRenderTarget=ds,f.WebGLRenderer=hp,f.WebGLUtils=VC,f.WebGPUCoordinateSystem=ej,f.Wireframe=lI,f.WireframeGeometry=Xp,f.WireframeGeometry2=Zv,f.WireframeGeometry3=qk,f.WrapAroundEnding=$Q,f.ZeroCurvatureEnding=XQ,f.ZeroFactor=NH,f.ZeroSlopeEnding=YQ,f.ZeroStencilOp=y5,f.Zip=jz,f.ZipDeflate=Hz,f.ZipLoader=N1,f.ZipPassThrough=jd,f.Zlib=D0,f._testFinish=l6,f._testStart=c6,f.absMax=US,f.addModelProcess=GM,f.aesGcmDecrypt=IS,f.aesGcmEncrypt=TS,f.animate=Hv,f.animateAsync=PM,f.animateCameraToViewLinear=RM,f.animateCameraToViewSpherical=DM,f.animateTarget=mk,f.arrayBufferToBase64=um,f.assetExportHook=K1,f.autoCenterObject3D=h6,f.autoGPUInstanceMeshes=pv,f.autoScaleObject3D=u6,f.base64ToArrayBuffer=T_,f.basicObjectConstraints=Fl,f.bindToValue=jt,f.blobToDataURL=dm,f.blobToImage=aF,f.buildTextSvg=VM,f.cLinearToRGBM=yk,f.cRGBMToLinear=Ak,f.canvasFlipY=B_,f.centerAllGeometries=Yv,f.checkTexMapReference=cd,f.clearBit=dF,f.clearCoatTintGLTFExtension=Sh,f.clonePrimitive=ga,f.cloneScriptTag=dS,f.colorToDataUrl=XU,f.compress=g1,f.compressSync=Cg,f.computeMikkTSpaceTangents=C3,f.computeMorphedAttributes=T3,f.computeScreenSpaceBoundingBox=rv,f.convertArrayBufferToStringsInMeta=Sv,f.convertStringsToArrayBuffersInMeta=HE,f.copyMaterialUserData=xv,f.copyObject3DUserData=Hm,f.copyPrimitive=Yu,f.copyProps=wS,f.copyTextureUserData=Cv,f.copyUserData=fd,f.createBindingsProxy=hP,f.createCameraPath=sT,f.createCanvasElement=hS,f.createCurvePropertyUi=tA,f.createCurveTypeDropdown=af,f.createDiv=Pr,f.createImage=uS,f.createRenderTargetKey=bT,f.createScriptFromURL=NU,f.createShapeFromPreset=Pb,f.createStyles=hl,f.css=gS,f.curveUiConfigs=Ki,f.customBumpMapGLTFExtension=Mh,f.dataTextureFromColor=b3,f.dataTextureFromVec4=w3,f.decompress=kz,f.decompressSync=Gz,f.deepAccessObject=ju,f.deepCloneAttribute=x3,f.defaultObjectProcessor=kM,f.deflate=p1,f.deflateSync=Hd,f.deinterleaveAttribute=Dm,f.deinterleaveGeometry=E3,f.deleteObjects=ZM,f.downloadBlob=Qu,f.downloadFile=AS,f.duplicateObjects=eT,f.embedUrlRefs=OS,f.equalsPrimitive=Xu,f.escapeRegExp=Hu,f.estimateBytesUsed=M3,f.extractAnimationKey=Xv,f.filterTopmostAncestors=xd,f.findLastIndex=xS,f.fontFormatExtensionMap=zM,f.fragmentClippingGLTFExtension=Ih,f.generateUUID=Oi,f.generateUiConfig=bi,f.generateUiFolder=pm,f.generateValueConfig=ii,f.getComponentTypes=Lh,f.getEmptyMeta=Fr,f.getFileHandle=KU,f.getFilenameFromPath=zU,f.getFittingDistance=Vm,f.getKeyByValue=$U,f.getNewFileHandle=JU,f.getOrCall=tt,f.getPartialProps=jE,f.getPropDesc=z_,f.getPropertyDescriptor=vS,f.getTexelDecoding=av,f.getTexelDecodingFunction=yE,f.getTextureDataType=hv,f.getTypedArray=pS,f.getUrlQueryParam=qu,f.glbEncryptionPreparser=zT,f.glbEncryptionProcessor=GT,f.glsl=ma,f.gunzip=y1,f.gunzipSync=Sg,f.gzip=g1,f.gzipSync=Cg,f.halfFloatToRgbe=AE,f.html=QU,f.htmlDialogWrapper=CF,f.htmlToCanvas=hF,f.htmlToPng=uF,f.htmlToSvg=O_,f.iCameraCommons=ht,f.iGeometryCommons=ni,f.iLightCommons=pn,f.iMaterialCommons=ve,f.iObjectCommons=qe,f.imageBitmapToBase64=PS,f.imageBitmapToBlob=nF,f.imageBitmapToCanvas=R_,f.imageDataToCanvas=sF,f.imageToCanvas=RS,f.imageUrlToImageData=DS,f.includesAll=CS,f.incrementObjectCloneName=ig,f.inflate=P0,f.inflateSync=_h,f.interleaveAttributes=S3,f.isInScene=cv,f.isNonRelativeUrl=Hc,f.isPropertyWritable=bS,f.isWebpExportSupported=rF,f.jsonToBlob=Mv,f.lerp=Jm,f.lerpAngle=jv,f.lerpNumber=Jc,f.lerpParams=LM,f.lerpTexture=BM,f.lerpVal=Zm,f.lerpVector=qv,f.literalStrings=t6,f.localToWorldQuaternion=B3,f.longestCommonPrefix=HU,f.makeColorSvg=oF,f.makeColorSvgCircle=BS,f.makeGLBFile=$E,f.makeICameraCommonUiConfig=eg,f.makeIObject3DUiConfig=HM,f.makeSamplerUi=Ii,f.makeSetterFor=Qv,f.makeTextSvg=lF,f.makeTextSvgAdvanced=Sk,f.matDefine=Tm,f.matDefineBool=Im,f.mergeAttributes=Pm,f.mergeBufferAttributes=R3,f.mergeBufferGeometries=D3,f.mergeGeometries=_E,f.mergeGroups=I3,f.mergeResources=rN,f.mergeVertices=vE,f.metaFromResources=Ev,f.metaToResources=pd,f.mobileAndTabletCheck=WU,f.noiseBumpMaterialGLTFExtension=Eh,f.now=Cn,f.objectActionsUiConfig=co,f.objectExtensionsUiConfig=tg,f.objectHasOwn=Wn,f.objectMap=ES,f.objectMap2=P_,f.onChange=he,f.onChange2=Zt,f.onChange3=rt,f.onChangeDispatchEvent=io,f.overrideThreeCache=gE,f.parseFileExtension=Vu,f.pathJoin=pF,f.prettyScrollbar=jU,f.readFile=ZU,f.recordUndoCommand=$u,f.remoteWorkerURL=mF,f.replaceAll=jn,f.reverseShapeWinding=MP,f.sRGBEncoding=ij,f.safeReplaceString=VU,f.safeSetProperty=an,f.sampleThreepipeViteHmrPlugin=K8,f.serializable=Vc,f.serialize=G,f.serializeTextureInExtras=QE,f.setInnerHTMLWithScripts=kU,f.setPartialProps=jm,f.setThreeRendererMode=tG,f.setUrlQueryParam=fF,f.setValueUndoCommand=G_,f.setupComponent=LP,f.shaderReplaceString=bt,f.shaderUtils=V_,f.snapObject=mv,f.sortPasses=AT,f.sphericalFromCameraView=Wv,f.strFromU8=Qd,f.strToU8=go,f.svgToCanvas=L_,f.svgToPng=LS,f.svgUrl=I_,f.texImageToCanvas=wE,f.textureDataToImageData=uv,f.textureToBlob=O3,f.textureToCanvas=Rm,f.textureToDataUrl=L3,f.threeConstMappings=dv,f.threeMaterialInterpolateProps=wa,f.threeMaterialPropList=It,f.timeout=Qn,f.toCamelCase=GU,f.toCreasedNormals=P3,f.toIndexedGeometry=lv,f.toTitleCase=mS,f.toTrianglesDrawMode=ov,f.uiButton=ct,f.uiColor=xn,f.uiConfig=Bi,f.uiConfigMaterialExtension=YM,f.uiContainer=H_,f.uiDropdown=Li,f.uiFolderContainer=vt,f.uiImage=Dr,f.uiInput=He,f.uiMonitor=dl,f.uiNumber=Ot,f.uiPanelContainer=Aa,f.uiSlider=Fe,f.uiToggle=se,f.uiVector=yi,f.uniform=_a,f.unzip=$z,f.unzipSync=U0,f.unzlib=v1,f.unzlibSync=Ea,f.updateBit=U_,f.updateMaterialDefines=ba,f.updateUi=Ib,f.upgradeTexture=Td,f.upgradeWebGLRenderer=fT,f.uploadFile=yS,f.uuidV4=F_,f.vLinearToRGBM=UM,f.vRGBMToLinear=OM,f.verifyPermission=iF,f.whiteImageData=Bm,f.whiteTexture=Lm,f.windowDialogWrapper=FS,f.worldToLocalQuaternion=bE,f.wrapThisFunction=YU,f.wrapThisFunction2=SS,f.writeFile=tF,f.zip=Wz,f.zipSync=Tg,f.zlib=Fz,f.zlibSync=Eg,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
//# sourceMappingURL=index.js.map
