/**
 * Minified by jsDelivr using Terser v5.48.0.
 * Original file: /npm/threepipe@0.6.0/dist/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
!function(e,t){"object"==typeof exports&&typeof module<"u"?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=typeof globalThis<"u"?globalThis:e||self).threepipe={})}(this,function(e){"use strict";var t,i,n,r,s,a,o,l,c,h,d,u;const p=0,m=1,g=2,f=0,A=1,y=2,v=3,_=0,b=1,x=2,w=0,C=1,S=2,M=3,E=4,T=5,I=100,P=101,D=102,R=103,B=104,L=200,O=201,U=202,F=203,k=204,N=205,j=206,z=207,G=208,Q=209,V=210,H=211,W=212,q=213,X=214,Y=0,K=1,J=2,Z=3,$=4,ee=5,te=6,ie=7,ne=1,re=2,se=3,ae=4,oe=6,le="attached",ce=300,he=301,de=302,ue=303,pe=304,me=306,ge=1e3,fe=1001,Ae=1002,ye=1003,ve=1004,_e=1005,be=1006,xe=1007,we=1008,Ce=1009,Se=1010,Me=1011,Ee=1012,Te=1013,Ie=1014,Pe=1015,De=1016,Re=1017,Be=1018,Le=1020,Oe=35902,Ue=1023,Fe=1026,ke=1027,Ne=1028,je=1029,ze=1030,Ge=1031,Qe=1033,Ve=33776,He=33777,We=33778,qe=33779,Xe=35840,Ye=35841,Ke=35842,Je=35843,Ze=36196,$e=37492,et=37496,tt=37808,it=37809,nt=37810,rt=37811,st=37812,at=37813,ot=37814,lt=37815,ct=37816,ht=37817,dt=37818,ut=37819,pt=37820,mt=37821,gt=36492,ft=36494,At=36495,yt=36284,vt=36285,_t=36286,bt=2200,xt=2201,wt=2300,Ct=2301,St=2302,Mt=2400,Et=2401,Tt=2402,It=2500,Pt=3200,Dt=3201,Rt=0,Bt=1,Lt="",Ot="srgb",Ut="srgb-linear",Ft="display-p3",kt="display-p3-linear",Nt="rgbm-16",jt="linear",zt="srgb",Gt="rec709",Qt="p3",Vt=7680,Ht=512,Wt=513,qt=514,Xt=515,Yt=516,Kt=517,Jt=518,Zt=519,$t=35044,ei="300 es",ti=2e3,ii=2001,ni=3001;class ri{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const i=this._listeners;void 0===i[e]&&(i[e]=[]),-1===i[e].indexOf(t)&&i[e].push(t)}hasEventListener(e,t){if(void 0===this._listeners)return!1;const i=this._listeners;return void 0!==i[e]&&-1!==i[e].indexOf(t)}removeEventListener(e,t){if(void 0===this._listeners)return;const i=this._listeners[e];if(void 0!==i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}dispatchEvent(e){if(void 0===this._listeners)return;const t=this._listeners[e.type];if(void 0!==t){e.target=this;const i=t.slice(0);for(let t=0,n=i.length;t<n;t++)i[t].call(this,e);e.target=null}}}const si=["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 ai=1234567;const oi=Math.PI/180,li=180/Math.PI;function ci(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,n=4294967295*Math.random()|0;return(si[255&e]+si[e>>8&255]+si[e>>16&255]+si[e>>24&255]+"-"+si[255&t]+si[t>>8&255]+"-"+si[t>>16&15|64]+si[t>>24&255]+"-"+si[63&i|128]+si[i>>8&255]+"-"+si[i>>16&255]+si[i>>24&255]+si[255&n]+si[n>>8&255]+si[n>>16&255]+si[n>>24&255]).toLowerCase()}function hi(e,t,i){return Math.max(t,Math.min(i,e))}function di(e,t){return(e%t+t)%t}function ui(e,t,i){return(1-i)*e+i*t}function pi(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function mi(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const gi={DEG2RAD:oi,RAD2DEG:li,generateUUID:ci,clamp:hi,euclideanModulo:di,mapLinear:function(e,t,i,n,r){return n+(e-t)*(r-n)/(i-t)},inverseLerp:function(e,t,i){return e!==t?(i-e)/(t-e):0},lerp:ui,damp:function(e,t,i,n){return ui(e,t,1-Math.exp(-i*n))},pingpong:function(e,t=1){return t-Math.abs(di(e,2*t)-t)},smoothstep:function(e,t,i){return e<=t?0:e>=i?1:(e=(e-t)/(i-t))*e*(3-2*e)},smootherstep:function(e,t,i){return e<=t?0:e>=i?1:(e=(e-t)/(i-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(ai=e);let t=ai+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*oi},radToDeg:function(e){return e*li},isPowerOfTwo:function(e){return!(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,i,n,r){const s=Math.cos,a=Math.sin,o=s(i/2),l=a(i/2),c=s((t+n)/2),h=a((t+n)/2),d=s((t-n)/2),u=a((t-n)/2),p=s((n-t)/2),m=a((n-t)/2);switch(r){case"XYX":e.set(o*h,l*d,l*u,o*c);break;case"YZY":e.set(l*u,o*h,l*d,o*c);break;case"ZXZ":e.set(l*d,l*u,o*h,o*c);break;case"XZX":e.set(o*h,l*m,l*p,o*c);break;case"YXY":e.set(l*p,o*h,l*m,o*c);break;case"ZYZ":e.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:mi,denormalize:pi};class fi{constructor(e=0,t=0){fi.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(0===t)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(hi(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),r=this.x-e.x,s=this.y-e.y;return this.x=r*i-s*n+e.x,this.y=r*n+s*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Ai{constructor(e,t,i,n,r,s,a,o,l){Ai.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,i,n,r,s,a,o,l)}set(e,t,i,n,r,s,a,o,l){const c=this.elements;return c[0]=e,c[1]=n,c[2]=a,c[3]=t,c[4]=r,c[5]=o,c[6]=i,c[7]=s,c[8]=l,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,r=this.elements,s=i[0],a=i[3],o=i[6],l=i[1],c=i[4],h=i[7],d=i[2],u=i[5],p=i[8],m=n[0],g=n[3],f=n[6],A=n[1],y=n[4],v=n[7],_=n[2],b=n[5],x=n[8];return r[0]=s*m+a*A+o*_,r[3]=s*g+a*y+o*b,r[6]=s*f+a*v+o*x,r[1]=l*m+c*A+h*_,r[4]=l*g+c*y+h*b,r[7]=l*f+c*v+h*x,r[2]=d*m+u*A+p*_,r[5]=d*g+u*y+p*b,r[8]=d*f+u*v+p*x,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],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8];return t*s*c-t*a*l-i*r*c+i*a*o+n*r*l-n*s*o}invert(){const e=this.elements,t=e[0],i=e[1],n=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8],h=c*s-a*l,d=a*o-c*r,u=l*r-s*o,p=t*h+i*d+n*u;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=h*m,e[1]=(n*l-c*i)*m,e[2]=(a*i-n*s)*m,e[3]=d*m,e[4]=(c*t-n*o)*m,e[5]=(n*r-a*t)*m,e[6]=u*m,e[7]=(i*o-l*t)*m,e[8]=(s*t-i*r)*m,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,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(i*o,i*l,-i*(o*s+l*a)+s+e,-n*l,n*o,-n*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(yi.makeScale(e,t)),this}rotate(e){return this.premultiply(yi.makeRotation(-e)),this}translate(e,t){return this.premultiply(yi.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 e=0;e<9;e++)if(t[e]!==i[e])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 yi=new Ai;function vi(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}const _i={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function bi(e,t){return new _i[e](t)}function xi(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function wi(){const e=xi("canvas");return e.style.display="block",e}const Ci={};function Si(e){e in Ci||(Ci[e]=!0,console.warn(e))}const Mi=(new Ai).set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),Ei=(new Ai).set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),Ti={[Ut]:{transfer:jt,primaries:Gt,luminanceCoefficients:[.2126,.7152,.0722],toReference:e=>e,fromReference:e=>e},[Ot]:{transfer:zt,primaries:Gt,luminanceCoefficients:[.2126,.7152,.0722],toReference:e=>e.convertSRGBToLinear(),fromReference:e=>e.convertLinearToSRGB()},[kt]:{transfer:jt,primaries:Qt,luminanceCoefficients:[.2289,.6917,.0793],toReference:e=>e.applyMatrix3(Ei),fromReference:e=>e.applyMatrix3(Mi)},[Ft]:{transfer:zt,primaries:Qt,luminanceCoefficients:[.2289,.6917,.0793],toReference:e=>e.convertSRGBToLinear().applyMatrix3(Ei),fromReference:e=>e.applyMatrix3(Mi).convertLinearToSRGB()}},Ii=new Set([Ut,kt]),Pi={enabled:!0,_workingColorSpace:Ut,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(e){if(!Ii.has(e))throw new Error(`Unsupported working color space, "${e}".`);this._workingColorSpace=e},convert:function(e,t,i){if(!1===this.enabled||t===i||!t||!i)return e;const n=Ti[t].toReference;return(0,Ti[i].fromReference)(n(e))},fromWorkingColorSpace:function(e,t){return this.convert(e,this._workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this._workingColorSpace)},getPrimaries:function(e){return Ti[e].primaries},getTransfer:function(e){return e===Lt||e===Nt?jt:Ti[e].transfer},getLuminanceCoefficients:function(e,t=this._workingColorSpace){return e.fromArray(Ti[t].luminanceCoefficients)}};function Di(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function Ri(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Bi;class Li{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{void 0===Bi&&(Bi=xi("canvas")),Bi.width=e.width,Bi.height=e.height;const t=Bi.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),i=Bi}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=xi("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),r=n.data;for(let e=0;e<r.length;e++)r[e]=255*Di(r[e]/255);return i.putImageData(n,0,0),t}if(e.data){const t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(255*Di(t[e]/255)):t[e]=Di(t[e]);return{data:t,width:e.width,height:e.height}}return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Oi=0;class Ui{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Oi++}),this.uuid=ci(),this.data=e,this.dataReady=!0,this.version=0}set needsUpdate(e){!0===e&&this.version++}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.images[this.uuid])return e.images[this.uuid];const i={uuid:this.uuid,url:""},n=this.data;if(null!==n){let e;if(Array.isArray(n)){e=[];for(let t=0,i=n.length;t<i;t++)n[t].isDataTexture?e.push(Fi(n[t].image)):e.push(Fi(n[t]))}else e=Fi(n);i.url=e}return t||(e.images[this.uuid]=i),i}}function Fi(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap)return Li.getDataURL(e);if(e.data){let t=[];try{t=Array.from(e.data)}catch(i){i.message.includes("Invalid array length")?console.warn("Serializing large texture, might not be saved in JSON structure."):console.error(i),t=e.data}return{data:t,width:e.width,height:e.height,type:e.data.constructor.name}}return void 0!==e.url?e.url:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let ki=0;class Ni extends ri{constructor(e=Ni.DEFAULT_IMAGE,t=Ni.DEFAULT_MAPPING,i=fe,n=fe,r=be,s=we,a=Ue,o=Ce,l=Ni.DEFAULT_ANISOTROPY,c=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:ki++}),this.uuid=ci(),this.name="",this.source=new Ui(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=r,this.minFilter=s,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new fi(0,0),this.repeat=new fi(1,1),this.center=new fi(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ai,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,"string"==typeof c?this.colorSpace=c:(Si("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=c===ni?Ot:Lt),this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.pmremVersion=0,typeof ImageData<"u"&&e instanceof ImageData&&e!==Ni.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=zi(this.userData,e.userData),this.needsUpdate=!0,this}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&e.textures&&void 0!==e.textures[this.uuid])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===Ot?ni:3e3,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=zi({},this.userData)),!t&&e.textures&&(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==ce)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ge:e.x=e.x-Math.floor(e.x);break;case fe:e.x=e.x<0?0:1;break;case Ae:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case ge:e.y=e.y-Math.floor(e.y);break;case fe:e.y=e.y<0?0:1;break;case Ae:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0,this.dispatchEvent({type:"update"}))}get encoding(){return Si("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===Ot?ni:3e3}set encoding(e){Si("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===ni?Ot:Lt}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}Ni.DEFAULT_IMAGE=null,Ni.DEFAULT_MAPPING=ce,Ni.DEFAULT_ANISOTROPY=1;const ji=["appliedMaterials","uuid"];function zi(e,t){if(t)for(const i of Object.keys(t))ji.includes(i)||i.startsWith("__")||"function"==typeof e[i]||"function"==typeof t[i]||(e[i]="object"==typeof t[i]?JSON.parse(JSON.stringify(t[i])):t[i]);return e}class Gi{constructor(e=0,t=0,i=0,n=1){Gi.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=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*n+s[12]*r,this.y=s[1]*t+s[5]*i+s[9]*n+s[13]*r,this.z=s[2]*t+s[6]*i+s[10]*n+s[14]*r,this.w=s[3]*t+s[7]*i+s[11]*n+s[15]*r,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,r;const s=e.elements,a=s[0],o=s[4],l=s[8],c=s[1],h=s[5],d=s[9],u=s[2],p=s[6],m=s[10];if(Math.abs(o-c)<.01&&Math.abs(l-u)<.01&&Math.abs(d-p)<.01){if(Math.abs(o+c)<.1&&Math.abs(l+u)<.1&&Math.abs(d+p)<.1&&Math.abs(a+h+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const e=(a+1)/2,s=(h+1)/2,g=(m+1)/2,f=(o+c)/4,A=(l+u)/4,y=(d+p)/4;return e>s&&e>g?e<.01?(i=0,n=.707106781,r=.707106781):(i=Math.sqrt(e),n=f/i,r=A/i):s>g?s<.01?(i=.707106781,n=0,r=.707106781):(n=Math.sqrt(s),i=f/n,r=y/n):g<.01?(i=.707106781,n=.707106781,r=0):(r=Math.sqrt(g),i=A/r,n=y/r),this.set(i,n,r,t),this}let g=Math.sqrt((p-d)*(p-d)+(l-u)*(l-u)+(c-o)*(c-o));return Math.abs(g)<.001&&(g=1),this.x=(p-d)/g,this.y=(l-u)/g,this.z=(c-o)/g,this.w=Math.acos((a+h+m-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 Qi extends ri{constructor(e=1,t=1,i={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new Gi(0,0,e,t),this.scissorTest=!1,this.viewport=new Gi(0,0,e,t);const n={width:e,height:t,depth:1};i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:be,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},i);const r=new Ni(n,i.mapping,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.format,i.type,i.anisotropy,i.colorSpace);r.flipY=!1,r.generateMipmaps=i.generateMipmaps,r.internalFormat=i.internalFormat,this.textures=[];const s=i.count;for(let e=0;e<s;e++)this.textures[e]=r.clone(),this.textures[e].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,r=this.textures.length;n<r;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 t=0,i=e.textures.length;t<i;t++)this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0;const t=Object.assign({},e.texture.image);return this.texture.source=new Ui(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 Vi extends Qi{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}}class Hi extends Ni{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=ye,this.minFilter=ye,this.wrapR=fe,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class Wi extends Ni{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=ye,this.minFilter=ye,this.wrapR=fe,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class qi{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,r,s,a){let o=i[n+0],l=i[n+1],c=i[n+2],h=i[n+3];const d=r[s+0],u=r[s+1],p=r[s+2],m=r[s+3];if(0===a)return e[t+0]=o,e[t+1]=l,e[t+2]=c,void(e[t+3]=h);if(1===a)return e[t+0]=d,e[t+1]=u,e[t+2]=p,void(e[t+3]=m);if(h!==m||o!==d||l!==u||c!==p){let e=1-a;const t=o*d+l*u+c*p+h*m,i=t>=0?1:-1,n=1-t*t;if(n>Number.EPSILON){const r=Math.sqrt(n),s=Math.atan2(r,t*i);e=Math.sin(e*s)/r,a=Math.sin(a*s)/r}const r=a*i;if(o=o*e+d*r,l=l*e+u*r,c=c*e+p*r,h=h*e+m*r,e===1-a){const e=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=e,l*=e,c*=e,h*=e}}e[t]=o,e[t+1]=l,e[t+2]=c,e[t+3]=h}static multiplyQuaternionsFlat(e,t,i,n,r,s){const a=i[n],o=i[n+1],l=i[n+2],c=i[n+3],h=r[s],d=r[s+1],u=r[s+2],p=r[s+3];return e[t]=a*p+c*h+o*u-l*d,e[t+1]=o*p+c*d+l*h-a*u,e[t+2]=l*p+c*u+a*d-o*h,e[t+3]=c*p-a*h-o*d-l*u,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,r=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(i/2),c=a(n/2),h=a(r/2),d=o(i/2),u=o(n/2),p=o(r/2);switch(s){case"XYZ":this._x=d*c*h+l*u*p,this._y=l*u*h-d*c*p,this._z=l*c*p+d*u*h,this._w=l*c*h-d*u*p;break;case"YXZ":this._x=d*c*h+l*u*p,this._y=l*u*h-d*c*p,this._z=l*c*p-d*u*h,this._w=l*c*h+d*u*p;break;case"ZXY":this._x=d*c*h-l*u*p,this._y=l*u*h+d*c*p,this._z=l*c*p+d*u*h,this._w=l*c*h-d*u*p;break;case"ZYX":this._x=d*c*h-l*u*p,this._y=l*u*h+d*c*p,this._z=l*c*p-d*u*h,this._w=l*c*h+d*u*p;break;case"YZX":this._x=d*c*h+l*u*p,this._y=l*u*h+d*c*p,this._z=l*c*p-d*u*h,this._w=l*c*h-d*u*p;break;case"XZY":this._x=d*c*h-l*u*p,this._y=l*u*h-d*c*p,this._z=l*c*p+d*u*h,this._w=l*c*h+d*u*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===t&&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],r=t[8],s=t[1],a=t[5],o=t[9],l=t[2],c=t[6],h=t[10],d=i+a+h;if(d>0){const e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(c-o)*e,this._y=(r-l)*e,this._z=(s-n)*e}else if(i>a&&i>h){const e=2*Math.sqrt(1+i-a-h);this._w=(c-o)/e,this._x=.25*e,this._y=(n+s)/e,this._z=(r+l)/e}else if(a>h){const e=2*Math.sqrt(1+a-i-h);this._w=(r-l)/e,this._x=(n+s)/e,this._y=.25*e,this._z=(o+c)/e}else{const e=2*Math.sqrt(1+h-i-a);this._w=(s-n)/e,this._x=(r+l)/e,this._y=(o+c)/e,this._z=.25*e}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(hi(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(0===i)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 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,n=e._y,r=e._z,s=e._w,a=t._x,o=t._y,l=t._z,c=t._w;return this._x=i*c+s*a+n*l-r*o,this._y=n*c+s*o+r*a-i*l,this._z=r*c+s*l+i*o-n*a,this._w=s*c-i*a-n*o-r*l,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const i=this._x,n=this._y,r=this._z,s=this._w;let a=s*e._w+i*e._x+n*e._y+r*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=s,this._x=i,this._y=n,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const e=1-t;return this._w=e*s+t*this._w,this._x=e*i+t*this._x,this._y=e*n+t*this._y,this._z=e*r+t*this._z,this.normalize(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),h=Math.sin((1-t)*c)/l,d=Math.sin(t*c)/l;return this._w=s*h+this._w*d,this._x=i*h+this._x*d,this._y=n*h+this._y*d,this._z=r*h+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),r=Math.sqrt(i);return this.set(n*Math.sin(e),n*Math.cos(e),r*Math.sin(t),r*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 Xi{constructor(e=0,t=0,i=0){Xi.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return void 0===i&&(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(Ki.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ki.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[3]*i+r[6]*n,this.y=r[1]*t+r[4]*i+r[7]*n,this.z=r[2]*t+r[5]*i+r[8]*n,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,n=this.z,r=e.elements,s=1/(r[3]*t+r[7]*i+r[11]*n+r[15]);return this.x=(r[0]*t+r[4]*i+r[8]*n+r[12])*s,this.y=(r[1]*t+r[5]*i+r[9]*n+r[13])*s,this.z=(r[2]*t+r[6]*i+r[10]*n+r[14])*s,this}applyQuaternion(e){const t=this.x,i=this.y,n=this.z,r=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*n-a*i),c=2*(a*t-r*n),h=2*(r*i-s*t);return this.x=t+o*l+s*h-a*c,this.y=i+o*c+a*l-r*h,this.z=n+o*h+r*c-s*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,n=this.z,r=e.elements;return this.x=r[0]*t+r[4]*i+r[8]*n,this.y=r[1]*t+r[5]*i+r[9]*n,this.z=r[2]*t+r[6]*i+r[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,r=e.z,s=t.x,a=t.y,o=t.z;return this.x=n*o-r*a,this.y=r*s-i*o,this.z=i*a-n*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return Yi.copy(this).projectOnVector(e),this.sub(Yi)}reflect(e){return this.sub(Yi.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(hi(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,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,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 Yi=new Xi,Ki=new qi;class Ji{constructor(e=new Xi(1/0,1/0,1/0),t=new Xi(-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($i.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint($i.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=$i.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(void 0!==i){const n=i.getAttribute("position");if(!0===t&&void 0!==n&&!0!==e.isInstancedMesh)for(let t=0,i=n.count;t<i;t++)!0===e.isMesh?e.getVertexPosition(t,$i):$i.fromBufferAttribute(n,t),$i.applyMatrix4(e.matrixWorld),this.expandByPoint($i);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),en.copy(e.boundingBox)):(null===i.boundingBox&&i.computeBoundingBox(),en.copy(i.boundingBox)),en.applyMatrix4(e.matrixWorld),this.union(en)}const n=e.children;for(let e=0,i=n.length;e<i;e++)this.expandByObject(n[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,$i),$i.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(ln),cn.subVectors(this.max,ln),tn.subVectors(e.a,ln),nn.subVectors(e.b,ln),rn.subVectors(e.c,ln),sn.subVectors(nn,tn),an.subVectors(rn,nn),on.subVectors(tn,rn);let t=[0,-sn.z,sn.y,0,-an.z,an.y,0,-on.z,on.y,sn.z,0,-sn.x,an.z,0,-an.x,on.z,0,-on.x,-sn.y,sn.x,0,-an.y,an.x,0,-on.y,on.x,0];return!(!un(t,tn,nn,rn,cn)||(t=[1,0,0,0,1,0,0,0,1],!un(t,tn,nn,rn,cn)))&&(hn.crossVectors(sn,an),t=[hn.x,hn.y,hn.z],un(t,tn,nn,rn,cn))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,$i).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize($i).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(Zi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Zi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Zi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Zi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Zi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Zi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Zi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Zi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Zi)),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 Zi=[new Xi,new Xi,new Xi,new Xi,new Xi,new Xi,new Xi,new Xi],$i=new Xi,en=new Ji,tn=new Xi,nn=new Xi,rn=new Xi,sn=new Xi,an=new Xi,on=new Xi,ln=new Xi,cn=new Xi,hn=new Xi,dn=new Xi;function un(e,t,i,n,r){for(let s=0,a=e.length-3;s<=a;s+=3){dn.fromArray(e,s);const a=r.x*Math.abs(dn.x)+r.y*Math.abs(dn.y)+r.z*Math.abs(dn.z),o=t.dot(dn),l=i.dot(dn),c=n.dot(dn);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const pn=new Ji,mn=new Xi,gn=new Xi;class fn{constructor(e=new Xi,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;void 0!==t?i.copy(t):pn.setFromPoints(e).getCenter(i);let n=0;for(let t=0,r=e.length;t<r;t++)n=Math.max(n,i.distanceToSquared(e[t]));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;mn.subVectors(e,this.center);const t=mn.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),i=.5*(e-this.radius);this.center.addScaledVector(mn,i/e),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(gn.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(mn.copy(e.center).add(gn)),this.expandByPoint(mn.copy(e.center).sub(gn))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const An=new Xi,yn=new Xi,vn=new Xi,_n=new Xi,bn=new Xi,xn=new Xi,wn=new Xi;class Cn{constructor(e=new Xi,t=new Xi(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,An)),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=An.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(An.copy(this.origin).addScaledVector(this.direction,t),An.distanceToSquared(e))}distanceSqToSegment(e,t,i,n){yn.copy(e).add(t).multiplyScalar(.5),vn.copy(t).sub(e).normalize(),_n.copy(this.origin).sub(yn);const r=.5*e.distanceTo(t),s=-this.direction.dot(vn),a=_n.dot(this.direction),o=-_n.dot(vn),l=_n.lengthSq(),c=Math.abs(1-s*s);let h,d,u,p;if(c>0)if(h=s*o-a,d=s*a-o,p=r*c,h>=0)if(d>=-p)if(d<=p){const e=1/c;h*=e,d*=e,u=h*(h+s*d+2*a)+d*(s*h+d+2*o)+l}else d=r,h=Math.max(0,-(s*d+a)),u=-h*h+d*(d+2*o)+l;else d=-r,h=Math.max(0,-(s*d+a)),u=-h*h+d*(d+2*o)+l;else d<=-p?(h=Math.max(0,-(-s*r+a)),d=h>0?-r:Math.min(Math.max(-r,-o),r),u=-h*h+d*(d+2*o)+l):d<=p?(h=0,d=Math.min(Math.max(-r,-o),r),u=d*(d+2*o)+l):(h=Math.max(0,-(s*r+a)),d=h>0?r:Math.min(Math.max(-r,-o),r),u=-h*h+d*(d+2*o)+l);else d=s>0?-r:r,h=Math.max(0,-(s*d+a)),u=-h*h+d*(d+2*o)+l;return i&&i.copy(this.origin).addScaledVector(this.direction,h),n&&n.copy(yn).addScaledVector(vn,d),u}intersectSphere(e,t){An.subVectors(e.center,this.origin);const i=An.dot(this.direction),n=An.dot(An)-i*i,r=e.radius*e.radius;if(n>r)return null;const s=Math.sqrt(r-n),a=i-s,o=i+s;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return null===i?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return 0===t||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,n,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,d=this.origin;return l>=0?(i=(e.min.x-d.x)*l,n=(e.max.x-d.x)*l):(i=(e.max.x-d.x)*l,n=(e.min.x-d.x)*l),c>=0?(r=(e.min.y-d.y)*c,s=(e.max.y-d.y)*c):(r=(e.max.y-d.y)*c,s=(e.min.y-d.y)*c),i>s||r>n||((r>i||isNaN(i))&&(i=r),(s<n||isNaN(n))&&(n=s),h>=0?(a=(e.min.z-d.z)*h,o=(e.max.z-d.z)*h):(a=(e.max.z-d.z)*h,o=(e.min.z-d.z)*h),i>o||a>n)||((a>i||i!=i)&&(i=a),(o<n||n!=n)&&(n=o),n<0)?null:this.at(i>=0?i:n,t)}intersectsBox(e){return null!==this.intersectBox(e,An)}intersectTriangle(e,t,i,n,r){bn.subVectors(t,e),xn.subVectors(i,e),wn.crossVectors(bn,xn);let s,a=this.direction.dot(wn);if(a>0){if(n)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}_n.subVectors(this.origin,e);const o=s*this.direction.dot(xn.crossVectors(_n,xn));if(o<0)return null;const l=s*this.direction.dot(bn.cross(_n));if(l<0||o+l>a)return null;const c=-s*_n.dot(wn);return c<0?null:this.at(c/a,r)}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 Sn{constructor(e,t,i,n,r,s,a,o,l,c,h,d,u,p,m,g){Sn.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,i,n,r,s,a,o,l,c,h,d,u,p,m,g)}set(e,t,i,n,r,s,a,o,l,c,h,d,u,p,m,g){const f=this.elements;return f[0]=e,f[4]=t,f[8]=i,f[12]=n,f[1]=r,f[5]=s,f[9]=a,f[13]=o,f[2]=l,f[6]=c,f[10]=h,f[14]=d,f[3]=u,f[7]=p,f[11]=m,f[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 Sn).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/Mn.setFromMatrixColumn(e,0).length(),r=1/Mn.setFromMatrixColumn(e,1).length(),s=1/Mn.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]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=0,t[8]=i[8]*s,t[9]=i[9]*s,t[10]=i[10]*s,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,r=e.z,s=Math.cos(i),a=Math.sin(i),o=Math.cos(n),l=Math.sin(n),c=Math.cos(r),h=Math.sin(r);if("XYZ"===e.order){const e=s*c,i=s*h,n=a*c,r=a*h;t[0]=o*c,t[4]=-o*h,t[8]=l,t[1]=i+n*l,t[5]=e-r*l,t[9]=-a*o,t[2]=r-e*l,t[6]=n+i*l,t[10]=s*o}else if("YXZ"===e.order){const e=o*c,i=o*h,n=l*c,r=l*h;t[0]=e+r*a,t[4]=n*a-i,t[8]=s*l,t[1]=s*h,t[5]=s*c,t[9]=-a,t[2]=i*a-n,t[6]=r+e*a,t[10]=s*o}else if("ZXY"===e.order){const e=o*c,i=o*h,n=l*c,r=l*h;t[0]=e-r*a,t[4]=-s*h,t[8]=n+i*a,t[1]=i+n*a,t[5]=s*c,t[9]=r-e*a,t[2]=-s*l,t[6]=a,t[10]=s*o}else if("ZYX"===e.order){const e=s*c,i=s*h,n=a*c,r=a*h;t[0]=o*c,t[4]=n*l-i,t[8]=e*l+r,t[1]=o*h,t[5]=r*l+e,t[9]=i*l-n,t[2]=-l,t[6]=a*o,t[10]=s*o}else if("YZX"===e.order){const e=s*o,i=s*l,n=a*o,r=a*l;t[0]=o*c,t[4]=r-e*h,t[8]=n*h+i,t[1]=h,t[5]=s*c,t[9]=-a*c,t[2]=-l*c,t[6]=i*h+n,t[10]=e-r*h}else if("XZY"===e.order){const e=s*o,i=s*l,n=a*o,r=a*l;t[0]=o*c,t[4]=-h,t[8]=l*c,t[1]=e*h+r,t[5]=s*c,t[9]=i*h-n,t[2]=n*h-i,t[6]=a*c,t[10]=r*h+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Tn,e,In)}lookAt(e,t,i){const n=this.elements;return Rn.subVectors(e,t),0===Rn.lengthSq()&&(Rn.z=1),Rn.normalize(),Pn.crossVectors(i,Rn),0===Pn.lengthSq()&&(1===Math.abs(i.z)?Rn.x+=1e-4:Rn.z+=1e-4,Rn.normalize(),Pn.crossVectors(i,Rn)),Pn.normalize(),Dn.crossVectors(Rn,Pn),n[0]=Pn.x,n[4]=Dn.x,n[8]=Rn.x,n[1]=Pn.y,n[5]=Dn.y,n[9]=Rn.y,n[2]=Pn.z,n[6]=Dn.z,n[10]=Rn.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,r=this.elements,s=i[0],a=i[4],o=i[8],l=i[12],c=i[1],h=i[5],d=i[9],u=i[13],p=i[2],m=i[6],g=i[10],f=i[14],A=i[3],y=i[7],v=i[11],_=i[15],b=n[0],x=n[4],w=n[8],C=n[12],S=n[1],M=n[5],E=n[9],T=n[13],I=n[2],P=n[6],D=n[10],R=n[14],B=n[3],L=n[7],O=n[11],U=n[15];return r[0]=s*b+a*S+o*I+l*B,r[4]=s*x+a*M+o*P+l*L,r[8]=s*w+a*E+o*D+l*O,r[12]=s*C+a*T+o*R+l*U,r[1]=c*b+h*S+d*I+u*B,r[5]=c*x+h*M+d*P+u*L,r[9]=c*w+h*E+d*D+u*O,r[13]=c*C+h*T+d*R+u*U,r[2]=p*b+m*S+g*I+f*B,r[6]=p*x+m*M+g*P+f*L,r[10]=p*w+m*E+g*D+f*O,r[14]=p*C+m*T+g*R+f*U,r[3]=A*b+y*S+v*I+_*B,r[7]=A*x+y*M+v*P+_*L,r[11]=A*w+y*E+v*D+_*O,r[15]=A*C+y*T+v*R+_*U,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],r=e[12],s=e[1],a=e[5],o=e[9],l=e[13],c=e[2],h=e[6],d=e[10],u=e[14];return e[3]*(+r*o*h-n*l*h-r*a*d+i*l*d+n*a*u-i*o*u)+e[7]*(+t*o*u-t*l*d+r*s*d-n*s*u+n*l*c-r*o*c)+e[11]*(+t*l*h-t*a*u-r*s*h+i*s*u+r*a*c-i*l*c)+e[15]*(-n*a*c-t*o*h+t*a*d+n*s*h-i*s*d+i*o*c)}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],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],c=e[8],h=e[9],d=e[10],u=e[11],p=e[12],m=e[13],g=e[14],f=e[15],A=h*g*l-m*d*l+m*o*u-a*g*u-h*o*f+a*d*f,y=p*d*l-c*g*l-p*o*u+s*g*u+c*o*f-s*d*f,v=c*m*l-p*h*l+p*a*u-s*m*u-c*a*f+s*h*f,_=p*h*o-c*m*o-p*a*d+s*m*d+c*a*g-s*h*g,b=t*A+i*y+n*v+r*_;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const x=1/b;return e[0]=A*x,e[1]=(m*d*r-h*g*r-m*n*u+i*g*u+h*n*f-i*d*f)*x,e[2]=(a*g*r-m*o*r+m*n*l-i*g*l-a*n*f+i*o*f)*x,e[3]=(h*o*r-a*d*r-h*n*l+i*d*l+a*n*u-i*o*u)*x,e[4]=y*x,e[5]=(c*g*r-p*d*r+p*n*u-t*g*u-c*n*f+t*d*f)*x,e[6]=(p*o*r-s*g*r-p*n*l+t*g*l+s*n*f-t*o*f)*x,e[7]=(s*d*r-c*o*r+c*n*l-t*d*l-s*n*u+t*o*u)*x,e[8]=v*x,e[9]=(p*h*r-c*m*r-p*i*u+t*m*u+c*i*f-t*h*f)*x,e[10]=(s*m*r-p*a*r+p*i*l-t*m*l-s*i*f+t*a*f)*x,e[11]=(c*a*r-s*h*r-c*i*l+t*h*l+s*i*u-t*a*u)*x,e[12]=_*x,e[13]=(c*m*n-p*h*n+p*i*d-t*m*d-c*i*g+t*h*g)*x,e[14]=(p*a*n-s*m*n-p*i*o+t*m*o+s*i*g-t*a*g)*x,e[15]=(s*h*n-c*a*n+c*i*o-t*h*o-s*i*d+t*a*d)*x,this}scale(e){const t=this.elements,i=e.x,n=e.y,r=e.z;return t[0]*=i,t[4]*=n,t[8]*=r,t[1]*=i,t[5]*=n,t[9]*=r,t[2]*=i,t[6]*=n,t[10]*=r,t[3]*=i,t[7]*=n,t[11]*=r,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),r=1-i,s=e.x,a=e.y,o=e.z,l=r*s,c=r*a;return this.set(l*s+i,l*a-n*o,l*o+n*a,0,l*a+n*o,c*a+i,c*o-n*s,0,l*o-n*a,c*o+n*s,r*o*o+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,r,s){return this.set(1,i,r,0,e,1,s,0,t,n,1,0,0,0,0,1),this}compose(e,t,i){const n=this.elements,r=t._x,s=t._y,a=t._z,o=t._w,l=r+r,c=s+s,h=a+a,d=r*l,u=r*c,p=r*h,m=s*c,g=s*h,f=a*h,A=o*l,y=o*c,v=o*h,_=i.x,b=i.y,x=i.z;return n[0]=(1-(m+f))*_,n[1]=(u+v)*_,n[2]=(p-y)*_,n[3]=0,n[4]=(u-v)*b,n[5]=(1-(d+f))*b,n[6]=(g+A)*b,n[7]=0,n[8]=(p+y)*x,n[9]=(g-A)*x,n[10]=(1-(d+m))*x,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 r=Mn.set(n[0],n[1],n[2]).length();const s=Mn.set(n[4],n[5],n[6]).length(),a=Mn.set(n[8],n[9],n[10]).length();this.determinant()<0&&(r=-r),e.x=n[12],e.y=n[13],e.z=n[14],En.copy(this);const o=1/r,l=1/s,c=1/a;return En.elements[0]*=o,En.elements[1]*=o,En.elements[2]*=o,En.elements[4]*=l,En.elements[5]*=l,En.elements[6]*=l,En.elements[8]*=c,En.elements[9]*=c,En.elements[10]*=c,t.setFromRotationMatrix(En),i.x=r,i.y=s,i.z=a,this}makePerspective(e,t,i,n,r,s,a=ti){const o=this.elements,l=2*r/(t-e),c=2*r/(i-n),h=(t+e)/(t-e),d=(i+n)/(i-n);let u,p;if(a===ti)u=-(s+r)/(s-r),p=-2*s*r/(s-r);else{if(a!==ii)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);u=-s/(s-r),p=-s*r/(s-r)}return o[0]=l,o[4]=0,o[8]=h,o[12]=0,o[1]=0,o[5]=c,o[9]=d,o[13]=0,o[2]=0,o[6]=0,o[10]=u,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(e,t,i,n,r,s,a=ti){const o=this.elements,l=1/(t-e),c=1/(i-n),h=1/(s-r),d=(t+e)*l,u=(i+n)*c;let p,m;if(a===ti)p=(s+r)*h,m=-2*h;else{if(a!==ii)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*h,m=-1*h}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-d,o[1]=0,o[5]=2*c,o[9]=0,o[13]=-u,o[2]=0,o[6]=0,o[10]=m,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let e=0;e<16;e++)if(t[e]!==i[e])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 Mn=new Xi,En=new Sn,Tn=new Xi(0,0,0),In=new Xi(1,1,1),Pn=new Xi,Dn=new Xi,Rn=new Xi,Bn=new Sn,Ln=new qi;class On{constructor(e=0,t=0,i=0,n=On.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,r=n[0],s=n[4],a=n[8],o=n[1],l=n[5],c=n[9],h=n[2],d=n[6],u=n[10];switch(t){case"XYZ":this._y=Math.asin(hi(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,u),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-hi(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,u),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,r),this._z=0);break;case"ZXY":this._x=Math.asin(hi(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-h,u),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-hi(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(d,u),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(hi(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,r)):(this._x=0,this._y=Math.atan2(a,u));break;case"XZY":this._z=Math.asin(-hi(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,u),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===i&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return Bn.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Bn,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Ln.setFromEuler(this),this.setFromQuaternion(Ln,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}On.DEFAULT_ORDER="XYZ";class Un{constructor(){this.mask=1}set(e){this.mask=1<<e>>>0}enable(e){this.mask|=1<<e}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e}disable(e){this.mask&=~(1<<e)}disableAll(){this.mask=0}test(e){return 0!==(this.mask&e.mask)}isEnabled(e){return!!(this.mask&1<<e)}}let Fn=0;const kn=new Xi,Nn=new qi,jn=new Sn,zn=new Xi,Gn=new Xi,Qn=new Xi,Vn=new qi,Hn=new Xi(1,0,0),Wn=new Xi(0,1,0),qn=new Xi(0,0,1),Xn={type:"added"},Yn={type:"removed"},Kn={type:"childadded",child:null},Jn={type:"childremoved",child:null};class Zn extends ri{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Fn++}),this.uuid=ci(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Zn.DEFAULT_UP.clone();const e=new Xi,t=new On,i=new qi,n=new Xi(1,1,1);t._onChange(function(){i.setFromEuler(t,!1)}),i._onChange(function(){t.setFromQuaternion(i,void 0,!1)}),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 Sn},normalMatrix:{value:new Ai}}),this.matrix=new Sn,this.matrixWorld=new Sn,this.matrixAutoUpdate=Zn.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Zn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Un,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,r,s){this.dispatchEvent({type:"beforeRender",renderer:e,scene:t,camera:i,geometry:n,material:r,group:s})}onAfterRender(e,t,i,n,r,s){this.dispatchEvent({type:"afterRender",renderer:e,scene:t,camera:i,geometry:n,material:r,group:s})}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 Nn.setFromAxisAngle(e,t),this.quaternion.multiply(Nn),this}rotateOnWorldAxis(e,t){return Nn.setFromAxisAngle(e,t),this.quaternion.premultiply(Nn),this}rotateX(e){return this.rotateOnAxis(Hn,e)}rotateY(e){return this.rotateOnAxis(Wn,e)}rotateZ(e){return this.rotateOnAxis(qn,e)}translateOnAxis(e,t){return kn.copy(e).applyQuaternion(this.quaternion),this.position.add(kn.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Hn,e)}translateY(e){return this.translateOnAxis(Wn,e)}translateZ(e){return this.translateOnAxis(qn,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(jn.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?zn.copy(e):zn.set(e,t,i);const n=this.parent;this.updateWorldMatrix(!0,!1),Gn.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?jn.lookAt(Gn,zn,this.up):jn.lookAt(zn,Gn,this.up),this.quaternion.setFromRotationMatrix(jn),n&&(jn.extractRotation(n.matrixWorld),Nn.setFromRotationMatrix(jn),this.quaternion.premultiply(Nn.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);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(Xn),Kn.child=e,this.dispatchEvent(Kn),Kn.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}const t=this.children.indexOf(e);return-1!==t&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(Yn),Jn.child=e,this.dispatchEvent(Jn),Jn.child=null),this}removeFromParent(){const e=this.parent;return null!==e&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),jn.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),jn.multiply(e.parent.matrixWorld)),e.applyMatrix4(jn),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Xn),Kn.child=e,this.dispatchEvent(Kn),Kn.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 n=this.children[i].getObjectByProperty(e,t);if(void 0!==n)return n}}getObjectsByProperty(e,t,i=[]){this[e]===t&&i.push(this);const n=this.children;for(let r=0,s=n.length;r<s;r++)n[r].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(Gn,e,Qn),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Gn,Vn,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(!1===this.visible)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;null!==t&&(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)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?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(!0===e&&null!==i&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),!0===t){const e=this.children;for(let t=0,i=e.length;t<i;t++)e[t].updateWorldMatrix(!1,!0)}}toJSON(e){const t=void 0===e||"string"==typeof e,i={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{},extras:{}},i.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});const n={};function r(t,i){return void 0===t[i.uuid]&&(t[i.uuid]=i.toJSON(e)),i.uuid}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),!0===this.castShadow&&(n.castShadow=!0),!0===this.receiveShadow&&(n.receiveShadow=!0),!1===this.visible&&(n.visible=!1),!1===this.frustumCulled&&(n.frustumCulled=!1),0!==this.renderOrder&&(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(),!1===this.matrixAutoUpdate&&(n.matrixAutoUpdate=!1),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(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(e=>({boxInitialized:e.boxInitialized,boxMin:e.box.min.toArray(),boxMax:e.box.max.toArray(),sphereInitialized:e.sphereInitialized,sphereRadius:e.sphere.radius,sphereCenter:e.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),null!==this._colorsTexture&&(n.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(n.boundingSphere={center:n.boundingSphere.center.toArray(),radius:n.boundingSphere.radius}),null!==this.boundingBox&&(n.boundingBox={min:n.boundingBox.min.toArray(),max:n.boundingBox.max.toArray()})),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&&!0!==this.environment.isRenderTargetTexture&&(n.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const i=t.shapes;if(Array.isArray(i))for(let t=0,n=i.length;t<n;t++){const n=i[t];r(e.shapes,n)}else r(e.shapes,i)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(e.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const t=[];for(let i=0,n=this.material.length;i<n;i++)t.push(r(e.materials,this.material[i]));n.material=t}else n.material=r(e.materials,this.material);if(this.children.length>0){n.children=[];for(let t=0;t<this.children.length;t++)n.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){n.animations=[];for(let t=0;t<this.animations.length;t++){const i=this.animations[t];n.animations.push(r(e.animations,i))}}if(t){const t=s(e.geometries),n=s(e.materials),r=s(e.textures),a=s(e.images),o=s(e.shapes),l=s(e.skeletons),c=s(e.animations),h=s(e.nodes);t.length>0&&(i.geometries=t),n.length>0&&(i.materials=n),r.length>0&&(i.textures=r),a.length>0&&(i.images=a),o.length>0&&(i.shapes=o),l.length>0&&(i.skeletons=l),c.length>0&&(i.animations=c),h.length>0&&(i.nodes=h)}return i.object=n,i;function s(e){const t=[];for(const i in e){const n=e[i];delete n.metadata,t.push(n)}return t}}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[t,i]of Object.entries(e.userData))this.userData[t]=!i||i&&(i.isTexture||i.isObject3D)?i:JSON.parse(JSON.stringify(i));if(!0===t)for(let t=0;t<e.children.length;t++){const i=e.children[t];this.add(i.clone())}return this}}Zn.DEFAULT_UP=new Xi(0,1,0),Zn.DEFAULT_MATRIX_AUTO_UPDATE=!0,Zn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const $n=new Xi,er=new Xi,tr=new Xi,ir=new Xi,nr=new Xi,rr=new Xi,sr=new Xi,ar=new Xi,or=new Xi,lr=new Xi;class cr{constructor(e=new Xi,t=new Xi,i=new Xi){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,n){n.subVectors(i,t),$n.subVectors(e,t),n.cross($n);const r=n.lengthSq();return r>0?n.multiplyScalar(1/Math.sqrt(r)):n.set(0,0,0)}static getBarycoord(e,t,i,n,r){$n.subVectors(n,t),er.subVectors(i,t),tr.subVectors(e,t);const s=$n.dot($n),a=$n.dot(er),o=$n.dot(tr),l=er.dot(er),c=er.dot(tr),h=s*l-a*a;if(0===h)return r.set(0,0,0),null;const d=1/h,u=(l*o-a*c)*d,p=(s*c-a*o)*d;return r.set(1-u-p,p,u)}static containsPoint(e,t,i,n){return null!==this.getBarycoord(e,t,i,n,ir)&&(ir.x>=0&&ir.y>=0&&ir.x+ir.y<=1)}static getInterpolation(e,t,i,n,r,s,a,o){return null===this.getBarycoord(e,t,i,n,ir)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,ir.x),o.addScaledVector(s,ir.y),o.addScaledVector(a,ir.z),o)}static isFrontFacing(e,t,i,n){return $n.subVectors(i,t),er.subVectors(e,t),$n.cross(er).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 $n.subVectors(this.c,this.b),er.subVectors(this.a,this.b),.5*$n.cross(er).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return cr.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return cr.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,n,r){return cr.getInterpolation(e,this.a,this.b,this.c,t,i,n,r)}containsPoint(e){return cr.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return cr.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,n=this.b,r=this.c;let s,a;nr.subVectors(n,i),rr.subVectors(r,i),ar.subVectors(e,i);const o=nr.dot(ar),l=rr.dot(ar);if(o<=0&&l<=0)return t.copy(i);or.subVectors(e,n);const c=nr.dot(or),h=rr.dot(or);if(c>=0&&h<=c)return t.copy(n);const d=o*h-c*l;if(d<=0&&o>=0&&c<=0)return s=o/(o-c),t.copy(i).addScaledVector(nr,s);lr.subVectors(e,r);const u=nr.dot(lr),p=rr.dot(lr);if(p>=0&&u<=p)return t.copy(r);const m=u*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(i).addScaledVector(rr,a);const g=c*p-u*h;if(g<=0&&h-c>=0&&u-p>=0)return sr.subVectors(r,n),a=(h-c)/(h-c+(u-p)),t.copy(n).addScaledVector(sr,a);const f=1/(g+m+d);return s=m*f,a=d*f,t.copy(i).addScaledVector(nr,s).addScaledVector(rr,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const hr={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},dr={h:0,s:0,l:0},ur={h:0,s:0,l:0};function pr(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+6*(t-e)*(2/3-i):e}class mr{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(void 0===t&&void 0===i){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Ot){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,Pi.toWorkingColorSpace(this,t),this}setRGB(e,t,i,n=Pi.workingColorSpace){return this.r=e,this.g=t,this.b=i,Pi.toWorkingColorSpace(this,n),this}setHSL(e,t,i,n=Pi.workingColorSpace){if(e=di(e,1),t=hi(t,0,1),i=hi(i,0,1),0===t)this.r=this.g=this.b=i;else{const n=i<=.5?i*(1+t):i+t-i*t,r=2*i-n;this.r=pr(r,n,e+1/3),this.g=pr(r,n,e),this.b=pr(r,n,e-1/3)}return Pi.toWorkingColorSpace(this,n),this}setStyle(e,t=Ot){function i(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=n[1],a=n[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(e)){const i=n[1],r=i.length;if(3===r)return this.setRGB(parseInt(i.charAt(0),16)/15,parseInt(i.charAt(1),16)/15,parseInt(i.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(i,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=Ot){const i=hr[e.toLowerCase()];return void 0!==i?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=Di(e.r),this.g=Di(e.g),this.b=Di(e.b),this}copyLinearToSRGB(e){return this.r=Ri(e.r),this.g=Ri(e.g),this.b=Ri(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Ot){return Pi.fromWorkingColorSpace(gr.copy(this),e),65536*Math.round(hi(255*gr.r,0,255))+256*Math.round(hi(255*gr.g,0,255))+Math.round(hi(255*gr.b,0,255))}getHexString(e=Ot){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Pi.workingColorSpace){Pi.fromWorkingColorSpace(gr.copy(this),t);const i=gr.r,n=gr.g,r=gr.b,s=Math.max(i,n,r),a=Math.min(i,n,r);let o,l;const c=(a+s)/2;if(a===s)o=0,l=0;else{const e=s-a;switch(l=c<=.5?e/(s+a):e/(2-s-a),s){case i:o=(n-r)/e+(n<r?6:0);break;case n:o=(r-i)/e+2;break;case r:o=(i-n)/e+4}o/=6}return e.h=o,e.s=l,e.l=c,e}getRGB(e,t=Pi.workingColorSpace){return Pi.fromWorkingColorSpace(gr.copy(this),t),e.r=gr.r,e.g=gr.g,e.b=gr.b,e}getStyle(e=Ot){Pi.fromWorkingColorSpace(gr.copy(this),e);const t=gr.r,i=gr.g,n=gr.b;return e!==Ot?`color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(255*t)},${Math.round(255*i)},${Math.round(255*n)})`}offsetHSL(e,t,i){return this.getHSL(dr),this.setHSL(dr.h+e,dr.s+t,dr.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(dr),e.getHSL(ur);const i=ui(dr.h,ur.h,t),n=ui(dr.s,ur.s,t),r=ui(dr.l,ur.l,t);return this.setHSL(i,n,r),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,r=e.elements;return this.r=r[0]*t+r[3]*i+r[6]*n,this.g=r[1]*t+r[4]*i+r[7]*n,this.b=r[2]*t+r[5]*i+r[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 gr=new mr;mr.NAMES=hr;let fr=0;class Ar extends ri{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:fr++}),this.uuid=ci(),this.name="",this.type="Material",this.blending=C,this.side=_,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=k,this.blendDst=N,this.blendEquation=I,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new mr(0,0,0),this.blendAlpha=0,this.depthFunc=Z,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Vt,this.stencilZFail=Vt,this.stencilZPass=Vt,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(void 0!==e)for(const t in e){const i=e[t];if(void 0===i){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const n=this[t];void 0!==n&&(n&&n.isColor?n.set(i):n&&n.isVector3&&i&&i.isVector3?n.copy(i):Array.isArray(i)&&n&&"function"==typeof n.fromArray?n.fromArray(i):this[t]=i)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const i={metadata:{version:4.6001,type:"Material",generator:"Material.toJSON"}};function n(e){const t=[];for(const i in e){const n=e[i];delete n.metadata,t.push(n)}return t}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),void 0!==this.roughness&&(i.roughness=this.roughness),void 0!==this.metalness&&(i.metalness=this.metalness),void 0!==this.sheen&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(i.shininess=this.shininess),void 0!==this.clearcoat&&(i.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(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()),void 0!==this.dispersion&&(i.dispersion=this.dispersion),void 0!==this.iridescence&&(i.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(i.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(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),void 0!==this.anisotropy&&(i.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(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,void 0!==this.combine&&(i.combine=this.combine)),void 0!==this.envMapRotation&&(i.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(i.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(i.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(i.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(i.size=this.size),null!==this.shadowSide&&(i.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==C&&(i.blending=this.blending),this.side!==_&&(i.side=this.side),!0===this.vertexColors&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),!0===this.transparent&&(i.transparent=!0),this.blendSrc!==k&&(i.blendSrc=this.blendSrc),this.blendDst!==N&&(i.blendDst=this.blendDst),this.blendEquation!==I&&(i.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(i.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(i.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==Z&&(i.depthFunc=this.depthFunc),!1===this.depthTest&&(i.depthTest=this.depthTest),!1===this.depthWrite&&(i.depthWrite=this.depthWrite),!1===this.colorWrite&&(i.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(i.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(i.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(i.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Vt&&(i.stencilFail=this.stencilFail),this.stencilZFail!==Vt&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==Vt&&(i.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(i.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(i.rotation=this.rotation),!0===this.polygonOffset&&(i.polygonOffset=!0),0!==this.polygonOffsetFactor&&(i.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(i.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(i.linewidth=this.linewidth),void 0!==this.dashSize&&(i.dashSize=this.dashSize),void 0!==this.gapSize&&(i.gapSize=this.gapSize),void 0!==this.scale&&(i.scale=this.scale),!0===this.dithering&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),!0===this.alphaHash&&(i.alphaHash=!0),!0===this.alphaToCoverage&&(i.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(i.premultipliedAlpha=!0),!0===this.forceSinglePass&&(i.forceSinglePass=!0),!0===this.wireframe&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(i.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(i.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(i.flatShading=!0),!1===this.visible&&(i.visible=!1),!1===this.toneMapped&&(i.toneMapped=!1),!1===this.fog&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData),t){const t=n(e.textures),r=n(e.images);t.length>0&&(i.textures=t),r.length>0&&(i.images=r)}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(null!==t){const e=t.length;i=new Array(e);for(let n=0;n!==e;++n)i[n]=t[n].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=yr({},e.userData),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}function yr(e,t){if(!t)return e;for(const i of Object.keys(t)){if(i.startsWith("__")||"function"==typeof e[i]||"function"==typeof t[i])continue;const n=t[i],r=!n||n.isTexture||n.isObject3D||n.isMaterial||n.isBufferGeometry||n.userDataSkipClone;r||"function"!=typeof t[i].clone?r||"object"!=typeof t[i]&&!Array.isArray(t[i])?e[i]=t[i]:e[i]=yr(Array.isArray(t[i])?[]:{},t[i]):e[i]=t[i].clone()}return e}class vr extends Ar{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new mr(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 On,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const _r=function(){const e=new ArrayBuffer(4),t=new Float32Array(e),i=new Uint32Array(e),n=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(n[e]=0,n[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(n[e]=1024>>-t-14,n[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(n[e]=t+15<<10,n[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(n[e]=31744,n[256|e]=64512,r[e]=24,r[256|e]=24):(n[e]=31744,n[256|e]=64512,r[e]=13,r[256|e]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,i=0;for(;!(8388608&t);)t<<=1,i-=8388608;t&=-8388609,i+=947912704,s[e]=t|i}for(let e=1024;e<2048;++e)s[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:i,baseTable:n,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}();function br(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=hi(e,-65504,65504),_r.floatView[0]=e;const t=_r.uint32View[0],i=t>>23&511;return _r.baseTable[i]+((8388607&t)>>_r.shiftTable[i])}function xr(e){const t=e>>10;return _r.uint32View[0]=_r.mantissaTable[_r.offsetTable[t]+(1023&e)]+_r.exponentTable[t],_r.floatView[0]}const wr={toHalfFloat:br,fromHalfFloat:xr},Cr=new Xi,Sr=new fi;class Mr{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=void 0!==e?e.length/t:0,this.normalized=i,this.usage=$t,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=Pe,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}get updateRange(){return Si("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,r=this.itemSize;n<r;n++)this.array[e+n]=t.array[i+n];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(2===this.itemSize)for(let t=0,i=this.count;t<i;t++)Sr.fromBufferAttribute(this,t),Sr.applyMatrix3(e),this.setXY(t,Sr.x,Sr.y);else if(3===this.itemSize)for(let t=0,i=this.count;t<i;t++)Cr.fromBufferAttribute(this,t),Cr.applyMatrix3(e),this.setXYZ(t,Cr.x,Cr.y,Cr.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)Cr.fromBufferAttribute(this,t),Cr.applyMatrix4(e),this.setXYZ(t,Cr.x,Cr.y,Cr.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)Cr.fromBufferAttribute(this,t),Cr.applyNormalMatrix(e),this.setXYZ(t,Cr.x,Cr.y,Cr.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)Cr.fromBufferAttribute(this,t),Cr.transformDirection(e),this.setXYZ(t,Cr.x,Cr.y,Cr.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=pi(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=mi(i,this.array)),this.array[e*this.itemSize+t]=i,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=pi(t,this.array)),t}setX(e,t){return this.normalized&&(t=mi(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=pi(t,this.array)),t}setY(e,t){return this.normalized&&(t=mi(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=pi(t,this.array)),t}setZ(e,t){return this.normalized&&(t=mi(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=pi(t,this.array)),t}setW(e,t){return this.normalized&&(t=mi(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=mi(t,this.array),i=mi(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=mi(t,this.array),i=mi(i,this.array),n=mi(n,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this}setXYZW(e,t,i,n,r){return e*=this.itemSize,this.normalized&&(t=mi(t,this.array),i=mi(i,this.array),n=mi(n,this.array),r=mi(r,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=n,this.array[e+3]=r,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!==$t&&(e.usage=this.usage),e}}class Er extends Mr{constructor(e,t,i){super(new Uint16Array(e),t,i)}}class Tr extends Mr{constructor(e,t,i){super(new Uint32Array(e),t,i)}}class Ir extends Mr{constructor(e,t,i){super(new Float32Array(e),t,i)}}let Pr=0;const Dr=new Sn,Rr=new Zn,Br=new Xi,Lr=new Ji,Or=new Ji,Ur=new Xi;class Fr extends ri{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Pr++}),this.uuid=ci(),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(vi(e)?Tr:Er)(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 void 0!==this.attributes[e]}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;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const i=this.attributes.normal;if(void 0!==i){const t=(new Ai).getNormalMatrix(e);i.applyNormalMatrix(t),i.needsUpdate=!0}const n=this.attributes.tangent;return void 0!==n&&(n.transformDirection(e),n.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return Dr.makeRotationFromQuaternion(e),this.applyMatrix4(Dr),this}rotateX(e){return Dr.makeRotationX(e),this.applyMatrix4(Dr),this}rotateY(e){return Dr.makeRotationY(e),this.applyMatrix4(Dr),this}rotateZ(e){return Dr.makeRotationZ(e),this.applyMatrix4(Dr),this}translate(e,t,i){return Dr.makeTranslation(e,t,i),this.applyMatrix4(Dr),this}scale(e,t,i){return Dr.makeScale(e,t,i),this.applyMatrix4(Dr),this}lookAt(e){return Rr.lookAt(e),Rr.updateMatrix(),this.applyMatrix4(Rr.matrix),this}center(e=void 0){return this.computeBoundingBox(),this.boundingBox.getCenter(Br).negate(),this.translate(Br.x,Br.y,Br.z),e&&e.copy(Br),this}setFromPoints(e){const t=[];for(let i=0,n=e.length;i<n;i++){const n=e[i];t.push(n.x,n.y,n.z||0)}return this.setAttribute("position",new Ir(t,3)),this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Ji);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new Xi(-1/0,-1/0,-1/0),new Xi(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,i=t.length;e<i;e++){const i=t[e];Lr.setFromBufferAttribute(i),this.morphTargetsRelative?(Ur.addVectors(this.boundingBox.min,Lr.min),this.boundingBox.expandByPoint(Ur),Ur.addVectors(this.boundingBox.max,Lr.max),this.boundingBox.expandByPoint(Ur)):(this.boundingBox.expandByPoint(Lr.min),this.boundingBox.expandByPoint(Lr.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(){null===this.boundingSphere&&(this.boundingSphere=new fn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new Xi,1/0);if(e){const i=this.boundingSphere.center;if(Lr.setFromBufferAttribute(e),t)for(let e=0,i=t.length;e<i;e++){const i=t[e];Or.setFromBufferAttribute(i),this.morphTargetsRelative?(Ur.addVectors(Lr.min,Or.min),Lr.expandByPoint(Ur),Ur.addVectors(Lr.max,Or.max),Lr.expandByPoint(Ur)):(Lr.expandByPoint(Or.min),Lr.expandByPoint(Or.max))}Lr.getCenter(i);let n=0;for(let t=0,r=e.count;t<r;t++)Ur.fromBufferAttribute(e,t),n=Math.max(n,i.distanceToSquared(Ur));if(t)for(let r=0,s=t.length;r<s;r++){const s=t[r],a=this.morphTargetsRelative;for(let t=0,r=s.count;t<r;t++)Ur.fromBufferAttribute(s,t),a&&(Br.fromBufferAttribute(e,t),Ur.add(Br)),n=Math.max(n,i.distanceToSquared(Ur))}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(null===e||void 0===t.position||void 0===t.normal||void 0===t.uv)return void console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const i=t.position,n=t.normal,r=t.uv;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new Mr(new Float32Array(4*i.count),4));const s=this.getAttribute("tangent"),a=[],o=[];for(let e=0;e<i.count;e++)a[e]=new Xi,o[e]=new Xi;const l=new Xi,c=new Xi,h=new Xi,d=new fi,u=new fi,p=new fi,m=new Xi,g=new Xi;function f(e,t,n){l.fromBufferAttribute(i,e),c.fromBufferAttribute(i,t),h.fromBufferAttribute(i,n),d.fromBufferAttribute(r,e),u.fromBufferAttribute(r,t),p.fromBufferAttribute(r,n),c.sub(l),h.sub(l),u.sub(d),p.sub(d);const s=1/(u.x*p.y-p.x*u.y);isFinite(s)&&(m.copy(c).multiplyScalar(p.y).addScaledVector(h,-u.y).multiplyScalar(s),g.copy(h).multiplyScalar(u.x).addScaledVector(c,-p.x).multiplyScalar(s),a[e].add(m),a[t].add(m),a[n].add(m),o[e].add(g),o[t].add(g),o[n].add(g))}let A=this.groups;0===A.length&&(A=[{start:0,count:e.count}]);for(let t=0,i=A.length;t<i;++t){const i=A[t],n=i.start;for(let t=n,r=n+i.count;t<r;t+=3)f(e.getX(t+0),e.getX(t+1),e.getX(t+2))}const y=new Xi,v=new Xi,_=new Xi,b=new Xi;function x(e){_.fromBufferAttribute(n,e),b.copy(_);const t=a[e];y.copy(t),y.sub(_.multiplyScalar(_.dot(t))).normalize(),v.crossVectors(b,t);const i=v.dot(o[e])<0?-1:1;s.setXYZW(e,y.x,y.y,y.z,i)}for(let t=0,i=A.length;t<i;++t){const i=A[t],n=i.start;for(let t=n,r=n+i.count;t<r;t+=3)x(e.getX(t+0)),x(e.getX(t+1)),x(e.getX(t+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(void 0!==t){let i=this.getAttribute("normal");if(void 0===i)i=new Mr(new Float32Array(3*t.count),3),this.setAttribute("normal",i);else for(let e=0,t=i.count;e<t;e++)i.setXYZ(e,0,0,0);const n=new Xi,r=new Xi,s=new Xi,a=new Xi,o=new Xi,l=new Xi,c=new Xi,h=new Xi;if(e)for(let d=0,u=e.count;d<u;d+=3){const u=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);n.fromBufferAttribute(t,u),r.fromBufferAttribute(t,p),s.fromBufferAttribute(t,m),c.subVectors(s,r),h.subVectors(n,r),c.cross(h),a.fromBufferAttribute(i,u),o.fromBufferAttribute(i,p),l.fromBufferAttribute(i,m),a.add(c),o.add(c),l.add(c),i.setXYZ(u,a.x,a.y,a.z),i.setXYZ(p,o.x,o.y,o.z),i.setXYZ(m,l.x,l.y,l.z)}else for(let e=0,a=t.count;e<a;e+=3)n.fromBufferAttribute(t,e+0),r.fromBufferAttribute(t,e+1),s.fromBufferAttribute(t,e+2),c.subVectors(s,r),h.subVectors(n,r),c.cross(h),i.setXYZ(e+0,c.x,c.y,c.z),i.setXYZ(e+1,c.x,c.y,c.z),i.setXYZ(e+2,c.x,c.y,c.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,i=e.count;t<i;t++)Ur.fromBufferAttribute(e,t),Ur.normalize(),e.setXYZ(t,Ur.x,Ur.y,Ur.z)}toNonIndexed(){function e(e,t){const i=e.array,n=e.itemSize,r=e.normalized,s=new i.constructor(t.length*n);let a=0,o=0;for(let r=0,l=t.length;r<l;r++){a=e.isInterleavedBufferAttribute?t[r]*e.data.stride+e.offset:t[r]*n;for(let e=0;e<n;e++)s[o++]=i[a++]}return new Mr(s,n,r)}if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Fr,i=this.index.array,n=this.attributes;for(const r in n){const s=e(n[r],i);t.setAttribute(r,s)}const r=this.morphAttributes;for(const n in r){const s=[],a=r[n];for(let t=0,n=a.length;t<n;t++){const n=e(a[t],i);s.push(n)}t.morphAttributes[n]=s}t.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let e=0,i=s.length;e<i;e++){const i=s[e];t.addGroup(i.start,i.count,i.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),void 0!==this.parameters){const t=this.parameters;for(const i in t)void 0!==t[i]&&(e[i]=t[i]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const t in i){const n=i[t];e.data.attributes[t]=n.toJSON(e.data)}const n={};let r=!1;for(const t in this.morphAttributes){const i=this.morphAttributes[t],s=[];for(let t=0,n=i.length;t<n;t++){const n=i[t];s.push(n.toJSON(e.data))}s.length>0&&(n[t]=s,r=!0)}r&&(e.data.morphAttributes=n,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.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;null!==i&&this.setIndex(i.clone(t));const n=e.attributes;for(const e in n){const i=n[e];this.setAttribute(e,i.clone(t))}const r=e.morphAttributes;for(const e in r){const i=[],n=r[e];for(let e=0,r=n.length;e<r;e++)i.push(n[e].clone(t));this.morphAttributes[e]=i}this.morphTargetsRelative=e.morphTargetsRelative;const s=e.groups;for(let e=0,t=s.length;e<t;e++){const t=s[e];this.addGroup(t.start,t.count,t.materialIndex)}const a=e.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=e.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const kr=new Sn,Nr=new Cn,jr=new fn,zr=new Xi,Gr=new Xi,Qr=new Xi,Vr=new Xi,Hr=new Xi,Wr=new Xi,qr=new fi,Xr=new fi,Yr=new fi,Kr=new Xi,Jr=new Xi,Zr=new Xi,$r=new Xi,es=new Xi;class ts extends Zn{constructor(e=new Fr,t=new vr){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?(void 0!==e.morphTargetInfluences&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),void 0!==e.morphTargetDictionary&&(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 e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const i=e[t[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=i.length;e<t;e++){const t=i[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){const i=this.geometry,n=i.attributes.position,r=i.morphAttributes.position,s=i.morphTargetsRelative;t.fromBufferAttribute(n,e);const a=this.morphTargetInfluences;if(r&&a){Wr.set(0,0,0);for(let i=0,n=r.length;i<n;i++){const n=a[i],o=r[i];0!==n&&(Hr.fromBufferAttribute(o,e),s?Wr.addScaledVector(Hr,n):Wr.addScaledVector(Hr.sub(t),n))}t.add(Wr)}return t}raycast(e,t){const i=this.geometry,n=this.material,r=this.matrixWorld;void 0!==n&&(null===i.boundingSphere&&i.computeBoundingSphere(),jr.copy(i.boundingSphere),jr.applyMatrix4(r),Nr.copy(e.ray).recast(e.near),(!1!==jr.containsPoint(Nr.origin)||!(null===Nr.intersectSphere(jr,zr)||Nr.origin.distanceToSquared(zr)>(e.far-e.near)**2))&&(kr.copy(r).invert(),Nr.copy(e.ray).applyMatrix4(kr),(null===i.boundingBox||!1!==Nr.intersectsBox(i.boundingBox))&&this._computeIntersections(e,t,Nr)))}_computeIntersections(e,t,i){let n;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,c=r.attributes.uv1,h=r.attributes.normal,d=r.groups,u=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=d.length;r<o;r++){const o=d[r],p=s[o.materialIndex];for(let r=Math.max(o.start,u.start),s=Math.min(a.count,Math.min(o.start+o.count,u.start+u.count));r<s;r+=3){n=is(this,p,e,i,l,c,h,a.getX(r),a.getX(r+1),a.getX(r+2)),n&&(n.faceIndex=Math.floor(r/3),n.face.materialIndex=o.materialIndex,t.push(n))}}else{for(let r=Math.max(0,u.start),o=Math.min(a.count,u.start+u.count);r<o;r+=3){n=is(this,s,e,i,l,c,h,a.getX(r),a.getX(r+1),a.getX(r+2)),n&&(n.faceIndex=Math.floor(r/3),t.push(n))}}else if(void 0!==o)if(Array.isArray(s))for(let r=0,a=d.length;r<a;r++){const a=d[r],p=s[a.materialIndex];for(let r=Math.max(a.start,u.start),s=Math.min(o.count,Math.min(a.start+a.count,u.start+u.count));r<s;r+=3){n=is(this,p,e,i,l,c,h,r,r+1,r+2),n&&(n.faceIndex=Math.floor(r/3),n.face.materialIndex=a.materialIndex,t.push(n))}}else{for(let r=Math.max(0,u.start),a=Math.min(o.count,u.start+u.count);r<a;r+=3){n=is(this,s,e,i,l,c,h,r,r+1,r+2),n&&(n.faceIndex=Math.floor(r/3),t.push(n))}}}}function is(e,t,i,n,r,s,a,o,l,c){e.getVertexPosition(o,Gr),e.getVertexPosition(l,Qr),e.getVertexPosition(c,Vr);const h=function(e,t,i,n,r,s,a,o){let l;if(l=t.side===b?n.intersectTriangle(a,s,r,!0,o):n.intersectTriangle(r,s,a,t.side===_,o),null===l)return null;es.copy(o),es.applyMatrix4(e.matrixWorld);const c=i.ray.origin.distanceTo(es);return c<i.near||c>i.far?null:{distance:c,point:es.clone(),object:e}}(e,t,i,n,Gr,Qr,Vr,$r);if(h){r&&(qr.fromBufferAttribute(r,o),Xr.fromBufferAttribute(r,l),Yr.fromBufferAttribute(r,c),h.uv=cr.getInterpolation($r,Gr,Qr,Vr,qr,Xr,Yr,new fi)),s&&(qr.fromBufferAttribute(s,o),Xr.fromBufferAttribute(s,l),Yr.fromBufferAttribute(s,c),h.uv1=cr.getInterpolation($r,Gr,Qr,Vr,qr,Xr,Yr,new fi)),a&&(Kr.fromBufferAttribute(a,o),Jr.fromBufferAttribute(a,l),Zr.fromBufferAttribute(a,c),h.normal=cr.getInterpolation($r,Gr,Qr,Vr,Kr,Jr,Zr,new Xi),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));const e={a:o,b:l,c:c,normal:new Xi,materialIndex:0};cr.getNormal(Gr,Qr,Vr,e.normal),h.face=e}return h}class ns extends Fr{constructor(e=1,t=1,i=1,n=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:n,heightSegments:r,depthSegments:s};const a=this;n=Math.floor(n),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],h=[];let d=0,u=0;function p(e,t,i,n,r,s,p,m,g,f,A){const y=s/g,v=p/f,_=s/2,b=p/2,x=m/2,w=g+1,C=f+1;let S=0,M=0;const E=new Xi;for(let s=0;s<C;s++){const a=s*v-b;for(let o=0;o<w;o++){const d=o*y-_;E[e]=d*n,E[t]=a*r,E[i]=x,l.push(E.x,E.y,E.z),E[e]=0,E[t]=0,E[i]=m>0?1:-1,c.push(E.x,E.y,E.z),h.push(o/g),h.push(1-s/f),S+=1}}for(let e=0;e<f;e++)for(let t=0;t<g;t++){const i=d+t+w*e,n=d+t+w*(e+1),r=d+(t+1)+w*(e+1),s=d+(t+1)+w*e;o.push(i,n,s),o.push(n,r,s),M+=6}a.addGroup(u,M,A),u+=M,d+=S}p("z","y","x",-1,-1,i,t,e,s,r,0),p("z","y","x",1,-1,i,t,-e,s,r,1),p("x","z","y",1,1,e,i,t,n,s,2),p("x","z","y",1,-1,e,i,-t,n,s,3),p("x","y","z",1,-1,e,t,i,n,r,4),p("x","y","z",-1,-1,e,t,-i,n,r,5),this.setIndex(o),this.setAttribute("position",new Ir(l,3)),this.setAttribute("normal",new Ir(c,3)),this.setAttribute("uv",new Ir(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ns(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function rs(e){const t={};for(const i in e){t[i]={};for(const n in e[i]){const r=e[i][n];r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)?r.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[i][n]=null):t[i][n]=r.clone():Array.isArray(r)?t[i][n]=r.slice():t[i][n]=r}}return t}function ss(e){const t={};for(let i=0;i<e.length;i++){const n=rs(e[i]);for(const e in n)t[e]=n[e]}return t}function as(e){const t=e.getRenderTarget();return null===t?e.outputColorSpace:!0===t.isXRRenderTarget?t.texture.colorSpace:Pi.workingColorSpace}const os={clone:rs,merge:ss};class ls extends Ar{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",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,void 0!==e&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=rs(e.uniforms),this.uniformsGroups=function(e){const t=[];for(let i=0;i<e.length;i++)t.push(e[i].clone());return t}(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 i in this.uniforms){const n=this.uniforms[i].value;n&&n.isTexture?t.uniforms[i]={type:"t",value:n.toJSON(e).uuid}:n&&n.isColor?t.uniforms[i]={type:"c",value:n.getHex()}:n&&n.isVector2?t.uniforms[i]={type:"v2",value:n.toArray()}:n&&n.isVector3?t.uniforms[i]={type:"v3",value:n.toArray()}:n&&n.isVector4?t.uniforms[i]={type:"v4",value:n.toArray()}:n&&n.isMatrix3?t.uniforms[i]={type:"m3",value:n.toArray()}:n&&n.isMatrix4?t.uniforms[i]={type:"m4",value:n.toArray()}:t.uniforms[i]={value:n}}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 e in this.extensions)!0===this.extensions[e]&&(i[e]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class cs extends Zn{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Sn,this.projectionMatrix=new Sn,this.projectionMatrixInverse=new Sn,this.coordinateSystem=ti}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 hs=new Xi,ds=new fi,us=new fi;class ps extends cs{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=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*li*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*oi*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*li*Math.atan(Math.tan(.5*oi*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){hs.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(hs.x,hs.y).multiplyScalar(-e/hs.z),hs.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(hs.x,hs.y).multiplyScalar(-e/hs.z)}getViewSize(e,t){return this.getViewBounds(e,ds,us),t.subVectors(us,ds)}setViewOffset(e,t,i,n,r,s){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=n,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*oi*this.fov)/this.zoom,i=2*t,n=this.aspect*i,r=-.5*n;const s=this.view;if(null!==this.view&&this.view.enabled){const e=s.fullWidth,a=s.fullHeight;r+=s.offsetX*n/e,t-=s.offsetY*i/a,n*=s.width/e,i*=s.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+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,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const ms=-90;class gs extends Zn{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const n=new ps(ms,1,e,t);n.layers=this.layers,this.add(n);const r=new ps(ms,1,e,t);r.layers=this.layers,this.add(r);const s=new ps(ms,1,e,t);s.layers=this.layers,this.add(s);const a=new ps(ms,1,e,t);a.layers=this.layers,this.add(a);const o=new ps(ms,1,e,t);o.layers=this.layers,this.add(o);const l=new ps(ms,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,n,r,s,a,o]=t;for(const e of t)this.remove(e);if(e===ti)i.up.set(0,1,0),i.lookAt(1,0,0),n.up.set(0,1,0),n.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==ii)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);i.up.set(0,-1,0),i.lookAt(-1,0,0),n.up.set(0,-1,0),n.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:n}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,c]=this.children,h=e.getRenderTarget(),d=e.getActiveCubeFace(),u=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,n),e.render(t,r),e.setRenderTarget(i,1,n),e.render(t,s),e.setRenderTarget(i,2,n),e.render(t,a),e.setRenderTarget(i,3,n),e.render(t,o),e.setRenderTarget(i,4,n),e.render(t,l),i.texture.generateMipmaps=m,e.setRenderTarget(i,5,n),e.render(t,c),e.setRenderTarget(h,d,u),e.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class fs extends Ni{constructor(e,t,i,n,r,s,a,o,l,c){super(e=void 0!==e?e:[],t=void 0!==t?t:he,i,n,r,s,a,o,l,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class As extends Vi{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 fs(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=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:be}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:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},n=new ns(5,5,5),r=new ls({name:"CubemapFromEquirect",uniforms:rs(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:b,blending:w});r.uniforms.tEquirect.value=t;const s=new ts(n,r),a=t.minFilter;return t.minFilter===we&&(t.minFilter=be),new gs(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t,i,n){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,i,n);e.setRenderTarget(r)}}const ys=new Xi,vs=new Xi,_s=new Ai;class bs{constructor(e=new Xi(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=ys.subVectors(i,t).cross(vs.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(ys),n=this.normal.dot(i);if(0===n)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/n;return r<0||r>1?null:t.copy(e.start).addScaledVector(i,r)}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||_s.getNormalMatrix(e),n=this.coplanarPoint(ys).applyMatrix4(e),r=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(r),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 xs=new fn,ws=new Xi;class Cs{constructor(e=new bs,t=new bs,i=new bs,n=new bs,r=new bs,s=new bs){this.planes=[e,t,i,n,r,s]}set(e,t,i,n,r,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(i),a[3].copy(n),a[4].copy(r),a[5].copy(s),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=ti){const i=this.planes,n=e.elements,r=n[0],s=n[1],a=n[2],o=n[3],l=n[4],c=n[5],h=n[6],d=n[7],u=n[8],p=n[9],m=n[10],g=n[11],f=n[12],A=n[13],y=n[14],v=n[15];if(i[0].setComponents(o-r,d-l,g-u,v-f).normalize(),i[1].setComponents(o+r,d+l,g+u,v+f).normalize(),i[2].setComponents(o+s,d+c,g+p,v+A).normalize(),i[3].setComponents(o-s,d-c,g-p,v-A).normalize(),i[4].setComponents(o-a,d-h,g-m,v-y).normalize(),t===ti)i[5].setComponents(o+a,d+h,g+m,v+y).normalize();else{if(t!==ii)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(a,h,m,y).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),xs.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),xs.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(xs)}intersectsSprite(e){return xs.center.set(0,0,0),xs.radius=.7071067811865476,xs.applyMatrix4(e.matrixWorld),this.intersectsSphere(xs)}intersectsSphere(e){const t=this.planes,i=e.center,n=-e.radius;for(let e=0;e<6;e++)if(t[e].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(ws.x=n.normal.x>0?e.max.x:e.min.x,ws.y=n.normal.y>0?e.max.y:e.min.y,ws.z=n.normal.z>0?e.max.z:e.min.z,n.distanceToPoint(ws)<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 Ss(){let e=null,t=!1,i=null,n=null;function r(t,s){i(t,s),n=e.requestAnimationFrame(r)}return{start:function(){!0!==t&&null!==i&&(n=e.requestAnimationFrame(r),t=!0)},stop:function(){e.cancelAnimationFrame(n),t=!1},setAnimationLoop:function(e){i=e},setContext:function(t){e=t}}}function Ms(e){const t=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)},remove:function(i){i.isInterleavedBufferAttribute&&(i=i.data);const n=t.get(i);n&&(e.deleteBuffer(n.buffer),t.delete(i))},update:function(i,n){if(i.isInterleavedBufferAttribute&&(i=i.data),i.isGLBufferAttribute){const e=t.get(i);return void((!e||e.version<i.version)&&t.set(i,{buffer:i.buffer,type:i.type,bytesPerElement:i.elementSize,version:i.version}))}const r=t.get(i);if(void 0===r)t.set(i,function(t,i){const n=t.array,r=t.usage,s=n.byteLength,a=e.createBuffer();let o;if(e.bindBuffer(i,a),e.bufferData(i,n,r),t.onUploadCallback(),n instanceof Float32Array)o=e.FLOAT;else if(n instanceof Uint16Array)o=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(n instanceof Int16Array)o=e.SHORT;else if(n instanceof Uint32Array)o=e.UNSIGNED_INT;else if(n instanceof Int32Array)o=e.INT;else if(n instanceof Int8Array)o=e.BYTE;else if(n instanceof Uint8Array)o=e.UNSIGNED_BYTE;else{if(!(n instanceof Uint8ClampedArray))throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+n);o=e.UNSIGNED_BYTE}return{buffer:a,type:o,bytesPerElement:n.BYTES_PER_ELEMENT,version:t.version,size:s}}(i,n));else if(r.version<i.version){if(r.size!==i.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.");(function(t,i,n){const r=i.array,s=i._updateRange,a=i.updateRanges;if(e.bindBuffer(n,t),-1===s.count&&0===a.length&&e.bufferSubData(n,0,r),0!==a.length){for(let t=0,i=a.length;t<i;t++){const i=a[t];e.bufferSubData(n,i.start*r.BYTES_PER_ELEMENT,r,i.start,i.count)}i.clearUpdateRanges()}-1!==s.count&&(e.bufferSubData(n,s.offset*r.BYTES_PER_ELEMENT,r,s.offset,s.count),s.count=-1),i.onUploadCallback()})(r.buffer,i,n),r.version=i.version}}}}class Es extends Fr{constructor(e=1,t=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:i,heightSegments:n};const r=e/2,s=t/2,a=Math.floor(i),o=Math.floor(n),l=a+1,c=o+1,h=e/a,d=t/o,u=[],p=[],m=[],g=[];for(let e=0;e<c;e++){const t=e*d-s;for(let i=0;i<l;i++){const n=i*h-r;p.push(n,-t,0),m.push(0,0,1),g.push(i/a),g.push(1-e/o)}}for(let e=0;e<o;e++)for(let t=0;t<a;t++){const i=t+l*e,n=t+l*(e+1),r=t+1+l*(e+1),s=t+1+l*e;u.push(i,n,s),u.push(n,r,s)}this.setIndex(u),this.setAttribute("position",new Ir(p,3)),this.setAttribute("normal",new Ir(m,3)),this.setAttribute("uv",new Ir(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Es(e.width,e.height,e.widthSegments,e.heightSegments)}}const Ts={alphahash_fragment:"#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif",alphahash_pars_fragment:"#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif",alphamap_fragment:"#ifdef USE_ALPHAMAP\n\t#if defined(INVERSE_ALPHAMAP) && INVERSE_ALPHAMAP >= 1\n\tdiffuseColor.a *= 1.0-texture2D( alphaMap, vAlphaMapUv ).g;\n\t#else\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n\t#endif\n#endif",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",alphatest_fragment:"#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif",alphatest_pars_fragment:"#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",batching_pars_vertex:"#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec3 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n\t}\n#endif",batching_vertex:"#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif",begin_vertex:"vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif",beginnormal_vertex:"vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif",bsdfs:"float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated",iridescence_fragment:"#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660,  0.0556434,\n\t\t-1.5371385,  1.8760108, -0.2040259,\n\t\t-0.4985314,  0.0415560,  1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 RGBM16ToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * value.a * 16.0, 1.0 );\n}\nvec4 LinearToRGBM16( in vec4 value ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / 16.0, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * 16.0 ), M );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t#if defined( FIX_ENV_DIRECTION )\n\t\t\tvec3 worldNormal = normal;\n\t\t#else\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#endif\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#if !defined( FIX_ENV_DIRECTION )\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\t#endif\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n    float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n    float x2 = x * x;\n    float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n    return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#if defined( USE_ANISOTROPY ) || defined( USE_ANISOTROPY_BRDF )\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3(    0, 1,    0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = 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 );\n\t\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] =  texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\ndiffuseColor.a = min(max(diffuseColor.a, 0.), 1.);\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t  f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t  f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3(  1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108,  1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605,  1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a *  a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\t#ifndef WebGL2Context\n\t#define textureLod texture2DLodEXT\n\t#define textureSize(s, lod) vec2(1024./pow(2.,float(lod)),1024./pow(2.,float(lod)))\n\t#define isinf(x) (x > 1e20 || x < -1e20)\n\t#endif\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tif(roughness == 0.0) return transmissionSamplerMapTexelToLinear( texture2D( transmissionSamplerMap, fragCoord.xy ) );\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn transmissionSamplerMapTexelToLinear( textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ) );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) || attenuationDistance == 0.0) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t\n\t\t#else\n\t\t\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"#ifdef HAS_TEXTURE\nvarying vec2 vUv;\nuniform mat3 uvTransform;\nuniform bool flipX;\nuniform bool flipY;\n#endif\nvoid main() {\n#ifdef HAS_TEXTURE\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n    vUv = flipX ? vec2( 1.0 - vUv.x, vUv.y ) : vUv;\n    vUv = flipY ? vec2( vUv.x, 1.0 - vUv.y ) : vUv;\n#endif\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"#ifdef HAS_TEXTURE\nuniform sampler2D t2D;\nvarying vec2 vUv;\n#endif\nuniform float backgroundIntensity;\nuniform vec3 backgroundColor;\nvoid main() {\n#ifdef HAS_TEXTURE\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n#else\n\tvec4 texColor = vec4( 1.0 );\n#endif\n\ttexColor.rgb *= backgroundColor * backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",cube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",depth_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",meshbasic_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",shadow_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}"},Is={common:{diffuse:{value:new mr(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ai},alphaMap:{value:null},alphaMapTransform:{value:new Ai},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ai}},envmap:{envMap:{value:null},envMapRotation:{value:new Ai},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ai}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ai}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ai},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ai},normalScale:{value:new fi(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ai},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ai}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ai}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ai}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new mr(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 mr(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ai},alphaTest:{value:0},uvTransform:{value:new Ai}},sprite:{diffuse:{value:new mr(16777215)},opacity:{value:1},center:{value:new fi(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ai},alphaMap:{value:null},alphaMapTransform:{value:new Ai},alphaTest:{value:0}}},Ps={basic:{uniforms:ss([Is.common,Is.specularmap,Is.envmap,Is.aomap,Is.lightmap,Is.fog]),vertexShader:Ts.meshbasic_vert,fragmentShader:Ts.meshbasic_frag},lambert:{uniforms:ss([Is.common,Is.specularmap,Is.envmap,Is.aomap,Is.lightmap,Is.emissivemap,Is.bumpmap,Is.normalmap,Is.displacementmap,Is.fog,Is.lights,{emissive:{value:new mr(0)}}]),vertexShader:Ts.meshlambert_vert,fragmentShader:Ts.meshlambert_frag},phong:{uniforms:ss([Is.common,Is.specularmap,Is.envmap,Is.aomap,Is.lightmap,Is.emissivemap,Is.bumpmap,Is.normalmap,Is.displacementmap,Is.fog,Is.lights,{emissive:{value:new mr(0)},specular:{value:new mr(1118481)},shininess:{value:30}}]),vertexShader:Ts.meshphong_vert,fragmentShader:Ts.meshphong_frag},standard:{uniforms:ss([Is.common,Is.envmap,Is.aomap,Is.lightmap,Is.emissivemap,Is.bumpmap,Is.normalmap,Is.displacementmap,Is.roughnessmap,Is.metalnessmap,Is.fog,Is.lights,{emissive:{value:new mr(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ts.meshphysical_vert,fragmentShader:Ts.meshphysical_frag},toon:{uniforms:ss([Is.common,Is.aomap,Is.lightmap,Is.emissivemap,Is.bumpmap,Is.normalmap,Is.displacementmap,Is.gradientmap,Is.fog,Is.lights,{emissive:{value:new mr(0)}}]),vertexShader:Ts.meshtoon_vert,fragmentShader:Ts.meshtoon_frag},matcap:{uniforms:ss([Is.common,Is.bumpmap,Is.normalmap,Is.displacementmap,Is.fog,{matcap:{value:null}}]),vertexShader:Ts.meshmatcap_vert,fragmentShader:Ts.meshmatcap_frag},points:{uniforms:ss([Is.points,Is.fog]),vertexShader:Ts.points_vert,fragmentShader:Ts.points_frag},dashed:{uniforms:ss([Is.common,Is.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ts.linedashed_vert,fragmentShader:Ts.linedashed_frag},depth:{uniforms:ss([Is.common,Is.displacementmap]),vertexShader:Ts.depth_vert,fragmentShader:Ts.depth_frag},normal:{uniforms:ss([Is.common,Is.bumpmap,Is.normalmap,Is.displacementmap,{opacity:{value:1}}]),vertexShader:Ts.meshnormal_vert,fragmentShader:Ts.meshnormal_frag},sprite:{uniforms:ss([Is.sprite,Is.fog]),vertexShader:Ts.sprite_vert,fragmentShader:Ts.sprite_frag},background:{uniforms:{uvTransform:{value:new Ai},t2D:{value:null},backgroundIntensity:{value:1},backgroundColor:{value:new mr(16777215)},flipX:{value:!1},flipY:{value:!1}},vertexShader:Ts.background_vert,fragmentShader:Ts.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 Ai}},vertexShader:Ts.backgroundCube_vert,fragmentShader:Ts.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ts.cube_vert,fragmentShader:Ts.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ts.equirect_vert,fragmentShader:Ts.equirect_frag},distanceRGBA:{uniforms:ss([Is.common,Is.displacementmap,{referencePosition:{value:new Xi},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ts.distanceRGBA_vert,fragmentShader:Ts.distanceRGBA_frag},shadow:{uniforms:ss([Is.lights,Is.fog,{color:{value:new mr(0)},opacity:{value:1}}]),vertexShader:Ts.shadow_vert,fragmentShader:Ts.shadow_frag}};Ps.physical={uniforms:ss([Ps.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ai},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ai},clearcoatNormalScale:{value:new fi(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ai},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ai},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ai},sheen:{value:0},sheenColor:{value:new mr(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ai},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ai},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ai},transmissionSamplerSize:{value:new fi},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ai},attenuationDistance:{value:0},attenuationColor:{value:new mr(0)},specularColor:{value:new mr(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ai},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ai},anisotropyVector:{value:new fi},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ai}}]),vertexShader:Ts.meshphysical_vert,fragmentShader:Ts.meshphysical_frag};const Ds={r:0,b:0,g:0},Rs=new On,Bs=new Sn,Ls=new Ai;function Os(e,t,i,n,r,s,a){const o=new mr(0);let l,c,h=!0===s?0:1,d=null,u=0,p=null;function m(e){let n=!0===e.isScene?e.background:null;return"environment"===n&&(n=e.environment),n&&n.isTexture&&(n=(e.backgroundBlurriness>0?i:t).get(n)),n}function g(t,i){t.getRGB(Ds,as(e)),n.buffers.color.setClear(Ds.r,Ds.g,Ds.b,i,a)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),h=t,g(o,h)},getClearAlpha:function(){return h},setClearAlpha:function(e){h=e,g(o,h)},getPlaneMesh:function(){return l},getBoxMesh:function(){return c},getBoxMesh2:function(){return void 0===c&&(c=new ts(new ns(1,1,1),new ls({name:"BackgroundCubeMaterial",uniforms:rs(Ps.backgroundCube.uniforms),vertexShader:Ps.backgroundCube.vertexShader,fragmentShader:Ps.backgroundCube.fragmentShader,side:b,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(e,t,i){this.matrixWorld.copyPosition(i.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(c)),c},render:function(t){let i=!1;const r=m(t);null===r?g(o,h):r&&r.isColor&&(g(r,1),i=!0);const s=e.xr.getEnvironmentBlendMode();"additive"===s?n.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===s&&n.buffers.color.setClear(0,0,0,0,a),(e.autoClear||i)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,i){const n=m(i),s=n&&n===i.environment,a=i.isScene&&void 0!==i.backgroundColor?i.backgroundColor:null;if(n&&(n.isCubeTexture||n.mapping===me))void 0===c&&(c=new ts(new ns(1,1,1),new ls({name:"BackgroundCubeMaterial",uniforms:rs(Ps.backgroundCube.uniforms),vertexShader:Ps.backgroundCube.vertexShader,fragmentShader:Ps.backgroundCube.fragmentShader,side:b,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(e,t,i){this.matrixWorld.copyPosition(i.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(c)),Rs.copy(i.backgroundRotation),Rs.x*=-1,Rs.y*=-1,Rs.z*=-1,n.isCubeTexture&&!1===n.isRenderTargetTexture&&(Rs.y*=-1,Rs.z*=-1),c.material.uniforms.envMap.value=n,c.material.uniforms.flipEnvMap.value=n.isCubeTexture&&!1===n.isRenderTargetTexture?-1:1,c.material.uniforms.backgroundBlurriness.value=i.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=i.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(Bs.makeRotationFromEuler(Rs)),c.material.toneMapped=Pi.getTransfer(n.colorSpace)!==zt,s&&(c.material.uniforms.backgroundIntensity.value*=i.environmentIntensity,Rs.copy(i.environmentRotation),Rs.x*=-1,Rs.y*=-1,Rs.z*=-1,n.isCubeTexture&&!1===n.isRenderTargetTexture&&(Rs.y*=-1,Rs.z*=-1),c.material.uniforms.backgroundRotation.value.premultiply(Ls.setFromMatrix4(Bs.makeRotationFromEuler(Rs)))),(d!==n||u!==n.version||p!==e.toneMapping)&&(c.material.needsUpdate=!0,d=n,u=n.version,p=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null);else if(n&&n.isTexture||!n&&a){void 0===l&&(l=new ts(new Es(2,2),new ls({name:"BackgroundMaterial",uniforms:rs(Ps.background.uniforms),vertexShader:Ps.background.vertexShader,fragmentShader:Ps.background.fragmentShader,side:_,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.backgroundColor.value.set(a||16777215),l.material.uniforms.t2D.value=n,l.material.uniforms.backgroundIntensity.value=i.backgroundIntensity,n?(l.material.toneMapped=Pi.getTransfer(n.colorSpace)!==zt,l.material.uniforms.flipX.value=n.userData.flipX||!1,l.material.uniforms.flipY.value=n.userData.flipY||!1,!0===n.matrixAutoUpdate&&n.updateMatrix(),l.material.uniforms.uvTransform.value.copy(n.matrix),l.material.defines.HAS_TEXTURE="1"):l.material.defines.HAS_TEXTURE&&delete l.material.defines.HAS_TEXTURE;const s=n?n.version:-1;(d!==n||u!==s||p!==e.toneMapping)&&(l.material.needsUpdate=!0,d=n,u=s,p=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)}}}}function Us(e,t){const i=e.getParameter(e.MAX_VERTEX_ATTRIBS),n={},r=c(null);let s=r,a=!1;function o(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function c(e){const t=[],n=[],r=[];for(let e=0;e<i;e++)t[e]=0,n[e]=0,r[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:n,attributeDivisors:r,object:e,attributes:{},index:null}}function h(){const e=s.newAttributes;for(let t=0,i=e.length;t<i;t++)e[t]=0}function d(e){u(e,0)}function u(t,i){const n=s.newAttributes,r=s.enabledAttributes,a=s.attributeDivisors;n[t]=1,0===r[t]&&(e.enableVertexAttribArray(t),r[t]=1),a[t]!==i&&(e.vertexAttribDivisor(t,i),a[t]=i)}function p(){const t=s.newAttributes,i=s.enabledAttributes;for(let n=0,r=i.length;n<r;n++)i[n]!==t[n]&&(e.disableVertexAttribArray(n),i[n]=0)}function m(t,i,n,r,s,a,o){!0===o?e.vertexAttribIPointer(t,i,n,s,a):e.vertexAttribPointer(t,i,n,r,s,a)}function g(){f(),a=!0,s!==r&&(s=r,o(s.object))}function f(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:function(i,r,l,g,f){let A=!1;const y=function(t,i,r){const s=!0===r.wireframe;let a=n[t.id];void 0===a&&(a={},n[t.id]=a);let o=a[i.id];void 0===o&&(o={},a[i.id]=o);let l=o[s];return void 0===l&&(l=c(e.createVertexArray()),o[s]=l),l}(g,l,r);s!==y&&(s=y,o(s.object)),A=function(e,t,i,n){const r=s.attributes,a=t.attributes;let o=0;const l=i.getAttributes();for(const t in l)if(l[t].location>=0){const i=r[t];let n=a[t];if(void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor)),void 0===i||i.attribute!==n||n&&i.data!==n.data)return!0;o++}return s.attributesNum!==o||s.index!==n}(i,g,l,f),A&&function(e,t,i,n){const r={},a=t.attributes;let o=0;const l=i.getAttributes();for(const t in l)if(l[t].location>=0){let i=a[t];void 0===i&&("instanceMatrix"===t&&e.instanceMatrix&&(i=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(i=e.instanceColor));const n={};n.attribute=i,i&&i.data&&(n.data=i.data),r[t]=n,o++}s.attributes=r,s.attributesNum=o,s.index=n}(i,g,l,f),null!==f&&t.update(f,e.ELEMENT_ARRAY_BUFFER),(A||a)&&(a=!1,function(i,n,r,s){h();const a=s.attributes,o=r.getAttributes(),l=n.defaultAttributeValues;for(const n in o){const r=o[n];if(r.location>=0){let o=a[n];if(void 0===o&&("instanceMatrix"===n&&i.instanceMatrix&&(o=i.instanceMatrix),"instanceColor"===n&&i.instanceColor&&(o=i.instanceColor)),void 0!==o){const n=o.normalized,a=o.itemSize,l=t.get(o);if(void 0===l)continue;const c=l.buffer,h=l.type,p=l.bytesPerElement,g=h===e.INT||h===e.UNSIGNED_INT||o.gpuType===Te;if(o.isInterleavedBufferAttribute){const t=o.data,l=t.stride,f=o.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<r.locationSize;e++)u(r.location+e,t.meshPerAttribute);!0!==i.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<r.locationSize;e++)d(r.location+e);e.bindBuffer(e.ARRAY_BUFFER,c);for(let e=0;e<r.locationSize;e++)m(r.location+e,a/r.locationSize,h,n,l*p,(f+a/r.locationSize*e)*p,g)}else{if(o.isInstancedBufferAttribute){for(let e=0;e<r.locationSize;e++)u(r.location+e,o.meshPerAttribute);!0!==i.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=o.meshPerAttribute*o.count)}else for(let e=0;e<r.locationSize;e++)d(r.location+e);e.bindBuffer(e.ARRAY_BUFFER,c);for(let e=0;e<r.locationSize;e++)m(r.location+e,a/r.locationSize,h,n,a*p,a/r.locationSize*e*p,g)}}else if(void 0!==l){const t=l[n];if(void 0!==t)switch(t.length){case 2:e.vertexAttrib2fv(r.location,t);break;case 3:e.vertexAttrib3fv(r.location,t);break;case 4:e.vertexAttrib4fv(r.location,t);break;default:e.vertexAttrib1fv(r.location,t)}}}}p()}(i,r,l,g),null!==f&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(f).buffer))},reset:g,resetDefaultState:f,dispose:function(){g();for(const e in n){const t=n[e];for(const e in t){const i=t[e];for(const e in i)l(i[e].object),delete i[e];delete t[e]}delete n[e]}},releaseStatesOfGeometry:function(e){if(void 0===n[e.id])return;const t=n[e.id];for(const e in t){const i=t[e];for(const e in i)l(i[e].object),delete i[e];delete t[e]}delete n[e.id]},releaseStatesOfProgram:function(e){for(const t in n){const i=n[t];if(void 0===i[e.id])continue;const r=i[e.id];for(const e in r)l(r[e].object),delete r[e];delete i[e.id]}},initAttributes:h,enableAttribute:d,disableUnusedAttributes:p}}function Fs(e,t,i){let n;function r(t,r,s){0!==s&&(e.drawArraysInstanced(n,t,r,s),i.update(r,n,s))}this.setMode=function(e){n=e},this.render=function(t,r){e.drawArrays(n,t,r),i.update(r,n,1)},this.renderInstances=r,this.renderMultiDraw=function(e,r,s){if(0===s)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,e,0,r,0,s);let a=0;for(let e=0;e<s;e++)a+=r[e];i.update(a,n,1)},this.renderMultiDrawInstances=function(e,s,a,o){if(0===a)return;const l=t.get("WEBGL_multi_draw");if(null===l)for(let t=0;t<e.length;t++)r(e[t],s[t],o[t]);else{l.multiDrawArraysInstancedWEBGL(n,e,0,s,0,o,0,a);let t=0;for(let e=0;e<a;e++)t+=s[e];for(let e=0;e<o.length;e++)i.update(t,n,o[e])}}}function ks(e,t,i,n){let r;function s(t){if("highp"===t){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==i.precision?i.precision:"highp";const o=s(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===i.logarithmicDepthBuffer,c=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===t.has("EXT_texture_filter_anisotropic")){const i=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(t){return!(t!==Ue&&n.convert(t)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))},textureTypeReadable:function(i){const r=i===De&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(i!==Ce&&n.convert(i)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&i!==Pe&&!r)},precision:a,logarithmicDepthBuffer:l,maxTextures:c,maxVertexTextures:h,maxTextureSize:e.getParameter(e.MAX_TEXTURE_SIZE),maxCubemapSize:e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:e.getParameter(e.MAX_VERTEX_ATTRIBS),maxVertexUniforms:e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:e.getParameter(e.MAX_VARYING_VECTORS),maxFragmentUniforms:e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:h>0,maxSamples:e.getParameter(e.MAX_SAMPLES)}}function Ns(e){const t=this;let i=null,n=0,r=!1,s=!1;const a=new bs,o=new Ai,l={value:null,needsUpdate:!1};function c(e,i,n,r){const s=null!==e?e.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const t=n+4*s,r=i.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length<t)&&(c=new Float32Array(t));for(let t=0,i=n;t!==s;++t,i+=4)a.copy(e[t]).applyMatrix4(r,o),a.normal.toArray(c,i),c[i+3]=a.constant}l.value=c,l.needsUpdate=!0}return t.numPlanes=s,t.numIntersection=0,c}this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){const i=0!==e.length||t||0!==n||r;return r=t,n=e.length,i},this.beginShadows=function(){s=!0,c(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(e,t){i=c(e,t,0)},this.setState=function(a,o,h){const d=a.clippingPlanes,u=a.clipIntersection,p=a.clipShadows,m=e.get(a);if(!r||null===d||0===d.length||s&&!p)s?c(null):(l.value!==i&&(l.value=i,l.needsUpdate=n>0),t.numPlanes=n,t.numIntersection=0);else{const e=s?0:n,t=4*e;let r=m.clippingState||null;l.value=r,r=c(d,o,t,h);for(let e=0;e!==t;++e)r[e]=i[e];m.clippingState=r,this.numIntersection=u?this.numPlanes:0,this.numPlanes+=e}}}function js(e){let t=new WeakMap;function i(e,t){return t===ue?e.mapping=he:t===pe&&(e.mapping=de),e}function n(e){const i=e.target;i.removeEventListener("dispose",n);const r=t.get(i);void 0!==r&&(t.delete(i),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping;if(s===ue||s===pe){if(t.has(r)){return i(t.get(r).texture,r.mapping)}{const s=r.image;if(s&&s.height>0){const a=new As(s.height);return a.fromEquirectangularTexture(e,r),t.set(r,a),r.addEventListener("dispose",n),i(a.texture,r.mapping)}return null}}}return r},dispose:function(){t=new WeakMap}}}class zs extends cs{constructor(e=-1,t=1,i=1,n=-1,r=.1,s=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=r,this.far=s,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=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,i,n,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=n,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(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 r=i-e,s=i+e,a=n+t,o=n-t;if(null!==this.view&&this.view.enabled){const e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=e*this.view.offsetX,s=r+e*this.view.width,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,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,null!==this.view&&(t.object.view=Object.assign({},this.view)),t}}const Gs=[.125,.215,.35,.446,.526,.582],Qs=20,Vs=new zs,Hs=new mr;let Ws=null,qs=0,Xs=0,Ys=!1;const Ks=(1+Math.sqrt(5))/2,Js=1/Ks,Zs=[new Xi(-Ks,Js,0),new Xi(Ks,Js,0),new Xi(-Js,0,Ks),new Xi(Js,0,Ks),new Xi(0,Ks,-Js),new Xi(0,Ks,Js),new Xi(-1,1,-1),new Xi(1,1,-1),new Xi(-1,1,1),new Xi(1,1,1)];class $s{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){Ws=this._renderer.getRenderTarget(),qs=this._renderer.getActiveCubeFace(),Xs=this._renderer.getActiveMipmapLevel(),Ys=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(e,i,n,r),t>0&&this._blur(r,0,0,t),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=na(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=ia(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(Ws,qs,Xs),this._renderer.xr.enabled=Ys,e.scissorTest=!1,ta(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===he||e.mapping===de?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Ws=this._renderer.getRenderTarget(),qs=this._renderer.getActiveCubeFace(),Xs=this._renderer.getActiveMipmapLevel(),Ys=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:be,minFilter:be,generateMipmaps:!1,type:De,format:Ue,colorSpace:Ut,depthBuffer:!1},n=ea(e,t,i);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=ea(e,t,i);const{_lodMax:n}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=function(e){const t=[],i=[],n=[];let r=e;const s=e-4+1+Gs.length;for(let a=0;a<s;a++){const s=Math.pow(2,r);i.push(s);let o=1/s;a>e-4?o=Gs[a-e+4-1]:0===a&&(o=0),n.push(o);const l=1/(s-2),c=-l,h=1+l,d=[c,c,h,c,h,h,c,c,h,h,c,h],u=6,p=6,m=3,g=2,f=1,A=new Float32Array(m*p*u),y=new Float32Array(g*p*u),v=new Float32Array(f*p*u);for(let e=0;e<u;e++){const t=e%3*2/3-1,i=e>2?0:-1,n=[t,i,0,t+2/3,i,0,t+2/3,i+1,0,t,i,0,t+2/3,i+1,0,t,i+1,0];A.set(n,m*p*e),y.set(d,g*p*e);const r=[e,e,e,e,e,e];v.set(r,f*p*e)}const _=new Fr;_.setAttribute("position",new Mr(A,m)),_.setAttribute("uv",new Mr(y,g)),_.setAttribute("faceIndex",new Mr(v,f)),t.push(_),r>4&&r--}return{lodPlanes:t,sizeLods:i,sigmas:n}}(n)),this._blurMaterial=function(e,t,i){const n=new Float32Array(Qs),r=new Xi(0,1,0);return new ls({name:"SphericalGaussianBlur",defines:{n:Qs,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/i,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:ra(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:w,depthTest:!1,depthWrite:!1})}(n,e,t)}return n}_compileMaterial(e){const t=new ts(this._lodPlanes[0],e);this._renderer.compile(t,Vs)}_sceneToCubeUV(e,t,i,n){const r=new ps(90,1,t,i),s=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(Hs),o.toneMapping=0,o.autoClear=!1;const h=new vr({name:"PMREM.Background",side:b,depthWrite:!1,depthTest:!1}),d=new ts(new ns,h);let u=!1;const p=e.background;p?p.isColor&&(h.color.copy(p),e.background=null,u=!0):(h.color.copy(Hs),u=!0);for(let t=0;t<6;t++){const i=t%3;0===i?(r.up.set(0,s[t],0),r.lookAt(a[t],0,0)):1===i?(r.up.set(0,0,s[t]),r.lookAt(0,a[t],0)):(r.up.set(0,s[t],0),r.lookAt(0,0,a[t]));const l=this._cubeSize;ta(n,i*l,t>2?l:0,l,l),o.setRenderTarget(n),u&&o.render(d,r),o.render(e,r)}d.geometry.dispose(),d.material.dispose(),o.toneMapping=c,o.autoClear=l,e.background=p}_textureToCubeUV(e,t){const i=this._renderer,n=e.mapping===he||e.mapping===de;n?(null===this._cubemapMaterial&&(this._cubemapMaterial=na()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=ia());const r=n?this._cubemapMaterial:this._equirectMaterial,s=new ts(this._lodPlanes[0],r);r.uniforms.envMap.value=e;const a=this._cubeSize;ta(t,0,0,3*a,2*a),i.setRenderTarget(t),i.render(s,Vs)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const n=this._lodPlanes.length;for(let t=1;t<n;t++){const i=Math.sqrt(this._sigmas[t]*this._sigmas[t]-this._sigmas[t-1]*this._sigmas[t-1]),r=Zs[(n-t-1)%Zs.length];this._blur(e,t-1,t,i,r)}t.autoClear=i}_blur(e,t,i,n,r){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,i,n,"latitudinal",r),this._halfBlur(s,e,i,i,n,"longitudinal",r)}_halfBlur(e,t,i,n,r,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&console.error("blur direction must be either latitudinal or longitudinal!");const c=new ts(this._lodPlanes[n],l),h=l.uniforms,d=this._sizeLods[i]-1,u=isFinite(r)?Math.PI/(2*d):2*Math.PI/39,p=r/u,m=isFinite(r)?1+Math.floor(3*p):Qs;m>Qs&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const g=[];let f=0;for(let e=0;e<Qs;++e){const t=e/p,i=Math.exp(-t*t/2);g.push(i),0===e?f+=i:e<m&&(f+=2*i)}for(let e=0;e<g.length;e++)g[e]=g[e]/f;h.envMap.value=e.texture,h.samples.value=m,h.weights.value=g,h.latitudinal.value="latitudinal"===s,a&&(h.poleAxis.value=a);const{_lodMax:A}=this;h.dTheta.value=u,h.mipInt.value=A-i;const y=this._sizeLods[n];ta(t,3*y*(n>A-4?n-A+4:0),4*(this._cubeSize-y),3*y,2*y),o.setRenderTarget(t),o.render(c,Vs)}}function ea(e,t,i){const n=new Vi(e,t,i);return n.texture.mapping=me,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function ta(e,t,i,n,r){e.viewport.set(t,i,n,r),e.scissor.set(t,i,n,r)}function ia(){return new ls({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:ra(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:w,depthTest:!1,depthWrite:!1})}function na(){return new ls({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:ra(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:w,depthTest:!1,depthWrite:!1})}function ra(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function sa(e){let t=new WeakMap,i=null;function n(e){const i=e.target;i.removeEventListener("dispose",n);const r=t.get(i);void 0!==r&&(t.delete(i),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping,a=s===ue||s===pe,o=s===he||s===de;if(a||o){let s=t.get(r);const l=void 0!==s?s.texture.pmremVersion:0;if(r.isRenderTargetTexture&&r.pmremVersion!==l)return null===i&&(i=new $s(e)),s=a?i.fromEquirectangular(r,s):i.fromCubemap(r,s),s.texture.pmremVersion=r.pmremVersion,t.set(r,s),s.texture;if(void 0!==s)return s.texture;{const l=r.image;return a&&l&&l.height>0||o&&l&&function(e){let t=0;const i=6;for(let n=0;n<i;n++)void 0!==e[n]&&t++;return t===i}(l)?(null===i&&(i=new $s(e)),s=a?i.fromEquirectangular(r):i.fromCubemap(r),s.texture.pmremVersion=r.pmremVersion,t.set(r,s),r.addEventListener("dispose",n),s.texture):null}}}return r},dispose:function(){t=new WeakMap,null!==i&&(i.dispose(),i=null)}}}function aa(e){const t={};function i(i){if(void 0!==t[i])return t[i];let n;switch(i){case"WEBGL_depth_texture":n=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:n=e.getExtension(i)}return t[i]=n,n}return{has:function(e){return null!==i(e)},init:function(){i("EXT_color_buffer_float"),i("WEBGL_clip_cull_distance"),i("OES_texture_float_linear"),i("EXT_color_buffer_half_float"),i("WEBGL_multisampled_render_to_texture"),i("WEBGL_render_shared_exponent")},get:function(e){const t=i(e);return null===t&&Si("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function oa(e,t,i,n){const r={},s=new WeakMap;function a(e){const o=e.target;null!==o.index&&t.remove(o.index);for(const e in o.attributes)t.remove(o.attributes[e]);for(const e in o.morphAttributes){const i=o.morphAttributes[e];for(let e=0,n=i.length;e<n;e++)t.remove(i[e])}o.removeEventListener("dispose",a),delete r[o.id];const l=s.get(o);l&&(t.remove(l),s.delete(o)),n.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,i.memory.geometries--}function o(e){const i=[],n=e.index,r=e.attributes.position;let a=0;if(null!==n){const e=n.array;a=n.version;for(let t=0,n=e.length;t<n;t+=3){const n=e[t+0],r=e[t+1],s=e[t+2];i.push(n,r,r,s,s,n)}}else{if(void 0===r)return;{const e=r.array;a=r.version;for(let t=0,n=e.length/3-1;t<n;t+=3){const e=t+0,n=t+1,r=t+2;i.push(e,n,n,r,r,e)}}}const o=new(vi(i)?Tr:Er)(i,1);o.version=a;const l=s.get(e);l&&t.remove(l),s.set(e,o)}return{get:function(e,t){return!0===r[t.id]||(t.addEventListener("dispose",a),r[t.id]=!0,i.memory.geometries++),t},update:function(i){const n=i.attributes;for(const i in n)t.update(n[i],e.ARRAY_BUFFER);const r=i.morphAttributes;for(const i in r){const n=r[i];for(let i=0,r=n.length;i<r;i++)t.update(n[i],e.ARRAY_BUFFER)}},getWireframeAttribute:function(e){const t=s.get(e);if(t){const i=e.index;null!==i&&t.version<i.version&&o(e)}else o(e);return s.get(e)}}}function la(e,t,i){let n,r,s;function a(t,a,o){0!==o&&(e.drawElementsInstanced(n,a,r,t*s,o),i.update(a,n,o))}this.setMode=function(e){n=e},this.setIndex=function(e){r=e.type,s=e.bytesPerElement},this.render=function(t,a){e.drawElements(n,a,r,t*s),i.update(a,n,1)},this.renderInstances=a,this.renderMultiDraw=function(e,s,a){if(0===a)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,s,0,r,e,0,a);let o=0;for(let e=0;e<a;e++)o+=s[e];i.update(o,n,1)},this.renderMultiDrawInstances=function(e,o,l,c){if(0===l)return;const h=t.get("WEBGL_multi_draw");if(null===h)for(let t=0;t<e.length;t++)a(e[t]/s,o[t],c[t]);else{h.multiDrawElementsInstancedWEBGL(n,o,0,r,e,0,c,0,l);let t=0;for(let e=0;e<l;e++)t+=o[e];for(let e=0;e<c.length;e++)i.update(t,n,c[e])}}}function ca(e){const t={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:t,programs:null,autoReset:!0,reset:function(){t.calls=0,t.triangles=0,t.points=0,t.lines=0},update:function(i,n,r){switch(t.calls++,n){case e.TRIANGLES:t.triangles+=r*(i/3);break;case e.LINES:t.lines+=r*(i/2);break;case e.LINE_STRIP:t.lines+=r*(i-1);break;case e.LINE_LOOP:t.lines+=r*i;break;case e.POINTS:t.points+=r*i;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",n)}}}}function ha(e,t,i){const n=new WeakMap,r=new Gi;return{update:function(s,a,o){const l=s.morphTargetInfluences,c=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,h=void 0!==c?c.length:0;let d=n.get(a);if(void 0===d||d.count!==h){let e=function(){A.dispose(),n.delete(a),a.removeEventListener("dispose",e)};void 0!==d&&d.texture.dispose();const i=void 0!==a.morphAttributes.position,s=void 0!==a.morphAttributes.normal,o=void 0!==a.morphAttributes.color,l=a.morphAttributes.position||[],c=a.morphAttributes.normal||[],u=a.morphAttributes.color||[];let p=0;!0===i&&(p=1),!0===s&&(p=2),!0===o&&(p=3);let m=a.attributes.position.count*p,g=1;m>t.maxTextureSize&&(g=Math.ceil(m/t.maxTextureSize),m=t.maxTextureSize);const f=new Float32Array(m*g*4*h),A=new Hi(f,m,g,h);A.type=Pe,A.needsUpdate=!0;const y=4*p;for(let e=0;e<h;e++){const t=l[e],n=c[e],a=u[e],h=m*g*4*e;for(let e=0;e<t.count;e++){const l=e*y;!0===i&&(r.fromBufferAttribute(t,e),f[h+l+0]=r.x,f[h+l+1]=r.y,f[h+l+2]=r.z,f[h+l+3]=0),!0===s&&(r.fromBufferAttribute(n,e),f[h+l+4]=r.x,f[h+l+5]=r.y,f[h+l+6]=r.z,f[h+l+7]=0),!0===o&&(r.fromBufferAttribute(a,e),f[h+l+8]=r.x,f[h+l+9]=r.y,f[h+l+10]=r.z,f[h+l+11]=4===a.itemSize?r.w:1)}}d={count:h,texture:A,size:new fi(m,g)},n.set(a,d),a.addEventListener("dispose",e)}if(!0===s.isInstancedMesh&&null!==s.morphTexture)o.getUniforms().setValue(e,"morphTexture",s.morphTexture,i);else{let t=0;for(let e=0;e<l.length;e++)t+=l[e];const i=a.morphTargetsRelative?1:1-t;o.getUniforms().setValue(e,"morphTargetBaseInfluence",i),o.getUniforms().setValue(e,"morphTargetInfluences",l)}o.getUniforms().setValue(e,"morphTargetsTexture",d.texture,i),o.getUniforms().setValue(e,"morphTargetsTextureSize",d.size)}}}function da(e,t,i,n){let r=new WeakMap;function s(e){const t=e.target;t.removeEventListener("dispose",s),i.remove(t.instanceMatrix),null!==t.instanceColor&&i.remove(t.instanceColor)}return{update:function(a){const o=n.render.frame,l=a.geometry,c=t.get(a,l);if(r.get(c)!==o&&(t.update(c),r.set(c,o)),a.isInstancedMesh&&(!1===a.hasEventListener("dispose",s)&&a.addEventListener("dispose",s),r.get(a)!==o&&(i.update(a.instanceMatrix,e.ARRAY_BUFFER),null!==a.instanceColor&&i.update(a.instanceColor,e.ARRAY_BUFFER),r.set(a,o))),a.isSkinnedMesh){const e=a.skeleton;r.get(e)!==o&&(e.update(),r.set(e,o))}return c},dispose:function(){r=new WeakMap}}}class ua extends Ni{constructor(e,t,i,n,r,s,a,o,l,c=Fe){if(c!==Fe&&c!==ke)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===i&&c===Fe&&(i=Ie),void 0===i&&c===ke&&(i=Le),super(null,n,r,s,a,o,c,i,l),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=void 0!==a?a:ye,this.minFilter=void 0!==o?o:ye,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 null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}const pa=new Ni,ma=new ua(1,1),ga=new Hi,fa=new Wi,Aa=new fs,ya=[],va=[],_a=new Float32Array(16),ba=new Float32Array(9),xa=new Float32Array(4);function wa(e,t,i){const n=e[0];if(n<=0||n>0)return e;const r=t*i;let s=ya[r];if(void 0===s&&(s=new Float32Array(r),ya[r]=s),0!==t){n.toArray(s,0);for(let n=1,r=0;n!==t;++n)r+=i,e[n].toArray(s,r)}return s}function Ca(e,t){if(e.length!==t.length)return!1;for(let i=0,n=e.length;i<n;i++)if(e[i]!==t[i])return!1;return!0}function Sa(e,t){for(let i=0,n=t.length;i<n;i++)e[i]=t[i]}function Ma(e,t){let i=va[t];void 0===i&&(i=new Int32Array(t),va[t]=i);for(let n=0;n!==t;++n)i[n]=e.allocateTextureUnit();return i}function Ea(e,t){const i=this.cache;i[0]!==t&&(e.uniform1f(this.addr,t),i[0]=t)}function Ta(e,t){const i=this.cache;if(void 0!==t.x)(i[0]!==t.x||i[1]!==t.y)&&(e.uniform2f(this.addr,t.x,t.y),i[0]=t.x,i[1]=t.y);else{if(Ca(i,t))return;e.uniform2fv(this.addr,t),Sa(i,t)}}function Ia(e,t){const i=this.cache;if(void 0!==t.x)(i[0]!==t.x||i[1]!==t.y||i[2]!==t.z)&&(e.uniform3f(this.addr,t.x,t.y,t.z),i[0]=t.x,i[1]=t.y,i[2]=t.z);else if(void 0!==t.r)(i[0]!==t.r||i[1]!==t.g||i[2]!==t.b)&&(e.uniform3f(this.addr,t.r,t.g,t.b),i[0]=t.r,i[1]=t.g,i[2]=t.b);else{if(Ca(i,t))return;e.uniform3fv(this.addr,t),Sa(i,t)}}function Pa(e,t){const i=this.cache;if(void 0!==t.x)(i[0]!==t.x||i[1]!==t.y||i[2]!==t.z||i[3]!==t.w)&&(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),i[0]=t.x,i[1]=t.y,i[2]=t.z,i[3]=t.w);else{if(Ca(i,t))return;e.uniform4fv(this.addr,t),Sa(i,t)}}function Da(e,t){const i=this.cache,n=t.elements;if(void 0===n){if(Ca(i,t))return;e.uniformMatrix2fv(this.addr,!1,t),Sa(i,t)}else{if(Ca(i,n))return;xa.set(n),e.uniformMatrix2fv(this.addr,!1,xa),Sa(i,n)}}function Ra(e,t){const i=this.cache,n=t.elements;if(void 0===n){if(Ca(i,t))return;e.uniformMatrix3fv(this.addr,!1,t),Sa(i,t)}else{if(Ca(i,n))return;ba.set(n),e.uniformMatrix3fv(this.addr,!1,ba),Sa(i,n)}}function Ba(e,t){const i=this.cache,n=t.elements;if(void 0===n){if(Ca(i,t))return;e.uniformMatrix4fv(this.addr,!1,t),Sa(i,t)}else{if(Ca(i,n))return;_a.set(n),e.uniformMatrix4fv(this.addr,!1,_a),Sa(i,n)}}function La(e,t){const i=this.cache;i[0]!==t&&(e.uniform1i(this.addr,t),i[0]=t)}function Oa(e,t){const i=this.cache;if(void 0!==t.x)(i[0]!==t.x||i[1]!==t.y)&&(e.uniform2i(this.addr,t.x,t.y),i[0]=t.x,i[1]=t.y);else{if(Ca(i,t))return;e.uniform2iv(this.addr,t),Sa(i,t)}}function Ua(e,t){const i=this.cache;if(void 0!==t.x)(i[0]!==t.x||i[1]!==t.y||i[2]!==t.z)&&(e.uniform3i(this.addr,t.x,t.y,t.z),i[0]=t.x,i[1]=t.y,i[2]=t.z);else{if(Ca(i,t))return;e.uniform3iv(this.addr,t),Sa(i,t)}}function Fa(e,t){const i=this.cache;if(void 0!==t.x)(i[0]!==t.x||i[1]!==t.y||i[2]!==t.z||i[3]!==t.w)&&(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),i[0]=t.x,i[1]=t.y,i[2]=t.z,i[3]=t.w);else{if(Ca(i,t))return;e.uniform4iv(this.addr,t),Sa(i,t)}}function ka(e,t){const i=this.cache;i[0]!==t&&(e.uniform1ui(this.addr,t),i[0]=t)}function Na(e,t){const i=this.cache;if(void 0!==t.x)(i[0]!==t.x||i[1]!==t.y)&&(e.uniform2ui(this.addr,t.x,t.y),i[0]=t.x,i[1]=t.y);else{if(Ca(i,t))return;e.uniform2uiv(this.addr,t),Sa(i,t)}}function ja(e,t){const i=this.cache;if(void 0!==t.x)(i[0]!==t.x||i[1]!==t.y||i[2]!==t.z)&&(e.uniform3ui(this.addr,t.x,t.y,t.z),i[0]=t.x,i[1]=t.y,i[2]=t.z);else{if(Ca(i,t))return;e.uniform3uiv(this.addr,t),Sa(i,t)}}function za(e,t){const i=this.cache;if(void 0!==t.x)(i[0]!==t.x||i[1]!==t.y||i[2]!==t.z||i[3]!==t.w)&&(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),i[0]=t.x,i[1]=t.y,i[2]=t.z,i[3]=t.w);else{if(Ca(i,t))return;e.uniform4uiv(this.addr,t),Sa(i,t)}}function Ga(e,t,i){const n=this.cache,r=i.allocateTextureUnit();let s;n[0]!==r&&(e.uniform1i(this.addr,r),n[0]=r),this.type===e.SAMPLER_2D_SHADOW?(ma.compareFunction=515,s=ma):s=pa,i.setTexture2D(t||s,r)}function Qa(e,t,i){const n=this.cache,r=i.allocateTextureUnit();n[0]!==r&&(e.uniform1i(this.addr,r),n[0]=r),i.setTexture3D(t||fa,r)}function Va(e,t,i){const n=this.cache,r=i.allocateTextureUnit();n[0]!==r&&(e.uniform1i(this.addr,r),n[0]=r),i.setTextureCube(t||Aa,r)}function Ha(e,t,i){const n=this.cache,r=i.allocateTextureUnit();n[0]!==r&&(e.uniform1i(this.addr,r),n[0]=r),i.setTexture2DArray(t||ga,r)}function Wa(e,t){e.uniform1fv(this.addr,t)}function qa(e,t){const i=wa(t,this.size,2);e.uniform2fv(this.addr,i)}function Xa(e,t){const i=wa(t,this.size,3);e.uniform3fv(this.addr,i)}function Ya(e,t){const i=wa(t,this.size,4);e.uniform4fv(this.addr,i)}function Ka(e,t){const i=wa(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,i)}function Ja(e,t){const i=wa(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,i)}function Za(e,t){const i=wa(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,i)}function $a(e,t){e.uniform1iv(this.addr,t)}function eo(e,t){e.uniform2iv(this.addr,t)}function to(e,t){e.uniform3iv(this.addr,t)}function io(e,t){e.uniform4iv(this.addr,t)}function no(e,t){e.uniform1uiv(this.addr,t)}function ro(e,t){e.uniform2uiv(this.addr,t)}function so(e,t){e.uniform3uiv(this.addr,t)}function ao(e,t){e.uniform4uiv(this.addr,t)}function oo(e,t,i){const n=this.cache,r=t.length,s=Ma(i,r);Ca(n,s)||(e.uniform1iv(this.addr,s),Sa(n,s));for(let e=0;e!==r;++e)i.setTexture2D(t[e]||pa,s[e])}function lo(e,t,i){const n=this.cache,r=t.length,s=Ma(i,r);Ca(n,s)||(e.uniform1iv(this.addr,s),Sa(n,s));for(let e=0;e!==r;++e)i.setTexture3D(t[e]||fa,s[e])}function co(e,t,i){const n=this.cache,r=t.length,s=Ma(i,r);Ca(n,s)||(e.uniform1iv(this.addr,s),Sa(n,s));for(let e=0;e!==r;++e)i.setTextureCube(t[e]||Aa,s[e])}function ho(e,t,i){const n=this.cache,r=t.length,s=Ma(i,r);Ca(n,s)||(e.uniform1iv(this.addr,s),Sa(n,s));for(let e=0;e!==r;++e)i.setTexture2DArray(t[e]||ga,s[e])}class uo{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.setValue=function(e){switch(e){case 5126:return Ea;case 35664:return Ta;case 35665:return Ia;case 35666:return Pa;case 35674:return Da;case 35675:return Ra;case 35676:return Ba;case 5124:case 35670:return La;case 35667:case 35671:return Oa;case 35668:case 35672:return Ua;case 35669:case 35673:return Fa;case 5125:return ka;case 36294:return Na;case 36295:return ja;case 36296:return za;case 35678:case 36198:case 36298:case 36306:case 35682:return Ga;case 35679:case 36299:case 36307:return Qa;case 35680:case 36300:case 36308:case 36293:return Va;case 36289:case 36303:case 36311:case 36292:return Ha}}(t.type)}}class po{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=function(e){switch(e){case 5126:return Wa;case 35664:return qa;case 35665:return Xa;case 35666:return Ya;case 35674:return Ka;case 35675:return Ja;case 35676:return Za;case 5124:case 35670:return $a;case 35667:case 35671:return eo;case 35668:case 35672:return to;case 35669:case 35673:return io;case 5125:return no;case 36294:return ro;case 36295:return so;case 36296:return ao;case 35678:case 36198:case 36298:case 36306:case 35682:return oo;case 35679:case 36299:case 36307:return lo;case 35680:case 36300:case 36308:case 36293:return co;case 36289:case 36303:case 36311:case 36292:return ho}}(t.type)}}class mo{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,i){const n=this.seq;for(let r=0,s=n.length;r!==s;++r){const s=n[r];s.setValue(e,t[s.id],i)}}}const go=/(\w+)(\])?(\[|\.)?/g;function fo(e,t){e.seq.push(t),e.map[t.id]=t}function Ao(e,t,i){const n=e.name,r=n.length;for(go.lastIndex=0;;){const s=go.exec(n),a=go.lastIndex;let o=s[1];const l="]"===s[2],c=s[3];if(l&&(o|=0),void 0===c||"["===c&&a+2===r){fo(i,void 0===c?new uo(o,e,t):new po(o,e,t));break}{let e=i.map[o];void 0===e&&(e=new mo(o),fo(i,e)),i=e}}}class yo{constructor(e,t){this.seq=[],this.map={};const i=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let n=0;n<i;++n){const i=e.getActiveUniform(t,n);Ao(i,e.getUniformLocation(t,i.name),this)}}setValue(e,t,i,n){const r=this.map[t];void 0!==r&&r.setValue(e,i,n)}setOptional(e,t,i){const n=t[i];void 0!==n&&this.setValue(e,i,n)}static upload(e,t,i,n){for(let r=0,s=t.length;r!==s;++r){const s=t[r],a=i[s.id];!1!==a.needsUpdate&&s.setValue(e,a.value,n)}}static seqWithValue(e,t){const i=[];for(let n=0,r=e.length;n!==r;++n){const r=e[n];r.id in t&&i.push(r)}return i}}function vo(e,t,i){const n=e.createShader(t);return e.shaderSource(n,i),e.compileShader(n),n}let _o=0;function bo(e,t,i){const n=e.getShaderParameter(t,e.COMPILE_STATUS),r=e.getShaderInfoLog(t).trim();if(n&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const n=parseInt(s[1]);return i.toUpperCase()+"\n\n"+r+"\n\n"+function(e,t){const i=e.split("\n"),n=[],r=Math.max(t-6,0),s=Math.min(t+6,i.length);for(let e=r;e<s;e++){const r=e+1;n.push(`${r===t?">":" "} ${r}: ${i[e]}`)}return n.join("\n")}(e.getShaderSource(t),n)}return r}function xo(e,t){let i;switch(t){case Ut:i="";break;case Ot:i="sRGBToLinear";break;case Nt:i="RGBM16ToLinear";break;default:console.warn("THREE.WebGLProgram: Unsupported color space:",t),i=""}return`vec4 ${e}( vec4 value ) { return ${i} ( value ); }`}function wo(e,t){const i=function(e){const t=Pi.getPrimaries(Pi.workingColorSpace),i=e===Lt||e===Nt?null:Pi.getPrimaries(e);let n;switch(t!==i&&i?t===Qt&&i===Gt?n="LinearDisplayP3ToLinearSRGB":t===Gt&&i===Qt&&(n="LinearSRGBToLinearDisplayP3"):n="",e){case Lt:return["",""];case Ut:case kt:return[n,"LinearTransferOETF"];case Ot:case Ft:return[n,"sRGBTransferOETF"];case Nt:return["","LinearToRGBM16"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",e),[n,"LinearTransferOETF"]}}(t);return`vec4 ${e}( vec4 value ) { return ${i[0]}( ${i[1]}( value ) ); }`}function Co(e,t){let i;switch(t){case ne:i="Linear";break;case re:i="Reinhard";break;case se:i="Cineon";break;case ae:i="ACESFilmic";break;case oe:i="AgX";break;case 7:i="Neutral";break;case 5:i="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),i="Linear"}return"vec3 "+e+"( vec3 color ) { return "+i+"ToneMapping( color ); }"}const So=new Xi;function Mo(){Pi.getLuminanceCoefficients(So);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${So.x.toFixed(4)}, ${So.y.toFixed(4)}, ${So.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function Eo(e){return""!==e}function To(e,t){const i=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,i).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function Io(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const Po=/^[ \t]*#include +<([\w\d./]+)>/gm;function Do(e){return e.replace(Po,Bo)}const Ro=new Map;function Bo(e,t){let i=Ts[t];if(void 0===i){const e=Ro.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");i=Ts[e],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return Do(i)}const Lo=/#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 Oo(e){return e.replace(Lo,Uo)}function Uo(e,t,i,n){let r="";for(let e=parseInt(t);e<parseInt(i);e++)r+=n.replace(/\[\s*i\s*\]/g,"[ "+e+" ]").replace(/UNROLLED_LOOP_INDEX/g,e);return r}function Fo(e){let t=`precision ${e.precision} float;\n\tprecision ${e.precision} int;\n\tprecision ${e.precision} sampler2D;\n\tprecision ${e.precision} samplerCube;\n\tprecision ${e.precision} sampler3D;\n\tprecision ${e.precision} sampler2DArray;\n\tprecision ${e.precision} sampler2DShadow;\n\tprecision ${e.precision} samplerCubeShadow;\n\tprecision ${e.precision} sampler2DArrayShadow;\n\tprecision ${e.precision} isampler2D;\n\tprecision ${e.precision} isampler3D;\n\tprecision ${e.precision} isamplerCube;\n\tprecision ${e.precision} isampler2DArray;\n\tprecision ${e.precision} usampler2D;\n\tprecision ${e.precision} usampler3D;\n\tprecision ${e.precision} usamplerCube;\n\tprecision ${e.precision} usampler2DArray;\n\t`;return"highp"===e.precision?t+="\n#define HIGH_PRECISION":"mediump"===e.precision?t+="\n#define MEDIUM_PRECISION":"lowp"===e.precision&&(t+="\n#define LOW_PRECISION"),t}function ko(e,t,i,n){const r=e.getContext(),s=i.defines;let a=i.vertexShader,o=i.fragmentShader;const l=function(e){let t="SHADOWMAP_TYPE_BASIC";return 1===e.shadowMapType?t="SHADOWMAP_TYPE_PCF":2===e.shadowMapType?t="SHADOWMAP_TYPE_PCF_SOFT":3===e.shadowMapType&&(t="SHADOWMAP_TYPE_VSM"),t}(i),c=function(e){let t="ENVMAP_TYPE_CUBE";if(e.envMap)switch(e.envMapMode){case he:case de:t="ENVMAP_TYPE_CUBE";break;case me:t="ENVMAP_TYPE_CUBE_UV"}return t}(i),h=function(e){let t="ENVMAP_MODE_REFLECTION";return e.envMap&&e.envMapMode===de&&(t="ENVMAP_MODE_REFRACTION"),t}(i),d=function(e){let t="ENVMAP_BLENDING_NONE";if(e.envMap)switch(e.combine){case 0:t="ENVMAP_BLENDING_MULTIPLY";break;case 1:t="ENVMAP_BLENDING_MIX";break;case 2:t="ENVMAP_BLENDING_ADD"}return t}(i),u=function(e){const t=e.envMapCubeUVHeight;if(null===t)return null;const i=Math.log2(t)-2,n=1/t;return{texelWidth:1/(3*Math.max(Math.pow(2,i),112)),texelHeight:n,maxMip:i}}(i),p=function(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Eo).join("\n")}(i),m=function(e){const t=[];for(const i in e){const n=e[i];!1!==n&&t.push("#define "+i+" "+n)}return t.join("\n")}(s),g=r.createProgram();let f,A,y=i.glslVersion?"#version "+i.glslVersion+"\n":"";i.isRawShaderMaterial?(f=["#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,m].filter(Eo).join("\n"),f.length>0&&(f+="\n"),A=["#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,m].filter(Eo).join("\n"),A.length>0&&(A+="\n")):(f=[Fo(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,m,i.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",i.batching?"#define USE_BATCHING":"",i.batchingColor?"#define USE_BATCHING_COLOR":"",i.instancing?"#define USE_INSTANCING":"",i.instancingColor?"#define USE_INSTANCING_COLOR":"",i.instancingMorph?"#define USE_INSTANCING_MORPH":"",i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.map?"#define USE_MAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+h:"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.displacementMap?"#define USE_DISPLACEMENTMAP":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.mapUv?"#define MAP_UV "+i.mapUv:"",i.alphaMapUv?"#define ALPHAMAP_UV "+i.alphaMapUv:"",i.lightMapUv?"#define LIGHTMAP_UV "+i.lightMapUv:"",i.aoMapUv?"#define AOMAP_UV "+i.aoMapUv:"",i.emissiveMapUv?"#define EMISSIVEMAP_UV "+i.emissiveMapUv:"",i.bumpMapUv?"#define BUMPMAP_UV "+i.bumpMapUv:"",i.normalMapUv?"#define NORMALMAP_UV "+i.normalMapUv:"",i.displacementMapUv?"#define DISPLACEMENTMAP_UV "+i.displacementMapUv:"",i.metalnessMapUv?"#define METALNESSMAP_UV "+i.metalnessMapUv:"",i.roughnessMapUv?"#define ROUGHNESSMAP_UV "+i.roughnessMapUv:"",i.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+i.anisotropyMapUv:"",i.clearcoatMapUv?"#define CLEARCOATMAP_UV "+i.clearcoatMapUv:"",i.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+i.clearcoatNormalMapUv:"",i.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+i.clearcoatRoughnessMapUv:"",i.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+i.iridescenceMapUv:"",i.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+i.iridescenceThicknessMapUv:"",i.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+i.sheenColorMapUv:"",i.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+i.sheenRoughnessMapUv:"",i.specularMapUv?"#define SPECULARMAP_UV "+i.specularMapUv:"",i.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+i.specularColorMapUv:"",i.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+i.specularIntensityMapUv:"",i.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+i.transmissionMapUv:"",i.thicknessMapUv?"#define THICKNESSMAP_UV "+i.thicknessMapUv:"",i.vertexTangents&&!1===i.flatShading?"#define USE_TANGENT":"",i.vertexColors?"#define USE_COLOR":"",i.vertexAlphas?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.flatShading?"#define FLAT_SHADED":"",i.skinning?"#define USE_SKINNING":"",i.morphTargets?"#define USE_MORPHTARGETS":"",i.morphNormals&&!1===i.flatShading?"#define USE_MORPHNORMALS":"",i.morphColors?"#define USE_MORPHCOLORS":"",i.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+i.morphTextureStride:"",i.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+i.morphTargetsCount:"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+l:"",i.sizeAttenuation?"#define USE_SIZEATTENUATION":"",i.numLightProbes>0?"#define USE_LIGHT_PROBES":"",i.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","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(Eo).join("\n"),A=[Fo(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,m,i.instancing?"#define USE_INSTANCING":"",i.instancingColor?"#define USE_INSTANCING_COLOR":"",i.useFog&&i.fog?"#define USE_FOG":"",i.useFog&&i.fogExp2?"#define FOG_EXP2":"",i.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",i.map?"#define USE_MAP":"",i.matcap?"#define USE_MATCAP":"",i.envMap?"#define USE_ENVMAP":"",i.envMap?"#define "+c:"",i.envMap?"#define "+h:"",i.envMap?"#define "+d:"",u?"#define CUBEUV_TEXEL_WIDTH "+u.texelWidth:"",u?"#define CUBEUV_TEXEL_HEIGHT "+u.texelHeight:"",u?"#define CUBEUV_MAX_MIP "+u.maxMip+".0":"",i.lightMap?"#define USE_LIGHTMAP":"",i.aoMap?"#define USE_AOMAP":"",i.bumpMap?"#define USE_BUMPMAP":"",i.normalMap?"#define USE_NORMALMAP":"",i.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",i.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",i.emissiveMap?"#define USE_EMISSIVEMAP":"",i.anisotropy?"#define USE_ANISOTROPY":"",i.anisotropyMap?"#define USE_ANISOTROPYMAP":"",i.clearcoat?"#define USE_CLEARCOAT":"",i.clearcoatMap?"#define USE_CLEARCOATMAP":"",i.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",i.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",i.dispersion?"#define USE_DISPERSION":"",i.iridescence?"#define USE_IRIDESCENCE":"",i.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",i.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",i.specularMap?"#define USE_SPECULARMAP":"",i.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",i.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",i.roughnessMap?"#define USE_ROUGHNESSMAP":"",i.metalnessMap?"#define USE_METALNESSMAP":"",i.alphaMap?"#define USE_ALPHAMAP":"",i.alphaTest?"#define USE_ALPHATEST":"",i.alphaHash?"#define USE_ALPHAHASH":"",i.sheen?"#define USE_SHEEN":"",i.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",i.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",i.transmission?"#define USE_TRANSMISSION":"",i.transmissionMap?"#define USE_TRANSMISSIONMAP":"",i.thicknessMap?"#define USE_THICKNESSMAP":"",i.vertexTangents&&!1===i.flatShading?"#define USE_TANGENT":"",i.vertexColors||i.instancingColor||i.batchingColor?"#define USE_COLOR":"",i.vertexAlphas?"#define USE_COLOR_ALPHA":"",i.vertexUv1s?"#define USE_UV1":"",i.vertexUv2s?"#define USE_UV2":"",i.vertexUv3s?"#define USE_UV3":"",i.pointsUvs?"#define USE_POINTS_UV":"",i.gradientMap?"#define USE_GRADIENTMAP":"",i.flatShading?"#define FLAT_SHADED":"",i.doubleSided?"#define DOUBLE_SIDED":"",i.flipSided?"#define FLIP_SIDED":"",i.shadowMapEnabled?"#define USE_SHADOWMAP":"",i.shadowMapEnabled?"#define "+l:"",i.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",i.numLightProbes>0?"#define USE_LIGHT_PROBES":"",i.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",i.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==i.toneMapping?"#define TONE_MAPPING":"",0!==i.toneMapping?Ts.tonemapping_pars_fragment:"",0!==i.toneMapping?Co("toneMapping",i.toneMapping):"",i.dithering?"#define DITHERING":"",i.opaque?"#define OPAQUE":"",Ts.colorspace_pars_fragment,wo("linearToOutputTexel",i.outputColorSpace),Mo(),i.transmissionSamplerMapEncoding?xo("transmissionSamplerMapTexelToLinear",i.transmissionSamplerMapEncoding):"",i.useDepthPacking?"#define DEPTH_PACKING "+i.depthPacking:"","\n"].filter(Eo).join("\n")),a=Do(a),a=To(a,i),a=Io(a,i),o=Do(o),o=To(o,i),o=Io(o,i),a=Oo(a),o=Oo(o),!0!==i.isRawShaderMaterial&&(y="#version 300 es\n",f=[p,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+f,A=["#define varying in",i.glslVersion===ei?"":"layout(location = 0) out highp vec4 pc_fragColor;",i.glslVersion===ei?"":"#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("\n")+"\n"+A);const v=y+f+a,_=y+A+o,b=vo(r,r.VERTEX_SHADER,v),x=vo(r,r.FRAGMENT_SHADER,_);function w(t){if(e.debug.checkShaderErrors){const i=r.getProgramInfoLog(g).trim(),n=r.getShaderInfoLog(b).trim(),s=r.getShaderInfoLog(x).trim();let a=!0,o=!0;if(!1===r.getProgramParameter(g,r.LINK_STATUS))if(a=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(r,g,b,x);else{const e=bo(r,b,"vertex"),n=bo(r,x,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(g,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+i+"\n"+e+"\n"+n)}else""!==i?console.warn("THREE.WebGLProgram: Program Info Log:",i):(""===n||""===s)&&(o=!1);o&&(t.diagnostics={runnable:a,programLog:i,vertexShader:{log:n,prefix:f},fragmentShader:{log:s,prefix:A}})}r.deleteShader(b),r.deleteShader(x),C=new yo(r,g),S=function(e,t){const i={},n=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<n;r++){const n=e.getActiveAttrib(t,r),s=n.name;let a=1;n.type===e.FLOAT_MAT2&&(a=2),n.type===e.FLOAT_MAT3&&(a=3),n.type===e.FLOAT_MAT4&&(a=4),i[s]={type:n.type,location:e.getAttribLocation(t,s),locationSize:a}}return i}(r,g)}let C,S;r.attachShader(g,b),r.attachShader(g,x),void 0!==i.index0AttributeName?r.bindAttribLocation(g,0,i.index0AttributeName):!0===i.morphTargets&&r.bindAttribLocation(g,0,"position"),r.linkProgram(g),this.getUniforms=function(){return void 0===C&&w(this),C},this.getAttributes=function(){return void 0===S&&w(this),S};let M=!1===i.rendererExtensionParallelShaderCompile;return this.isReady=function(){return!1===M&&(M=r.getProgramParameter(g,37297)),M},this.destroy=function(){n.releaseStatesOfProgram(this),r.deleteProgram(g),this.program=void 0},this.type=i.shaderType,this.name=i.shaderName,this.id=_o++,this.cacheKey=t,this.usedTimes=1,this.program=g,this.vertexShader=b,this.fragmentShader=x,this}let No=0;class jo{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,n=this._getShaderStage(t),r=this._getShaderStage(i),s=this._getShaderCacheForMaterial(e);return!1===s.has(n)&&(s.add(n),n.usedTimes++),!1===s.has(r)&&(s.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const e of t)e.usedTimes--,0===e.usedTimes&&this.shaderCache.delete(e.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 void 0===i&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return void 0===i&&(i=new zo(e),t.set(e,i)),i}}class zo{constructor(e){this.id=No++,this.code=e,this.usedTimes=0}}function Go(e,t,i,n,r,s,a){const o=new Un,l=new jo,c=new Set,h=[],d=r.logarithmicDepthBuffer,u=r.vertexTextures;let p=r.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 g(e){return c.add(e),0===e?"uv":`uv${e}`}return{getParameters:function(s,o,h,f,A){const y=f.fog,v=A.geometry,_=s.isMeshStandardMaterial?f.environment:null,w=(s.isMeshStandardMaterial?i:t).get(s.envMap||_),S=w&&w.mapping===me?w.image.height:null,M=m[s.type];null!==s.precision&&(p=r.getMaxPrecision(s.precision),p!==s.precision&&console.warn("THREE.WebGLProgram.getParameters:",s.precision,"not supported, using",p,"instead."));const E=v.morphAttributes.position||v.morphAttributes.normal||v.morphAttributes.color,T=void 0!==E?E.length:0;let I,P,D,R,B=0;if(void 0!==v.morphAttributes.position&&(B=1),void 0!==v.morphAttributes.normal&&(B=2),void 0!==v.morphAttributes.color&&(B=3),M){const e=Ps[M];I=e.vertexShader,P=e.fragmentShader}else I=s.vertexShader,P=s.fragmentShader,l.update(s),D=l.getVertexShaderID(s),R=l.getFragmentShaderID(s);const L=e.getRenderTarget(),O=e.userData&&e.userData.transmissionRenderTarget,U=!0===A.isInstancedMesh,F=!0===A.isBatchedMesh,k=!!s.map,N=!!s.matcap,j=!!w,z=!!s.aoMap,G=!!s.lightMap,Q=!!s.bumpMap,V=!!s.normalMap,H=!!s.displacementMap,W=!!s.emissiveMap,q=!!s.metalnessMap,X=!!s.roughnessMap,Y=s.anisotropy>0,K=s.clearcoat>0,J=s.dispersion>0,Z=s.iridescence>0,$=s.sheen>0,ee=s.transmission>0,te=Y&&!!s.anisotropyMap,ie=K&&!!s.clearcoatMap,ne=K&&!!s.clearcoatNormalMap,re=K&&!!s.clearcoatRoughnessMap,se=Z&&!!s.iridescenceMap,ae=Z&&!!s.iridescenceThicknessMap,oe=$&&!!s.sheenColorMap,le=$&&!!s.sheenRoughnessMap,ce=!!s.specularMap,he=!!s.specularColorMap,de=!!s.specularIntensityMap,ue=ee&&!!s.transmissionMap,pe=ee&&!!s.thicknessMap,ge=!!s.gradientMap,fe=!!s.alphaMap,Ae=s.alphaTest>0,ye=!!s.alphaHash,ve=!!s.extensions;let _e=0;s.toneMapped&&(null===L||!0===L.isXRRenderTarget)&&(_e=e.toneMapping);const be={shaderID:M,shaderType:s.type,shaderName:s.name,vertexShader:I,fragmentShader:P,defines:s.defines,customVertexShaderID:D,customFragmentShaderID:R,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:p,batching:F,batchingColor:F&&null!==A._colorsTexture,instancing:U,instancingColor:U&&null!==A.instanceColor,instancingMorph:U&&null!==A.morphTexture,supportsVertexTextures:u,outputColorSpace:null===L?e.outputColorSpace:!0===L.isXRRenderTarget||L.texture.colorSpace&&L.texture.colorSpace!==Ot?L.texture.colorSpace:Ut,alphaToCoverage:!!s.alphaToCoverage,map:k,matcap:N,envMap:j,envMapMode:j&&w.mapping,envMapCubeUVHeight:S,aoMap:z,lightMap:G,bumpMap:Q,normalMap:V,displacementMap:u&&H,emissiveMap:W,normalMapObjectSpace:V&&s.normalMapType===Bt,normalMapTangentSpace:V&&s.normalMapType===Rt,metalnessMap:q,roughnessMap:X,anisotropy:Y,anisotropyMap:te,clearcoat:K,clearcoatMap:ie,clearcoatNormalMap:ne,clearcoatRoughnessMap:re,dispersion:J,iridescence:Z,iridescenceMap:se,iridescenceThicknessMap:ae,sheen:$,sheenColorMap:oe,sheenRoughnessMap:le,specularMap:ce,specularColorMap:he,specularIntensityMap:de,transmission:ee,transmissionMap:ue,thicknessMap:pe,transmissionSamplerMapEncoding:O&&O.texture.colorSpace||Ut,gradientMap:ge,opaque:!1===s.transparent&&s.blending===C&&!1===s.alphaToCoverage&&!(s.transmission>0),alphaMap:fe,alphaTest:Ae,alphaHash:ye,combine:s.combine,mapUv:k&&g(s.map.channel),aoMapUv:z&&g(s.aoMap.channel),lightMapUv:G&&g(s.lightMap.channel),bumpMapUv:Q&&g(s.bumpMap.channel),normalMapUv:V&&g(s.normalMap.channel),displacementMapUv:H&&g(s.displacementMap.channel),emissiveMapUv:W&&g(s.emissiveMap.channel),metalnessMapUv:q&&g(s.metalnessMap.channel),roughnessMapUv:X&&g(s.roughnessMap.channel),anisotropyMapUv:te&&g(s.anisotropyMap.channel),clearcoatMapUv:ie&&g(s.clearcoatMap.channel),clearcoatNormalMapUv:ne&&g(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:re&&g(s.clearcoatRoughnessMap.channel),iridescenceMapUv:se&&g(s.iridescenceMap.channel),iridescenceThicknessMapUv:ae&&g(s.iridescenceThicknessMap.channel),sheenColorMapUv:oe&&g(s.sheenColorMap.channel),sheenRoughnessMapUv:le&&g(s.sheenRoughnessMap.channel),specularMapUv:ce&&g(s.specularMap.channel),specularColorMapUv:he&&g(s.specularColorMap.channel),specularIntensityMapUv:de&&g(s.specularIntensityMap.channel),transmissionMapUv:ue&&g(s.transmissionMap.channel),thicknessMapUv:pe&&g(s.thicknessMap.channel),alphaMapUv:fe&&g(s.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(V||Y||v.userData.__forceUseTangent),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!v.attributes.color&&4===v.attributes.color.itemSize,pointsUvs:!0===A.isPoints&&!!v.attributes.uv&&(k||fe),fog:!!y,useFog:!0===s.fog,fogExp2:!!y&&y.isFogExp2,flatShading:!0===s.flatShading,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:d,skinning:!0===A.isSkinnedMesh,morphTargets:void 0!==v.morphAttributes.position,morphNormals:void 0!==v.morphAttributes.normal,morphColors:void 0!==v.morphAttributes.color,morphTargetsCount:T,morphTextureStride:B,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:e.shadowMap.enabled&&h.length>0,shadowMapType:e.shadowMap.type,toneMapping:_e,decodeVideoTexture:k&&!0===s.map.isVideoTexture&&Pi.getTransfer(s.map.colorSpace)===zt,premultipliedAlpha:s.premultipliedAlpha,doubleSided:s.side===x,flipSided:s.side===b,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionClipCullDistance:ve&&!0===s.extensions.clipCullDistance&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ve&&!0===s.extensions.multiDraw||F)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return be.vertexUv1s=c.has(1),be.vertexUv2s=c.has(2),be.vertexUv3s=c.has(3),c.clear(),be},getProgramCacheKey:function(t){const i=[];if(t.shaderID?i.push(t.shaderID):(i.push(t.customVertexShaderID),i.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)i.push(e),i.push(t.defines[e]);return!1===t.isRawShaderMaterial&&(function(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}(i,t),function(e,t){o.disableAll(),t.supportsVertexTextures&&o.enable(0),t.instancing&&o.enable(1),t.instancingColor&&o.enable(2),t.instancingMorph&&o.enable(3),t.matcap&&o.enable(4),t.envMap&&o.enable(5),t.normalMapObjectSpace&&o.enable(6),t.normalMapTangentSpace&&o.enable(7),t.clearcoat&&o.enable(8),t.iridescence&&o.enable(9),t.alphaTest&&o.enable(10),t.vertexColors&&o.enable(11),t.vertexAlphas&&o.enable(12),t.vertexUv1s&&o.enable(13),t.vertexUv2s&&o.enable(14),t.vertexUv3s&&o.enable(15),t.vertexTangents&&o.enable(16),t.anisotropy&&o.enable(17),t.alphaHash&&o.enable(18),t.batching&&o.enable(19),t.dispersion&&o.enable(20),t.batchingColor&&o.enable(21),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.skinning&&o.enable(4),t.morphTargets&&o.enable(5),t.morphNormals&&o.enable(6),t.morphColors&&o.enable(7),t.premultipliedAlpha&&o.enable(8),t.shadowMapEnabled&&o.enable(9),t.doubleSided&&o.enable(10),t.flipSided&&o.enable(11),t.useDepthPacking&&o.enable(12),t.dithering&&o.enable(13),t.transmission&&o.enable(14),t.sheen&&o.enable(15),t.opaque&&o.enable(16),t.pointsUvs&&o.enable(17),t.decodeVideoTexture&&o.enable(18),t.alphaToCoverage&&o.enable(19),e.push(o.mask)}(i,t),i.push(e.outputColorSpace)),i.push(t.customProgramCacheKey),i.join()},getUniforms:function(e){const t=m[e.type];let i;if(t){const e=Ps[t];i=os.clone(e.uniforms)}else i=e.uniforms;return i},acquireProgram:function(t,i){let n;for(let e=0,t=h.length;e<t;e++){const t=h[e];if(t.cacheKey===i){n=t,++n.usedTimes;break}}return void 0===n&&(n=new ko(e,i,t,s),h.push(n)),n},releaseProgram:function(e){if(0===--e.usedTimes){const t=h.indexOf(e);h[t]=h[h.length-1],h.pop(),e.destroy()}},releaseShaderCache:function(e){l.remove(e)},programs:h,dispose:function(){l.dispose()}}}function Qo(){let e=new WeakMap;return{has:function(t){return e.has(t)},get:function(t){let i=e.get(t);return void 0===i&&(i={},e.set(t,i)),i},remove:function(t){e.delete(t)},update:function(t,i,n){e.get(t)[i]=n},dispose:function(){e=new WeakMap}}}function Vo(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function Ho(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function Wo(){const e=[];let t=0;const i=[],n=[],r=[];function s(i,n,r,s,a,o){let l=e[t];return void 0===l?(l={id:i.id,object:i,geometry:n,material:r,groupOrder:s,renderOrder:i.renderOrder,z:a,group:o},e[t]=l):(l.id=i.id,l.object=i,l.geometry=n,l.material=r,l.groupOrder=s,l.renderOrder=i.renderOrder,l.z=a,l.group=o),t++,l}return{opaque:i,transmissive:n,transparent:r,init:function(){t=0,i.length=0,n.length=0,r.length=0},push:function(e,t,a,o,l,c){const h=s(e,t,a,o,l,c);a.transmission>0?n.push(h):!0===a.transparent?r.push(h):i.push(h)},unshift:function(e,t,a,o,l,c){const h=s(e,t,a,o,l,c);a.transmission>0?n.unshift(h):!0===a.transparent?r.unshift(h):i.unshift(h)},finish:function(){for(let i=t,n=e.length;i<n;i++){const t=e[i];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}},sort:function(e,t){i.length>1&&i.sort(e||Vo),n.length>1&&n.sort(t||Ho),r.length>1&&r.sort(t||Ho)}}}function qo(){let e=new WeakMap;return{get:function(t,i){const n=e.get(t);let r;return void 0===n?(r=new Wo,e.set(t,[r])):i>=n.length?(r=new Wo,n.push(r)):r=n[i],r},dispose:function(){e=new WeakMap}}}function Xo(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let i;switch(t.type){case"DirectionalLight":i={direction:new Xi,color:new mr};break;case"SpotLight":i={position:new Xi,direction:new Xi,color:new mr,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":i={position:new Xi,color:new mr,distance:0,decay:0};break;case"HemisphereLight":i={direction:new Xi,skyColor:new mr,groundColor:new mr};break;case"RectAreaLight":i={color:new mr,position:new Xi,halfWidth:new Xi,halfHeight:new Xi}}return e[t.id]=i,i}}}let Yo=0;function Ko(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Jo(e){const t=new Xo,i=function(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let i;switch(t.type){case"DirectionalLight":case"SpotLight":i={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new fi};break;case"PointLight":i={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new fi,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=i,i}}}(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)n.probe.push(new Xi);const r=new Xi,s=new Sn,a=new Sn;return{setup:function(r){let s=0,a=0,o=0;for(let e=0;e<9;e++)n.probe[e].set(0,0,0);let l=0,c=0,h=0,d=0,u=0,p=0,m=0,g=0,f=0,A=0,y=0;r.sort(Ko);for(let e=0,v=r.length;e<v;e++){const v=r[e],_=v.color,b=v.intensity,x=v.distance,w=v.shadow&&v.shadow.map?v.shadow.map.texture:null;if(v.isAmbientLight)s+=_.r*b,a+=_.g*b,o+=_.b*b;else if(v.isLightProbe){for(let e=0;e<9;e++)n.probe[e].addScaledVector(v.sh.coefficients[e],b);y++}else if(v.isDirectionalLight){const e=t.get(v);if(e.color.copy(v.color).multiplyScalar(v.intensity),v.castShadow){const e=v.shadow,t=i.get(v);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,n.directionalShadow[l]=t,n.directionalShadowMap[l]=w,n.directionalShadowMatrix[l]=v.shadow.matrix,p++}n.directional[l]=e,l++}else if(v.isSpotLight){const e=t.get(v);e.position.setFromMatrixPosition(v.matrixWorld),e.color.copy(_).multiplyScalar(b),e.distance=x,e.coneCos=Math.cos(v.angle),e.penumbraCos=Math.cos(v.angle*(1-v.penumbra)),e.decay=v.decay,n.spot[h]=e;const r=v.shadow;if(v.map&&(n.spotLightMap[f]=v.map,f++,r.updateMatrices(v),v.castShadow&&A++),n.spotLightMatrix[h]=r.matrix,v.castShadow){const e=i.get(v);e.shadowIntensity=r.intensity,e.shadowBias=r.bias,e.shadowNormalBias=r.normalBias,e.shadowRadius=r.radius,e.shadowMapSize=r.mapSize,n.spotShadow[h]=e,n.spotShadowMap[h]=w,g++}h++}else if(v.isRectAreaLight){const e=t.get(v);e.color.copy(_).multiplyScalar(b),e.halfWidth.set(.5*v.width,0,0),e.halfHeight.set(0,.5*v.height,0),n.rectArea[d]=e,d++}else if(v.isPointLight){const e=t.get(v);if(e.color.copy(v.color).multiplyScalar(v.intensity),e.distance=v.distance,e.decay=v.decay,v.castShadow){const e=v.shadow,t=i.get(v);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,n.pointShadow[c]=t,n.pointShadowMap[c]=w,n.pointShadowMatrix[c]=v.shadow.matrix,m++}n.point[c]=e,c++}else if(v.isHemisphereLight){const e=t.get(v);e.skyColor.copy(v.color).multiplyScalar(b),e.groundColor.copy(v.groundColor).multiplyScalar(b),n.hemi[u]=e,u++}}d>0&&(!0===e.has("OES_texture_float_linear")?(n.rectAreaLTC1=Is.LTC_FLOAT_1,n.rectAreaLTC2=Is.LTC_FLOAT_2):(n.rectAreaLTC1=Is.LTC_HALF_1,n.rectAreaLTC2=Is.LTC_HALF_2)),n.ambient[0]=s,n.ambient[1]=a,n.ambient[2]=o;const v=n.hash;(v.directionalLength!==l||v.pointLength!==c||v.spotLength!==h||v.rectAreaLength!==d||v.hemiLength!==u||v.numDirectionalShadows!==p||v.numPointShadows!==m||v.numSpotShadows!==g||v.numSpotMaps!==f||v.numLightProbes!==y)&&(n.directional.length=l,n.spot.length=h,n.rectArea.length=d,n.point.length=c,n.hemi.length=u,n.directionalShadow.length=p,n.directionalShadowMap.length=p,n.pointShadow.length=m,n.pointShadowMap.length=m,n.spotShadow.length=g,n.spotShadowMap.length=g,n.directionalShadowMatrix.length=p,n.pointShadowMatrix.length=m,n.spotLightMatrix.length=g+f-A,n.spotLightMap.length=f,n.numSpotLightShadowsWithMaps=A,n.numLightProbes=y,v.directionalLength=l,v.pointLength=c,v.spotLength=h,v.rectAreaLength=d,v.hemiLength=u,v.numDirectionalShadows=p,v.numPointShadows=m,v.numSpotShadows=g,v.numSpotMaps=f,v.numLightProbes=y,n.version=Yo++)},setupView:function(e,t){let i=0,o=0,l=0,c=0,h=0;const d=t.matrixWorldInverse;for(let t=0,u=e.length;t<u;t++){const u=e[t];if(u.isDirectionalLight){const e=n.directional[i];e.direction.setFromMatrixPosition(u.matrixWorld),r.setFromMatrixPosition(u.target.matrixWorld),e.direction.sub(r),e.direction.transformDirection(d),i++}else if(u.isSpotLight){const e=n.spot[l];e.position.setFromMatrixPosition(u.matrixWorld),e.position.applyMatrix4(d),e.direction.setFromMatrixPosition(u.matrixWorld),r.setFromMatrixPosition(u.target.matrixWorld),e.direction.sub(r),e.direction.transformDirection(d),l++}else if(u.isRectAreaLight){const e=n.rectArea[c];e.position.setFromMatrixPosition(u.matrixWorld),e.position.applyMatrix4(d),a.identity(),s.copy(u.matrixWorld),s.premultiply(d),a.extractRotation(s),e.halfWidth.set(.5*u.width,0,0),e.halfHeight.set(0,.5*u.height,0),e.halfWidth.applyMatrix4(a),e.halfHeight.applyMatrix4(a),c++}else if(u.isPointLight){const e=n.point[o];e.position.setFromMatrixPosition(u.matrixWorld),e.position.applyMatrix4(d),o++}else if(u.isHemisphereLight){const e=n.hemi[h];e.direction.setFromMatrixPosition(u.matrixWorld),e.direction.transformDirection(d),h++}}},state:n}}function Zo(e){const t=new Jo(e),i=[],n=[];const r={lightsArray:i,shadowsArray:n,camera:null,lights:t,transmissionRenderTarget:{}};return{init:function(e){r.camera=e,i.length=0,n.length=0},state:r,setupLights:function(){t.setup(i)},setupLightsView:function(e){t.setupView(i,e)},pushLight:function(e){i.push(e)},pushShadow:function(e){n.push(e)}}}function $o(e){let t=new WeakMap;return{get:function(i,n=0){const r=t.get(i);let s;return void 0===r?(s=new Zo(e),t.set(i,[s])):n>=r.length?(s=new Zo(e),r.push(s)):s=r[n],s},dispose:function(){t=new WeakMap}}}class el extends Ar{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=Pt,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 tl extends Ar{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}}function il(e,t,i){let n=new Cs;const r=new fi,s=new fi,a=new Gi,o=new el({depthPacking:Dt}),l=new tl,c={},h=i.maxTextureSize,d={[_]:b,[b]:_,[x]:x},u=new ls({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new fi},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),p=u.clone();p.defines.HORIZONTAL_PASS=1;const m=new Fr;m.setAttribute("position",new Mr(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new ts(m,u),f=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let A=this.type;function y(i,n){const s=t.update(g);u.defines.VSM_SAMPLES!==i.blurSamples&&(u.defines.VSM_SAMPLES=i.blurSamples,p.defines.VSM_SAMPLES=i.blurSamples,u.needsUpdate=!0,p.needsUpdate=!0),null===i.mapPass&&(i.mapPass=new Vi(r.x,r.y)),u.uniforms.shadow_pass.value=i.map.texture,u.uniforms.resolution.value=i.mapSize,u.uniforms.radius.value=i.radius,e.setRenderTarget(i.mapPass),e.clear(),e.renderBufferDirect(n,null,s,u,g,null),p.uniforms.shadow_pass.value=i.mapPass.texture,p.uniforms.resolution.value=i.mapSize,p.uniforms.radius.value=i.radius,e.setRenderTarget(i.map),e.clear(),e.renderBufferDirect(n,null,s,p,g,null)}function v(t,i,n,r){let s=null;const a=!0===n.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===n.isPointLight?l:o,e.localClippingEnabled&&!0===i.clipShadows&&Array.isArray(i.clippingPlanes)&&0!==i.clippingPlanes.length||i.displacementMap&&0!==i.displacementScale||i.alphaMap&&i.alphaTest>0||i.map&&i.alphaTest>0){const e=s.uuid,t=i.uuid;let n=c[e];void 0===n&&(n={},c[e]=n);let r=n[t];void 0===r&&(r=s.clone(),n[t]=r,i.addEventListener("dispose",S)),s=r}if(s.visible=i.visible,s.wireframe=i.wireframe,s.side=3===r?null!==i.shadowSide?i.shadowSide:i.side:null!==i.shadowSide?i.shadowSide:d[i.side],s.alphaMap=i.alphaMap,s.alphaTest=i.alphaTest,s.map=i.map,s.clipShadows=i.clipShadows,s.clippingPlanes=i.clippingPlanes,s.clipIntersection=i.clipIntersection,s.displacementMap=i.displacementMap,s.displacementScale=i.displacementScale,s.displacementBias=i.displacementBias,s.wireframeLinewidth=i.wireframeLinewidth,s.linewidth=i.linewidth,!0===n.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=n}return s}function C(i,r,s,a,o){if(!1===i.visible)return;if(i.layers.test(r.layers)&&(i.isMesh||i.isLine||i.isPoints)&&(i.castShadow||i.receiveShadow&&3===o)&&(!i.frustumCulled||n.intersectsObject(i))){i.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,i.matrixWorld);const n=t.update(i),l=i.material;if(Array.isArray(l)){const t=n.groups;for(let c=0,h=t.length;c<h;c++){const h=t[c],d=l[h.materialIndex];if(d&&d.visible){const t=v(i,d,a,o);i.onBeforeShadow(e,i,r,s,n,t,h),e.renderBufferDirect(s,null,n,t,i,h),i.onAfterShadow(e,i,r,s,n,t,h)}}}else if(l.visible){const t=v(i,l,a,o);i.onBeforeShadow(e,i,r,s,n,t,null),e.renderBufferDirect(s,null,n,t,i,null),i.onAfterShadow(e,i,r,s,n,t,null)}}const l=i.children;for(let e=0,t=l.length;e<t;e++)C(l[e],r,s,a,o)}function S(e){e.target.removeEventListener("dispose",S);for(const t in c){const i=c[t],n=e.target.uuid;n in i&&(i[n].dispose(),delete i[n])}}this.render=function(t,i,o){if(!1===f.enabled||!1===f.autoUpdate&&!1===f.needsUpdate||0===t.length)return;const l=e.getRenderTarget(),c=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),u=e.state;u.setBlending(w),u.buffers.color.setClear(1,1,1,1),u.buffers.depth.setTest(!0),u.setScissorTest(!1);const p=3!==A&&3===this.type,m=3===A&&3!==this.type;for(let l=0,c=t.length;l<c;l++){const c=t[l],d=c.shadow;if(void 0===d){console.warn("THREE.WebGLShadowMap:",c,"has no shadow.");continue}if(!1===d.autoUpdate&&!1===d.needsUpdate)continue;r.copy(d.mapSize);const g=d.getFrameExtents();if(r.multiply(g),s.copy(d.mapSize),(r.x>h||r.y>h)&&(r.x>h&&(s.x=Math.floor(h/g.x),r.x=s.x*g.x,d.mapSize.x=s.x),r.y>h&&(s.y=Math.floor(h/g.y),r.y=s.y*g.y,d.mapSize.y=s.y)),null===d.map||!0===p||!0===m){const e=3!==this.type?{minFilter:ye,magFilter:ye}:{};null!==d.map&&d.map.dispose(),d.map=new Vi(r.x,r.y,e),d.map.texture.name=c.name+".shadowMap",d.camera.updateProjectionMatrix()}e.setRenderTarget(d.map),e.clear();const f=d.getViewportCount();for(let e=0;e<f;e++){const t=d.getViewport(e);a.set(s.x*t.x,s.y*t.y,s.x*t.z,s.y*t.w),u.viewport(a),d.updateMatrices(c,e),n=d.getFrustum(),C(i,o,d.camera,c,this.type)}!0!==d.isPointLightShadow&&3===this.type&&y(d,o),d.needsUpdate=!1}A=this.type,f.needsUpdate=!1,e.setRenderTarget(l,c,d)}}function nl(e){const t=new function(){let t=!1;const i=new Gi;let n=null;const r=new Gi(0,0,0,0);return{setMask:function(i){n!==i&&!t&&(e.colorMask(i,i,i,i),n=i)},setLocked:function(e){t=e},setClear:function(t,n,s,a,o){!0===o&&(t*=a,n*=a,s*=a),i.set(t,n,s,a),!1===r.equals(i)&&(e.clearColor(t,n,s,a),r.copy(i))},reset:function(){t=!1,n=null,r.set(-1,0,0,0)}}},i=new function(){let t=!1,i=null,n=null,r=null;return{setTest:function(t){t?be(e.DEPTH_TEST):xe(e.DEPTH_TEST)},setMask:function(n){i!==n&&!t&&(e.depthMask(n),i=n)},setFunc:function(t){if(n!==t){switch(t){case Y:e.depthFunc(e.NEVER);break;case K:e.depthFunc(e.ALWAYS);break;case J:e.depthFunc(e.LESS);break;case Z:e.depthFunc(e.LEQUAL);break;case $:e.depthFunc(e.EQUAL);break;case ee:e.depthFunc(e.GEQUAL);break;case te:e.depthFunc(e.GREATER);break;case ie:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}n=t}},setLocked:function(e){t=e},setClear:function(t){r!==t&&(e.clearDepth(t),r=t)},reset:function(){t=!1,i=null,n=null,r=null}}},n=new function(){let t=!1,i=null,n=null,r=null,s=null,a=null,o=null,l=null,c=null;return{setTest:function(i){t||(i?be(e.STENCIL_TEST):xe(e.STENCIL_TEST))},setMask:function(n){i!==n&&!t&&(e.stencilMask(n),i=n)},setFunc:function(t,i,a){(n!==t||r!==i||s!==a)&&(e.stencilFunc(t,i,a),n=t,r=i,s=a)},setOp:function(t,i,n){(a!==t||o!==i||l!==n)&&(e.stencilOp(t,i,n),a=t,o=i,l=n)},setLocked:function(e){t=e},setClear:function(t){c!==t&&(e.clearStencil(t),c=t)},reset:function(){t=!1,i=null,n=null,r=null,s=null,a=null,o=null,l=null,c=null}}},r=new WeakMap,s=new WeakMap;let a={},o={},l=new WeakMap,c=[],h=null,d=!1,u=null,p=null,m=null,g=null,f=null,A=null,y=null,v=new mr(0,0,0),_=0,ne=!1,re=null,se=null,ae=null,oe=null,le=null;const ce=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let he=!1,de=0;const ue=e.getParameter(e.VERSION);-1!==ue.indexOf("WebGL")?(de=parseFloat(/^WebGL (\d)/.exec(ue)[1]),he=de>=1):-1!==ue.indexOf("OpenGL ES")&&(de=parseFloat(/^OpenGL ES (\d)/.exec(ue)[1]),he=de>=2);let pe=null,me={};const ge=e.getParameter(e.SCISSOR_BOX),fe=e.getParameter(e.VIEWPORT),Ae=(new Gi).fromArray(ge),ye=(new Gi).fromArray(fe);function ve(t,i,n,r){const s=new Uint8Array(4),a=e.createTexture();e.bindTexture(t,a),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let a=0;a<n;a++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(i,0,e.RGBA,1,1,r,0,e.RGBA,e.UNSIGNED_BYTE,s):e.texImage2D(i+a,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,s);return a}const _e={};function be(t){!0!==a[t]&&(e.enable(t),a[t]=!0)}function xe(t){!1!==a[t]&&(e.disable(t),a[t]=!1)}_e[e.TEXTURE_2D]=ve(e.TEXTURE_2D,e.TEXTURE_2D,1),_e[e.TEXTURE_CUBE_MAP]=ve(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),_e[e.TEXTURE_2D_ARRAY]=ve(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),_e[e.TEXTURE_3D]=ve(e.TEXTURE_3D,e.TEXTURE_3D,1,1),t.setClear(0,0,0,1),i.setClear(1),n.setClear(0),be(e.DEPTH_TEST),i.setFunc(Z),Me(!1),Ee(1),be(e.CULL_FACE),Se(w);const we={[I]:e.FUNC_ADD,[P]:e.FUNC_SUBTRACT,[D]:e.FUNC_REVERSE_SUBTRACT};we[R]=e.MIN,we[B]=e.MAX;const Ce={[L]:e.ZERO,[O]:e.ONE,[U]:e.SRC_COLOR,[k]:e.SRC_ALPHA,[V]:e.SRC_ALPHA_SATURATE,[G]:e.DST_COLOR,[j]:e.DST_ALPHA,[F]:e.ONE_MINUS_SRC_COLOR,[N]:e.ONE_MINUS_SRC_ALPHA,[Q]:e.ONE_MINUS_DST_COLOR,[z]:e.ONE_MINUS_DST_ALPHA,[H]:e.CONSTANT_COLOR,[W]:e.ONE_MINUS_CONSTANT_COLOR,[q]:e.CONSTANT_ALPHA,[X]:e.ONE_MINUS_CONSTANT_ALPHA};function Se(t,i,n,r,s,a,o,l,c,h){if(t!==w){if(!1===d&&(be(e.BLEND),d=!0),t===T)s=s||i,a=a||n,o=o||r,(i!==p||s!==f)&&(e.blendEquationSeparate(we[i],we[s]),p=i,f=s),(n!==m||r!==g||a!==A||o!==y)&&(e.blendFuncSeparate(Ce[n],Ce[r],Ce[a],Ce[o]),m=n,g=r,A=a,y=o),(!1===l.equals(v)||c!==_)&&(e.blendColor(l.r,l.g,l.b,c),v.copy(l),_=c),u=t,ne=!1;else if(t!==u||h!==ne){if((p!==I||f!==I)&&(e.blendEquation(e.FUNC_ADD),p=I,f=I),h)switch(t){case C:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case S:e.blendFunc(e.ONE,e.ONE);break;case M:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case E:e.blendFuncSeparate(e.ZERO,e.SRC_COLOR,e.ZERO,e.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",t)}else switch(t){case C:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case S:e.blendFunc(e.SRC_ALPHA,e.ONE);break;case M:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case E:e.blendFunc(e.ZERO,e.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",t)}m=null,g=null,A=null,y=null,v.set(0,0,0),_=0,u=t,ne=h}}else!0===d&&(xe(e.BLEND),d=!1)}function Me(t){re!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),re=t)}function Ee(t){0!==t?(be(e.CULL_FACE),t!==se&&(1===t?e.cullFace(e.BACK):2===t?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))):xe(e.CULL_FACE),se=t}function Te(t,i,n){t?(be(e.POLYGON_OFFSET_FILL),(oe!==i||le!==n)&&(e.polygonOffset(i,n),oe=i,le=n)):xe(e.POLYGON_OFFSET_FILL)}return{buffers:{color:t,depth:i,stencil:n},enable:be,disable:xe,bindFramebuffer:function(t,i){return o[t]!==i&&(e.bindFramebuffer(t,i),o[t]=i,t===e.DRAW_FRAMEBUFFER&&(o[e.FRAMEBUFFER]=i),t===e.FRAMEBUFFER&&(o[e.DRAW_FRAMEBUFFER]=i),!0)},drawBuffers:function(t,i){let n=c,r=!1;if(t){n=l.get(i),void 0===n&&(n=[],l.set(i,n));const s=t.textures;if(n.length!==s.length||n[0]!==e.COLOR_ATTACHMENT0){for(let t=0,i=s.length;t<i;t++)n[t]=e.COLOR_ATTACHMENT0+t;n.length=s.length,r=!0}}else n[0]!==e.BACK&&(n[0]=e.BACK,r=!0);r&&e.drawBuffers(n)},useProgram:function(t){return h!==t&&(e.useProgram(t),h=t,!0)},setBlending:Se,setMaterial:function(r,s){r.side===x?xe(e.CULL_FACE):be(e.CULL_FACE);let a=r.side===b;s&&(a=!a),Me(a),r.blending===C&&!1===r.transparent?Se(w):Se(r.blending,r.blendEquation,r.blendSrc,r.blendDst,r.blendEquationAlpha,r.blendSrcAlpha,r.blendDstAlpha,r.blendColor,r.blendAlpha,r.premultipliedAlpha),i.setFunc(r.depthFunc),i.setTest(r.depthTest),i.setMask(r.depthWrite),t.setMask(r.colorWrite);const o=r.stencilWrite;n.setTest(o),o&&(n.setMask(r.stencilWriteMask),n.setFunc(r.stencilFunc,r.stencilRef,r.stencilFuncMask),n.setOp(r.stencilFail,r.stencilZFail,r.stencilZPass)),Te(r.polygonOffset,r.polygonOffsetFactor,r.polygonOffsetUnits),!0===r.alphaToCoverage?be(e.SAMPLE_ALPHA_TO_COVERAGE):xe(e.SAMPLE_ALPHA_TO_COVERAGE)},setFlipSided:Me,setCullFace:Ee,setLineWidth:function(t){t!==ae&&(he&&e.lineWidth(t),ae=t)},setPolygonOffset:Te,setScissorTest:function(t){t?be(e.SCISSOR_TEST):xe(e.SCISSOR_TEST)},activeTexture:function(t){void 0===t&&(t=e.TEXTURE0+ce-1),pe!==t&&(e.activeTexture(t),pe=t)},bindTexture:function(t,i,n){void 0===n&&(n=null===pe?e.TEXTURE0+ce-1:pe);let r=me[n];void 0===r&&(r={type:void 0,texture:void 0},me[n]=r),(r.type!==t||r.texture!==i)&&(pe!==n&&(e.activeTexture(n),pe=n),e.bindTexture(t,i||_e[t]),r.type=t,r.texture=i)},unbindTexture:function(){const t=me[pe];void 0!==t&&void 0!==t.type&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)},compressedTexImage2D:function(){try{e.compressedTexImage2D.apply(e,arguments)}catch(e){console.error("THREE.WebGLState:",e)}},compressedTexImage3D:function(){try{e.compressedTexImage3D.apply(e,arguments)}catch(e){console.error("THREE.WebGLState:",e)}},texImage2D:function(){try{e.texImage2D.apply(e,arguments)}catch(e){console.error("THREE.WebGLState:",e)}},texImage3D:function(){try{e.texImage3D.apply(e,arguments)}catch(e){console.error("THREE.WebGLState:",e)}},updateUBOMapping:function(t,i){let n=s.get(i);void 0===n&&(n=new WeakMap,s.set(i,n));let r=n.get(t);void 0===r&&(r=e.getUniformBlockIndex(i,t.name),n.set(t,r))},uniformBlockBinding:function(t,i){const n=s.get(i).get(t);r.get(i)!==n&&(e.uniformBlockBinding(i,n,t.__bindingPointIndex),r.set(i,n))},texStorage2D:function(){try{e.texStorage2D.apply(e,arguments)}catch(e){console.error("THREE.WebGLState:",e)}},texStorage3D:function(){try{e.texStorage3D.apply(e,arguments)}catch(e){console.error("THREE.WebGLState:",e)}},texSubImage2D:function(){try{e.texSubImage2D.apply(e,arguments)}catch(e){console.error("THREE.WebGLState:",e)}},texSubImage3D:function(){try{e.texSubImage3D.apply(e,arguments)}catch(e){console.error("THREE.WebGLState:",e)}},compressedTexSubImage2D:function(){try{e.compressedTexSubImage2D.apply(e,arguments)}catch(e){console.error("THREE.WebGLState:",e)}},compressedTexSubImage3D:function(){try{e.compressedTexSubImage3D.apply(e,arguments)}catch(e){console.error("THREE.WebGLState:",e)}},scissor:function(t){!1===Ae.equals(t)&&(e.scissor(t.x,t.y,t.z,t.w),Ae.copy(t))},viewport:function(t){!1===ye.equals(t)&&(e.viewport(t.x,t.y,t.z,t.w),ye.copy(t))},reset:function(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),a={},pe=null,me={},o={},l=new WeakMap,c=[],h=null,d=!1,u=null,p=null,m=null,g=null,f=null,A=null,y=null,v=new mr(0,0,0),_=0,ne=!1,re=null,se=null,ae=null,oe=null,le=null,Ae.set(0,0,e.canvas.width,e.canvas.height),ye.set(0,0,e.canvas.width,e.canvas.height),t.reset(),i.reset(),n.reset()}}}function rl(e,t,i,n){const r=function(e){switch(e){case Ce:case Se:return{byteLength:1,components:1};case Ee:case Me:case De:return{byteLength:2,components:1};case Re:case Be:return{byteLength:2,components:4};case Ie:case Te:case Pe:return{byteLength:4,components:1};case Oe:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}(n);switch(i){case 1021:case 1024:return e*t;case 1025:return e*t*2;case Ne:case je:return e*t/r.components*r.byteLength;case ze:case Ge:return e*t*2/r.components*r.byteLength;case 1022:return e*t*3/r.components*r.byteLength;case Ue:case Qe:return e*t*4/r.components*r.byteLength;case Ve:case He:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case We:case qe:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ye:case Je:return Math.max(e,16)*Math.max(t,8)/4;case Xe:case Ke:return Math.max(e,8)*Math.max(t,8)/2;case Ze:case $e:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case et:case tt:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case it:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case nt:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case rt:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case st:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case at:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case ot:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case lt:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case ct:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case ht:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case dt:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case ut:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case pt:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case mt:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case gt:case ft:case At:return Math.ceil(e/4)*Math.ceil(t/4)*16;case 36283:case yt:return Math.ceil(e/4)*Math.ceil(t/4)*8;case vt:case _t:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${i} format.`)}function sl(e,t,i,n,r,s,a){const o=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,l=!(typeof navigator>"u")&&/OculusBrowser/g.test(navigator.userAgent),c=new fi,h=new WeakMap;let d;const u=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch{}function m(e,t){return p?new OffscreenCanvas(e,t):xi("canvas")}function g(e,t,i){let n=1;const r=j(e);if((r.width>i||r.height>i)&&(n=i/Math.max(r.width,r.height)),n<1){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof VideoFrame<"u"&&e instanceof VideoFrame){const i=Math.floor(n*r.width),s=Math.floor(n*r.height);void 0===d&&(d=m(i,s));const a=t?m(i,s):d;return a.width=i,a.height=s,a.getContext("2d").drawImage(e,0,0,i,s),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+r.width+"x"+r.height+") to ("+i+"x"+s+")."),a}return"data"in e&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.height+")."),e}return e}function f(e){return e.generateMipmaps&&e.minFilter!==ye&&e.minFilter!==be}function A(t){e.generateMipmap(t)}function y(i,n,r,s,a=!1){if(null!==i){if(void 0!==e[i])return e[i];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+i+"'")}let o=n;if(n===e.RED&&(r===e.FLOAT&&(o=e.R32F),r===e.HALF_FLOAT&&(o=e.R16F),r===e.UNSIGNED_BYTE&&(o=e.R8)),n===e.RED_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.R8UI),r===e.UNSIGNED_SHORT&&(o=e.R16UI),r===e.UNSIGNED_INT&&(o=e.R32UI),r===e.BYTE&&(o=e.R8I),r===e.SHORT&&(o=e.R16I),r===e.INT&&(o=e.R32I)),n===e.RG&&(r===e.FLOAT&&(o=e.RG32F),r===e.HALF_FLOAT&&(o=e.RG16F),r===e.UNSIGNED_BYTE&&(o=e.RG8)),n===e.RG_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RG8UI),r===e.UNSIGNED_SHORT&&(o=e.RG16UI),r===e.UNSIGNED_INT&&(o=e.RG32UI),r===e.BYTE&&(o=e.RG8I),r===e.SHORT&&(o=e.RG16I),r===e.INT&&(o=e.RG32I)),n===e.RGB&&r===e.UNSIGNED_INT_5_9_9_9_REV&&(o=e.RGB9_E5),n===e.RGBA){const t=a?jt:Pi.getTransfer(s);r===e.FLOAT&&(o=e.RGBA32F),r===e.HALF_FLOAT&&(o=e.RGBA16F),r===e.UNSIGNED_BYTE&&(o=t===zt?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)}return(o===e.R16F||o===e.R32F||o===e.RG16F||o===e.RG32F||o===e.RGBA16F||o===e.RGBA32F)&&t.get("EXT_color_buffer_float"),o}function v(t,i){let n;return t?null===i||i===Ie||i===Le?n=e.DEPTH24_STENCIL8:i===Pe?n=e.DEPTH32F_STENCIL8:i===Ee&&(n=e.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===i||i===Ie||i===Le?n=e.DEPTH_COMPONENT24:i===Pe?n=e.DEPTH_COMPONENT32F:i===Ee&&(n=e.DEPTH_COMPONENT16),n}function _(e,t){return!0===f(e)||e.isFramebufferTexture&&e.minFilter!==ye&&e.minFilter!==be?Math.log2(Math.max(t.width,t.height))+1:void 0!==e.mipmaps&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function b(e){const t=e.target;t.removeEventListener("dispose",b),function(e){const t=n.get(e);if(void 0===t.__webglInit)return;const i=e.source,r=u.get(i);if(r){const n=r[t.__cacheKey];n.usedTimes--,0===n.usedTimes&&w(e),0===Object.keys(r).length&&u.delete(i)}n.remove(e)}(t),t.isVideoTexture&&h.delete(t)}function x(t){const i=t.target;i.removeEventListener("dispose",x),function(t){const i=n.get(t);if(t.depthTexture&&t.depthTexture.dispose(),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(i.__webglFramebuffer[t]))for(let n=0;n<i.__webglFramebuffer[t].length;n++)e.deleteFramebuffer(i.__webglFramebuffer[t][n]);else e.deleteFramebuffer(i.__webglFramebuffer[t]);i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer[t])}else{if(Array.isArray(i.__webglFramebuffer))for(let t=0;t<i.__webglFramebuffer.length;t++)e.deleteFramebuffer(i.__webglFramebuffer[t]);else e.deleteFramebuffer(i.__webglFramebuffer);if(i.__webglDepthbuffer&&e.deleteRenderbuffer(i.__webglDepthbuffer),i.__webglMultisampledFramebuffer&&e.deleteFramebuffer(i.__webglMultisampledFramebuffer),i.__webglColorRenderbuffer)for(let t=0;t<i.__webglColorRenderbuffer.length;t++)i.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(i.__webglColorRenderbuffer[t]);i.__webglDepthRenderbuffer&&e.deleteRenderbuffer(i.__webglDepthRenderbuffer)}const r=t.textures;for(let t=0,i=r.length;t<i;t++){const i=n.get(r[t]);i.__webglTexture&&(e.deleteTexture(i.__webglTexture),a.memory.textures--),n.remove(r[t])}n.remove(t)}(i)}function w(t){const i=n.get(t);e.deleteTexture(i.__webglTexture);const r=t.source;delete u.get(r)[i.__cacheKey],a.memory.textures--}let C=0;function S(t,r){const s=n.get(t);if(t.isVideoTexture&&function(e){const t=a.render.frame;h.get(e)!==t&&(h.set(e,t),e.update())}(t),!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version){const e=t.image;if(null===e)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void D(s,t,r);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}i.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+r)}const M={[ge]:e.REPEAT,[fe]:e.CLAMP_TO_EDGE,[Ae]:e.MIRRORED_REPEAT},E={[ye]:e.NEAREST,[ve]:e.NEAREST_MIPMAP_NEAREST,[_e]:e.NEAREST_MIPMAP_LINEAR,[be]:e.LINEAR,[xe]:e.LINEAR_MIPMAP_NEAREST,[we]:e.LINEAR_MIPMAP_LINEAR},T={[Ht]:e.NEVER,[Zt]:e.ALWAYS,[Wt]:e.LESS,[Xt]:e.LEQUAL,[qt]:e.EQUAL,[Jt]:e.GEQUAL,[Yt]:e.GREATER,[Kt]:e.NOTEQUAL};function I(i,s){if(s.type===Pe&&!1===t.has("OES_texture_float_linear")&&(s.magFilter===be||s.magFilter===xe||s.magFilter===_e||s.magFilter===we||s.minFilter===be||s.minFilter===xe||s.minFilter===_e||s.minFilter===we)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(i,e.TEXTURE_WRAP_S,M[s.wrapS]),e.texParameteri(i,e.TEXTURE_WRAP_T,M[s.wrapT]),(i===e.TEXTURE_3D||i===e.TEXTURE_2D_ARRAY)&&e.texParameteri(i,e.TEXTURE_WRAP_R,M[s.wrapR]),e.texParameteri(i,e.TEXTURE_MAG_FILTER,E[s.magFilter]),e.texParameteri(i,e.TEXTURE_MIN_FILTER,E[s.minFilter]),s.compareFunction&&(e.texParameteri(i,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(i,e.TEXTURE_COMPARE_FUNC,T[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(s.magFilter===ye||s.minFilter!==_e&&s.minFilter!==we||s.type===Pe&&!1===t.has("OES_texture_float_linear"))return;if(s.anisotropy>1||n.get(s).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(i,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),n.get(s).__currentAnisotropy=s.anisotropy}}}function P(t,i){let n=!1;void 0===t.__webglInit&&(t.__webglInit=!0,i.addEventListener("dispose",b));const r=i.source;let s=u.get(r);void 0===s&&(s={},u.set(r,s));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(i);if(o!==t.__cacheKey){void 0===s[o]&&(s[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,n=!0),s[o].usedTimes++;const r=s[t.__cacheKey];void 0!==r&&(s[t.__cacheKey].usedTimes--,0===r.usedTimes&&w(i)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return n}function D(t,a,o){let l=e.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=e.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=e.TEXTURE_3D);const c=P(t,a),h=a.source;i.bindTexture(l,t.__webglTexture,e.TEXTURE0+o);const d=n.get(h);if(h.version!==d.__version||!0===c){i.activeTexture(e.TEXTURE0+o);const t=Pi.getPrimaries(Pi.workingColorSpace),n=a.colorSpace===Lt||a.colorSpace===Nt?null:Pi.getPrimaries(a.colorSpace),u=a.colorSpace===Lt||a.colorSpace===Nt||t===n?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,u);let p=g(a.image,!1,r.maxTextureSize);p=N(a,p);const m=s.convert(a.format,a.colorSpace),b=s.convert(a.type);let x,w=y(a.internalFormat,m,b,a.colorSpace,a.isVideoTexture);I(l,a);const C=a.mipmaps,S=!0!==a.isVideoTexture,M=void 0===d.__version||!0===c,E=h.dataReady,T=_(a,p);if(a.isDepthTexture)w=v(a.format===ke,a.type),M&&(S?i.texStorage2D(e.TEXTURE_2D,1,w,p.width,p.height):i.texImage2D(e.TEXTURE_2D,0,w,p.width,p.height,0,m,b,null));else if(a.isDataTexture)if(C.length>0){S&&M&&i.texStorage2D(e.TEXTURE_2D,T,w,C[0].width,C[0].height);for(let t=0,n=C.length;t<n;t++)x=C[t],S?E&&i.texSubImage2D(e.TEXTURE_2D,t,0,0,x.width,x.height,m,b,x.data):i.texImage2D(e.TEXTURE_2D,t,w,x.width,x.height,0,m,b,x.data);a.generateMipmaps=!1}else S?(M&&i.texStorage2D(e.TEXTURE_2D,T,w,p.width,p.height),E&&i.texSubImage2D(e.TEXTURE_2D,0,0,0,p.width,p.height,m,b,p.data)):i.texImage2D(e.TEXTURE_2D,0,w,p.width,p.height,0,m,b,p.data);else if(a.isCompressedTexture)if(a.isCompressedArrayTexture){S&&M&&i.texStorage3D(e.TEXTURE_2D_ARRAY,T,w,C[0].width,C[0].height,p.depth);for(let t=0,n=C.length;t<n;t++)if(x=C[t],a.format!==Ue)if(null!==m)if(S){if(E)if(a.layerUpdates.size>0){const n=rl(x.width,x.height,a.format,a.type);for(const r of a.layerUpdates){const s=x.data.subarray(r*n/x.data.BYTES_PER_ELEMENT,(r+1)*n/x.data.BYTES_PER_ELEMENT);i.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,r,x.width,x.height,1,m,s,0,0)}a.clearLayerUpdates()}else i.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,x.width,x.height,p.depth,m,x.data,0,0)}else i.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,w,x.width,x.height,p.depth,0,x.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else S?E&&i.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,x.width,x.height,p.depth,m,b,x.data):i.texImage3D(e.TEXTURE_2D_ARRAY,t,w,x.width,x.height,p.depth,0,m,b,x.data)}else{S&&M&&i.texStorage2D(e.TEXTURE_2D,T,w,C[0].width,C[0].height);for(let t=0,n=C.length;t<n;t++)x=C[t],a.format!==Ue?null!==m?S?E&&i.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,x.width,x.height,m,x.data):i.compressedTexImage2D(e.TEXTURE_2D,t,w,x.width,x.height,0,x.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):S?E&&i.texSubImage2D(e.TEXTURE_2D,t,0,0,x.width,x.height,m,b,x.data):i.texImage2D(e.TEXTURE_2D,t,w,x.width,x.height,0,m,b,x.data)}else if(a.isDataArrayTexture)if(S){if(M&&i.texStorage3D(e.TEXTURE_2D_ARRAY,T,w,p.width,p.height,p.depth),E)if(a.layerUpdates.size>0){const t=rl(p.width,p.height,a.format,a.type);for(const n of a.layerUpdates){const r=p.data.subarray(n*t/p.data.BYTES_PER_ELEMENT,(n+1)*t/p.data.BYTES_PER_ELEMENT);i.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,n,p.width,p.height,1,m,b,r)}a.clearLayerUpdates()}else i.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,m,b,p.data)}else i.texImage3D(e.TEXTURE_2D_ARRAY,0,w,p.width,p.height,p.depth,0,m,b,p.data);else if(a.isData3DTexture)S?(M&&i.texStorage3D(e.TEXTURE_3D,T,w,p.width,p.height,p.depth),E&&i.texSubImage3D(e.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,m,b,p.data)):i.texImage3D(e.TEXTURE_3D,0,w,p.width,p.height,p.depth,0,m,b,p.data);else if(a.isFramebufferTexture){if(M)if(S)i.texStorage2D(e.TEXTURE_2D,T,w,p.width,p.height);else{let t=p.width,n=p.height;for(let r=0;r<T;r++)i.texImage2D(e.TEXTURE_2D,r,w,t,n,0,m,b,null),t>>=1,n>>=1}}else if(C.length>0){if(S&&M){const t=j(C[0]);i.texStorage2D(e.TEXTURE_2D,T,w,t.width,t.height)}for(let t=0,n=C.length;t<n;t++)x=C[t],S?E&&i.texSubImage2D(e.TEXTURE_2D,t,0,0,m,b,x):i.texImage2D(e.TEXTURE_2D,t,w,m,b,x);a.generateMipmaps=!1}else if(S){if(M){const t=j(p);i.texStorage2D(e.TEXTURE_2D,T,w,t.width,t.height)}E&&i.texSubImage2D(e.TEXTURE_2D,0,0,0,m,b,p)}else i.texImage2D(e.TEXTURE_2D,0,w,m,b,p);f(a)&&A(l),d.__version=h.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}function R(t,r,a,l,c,h){const d=s.convert(a.format,a.colorSpace),u=s.convert(a.type),p=y(a.internalFormat,d,u,a.colorSpace);if(!n.get(r).__hasExternalTextures){const t=Math.max(1,r.width>>h),n=Math.max(1,r.height>>h);c===e.TEXTURE_3D||c===e.TEXTURE_2D_ARRAY?i.texImage3D(c,h,p,t,n,r.depth,0,d,u,null):i.texImage2D(c,h,p,t,n,0,d,u,null)}i.bindFramebuffer(e.FRAMEBUFFER,t),k(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,c,n.get(a).__webglTexture,0,F(r)):(c===e.TEXTURE_2D||c>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,l,c,n.get(a).__webglTexture,h),i.bindFramebuffer(e.FRAMEBUFFER,null)}function B(t,i,n){if(e.bindRenderbuffer(e.RENDERBUFFER,t),i.depthBuffer){const r=i.depthTexture,s=r&&r.isDepthTexture?r.type:null,a=v(i.stencilBuffer,s),l=i.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,c=F(i);k(i)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,c,a,i.width,i.height):n?e.renderbufferStorageMultisample(e.RENDERBUFFER,c,a,i.width,i.height):e.renderbufferStorage(e.RENDERBUFFER,a,i.width,i.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,l,e.RENDERBUFFER,t)}else{const t=i.textures;for(let r=0;r<t.length;r++){const a=t[r],l=s.convert(a.format,a.colorSpace),c=s.convert(a.type),h=y(a.internalFormat,l,c,a.colorSpace),d=F(i);n&&!1===k(i)?e.renderbufferStorageMultisample(e.RENDERBUFFER,d,h,i.width,i.height):k(i)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,d,h,i.width,i.height):e.renderbufferStorage(e.RENDERBUFFER,h,i.width,i.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function L(t){const r=n.get(t),s=!0===t.isWebGLCubeRenderTarget;if(r.__boundDepthTexture!==t.depthTexture){const e=t.depthTexture;if(r.__depthDisposeCallback&&r.__depthDisposeCallback(),e){const t=()=>{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),r.__depthDisposeCallback=t}r.__boundDepthTexture=e}if(t.depthTexture&&!r.__autoAllocateDepthBuffer){if(s)throw new Error("target.depthTexture not supported in Cube render targets");!function(t,r){if(r&&r.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(i.bindFramebuffer(e.FRAMEBUFFER,t),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");(!n.get(r.depthTexture).__webglTexture||r.depthTexture.image.width!==r.width||r.depthTexture.image.height!==r.height)&&(r.depthTexture.image.width=r.width,r.depthTexture.image.height=r.height,r.depthTexture.needsUpdate=!0),S(r.depthTexture,0);const s=n.get(r.depthTexture).__webglTexture,a=F(r);if(r.depthTexture.format===Fe)k(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,s,0,a):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,s,0);else{if(r.depthTexture.format!==ke)throw new Error("Unknown depthTexture format");k(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,s,0,a):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,s,0)}}(r.__webglFramebuffer,t)}else if(s){r.__webglDepthbuffer=[];for(let n=0;n<6;n++)if(i.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[n]),void 0===r.__webglDepthbuffer[n])r.__webglDepthbuffer[n]=e.createRenderbuffer(),B(r.__webglDepthbuffer[n],t,!1);else{const i=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[n];e.bindRenderbuffer(e.RENDERBUFFER,s),e.framebufferRenderbuffer(e.FRAMEBUFFER,i,e.RENDERBUFFER,s)}}else if(i.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=e.createRenderbuffer(),B(r.__webglDepthbuffer,t,!1);else{const i=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,n=r.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,n),e.framebufferRenderbuffer(e.FRAMEBUFFER,i,e.RENDERBUFFER,n)}i.bindFramebuffer(e.FRAMEBUFFER,null)}const O=[],U=[];function F(e){return Math.min(r.maxSamples,e.samples)}function k(e){const i=n.get(e);return e.samples>0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==i.__useRenderToTexture}function N(e,t){const i=e.colorSpace,n=e.format,r=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||i!==Ut&&i!==Lt&&(Pi.getTransfer(i)===zt?(n!==Ue||r!==Ce)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):i===Nt||console.error("THREE.WebGLTextures: Unsupported texture color space:",i)),t}function j(e){return typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement?(c.width=e.naturalWidth||e.width,c.height=e.naturalHeight||e.height):typeof VideoFrame<"u"&&e instanceof VideoFrame?(c.width=e.displayWidth,c.height=e.displayHeight):(c.width=e.width,c.height=e.height),c}this.allocateTextureUnit=function(){const e=C;return e>=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+r.maxTextures),C+=1,e},this.resetTextureUnits=function(){C=0},this.setTexture2D=S,this.setTexture2DArray=function(t,r){const s=n.get(t);t.version>0&&s.__version!==t.version?D(s,t,r):i.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+r)},this.setTexture3D=function(t,r){const s=n.get(t);t.version>0&&s.__version!==t.version?D(s,t,r):i.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+r)},this.setTextureCube=function(t,a){const o=n.get(t);t.version>0&&o.__version!==t.version?function(t,a,o){if(6!==a.image.length)return;const l=P(t,a),c=a.source;i.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+o);const h=n.get(c);if(c.version!==h.__version||!0===l){i.activeTexture(e.TEXTURE0+o);const t=Pi.getPrimaries(Pi.workingColorSpace),n=a.colorSpace===Lt||a.colorSpace===Nt?null:Pi.getPrimaries(a.colorSpace),d=a.colorSpace===Lt||a.colorSpace===Nt||t===n?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);const u=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)m[e]=u||p?p?a.image[e].image:a.image[e]:g(a.image[e],!0,r.maxCubemapSize),m[e]=N(a,m[e]);const v=m[0],b=s.convert(a.format,a.colorSpace),x=s.convert(a.type),w=y(a.internalFormat,b,x,a.colorSpace),C=!0!==a.isVideoTexture,S=void 0===h.__version||!0===l,M=c.dataReady;let E,T=_(a,v);if(I(e.TEXTURE_CUBE_MAP,a),u){C&&S&&i.texStorage2D(e.TEXTURE_CUBE_MAP,T,w,v.width,v.height);for(let t=0;t<6;t++){E=m[t].mipmaps;for(let n=0;n<E.length;n++){const r=E[n];a.format!==Ue?null!==b?C?M&&i.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n,0,0,r.width,r.height,b,r.data):i.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n,w,r.width,r.height,0,r.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):C?M&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n,0,0,r.width,r.height,b,x,r.data):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n,w,r.width,r.height,0,b,x,r.data)}}}else{if(E=a.mipmaps,C&&S){E.length>0&&T++;const t=j(m[0]);i.texStorage2D(e.TEXTURE_CUBE_MAP,T,w,t.width,t.height)}for(let t=0;t<6;t++)if(p){C?M&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,b,x,m[t].data):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,w,m[t].width,m[t].height,0,b,x,m[t].data);for(let n=0;n<E.length;n++){const r=E[n].image[t].image;C?M&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n+1,0,0,r.width,r.height,b,x,r.data):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n+1,w,r.width,r.height,0,b,x,r.data)}}else{C?M&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,b,x,m[t]):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,w,b,x,m[t]);for(let n=0;n<E.length;n++){const r=E[n];C?M&&i.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n+1,0,0,b,x,r.image[t]):i.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n+1,w,b,x,r.image[t])}}}f(a)&&A(e.TEXTURE_CUBE_MAP),h.__version=c.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}(o,t,a):i.bindTexture(e.TEXTURE_CUBE_MAP,o.__webglTexture,e.TEXTURE0+a)},this.rebindTextures=function(t,i,r){const s=n.get(t);void 0!==i&&R(s.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),void 0!==r&&L(t)},this.setupRenderTarget=function(t){const r=t.texture,o=n.get(t),l=n.get(r);t.addEventListener("dispose",x);const c=t.textures,h=!0===t.isWebGLCubeRenderTarget,d=c.length>1;if(d||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=r.version,a.memory.textures++),h){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let i=0;i<r.mipmaps.length;i++)o.__webglFramebuffer[t][i]=e.createFramebuffer()}else o.__webglFramebuffer[t]=e.createFramebuffer()}else{if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer=[];for(let t=0;t<r.mipmaps.length;t++)o.__webglFramebuffer[t]=e.createFramebuffer()}else o.__webglFramebuffer=e.createFramebuffer();if(d)for(let t=0,i=c.length;t<i;t++){const i=n.get(c[t]);void 0===i.__webglTexture&&(i.__webglTexture=e.createTexture(),a.memory.textures++)}if(t.samples>0&&!1===k(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],i.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let i=0;i<c.length;i++){const n=c[i];o.__webglColorRenderbuffer[i]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,o.__webglColorRenderbuffer[i]);const r=s.convert(n.format,n.colorSpace),a=s.convert(n.type),l=y(n.internalFormat,r,a,n.colorSpace,!0===t.isXRRenderTarget),h=F(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,h,l,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+i,e.RENDERBUFFER,o.__webglColorRenderbuffer[i])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(o.__webglDepthRenderbuffer=e.createRenderbuffer(),B(o.__webglDepthRenderbuffer,t,!0)),i.bindFramebuffer(e.FRAMEBUFFER,null)}}if(h){i.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),I(e.TEXTURE_CUBE_MAP,r);for(let i=0;i<6;i++)if(r.mipmaps&&r.mipmaps.length>0)for(let n=0;n<r.mipmaps.length;n++)R(o.__webglFramebuffer[i][n],t,r,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+i,n);else R(o.__webglFramebuffer[i],t,r,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+i,0);f(r)&&A(e.TEXTURE_CUBE_MAP),i.unbindTexture()}else if(d){for(let r=0,s=c.length;r<s;r++){const s=c[r],a=n.get(s);i.bindTexture(e.TEXTURE_2D,a.__webglTexture),I(e.TEXTURE_2D,s),R(o.__webglFramebuffer,t,s,e.COLOR_ATTACHMENT0+r,e.TEXTURE_2D,0),f(s)&&A(e.TEXTURE_2D)}i.unbindTexture()}else{let n=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(n=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),i.bindTexture(n,l.__webglTexture),I(n,r),r.mipmaps&&r.mipmaps.length>0)for(let i=0;i<r.mipmaps.length;i++)R(o.__webglFramebuffer[i],t,r,e.COLOR_ATTACHMENT0,n,i);else R(o.__webglFramebuffer,t,r,e.COLOR_ATTACHMENT0,n,0);f(r)&&A(n),i.unbindTexture()}t.depthBuffer&&L(t)},this.updateRenderTargetMipmap=function(t){const r=!0===t.isWebGLMultipleRenderTargets&&Array.isArray(t.texture)?t.texture:t.textures||[t.texture],s=t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:e.TEXTURE_2D;for(let e=0,t=r.length;e<t;e++){const t=r[e],a=n.get(t),o=a.__webglTexture;a.__version!==t.version&&(i.bindTexture(s,o),I(s,t),i.unbindTexture(),a.__version=t.version),f(t)&&(i.bindTexture(s,o),A(s),i.unbindTexture())}},this.updateMultisampleRenderTarget=function(t){if(t.samples>0)if(!1===k(t)){const r=t.textures,s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const c=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,h=n.get(t),d=r.length>1;if(d)for(let t=0;t<r.length;t++)i.bindFramebuffer(e.FRAMEBUFFER,h.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),i.bindFramebuffer(e.FRAMEBUFFER,h.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);i.bindFramebuffer(e.READ_FRAMEBUFFER,h.__webglMultisampledFramebuffer),i.bindFramebuffer(e.DRAW_FRAMEBUFFER,h.__webglFramebuffer);for(let i=0;i<r.length;i++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(o|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(o|=e.STENCIL_BUFFER_BIT)),d){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,h.__webglColorRenderbuffer[i]);const t=n.get(r[i]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,s,a,0,0,s,a,o,e.NEAREST),!0===l&&(O.length=0,U.length=0,O.push(e.COLOR_ATTACHMENT0+i),t.depthBuffer&&!1===t.resolveDepthBuffer&&(O.push(c),U.push(c),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,U)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,O))}if(i.bindFramebuffer(e.READ_FRAMEBUFFER,null),i.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),d)for(let t=0;t<r.length;t++){i.bindFramebuffer(e.FRAMEBUFFER,h.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,h.__webglColorRenderbuffer[t]);const s=n.get(r[t]).__webglTexture;i.bindFramebuffer(e.FRAMEBUFFER,h.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,s,0)}i.bindFramebuffer(e.DRAW_FRAMEBUFFER,h.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&!1===t.resolveDepthBuffer&&l){const i=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[i])}},this.setupDepthRenderbuffer=L,this.setupFrameBufferTexture=R,this.useMultisampledRTT=k}function al(e,t){return{convert:function(i,n=""){let r;const s=Pi.getTransfer(n);if(i===Ce)return e.UNSIGNED_BYTE;if(i===Re)return e.UNSIGNED_SHORT_4_4_4_4;if(i===Be)return e.UNSIGNED_SHORT_5_5_5_1;if(i===Oe)return e.UNSIGNED_INT_5_9_9_9_REV;if(i===Se)return e.BYTE;if(i===Me)return e.SHORT;if(i===Ee)return e.UNSIGNED_SHORT;if(i===Te)return e.INT;if(i===Ie)return e.UNSIGNED_INT;if(i===Pe)return e.FLOAT;if(i===De)return e.HALF_FLOAT;if(1021===i)return e.ALPHA;if(1022===i)return e.RGB;if(i===Ue)return e.RGBA;if(1024===i)return e.LUMINANCE;if(1025===i)return e.LUMINANCE_ALPHA;if(i===Fe)return e.DEPTH_COMPONENT;if(i===ke)return e.DEPTH_STENCIL;if(i===Ne)return e.RED;if(i===je)return e.RED_INTEGER;if(i===ze)return e.RG;if(i===Ge)return e.RG_INTEGER;if(i===Qe)return e.RGBA_INTEGER;if(i===Ve||i===He||i===We||i===qe)if(s===zt){if(r=t.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(i===Ve)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===He)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===We)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===qe)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=t.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(i===Ve)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===He)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===We)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===qe)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(i===Xe||i===Ye||i===Ke||i===Je){if(r=t.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(i===Xe)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Ye)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Ke)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Je)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(i===Ze||i===$e||i===et){if(r=t.get("WEBGL_compressed_texture_etc"),null===r)return null;if(i===Ze||i===$e)return s===zt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(i===et)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}if(i===tt||i===it||i===nt||i===rt||i===st||i===at||i===ot||i===lt||i===ct||i===ht||i===dt||i===ut||i===pt||i===mt){if(r=t.get("WEBGL_compressed_texture_astc"),null===r)return null;if(i===tt)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===it)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===nt)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===rt)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===st)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===at)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===ot)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===lt)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===ct)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===ht)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===dt)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===ut)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===pt)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===mt)return s===zt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(i===gt||i===ft||i===At){if(r=t.get("EXT_texture_compression_bptc"),null===r)return null;if(i===gt)return s===zt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===ft)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===At)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(36283===i||i===yt||i===vt||i===_t){if(r=t.get("EXT_texture_compression_rgtc"),null===r)return null;if(i===gt)return r.COMPRESSED_RED_RGTC1_EXT;if(i===yt)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===vt)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===_t)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return i===Le?e.UNSIGNED_INT_24_8:void 0!==e[i]?e[i]:null}}}class ol extends ps{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class ll extends Zn{constructor(){super(),this.isGroup=!0,this.type="Group"}}const cl={type:"move"};class hl{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new ll,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new ll,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Xi,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Xi),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new ll,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Xi,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Xi),this._grip}dispatchEvent(e){return null!==this._targetRay&&this._targetRay.dispatchEvent(e),null!==this._grip&&this._grip.dispatchEvent(e),null!==this._hand&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const 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}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(e,t,i){let n=null,r=null,s=null;const a=this._targetRay,o=this._grip,l=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(l&&e.hand){s=!0;for(const n of e.hand.values()){const e=t.getJointPose(n,i),r=this._getHandJoint(l,n);null!==e&&(r.matrix.fromArray(e.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=e.radius),r.visible=null!==e}const n=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],a=n.position.distanceTo(r.position),o=.02,c=.005;l.inputState.pinching&&a>o+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,i),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(n=t.getPose(e.targetRaySpace,i),null===n&&null!==r&&(n=r),null!==n&&(a.matrix.fromArray(n.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,n.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(n.linearVelocity)):a.hasLinearVelocity=!1,n.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(n.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(cl)))}return null!==a&&(a.visible=null!==n),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const i=new ll;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class dl{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,i){if(null===this.texture){const n=new Ni;e.properties.get(n).__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(null!==this.texture&&null===this.mesh){const t=e.cameras[0].viewport,i=new ls({vertexShader:"\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}",fragmentShader:"\nuniform sampler2DArray depthColor;\nuniform float depthWidth;\nuniform float depthHeight;\n\nvoid main() {\n\n\tvec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );\n\n\tif ( coord.x >= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new ts(new Es(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class ul extends ri{constructor(e,t){super();const i=this;let n=null,r=1,s=null,a="local-floor",o=1,l=null,c=null,h=null,d=null,u=null,p=null;const m=new dl,g=t.getContextAttributes();let f=null,A=null;const y=[],v=[],_=new fi;let b=null;const x=new ps;x.layers.enable(1),x.viewport=new Gi;const w=new ps;w.layers.enable(2),w.viewport=new Gi;const C=[x,w],S=new ol;S.layers.enable(1),S.layers.enable(2);let M=null,E=null;function T(e){const t=v.indexOf(e.inputSource);if(-1===t)return;const i=y[t];void 0!==i&&(i.update(e.inputSource,e.frame,l||s),i.dispatchEvent({type:e.type,data:e.inputSource}))}function I(){n.removeEventListener("select",T),n.removeEventListener("selectstart",T),n.removeEventListener("selectend",T),n.removeEventListener("squeeze",T),n.removeEventListener("squeezestart",T),n.removeEventListener("squeezeend",T),n.removeEventListener("end",I),n.removeEventListener("inputsourceschange",P);for(let e=0;e<y.length;e++){const t=v[e];null!==t&&(v[e]=null,y[e].disconnect(t))}M=null,E=null,m.reset(),e.setRenderTarget(f),u=null,d=null,h=null,n=null,A=null,O.stop(),i.isPresenting=!1,e.setPixelRatio(b),e.setSize(_.width,_.height,!1),i.dispatchEvent({type:"sessionend"})}function P(e){for(let t=0;t<e.removed.length;t++){const i=e.removed[t],n=v.indexOf(i);n>=0&&(v[n]=null,y[n].disconnect(i))}for(let t=0;t<e.added.length;t++){const i=e.added[t];let n=v.indexOf(i);if(-1===n){for(let e=0;e<y.length;e++){if(e>=v.length){v.push(i),n=e;break}if(null===v[e]){v[e]=i,n=e;break}}if(-1===n)break}const r=y[n];r&&r.connect(i)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=y[e];return void 0===t&&(t=new hl,y[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=y[e];return void 0===t&&(t=new hl,y[e]=t),t.getGripSpace()},this.getHand=function(e){let t=y[e];return void 0===t&&(t=new hl,y[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){r=e,!0===i.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===i.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(e){l=e},this.getBaseLayer=function(){return null!==d?d:u},this.getBinding=function(){return h},this.getFrame=function(){return p},this.getSession=function(){return n},this.setSession=async function(c){if(n=c,null!==n){if(f=e.getRenderTarget(),n.addEventListener("select",T),n.addEventListener("selectstart",T),n.addEventListener("selectend",T),n.addEventListener("squeeze",T),n.addEventListener("squeezestart",T),n.addEventListener("squeezeend",T),n.addEventListener("end",I),n.addEventListener("inputsourceschange",P),!0!==g.xrCompatible&&await t.makeXRCompatible(),b=e.getPixelRatio(),e.getSize(_),void 0===n.renderState.layers){const i={antialias:g.antialias,alpha:!0,depth:g.depth,stencil:g.stencil,framebufferScaleFactor:r};u=new XRWebGLLayer(n,t,i),n.updateRenderState({baseLayer:u}),e.setPixelRatio(1),e.setSize(u.framebufferWidth,u.framebufferHeight,!1),A=new Vi(u.framebufferWidth,u.framebufferHeight,{format:Ue,type:Ce,colorSpace:e.outputColorSpace,stencilBuffer:g.stencil})}else{let i=null,s=null,a=null;g.depth&&(a=g.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,i=g.stencil?ke:Fe,s=g.stencil?Le:Ie);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:r};h=new XRWebGLBinding(n,t),d=h.createProjectionLayer(o),n.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),A=new Vi(d.textureWidth,d.textureHeight,{format:Ue,type:Ce,depthTexture:new ua(d.textureWidth,d.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,i),stencilBuffer:g.stencil,colorSpace:e.outputColorSpace,samples:g.antialias?4:0,resolveDepthBuffer:!1===d.ignoreDepthValues})}A.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await n.requestReferenceSpace(a),O.setContext(n),O.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==n)return n.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};const D=new Xi,R=new Xi;function B(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(null===n)return;let t=e.near,i=e.far;null!==m.texture&&(m.depthNear>0&&(t=m.depthNear),m.depthFar>0&&(i=m.depthFar)),S.near=w.near=x.near=t,S.far=w.far=x.far=i,(M!==S.near||E!==S.far)&&(n.updateRenderState({depthNear:S.near,depthFar:S.far}),M=S.near,E=S.far);const r=e.parent,s=S.cameras;B(S,r);for(let e=0;e<s.length;e++)B(s[e],r);2===s.length?function(e,t,i){D.setFromMatrixPosition(t.matrixWorld),R.setFromMatrixPosition(i.matrixWorld);const n=D.distanceTo(R),r=t.projectionMatrix.elements,s=i.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),l=(r[9]+1)/r[5],c=(r[9]-1)/r[5],h=(r[8]-1)/r[0],d=(s[8]+1)/s[0],u=a*h,p=a*d,m=n/(-h+d),g=m*-h;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(g),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===r[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+m,i=o+m,r=u-g,s=p+(n-g),h=l*o/i*t,d=c*o/i*t;e.projectionMatrix.makePerspective(r,s,h,d,t,i),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(S,x,w):S.projectionMatrix.copy(x.projectionMatrix),function(e,t,i){null===i?e.matrix.copy(t.matrixWorld):(e.matrix.copy(i.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*li*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,S,r)},this.getCamera=function(){return S},this.getFoveation=function(){if(null!==d||null!==u)return o},this.setFoveation=function(e){o=e,null!==d&&(d.fixedFoveation=e),null!==u&&void 0!==u.fixedFoveation&&(u.fixedFoveation=e)},this.hasDepthSensing=function(){return null!==m.texture},this.getDepthSensingMesh=function(){return m.getMesh(S)};let L=null;this.onPreAnimationFrameCallback=null;const O=new Ss;O.setAnimationLoop(function(t,r){if(i.onPreAnimationFrameCallback&&i.onPreAnimationFrameCallback(t,r),c=r.getViewerPose(l||s),p=r,null!==c){const t=c.views;null!==u&&(e.setRenderTargetFramebuffer(A,u.framebuffer),e.setRenderTarget(A));let i=!1;t.length!==S.cameras.length&&(S.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){const r=t[n];let s=null;if(null!==u)s=u.getViewport(r);else{const t=h.getViewSubImage(d,r);s=t.viewport,0===n&&(e.setRenderTargetTextures(A,t.colorTexture,d.ignoreDepthValues?void 0:t.depthStencilTexture),e.setRenderTarget(A))}let a=C[n];void 0===a&&(a=new ps,a.layers.enable(n),a.viewport=new Gi,C[n]=a),a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.projectionMatrix.fromArray(r.projectionMatrix),a.projectionMatrixInverse.copy(a.projectionMatrix).invert(),a.viewport.set(s.x,s.y,s.width,s.height),0===n&&(S.matrix.copy(a.matrix),S.matrix.decompose(S.position,S.quaternion,S.scale)),!0===i&&S.cameras.push(a)}const r=n.enabledFeatures;if(r&&r.includes("depth-sensing")){const i=h.getDepthInformation(t[0]);i&&i.isValid&&i.texture&&m.init(e,i,n.renderState)}}for(let e=0;e<y.length;e++){const t=v[e],i=y[e];null!==t&&void 0!==i&&i.update(t,r,l||s)}L&&L(t,r),r.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:r}),p=null}),this.setAnimationLoop=function(e){L=e},this.dispose=function(){}}}const pl=new On,ml=new Sn;function gl(e,t){function i(e,t){!0===e.matrixAutoUpdate&&e.updateMatrix(),t.value.copy(e.matrix)}function n(e,n){e.opacity.value=n.opacity,n.color&&e.diffuse.value.copy(n.color),n.emissive&&e.emissive.value.copy(n.emissive).multiplyScalar(n.emissiveIntensity),n.map&&(e.map.value=n.map,i(n.map,e.mapTransform)),n.alphaMap&&(e.alphaMap.value=n.alphaMap,i(n.alphaMap,e.alphaMapTransform)),n.bumpMap&&(e.bumpMap.value=n.bumpMap,i(n.bumpMap,e.bumpMapTransform),e.bumpScale.value=n.bumpScale,n.side===b&&(e.bumpScale.value*=-1)),n.normalMap&&(e.normalMap.value=n.normalMap,i(n.normalMap,e.normalMapTransform),e.normalScale.value.copy(n.normalScale),n.side===b&&e.normalScale.value.negate()),n.displacementMap&&(e.displacementMap.value=n.displacementMap,i(n.displacementMap,e.displacementMapTransform),e.displacementScale.value=n.displacementScale,e.displacementBias.value=n.displacementBias),n.emissiveMap&&(e.emissiveMap.value=n.emissiveMap,i(n.emissiveMap,e.emissiveMapTransform)),n.specularMap&&(e.specularMap.value=n.specularMap,i(n.specularMap,e.specularMapTransform)),n.alphaTest>0&&(e.alphaTest.value=n.alphaTest);const r=t.get(n),s=r.envMap,a=r.envMapRotation;s&&(e.envMap.value=s,pl.copy(a),pl.x*=-1,pl.y*=-1,pl.z*=-1,s.isCubeTexture&&!1===s.isRenderTargetTexture&&(pl.y*=-1,pl.z*=-1),e.envMapRotation.value.setFromMatrix4(ml.makeRotationFromEuler(pl)),e.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,e.reflectivity.value=n.reflectivity,e.ior.value=n.ior,e.refractionRatio.value=n.refractionRatio),n.lightMap&&(e.lightMap.value=n.lightMap,e.lightMapIntensity.value=n.lightMapIntensity,i(n.lightMap,e.lightMapTransform)),n.aoMap&&(e.aoMap.value=n.aoMap,e.aoMapIntensity.value=n.aoMapIntensity,i(n.aoMap,e.aoMapTransform))}return{refreshTransformUniform:i,refreshFogUniforms:function(t,i){i.color.getRGB(t.fogColor.value,as(e)),i.isFog?(t.fogNear.value=i.near,t.fogFar.value=i.far):i.isFogExp2&&(t.fogDensity.value=i.density)},refreshMaterialUniforms:function(e,r,s,a,o){r.isMeshBasicMaterial||r.isMeshLambertMaterial?n(e,r):r.isMeshToonMaterial?(n(e,r),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,r)):r.isMeshPhongMaterial?(n(e,r),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,r)):r.isMeshStandardMaterial?(n(e,r),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,i(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,i(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,r),r.isMeshPhysicalMaterial&&function(e,t,n){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,i(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,i(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,i(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,i(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,i(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===b&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,i(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,i(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=n.texture,e.transmissionSamplerSize.value.set(n.width,n.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,i(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,i(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,i(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,i(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,i(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,r,o)):r.isMeshMatcapMaterial?(n(e,r),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,r)):r.isMeshDepthMaterial?n(e,r):r.isMeshDistanceMaterial?(n(e,r),function(e,i){const n=t.get(i).light;e.referencePosition.value.setFromMatrixPosition(n.matrixWorld),e.nearDistance.value=n.shadow.camera.near,e.farDistance.value=n.shadow.camera.far}(e,r)):r.isMeshNormalMaterial?n(e,r):r.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,i(t.map,e.mapTransform))}(e,r),r.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,r)):r.isPointsMaterial?function(e,t,n,r){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*n,e.scale.value=.5*r,t.map&&(e.map.value=t.map,i(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,i(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r,s,a):r.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,i(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,i(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r):r.isShadowMaterial?(e.color.value.copy(r.color),e.opacity.value=r.opacity):r.isShaderMaterial&&(void 0!==r.transmission&&(e.transmission&&(e.transmission.value=r.transmission),e.transmissionSamplerMap&&o&&(e.transmissionSamplerMap.value=o?o.texture:null),e.transmissionSamplerSize&&o&&e.transmissionSamplerSize.value.set(o.width,o.height)),r.uniformsNeedUpdate=!1)}}}function fl(e,t,i,n){let r={},s={},a=[];const o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(e,t,i,n){const r=e.value,s=t+"_"+i;if(void 0===n[s])return n[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const e=n[s];if("number"==typeof r||"boolean"==typeof r){if(e!==r)return n[s]=r,!0}else if(!1===e.equals(r))return e.copy(r),!0}return!1}function c(e){const t={boundary:0,storage:0};return"number"==typeof e||"boolean"==typeof e?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",e),t}function h(t){const i=t.target;i.removeEventListener("dispose",h);const n=a.indexOf(i.__bindingPointIndex);a.splice(n,1),e.deleteBuffer(r[i.id]),delete r[i.id],delete s[i.id]}return{bind:function(e,t){const i=t.program;n.uniformBlockBinding(e,i)},update:function(i,d){let u=r[i.id];void 0===u&&(function(e){const t=e.uniforms;let i=0;const n=16;for(let e=0,r=t.length;e<r;e++){const r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){const t=r[e],s=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=s.length;e<r;e++){const r=c(s[e]),a=i%n,o=a%r.boundary,l=a+o;i+=o,0!==l&&n-l<r.storage&&(i+=n-l),t.__data=new Float32Array(r.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=i,i+=r.storage}}}const r=i%n;r>0&&(i+=n-r),e.__size=i,e.__cache={}}(i),u=function(t){const i=function(){for(let e=0;e<o;e++)if(-1===a.indexOf(e))return a.push(e),e;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}();t.__bindingPointIndex=i;const n=e.createBuffer(),r=t.__size,s=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,n),e.bufferData(e.UNIFORM_BUFFER,r,s),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,i,n),n}(i),r[i.id]=u,i.addEventListener("dispose",h));const p=d.program;n.updateUBOMapping(i,p);const m=t.render.frame;s[i.id]!==m&&(function(t){const i=r[t.id],n=t.uniforms,s=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,i);for(let t=0,i=n.length;t<i;t++){const i=Array.isArray(n[t])?n[t]:[n[t]];for(let n=0,r=i.length;n<r;n++){const r=i[n];if(!0===l(r,t,n,s)){const t=r.__offset,i=Array.isArray(r.value)?r.value:[r.value];let n=0;for(let s=0;s<i.length;s++){const a=i[s],o=c(a);"number"==typeof a||"boolean"==typeof a?(r.__data[0]=a,e.bufferSubData(e.UNIFORM_BUFFER,t+n,r.__data)):a.isMatrix3?(r.__data[0]=a.elements[0],r.__data[1]=a.elements[1],r.__data[2]=a.elements[2],r.__data[3]=0,r.__data[4]=a.elements[3],r.__data[5]=a.elements[4],r.__data[6]=a.elements[5],r.__data[7]=0,r.__data[8]=a.elements[6],r.__data[9]=a.elements[7],r.__data[10]=a.elements[8],r.__data[11]=0):(a.toArray(r.__data,n),n+=o.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,r.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}(i),s[i.id]=m)},dispose:function(){for(const t in r)e.deleteBuffer(r[t]);a=[],r={},s={}}}}class Al{constructor(e={}){const{canvas:t=wi(),context:i=null,depth:n=!0,stencil:r=!1,alpha:s=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:l=!1,powerPreference:c="default",failIfMajorPerformanceCaveat:h=!1}=e;let d;if(this.isWebGLRenderer=!0,null!==i){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=s;const u=new Uint32Array(4),p=new Int32Array(4);let m=null,g=null;const f=[],A=[];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=Ot,this.toneMapping=0,this.toneMappingExposure=1,this.userData={},this.onContextLost=()=>{},this.onContextRestore=()=>{},this.onContextCreationError=()=>{};const y=this;let v=!1,w=0,C=0,S=null,M=-1,E=null;const T=new Gi,I=new Gi;let P=null;const D=new mr(0);let R=0,B=t.width,L=t.height,O=1,U=null,F=null;const k=new Gi(0,0,B,L),N=new Gi(0,0,B,L);let j=!1;const z=new Cs;let G=!1,Q=!1;const V=new Sn,H=new Xi,W=new Gi,q={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let X=!1;function Y(){return null===S?O:1}let K,J,Z,$,ee,te,ie,ne,re,se,ae,oe,le,ce,he,de,ue,pe,me,ge,fe,Ae,ye,ve,_e=i;function be(e,i){return t.getContext(e,i)}try{const e={alpha:!0,depth:n,stencil:r,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:c,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine","three.js r168"),t.addEventListener("webglcontextlost",Me,!1),t.addEventListener("webglcontextrestored",Te,!1),t.addEventListener("webglcontextcreationerror",Pe,!1),null===_e){const t="webgl2";if(_e=be(t,e),null===_e)throw be(t)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(e){throw console.error("THREE.WebGLRenderer: "+e.message),e}function xe(){K=new aa(_e),K.init(),Ae=new al(_e,K),J=new ks(_e,K,e,Ae),Z=new nl(_e),$=new ca(_e),ee=new Qo,te=new sl(_e,K,Z,ee,J,Ae,$),ie=new js(y),ne=new sa(y),re=new Ms(_e),ye=new Us(_e,re),se=new oa(_e,re,$,ye),ae=new da(_e,se,re,$),me=new ha(_e,J,te),de=new Ns(ee),oe=new Go(y,ie,ne,K,J,ye,de),le=new gl(y,ee),ce=new qo,he=new $o(K),pe=new Os(y,ie,ne,Z,ae,d,o),ue=new il(y,ae,J),ve=new fl(_e,$,J,Z),ge=new Fs(_e,K,$),fe=new la(_e,K,$),$.programs=oe.programs,y.capabilities=J,y.extensions=K,y.properties=ee,y.renderLists=ce,y.shadowMap=ue,y.state=Z,y.info=$,y.background=pe,y.cubemaps=ie,y.cubeuvmaps=ne,y.materials=le}xe();const Se=new ul(y,_e);function Me(e){e.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),v=!0,y.onContextLost(e)}function Te(){console.log("THREE.WebGLRenderer: Context Restored."),v=!1;const e=y.info?y.info.autoReset:void 0,t=ue.enabled,i=ue.autoUpdate,n=ue.needsUpdate,r=ue.type;xe(),y.info&&void 0!==e&&(y.info.autoReset=e),ue.enabled=t,ue.autoUpdate=i,ue.needsUpdate=n,ue.type=r,y.onContextRestore&&y.onContextRestore()}function Pe(e){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",e.statusMessage),y.onContextCreationError(e)}function Oe(e){const t=e.target;t.removeEventListener("dispose",Oe),function(e){(function(e){const t=ee.get(e).programs;void 0!==t&&(t.forEach(function(e){oe.releaseProgram(e)}),e.isShaderMaterial&&oe.releaseShaderCache(e))})(e),ee.remove(e)}(t)}function Ue(e,t,i){!0===e.transparent&&e.side===x&&!1===e.forceSinglePass?(e.side=b,e.needsUpdate=!0,Ye(e,t,i),e.side=_,e.needsUpdate=!0,Ye(e,t,i),e.side=x):Ye(e,t,i)}this.xr=Se,this.getContext=function(){return _e},this.getContextAttributes=function(){return _e.getContextAttributes()},this.forceContextLoss=function(){const e=K.get("WEBGL_lose_context");e&&e.loseContext()},this.forceContextRestore=function(){const e=K.get("WEBGL_lose_context");e&&e.restoreContext()},this.getPixelRatio=function(){return O},this.setPixelRatio=function(e){void 0!==e&&(O=e,this.setSize(B,L,!1))},this.getSize=function(e){return e.set(B,L)},this.setSize=function(e,i,n=!0){Se.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(B=e,L=i,t.width=Math.floor(e*O),t.height=Math.floor(i*O),!0===n&&(t.style.width=e+"px",t.style.height=i+"px"),this.setViewport(0,0,e,i))},this.getDrawingBufferSize=function(e){return e.set(B*O,L*O).floor()},this.setDrawingBufferSize=function(e,i,n){B=e,L=i,O=n,t.width=Math.floor(e*n),t.height=Math.floor(i*n),this.setViewport(0,0,e,i)},this.getCurrentViewport=function(e){return e.copy(T)},this.getViewport=function(e){return e.copy(k)},this.setViewport=function(e,t,i,n){e.isVector4?k.set(e.x,e.y,e.z,e.w):k.set(e,t,i,n),Z.viewport(T.copy(k).multiplyScalar(O).round())},this.getScissor=function(e){return e.copy(N)},this.setScissor=function(e,t,i,n){e.isVector4?N.set(e.x,e.y,e.z,e.w):N.set(e,t,i,n),Z.scissor(I.copy(N).multiplyScalar(O).round())},this.getScissorTest=function(){return j},this.setScissorTest=function(e){Z.setScissorTest(j=e)},this.setOpaqueSort=function(e){U=e},this.setTransparentSort=function(e){F=e},this.getClearColor=function(e){return e.copy(pe.getClearColor())},this.setClearColor=function(){pe.setClearColor.apply(pe,arguments)},this.getClearAlpha=function(){return pe.getClearAlpha()},this.setClearAlpha=function(){pe.setClearAlpha.apply(pe,arguments)},this.clear=function(e=!0,t=!0,i=!0){let n=0;if(e){let e=!1;if(null!==S){const t=S.texture.format;e=t===Qe||t===Ge||t===je}if(e){const e=S.texture.type,t=e===Ce||e===Ie||e===Ee||e===Le||e===Re||e===Be,i=pe.getClearColor(),n=pe.getClearAlpha(),r=i.r,s=i.g,a=i.b;t?(u[0]=r,u[1]=s,u[2]=a,u[3]=n,_e.clearBufferuiv(_e.COLOR,0,u)):(p[0]=r,p[1]=s,p[2]=a,p[3]=n,_e.clearBufferiv(_e.COLOR,0,p))}else n|=_e.COLOR_BUFFER_BIT}t&&(n|=_e.DEPTH_BUFFER_BIT),i&&(n|=_e.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),_e.clear(n)},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",Me,!1),t.removeEventListener("webglcontextrestored",Te,!1),t.removeEventListener("webglcontextcreationerror",Pe,!1),ce.dispose(),he.dispose(),ee.dispose(),ie.dispose(),ne.dispose(),ae.dispose(),ye.dispose(),ve.dispose(),oe.dispose(),Se.dispose(),Se.removeEventListener("sessionstart",ke),Se.removeEventListener("sessionend",Ne),ze.stop()},this.renderBufferDirect=function(e,t,i,n,r,s){null===t&&(t=q);const a=r.isMesh&&r.matrixWorld.determinant()<0,o=function(e,t,i,n,r){!0!==t.isScene&&(t=q),te.resetTextureUnits();const s=t.fog,a=n.userData&&n.userData.envMapSlotKey&&t.textureSlots&&t.textureSlots[n.userData.envMapSlotKey]?t.textureSlots[n.userData.envMapSlotKey]:n.isMeshStandardMaterial?t.environment:null,o=null===S?y.outputColorSpace:!0===S.isXRRenderTarget||S.texture.colorSpace&&S.texture.colorSpace!==Ot?S.texture.colorSpace:Ut,l=(n.isMeshStandardMaterial?ne:ie).get(n.envMap||a),c=!0===n.vertexColors&&!!i.attributes.color&&4===i.attributes.color.itemSize,h=!!i.attributes.tangent&&(!!n.normalMap||n.anisotropy>0||i.userData.__forceUseTangent),d=!!i.morphAttributes.position,u=!!i.morphAttributes.normal,p=!!i.morphAttributes.color;let m=0;n.toneMapped&&(null===S||!0===S.isXRRenderTarget)&&(m=y.toneMapping);const f=i.morphAttributes.position||i.morphAttributes.normal||i.morphAttributes.color,A=void 0!==f?f.length:0,v=ee.get(n),_=g.state.lights;if(!0===G&&(!0===Q||e!==E)){const t=e===E&&n.id===M;de.setState(n,e,t)}let b=!1;n.version===v.__version?(v.needsLights&&v.lightsStateVersion!==_.state.version||v.outputColorSpace!==o||r.isBatchedMesh&&!1===v.batching||!r.isBatchedMesh&&!0===v.batching||r.isBatchedMesh&&!0===v.batchingColor&&null===r.colorTexture||r.isBatchedMesh&&!1===v.batchingColor&&null!==r.colorTexture||r.isInstancedMesh&&!1===v.instancing||!r.isInstancedMesh&&!0===v.instancing||r.isSkinnedMesh&&!1===v.skinning||!r.isSkinnedMesh&&!0===v.skinning||r.isInstancedMesh&&!0===v.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===v.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===v.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===v.instancingMorph&&null!==r.morphTexture||v.envMap!==l||!0===n.fog&&v.fog!==s||void 0!==v.numClippingPlanes&&(v.numClippingPlanes!==de.numPlanes||v.numIntersection!==de.numIntersection)||v.vertexAlphas!==c||v.vertexTangents!==h||v.morphTargets!==d||v.morphNormals!==u||v.morphColors!==p||v.toneMapping!==m||v.morphTargetsCount!==A)&&(b=!0):(b=!0,v.__version=n.version);let x=v.currentProgram;!0===b&&(x=Ye(n,t,r));let w=!1,C=!1,T=!1;const I=x.getUniforms(),P=v.uniforms;if(Z.useProgram(x.program)&&(w=!0,C=!0,T=!0),n.id!==M&&(M=n.id,C=!0),w||E!==e){I.setValue(_e,"projectionMatrix",e.projectionMatrix),I.setValue(_e,"viewMatrix",e.matrixWorldInverse);const t=I.map.cameraPosition;void 0!==t&&t.setValue(_e,H.setFromMatrixPosition(e.matrixWorld)),J.logarithmicDepthBuffer&&I.setValue(_e,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(n.isMeshPhongMaterial||n.isMeshToonMaterial||n.isMeshLambertMaterial||n.isMeshBasicMaterial||n.isMeshStandardMaterial||n.isShaderMaterial)&&I.setValue(_e,"isOrthographic",!0===e.isOrthographicCamera),E!==e&&(E=e,C=!0,T=!0)}if(r.isSkinnedMesh){I.setOptional(_e,r,"bindMatrix"),I.setOptional(_e,r,"bindMatrixInverse");const e=r.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),I.setValue(_e,"boneTexture",e.boneTexture,te))}r.isBatchedMesh&&(I.setOptional(_e,r,"batchingTexture"),I.setValue(_e,"batchingTexture",r._matricesTexture,te),I.setOptional(_e,r,"batchingIdTexture"),I.setValue(_e,"batchingIdTexture",r._indirectTexture,te),I.setOptional(_e,r,"batchingColorTexture"),null!==r._colorsTexture&&I.setValue(_e,"batchingColorTexture",r._colorsTexture,te));const D=i.morphAttributes;(void 0!==D.position||void 0!==D.normal||void 0!==D.color)&&me.update(r,i,x),(C||v.receiveShadow!==r.receiveShadow)&&(v.receiveShadow=r.receiveShadow,I.setValue(_e,"receiveShadow",r.receiveShadow)),n.isMeshGouraudMaterial&&null!==n.envMap&&(P.envMap.value=l,P.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1),n.isMeshStandardMaterial&&null===n.envMap&&null!==t.environment&&(n.userData&&n.userData.separateEnvMapIntensity?P.envMapIntensity.value=n.envMapIntensity:P.envMapIntensity.value=t.environmentIntensity),C&&(I.setValue(_e,"toneMappingExposure",y.toneMappingExposure),v.needsLights&&function(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}(P,T),s&&!0===n.fog&&le.refreshFogUniforms(P,s),le.refreshMaterialUniforms(P,n,O,L,y.userData.transmissionRenderTarget||g.state.transmissionRenderTarget[e.id]),yo.upload(_e,Ke(v),P,te)),n.isShaderMaterial&&!0===n.uniformsNeedUpdate&&(yo.upload(_e,Ke(v),P,te),n.uniformsNeedUpdate=!1),n.isSpriteMaterial&&I.setValue(_e,"center",r.center),I.setValue(_e,"modelViewMatrix",r.modelViewMatrix),I.setValue(_e,"normalMatrix",r.normalMatrix),I.setValue(_e,"modelMatrix",r.matrixWorld);const R=n.extraUniformsToUpload;if(R&&Object.entries(R).forEach(([e,t])=>{!1!==t.needsUpdate&&I.setValue(_e,e,t.value,te)}),n.isShaderMaterial||n.isRawShaderMaterial){const e=n.uniformsGroups;for(let t=0,i=e.length;t<i;t++){const i=e[t];ve.update(i,x),ve.bind(i,x)}}return x}(e,t,i,n,r);Z.setMaterial(n,a);let l=i.index,c=1;if(!0===n.wireframe){if(l=se.getWireframeAttribute(i),void 0===l)return;c=2}const h=i.drawRange,d=i.attributes.position;let u=h.start*c,p=(h.start+h.count)*c;null!==s&&(u=Math.max(u,s.start*c),p=Math.min(p,(s.start+s.count)*c)),null!==l?(u=Math.max(u,0),p=Math.min(p,l.count)):null!=d&&(u=Math.max(u,0),p=Math.min(p,d.count));const m=p-u;if(m<0||m===1/0)return;ye.setup(r,n,o,i,l);let f,A=ge;if(null!==l&&(f=re.get(l),A=fe,A.setIndex(f)),r.isMesh)!0===n.wireframe?(Z.setLineWidth(n.wireframeLinewidth*Y()),A.setMode(_e.LINES)):A.setMode(_e.TRIANGLES);else if(r.isLine){let e=n.linewidth;void 0===e&&(e=1),Z.setLineWidth(e*Y()),r.isLineSegments?A.setMode(_e.LINES):r.isLineLoop?A.setMode(_e.LINE_LOOP):A.setMode(_e.LINE_STRIP)}else r.isPoints?A.setMode(_e.POINTS):r.isSprite&&A.setMode(_e.TRIANGLES);if(r.isBatchedMesh)if(null!==r._multiDrawInstances)A.renderMultiDrawInstances(r._multiDrawStarts,r._multiDrawCounts,r._multiDrawCount,r._multiDrawInstances);else if(K.get("WEBGL_multi_draw"))A.renderMultiDraw(r._multiDrawStarts,r._multiDrawCounts,r._multiDrawCount);else{const e=r._multiDrawStarts,t=r._multiDrawCounts,i=r._multiDrawCount,s=l?re.get(l).bytesPerElement:1,a=ee.get(n).currentProgram.getUniforms();for(let n=0;n<i;n++)a.setValue(_e,"_gl_DrawID",n),A.render(e[n]/s,t[n])}else if(r.isInstancedMesh)A.renderInstances(u,m,r.count);else if(i.isInstancedBufferGeometry){const e=void 0!==i._maxInstanceCount?i._maxInstanceCount:1/0,t=Math.min(i.instanceCount,e);A.renderInstances(u,m,t)}else A.render(u,m)},this.compile=function(e,t,i=null){null===i&&(i=e),g=he.get(i),g.init(t),A.push(g),i.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(g.pushLight(e),e.castShadow&&g.pushShadow(e))}),e!==i&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(g.pushLight(e),e.castShadow&&g.pushShadow(e))}),g.setupLights();const n=new Set;return e.traverse(function(e){const t=e.material;if(t)if(Array.isArray(t))for(let r=0;r<t.length;r++){const s=t[r];Ue(s,i,e),n.add(s)}else Ue(t,i,e),n.add(t)}),A.pop(),g=null,n},this.compileAsync=function(e,t,i=null){const n=this.compile(e,t,i);return new Promise(t=>{function i(){n.forEach(function(e){ee.get(e).currentProgram.isReady()&&n.delete(e)}),0!==n.size?setTimeout(i,10):t(e)}null!==K.get("KHR_parallel_shader_compile")?i():setTimeout(i,10)})};let Fe=null;function ke(){ze.stop()}function Ne(){ze.start()}const ze=new Ss;function Ve(e,t,i,n){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)i=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)g.pushLight(e),e.castShadow&&g.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||z.intersectsSprite(e)){n&&W.setFromMatrixPosition(e.matrixWorld).applyMatrix4(V);const t=ae.update(e),r=e.material;r.visible&&m.push(e,t,r,i,W.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||z.intersectsObject(e))){const t=ae.update(e),r=e.material;if(n&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),W.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),W.copy(t.boundingSphere.center)),W.applyMatrix4(e.matrixWorld).applyMatrix4(V)),Array.isArray(r)){const n=t.groups;for(let s=0,a=n.length;s<a;s++){const a=n[s],o=r[a.materialIndex];o&&o.visible&&m.push(e,t,o,i,W.z,a)}}else r.visible&&m.push(e,t,r,i,W.z,null)}const r=e.children;for(let e=0,s=r.length;e<s;e++)Ve(r[e],t,i,n)}function He(e,t,i,n){const r=e.opaque,s=e.transmissive,a=e.transparent;if(g.setupLightsView(i),!0===G&&de.setGlobalState(y.clippingPlanes,i),n&&Z.viewport(T.copy(n)),!1!==y.userData.opaqueRender&&r.length>0&&qe(r,t,i),!1!==y.userData.transparentRender&&a.length>0&&qe(a,t,i),!1!==y.userData.transmissionRender)if(void 0===y.userData.transmissionRender&&!1!==y.userData.renderTransmissionPass)s.length>0&&qe(s,t,i);else if(s.length>0){g.state.transmissionRenderTarget||(g.state.transmissionRenderTarget={}),g.state.transmissionRenderTarget[i.id]||(g.state.transmissionRenderTarget[i.id]=new Vi(1,1));const e=(y.userData.transmissionRenderTarget||g.state.transmissionRenderTarget[i.id]).texture,n=J.isWebGL2,r=e.generateMipmaps,a=e.minFilter;n&&y.userData.blurTransmissionTarget&&y.userData.transmissionRenderTarget&&(e.generateMipmaps=!0,e.minFilter=we,e.needsUpdate=!0,te.updateMultisampleRenderTarget(y.userData.transmissionRenderTarget),te.updateRenderTargetMipmap(y.userData.transmissionRenderTarget)),qe(s,t,i),n&&y.userData.blurTransmissionTarget&&y.userData.transmissionRenderTarget&&(e.generateMipmaps=r,e.minFilter=a,e.needsUpdate=!0,te.updateMultisampleRenderTarget(y.userData.transmissionRenderTarget),te.updateRenderTargetMipmap(y.userData.transmissionRenderTarget))}Z.buffers.depth.setTest(!0),Z.buffers.depth.setMask(!0),Z.buffers.color.setMask(!0),Z.setPolygonOffset(!1)}function We(e,t,i,n){if(null!==(!0===i.isScene?i.overrideMaterial:null))return;void 0===g.state.transmissionRenderTarget[n.id]&&(g.state.transmissionRenderTarget[n.id]=new Vi(1,1,{generateMipmaps:!0,type:K.has("EXT_color_buffer_half_float")||K.has("EXT_color_buffer_float")?De:Ce,minFilter:we,samples:4,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Pi.workingColorSpace}));const s=g.state.transmissionRenderTarget[n.id],a=n.viewport||T;s.setSize(a.z,a.w);const o=y.getRenderTarget();y.setRenderTarget(s),y.getClearColor(D),R=y.getClearAlpha(),R<1&&y.setClearColor(16777215,.5),y.clear(),X&&pe.render(i);const l=y.toneMapping;y.toneMapping=0;const c=n.viewport;if(void 0!==n.viewport&&(n.viewport=void 0),g.setupLightsView(n),!0===G&&de.setGlobalState(y.clippingPlanes,n),qe(e,i,n),te.updateMultisampleRenderTarget(s),te.updateRenderTargetMipmap(s),!1===K.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let r=0,s=t.length;r<s;r++){const s=t[r],a=s.object,o=s.geometry,l=s.material,c=s.group;if(l.side===x&&a.layers.test(n.layers)){const t=l.side;l.side=b,l.needsUpdate=!0,Xe(a,i,n,o,l,c),l.side=t,l.needsUpdate=!0,e=!0}}!0===e&&(te.updateMultisampleRenderTarget(s),te.updateRenderTargetMipmap(s))}y.setRenderTarget(o),y.setClearColor(D,R),void 0!==c&&(n.viewport=c),y.toneMapping=l}function qe(e,t,i){const n={...y.userData};y.userData.opaqueRender=void 0,y.userData.transparentRender=void 0,y.userData.transmissionRender=void 0,y.userData.backgroundRender=void 0;const r=!0===t.isScene?t.overrideMaterial:null;for(let n=0,s=e.length;n<s;n++){const s=e[n],a=s.object,o=s.geometry,l=s.group;let c=s.material;!0===c.allowOverride&&null!==r&&(c=r),a.layers.test(i.layers)&&Xe(a,t,i,o,c,l)}Object.assign(y.userData,n)}function Xe(e,t,i,n,r,s){e.onBeforeRender(y,t,i,n,r,s),e.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),r.onBeforeRender(y,t,i,n,e,s),!0===r.transparent&&r.side===x&&!1===r.forceSinglePass?(r.side=b,r.needsUpdate=!0,y.renderBufferDirect(i,t,n,r,e,s),r.side=_,r.needsUpdate=!0,y.renderBufferDirect(i,t,n,r,e,s),r.side=x):y.renderBufferDirect(i,t,n,r,e,s),e.onAfterRender(y,t,i,n,r,s),r.onAfterRender(y,t,i,n,e,s)}function Ye(e,t,i){!0!==t.isScene&&(t=q);const n=ee.get(e),r=g.state.lights,s=g.state.shadowsArray,a=r.state.version,o=oe.getParameters(e,r.state,s,t,i),l=oe.getProgramCacheKey(o);let c=n.programs;n.environment=e.userData&&e.userData.envMapSlotKey&&t.textureSlots&&t.textureSlots[e.userData.envMapSlotKey]?t.textureSlots[e.userData.envMapSlotKey]:e.isMeshStandardMaterial?t.environment:null,n.fog=t.fog,n.envMap=(e.isMeshStandardMaterial?ne:ie).get(e.envMap||n.environment),n.envMapRotation=null!==n.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation,void 0===c&&(e.addEventListener("dispose",Oe),c=new Map,n.programs=c);let h=c.get(l);if(void 0!==h){if(n.currentProgram===h&&n.lightsStateVersion===a)return Je(e,o),h}else o.uniforms=oe.getUniforms(e),e.onBeforeCompile(o,y),h=oe.acquireProgram(o,l),c.set(l,h),n.uniforms=o.uniforms;const d=n.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||!0===e.clipping)&&(d.clippingPlanes=de.uniform),Je(e,o),n.needsLights=function(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&!0===e.lights}(e),n.lightsStateVersion=a,n.needsLights&&(d.ambientLightColor.value=r.state.ambient,d.lightProbe.value=r.state.probe,d.directionalLights.value=r.state.directional,d.directionalLightShadows.value=r.state.directionalShadow,d.spotLights.value=r.state.spot,d.spotLightShadows.value=r.state.spotShadow,d.rectAreaLights.value=r.state.rectArea,d.ltc_1.value=r.state.rectAreaLTC1,d.ltc_2.value=r.state.rectAreaLTC2,d.pointLights.value=r.state.point,d.pointLightShadows.value=r.state.pointShadow,d.hemisphereLights.value=r.state.hemi,d.directionalShadowMap.value=r.state.directionalShadowMap,d.directionalShadowMatrix.value=r.state.directionalShadowMatrix,d.spotShadowMap.value=r.state.spotShadowMap,d.spotLightMatrix.value=r.state.spotLightMatrix,d.spotLightMap.value=r.state.spotLightMap,d.pointShadowMap.value=r.state.pointShadowMap,d.pointShadowMatrix.value=r.state.pointShadowMatrix),n.currentProgram=h,n.uniformsList=null,h}function Ke(e){if(null===e.uniformsList){const t=e.currentProgram.getUniforms();e.uniformsList=yo.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function Je(e,t){const i=ee.get(e);i.outputColorSpace=t.outputColorSpace,i.batching=t.batching,i.batchingColor=t.batchingColor,i.instancing=t.instancing,i.instancingColor=t.instancingColor,i.instancingMorph=t.instancingMorph,i.skinning=t.skinning,i.morphTargets=t.morphTargets,i.morphNormals=t.morphNormals,i.morphColors=t.morphColors,i.morphTargetsCount=t.morphTargetsCount,i.numClippingPlanes=t.numClippingPlanes,i.numIntersection=t.numClipIntersection,i.vertexAlphas=t.vertexAlphas,i.vertexTangents=t.vertexTangents,i.toneMapping=t.toneMapping}ze.setAnimationLoop(function(e){Fe&&Fe(e)}),typeof self<"u"&&ze.setContext(self),this.setAnimationLoop=function(e){Fe=e,Se.setAnimationLoop(e),null===e?ze.stop():ze.start()},Se.addEventListener("sessionstart",ke),Se.addEventListener("sessionend",Ne),this.render=function(e,t){if(void 0===t||!0===t.isCamera){if(!0!==v){if(!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===Se.enabled&&!0===Se.isPresenting&&(!0===Se.cameraAutoUpdate&&Se.updateCamera(t),t=Se.getCamera()),!0===e.isScene&&e.onBeforeRender(y,e,t,S),g=he.get(e,A.length),g.init(t),A.push(g),V.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),z.setFromProjectionMatrix(V),Q=this.localClippingEnabled,G=de.init(this.clippingPlanes,Q),m=ce.get(e,f.length),m.init(),f.push(m),!0===Se.enabled&&!0===Se.isPresenting){const e=y.xr.getDepthSensingMesh();null!==e&&Ve(e,t,-1/0,y.sortObjects)}if(Ve(e,t,0,y.sortObjects),m.finish(),!0===y.sortObjects&&m.sort(U,F),X=!1===Se.enabled||!1===Se.isPresenting||!1===Se.hasDepthSensing(),X=X&&!1!==y.userData.backgroundRender,X&&pe.addToRenderList(m,e),this.info.render.frame++,!1!==y.userData.shadowMapRender){!0===G&&de.beginShadows();const i=g.state.shadowsArray;i.length>0&&ue.render(i,e,t),!0===G&&de.endShadows()}if(!0===this.info.autoReset&&this.info.reset(),!1!==y.userData.sceneRender){const i=m.opaque,n=m.transmissive;if(g.setupLights(),t.isArrayCamera){const r=t.cameras;if(n.length>0)for(let t=0,s=r.length;t<s;t++){We(i,n,e,r[t])}X&&pe.render(e);for(let t=0,i=r.length;t<i;t++){const i=r[t];He(m,e,i,i.viewport)}}else void 0===y.userData.transmissionRender&&!1!==y.userData.renderTransmissionPass&&n.length>0&&We(i,n,e,t),X&&pe.render(e),He(m,e,t)}null!==S&&(te.updateMultisampleRenderTarget(S),te.updateRenderTargetMipmap(S)),!0===e.isScene&&e.onAfterRender(y,e,t),ye.resetDefaultState(),M=-1,E=null,A.pop(),A.length>0?(g=A[A.length-1],!0===G&&de.setGlobalState(y.clippingPlanes,g.state.camera)):g=null,f.pop(),m=f.length>0?f[f.length-1]:null}}else console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.")},this.getActiveCubeFace=function(){return w},this.getActiveMipmapLevel=function(){return C},this.getRenderTarget=function(){return S},this.setRenderTargetTextures=function(e,t,i){ee.get(e.texture).__webglTexture=t,ee.get(e.depthTexture).__webglTexture=i;const n=ee.get(e);n.__hasExternalTextures=!0,n.__autoAllocateDepthBuffer=void 0===i,n.__autoAllocateDepthBuffer||!0===K.has("WEBGL_multisampled_render_to_texture")&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),n.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(e,t){const i=ee.get(e);i.__webglFramebuffer=t,i.__useDefaultFramebuffer=void 0===t},this.setRenderTarget=function(e,t=0,i=0){S=e,w=t,C=i;let n=!0,r=null,s=!1,a=!1;if(e){const o=ee.get(e);if(void 0!==o.__useDefaultFramebuffer)Z.bindFramebuffer(_e.FRAMEBUFFER,null),n=!1;else if(void 0===o.__webglFramebuffer)te.setupRenderTarget(e);else if(o.__hasExternalTextures)te.rebindTextures(e,ee.get(e.texture).__webglTexture,ee.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(o.__boundDepthTexture!==t){if(null!==t&&ee.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");te.setupDepthRenderbuffer(e)}}const l=e.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const c=ee.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][i]:c[t],s=!0):r=e.samples>0&&!1===te.useMultisampledRTT(e)?ee.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[i]:c,T.copy(e.viewport),I.copy(e.scissor),P=e.scissorTest}else T.copy(k).multiplyScalar(O).floor(),I.copy(N).multiplyScalar(O).floor(),P=j;if(Z.bindFramebuffer(_e.FRAMEBUFFER,r)&&n&&Z.drawBuffers(e,r),Z.viewport(T),Z.scissor(I),Z.setScissorTest(P),s){const n=ee.get(e.texture);_e.framebufferTexture2D(_e.FRAMEBUFFER,_e.COLOR_ATTACHMENT0,_e.TEXTURE_CUBE_MAP_POSITIVE_X+t,n.__webglTexture,i)}else if(a){const n=ee.get(e.texture),r=t||0;_e.framebufferTextureLayer(_e.FRAMEBUFFER,_e.COLOR_ATTACHMENT0,n.__webglTexture,i||0,r)}M=-1},this.readRenderTargetPixels=function(e,t,i,n,r,s,a,o){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=ee.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){Z.bindFramebuffer(_e.FRAMEBUFFER,l);try{const a=Array.isArray(e.textures)?e.textures[o||0]:e.texture,l=a.format,c=a.type;if(!J.textureFormatReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!J.textureTypeReadable(c))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-n&&i>=0&&i<=e.height-r&&((e.isWebGLMultipleRenderTargets||e.textures.length>1)&&_e.readBuffer(_e.COLOR_ATTACHMENT0+(o||0)),_e.readPixels(t,i,n,r,Ae.convert(l),Ae.convert(c),s))}finally{const e=S?ee.get(S).__webglFramebuffer:null;Z.bindFramebuffer(_e.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,i,n,r,s,a){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=ee.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){Z.bindFramebuffer(_e.FRAMEBUFFER,o);try{const a=e.texture,o=a.format,l=a.type;if(!J.textureFormatReadable(o))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!J.textureTypeReadable(l))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(t>=0&&t<=e.width-n&&i>=0&&i<=e.height-r){const e=_e.createBuffer();_e.bindBuffer(_e.PIXEL_PACK_BUFFER,e),_e.bufferData(_e.PIXEL_PACK_BUFFER,s.byteLength,_e.STREAM_READ),_e.readPixels(t,i,n,r,Ae.convert(o),Ae.convert(l),0),_e.flush();const a=_e.fenceSync(_e.SYNC_GPU_COMMANDS_COMPLETE,0);await function(e,t,i){return new Promise(function(n,r){setTimeout(function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:r();break;case e.TIMEOUT_EXPIRED:setTimeout(s,i);break;default:n()}},i)})}(_e,a,4);try{_e.bindBuffer(_e.PIXEL_PACK_BUFFER,e),_e.getBufferSubData(_e.PIXEL_PACK_BUFFER,0,s)}finally{_e.deleteBuffer(e),_e.deleteSync(a)}return s}}finally{const e=null!==S?ee.get(S).__webglFramebuffer:null;Z.bindFramebuffer(_e.FRAMEBUFFER,e)}}},this.copyFramebufferToTexture=function(e,t=null,i=0){!0!==e.isTexture&&(Si("WebGLRenderer: copyFramebufferToTexture function signature has changed."),t=arguments[0]||null,e=arguments[1]);const n=Math.pow(2,-i),r=Math.floor(e.image.width*n),s=Math.floor(e.image.height*n),a=null!==t?t.x:0,o=null!==t?t.y:0;te.setTexture2D(e,0),_e.copyTexSubImage2D(_e.TEXTURE_2D,i,0,0,a,o,r,s),Z.unbindTexture()},this.copyTextureToTexture=function(e,t,i=null,n=null,r=0){let s,a,o,l,c,h;!0!==e.isTexture&&(Si("WebGLRenderer: copyTextureToTexture function signature has changed."),n=arguments[0]||null,e=arguments[1],t=arguments[2],r=arguments[3]||0,i=null),null!==i?(s=i.max.x-i.min.x,a=i.max.y-i.min.y,o=i.min.x,l=i.min.y):(s=e.image.width,a=e.image.height,o=0,l=0),null!==n?(c=n.x,h=n.y):(c=0,h=0);const d=Ae.convert(t.format),u=Ae.convert(t.type);te.setTexture2D(t,0),_e.pixelStorei(_e.UNPACK_FLIP_Y_WEBGL,t.flipY),_e.pixelStorei(_e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),_e.pixelStorei(_e.UNPACK_ALIGNMENT,t.unpackAlignment);const p=_e.getParameter(_e.UNPACK_ROW_LENGTH),m=_e.getParameter(_e.UNPACK_IMAGE_HEIGHT),g=_e.getParameter(_e.UNPACK_SKIP_PIXELS),f=_e.getParameter(_e.UNPACK_SKIP_ROWS),A=_e.getParameter(_e.UNPACK_SKIP_IMAGES),y=e.isCompressedTexture?e.mipmaps[r]:e.image;_e.pixelStorei(_e.UNPACK_ROW_LENGTH,y.width),_e.pixelStorei(_e.UNPACK_IMAGE_HEIGHT,y.height),_e.pixelStorei(_e.UNPACK_SKIP_PIXELS,o),_e.pixelStorei(_e.UNPACK_SKIP_ROWS,l),e.isDataTexture?_e.texSubImage2D(_e.TEXTURE_2D,r,c,h,s,a,d,u,y.data):e.isCompressedTexture?_e.compressedTexSubImage2D(_e.TEXTURE_2D,r,c,h,y.width,y.height,d,y.data):_e.texSubImage2D(_e.TEXTURE_2D,r,c,h,s,a,d,u,y),_e.pixelStorei(_e.UNPACK_ROW_LENGTH,p),_e.pixelStorei(_e.UNPACK_IMAGE_HEIGHT,m),_e.pixelStorei(_e.UNPACK_SKIP_PIXELS,g),_e.pixelStorei(_e.UNPACK_SKIP_ROWS,f),_e.pixelStorei(_e.UNPACK_SKIP_IMAGES,A),0===r&&t.generateMipmaps&&_e.generateMipmap(_e.TEXTURE_2D),Z.unbindTexture()},this.copyTextureToTexture3D=function(e,t,i=null,n=null,r=0){let s,a,o,l,c,h,d,u,p;!0!==e.isTexture&&(Si("WebGLRenderer: copyTextureToTexture3D function signature has changed."),i=arguments[0]||null,n=arguments[1]||null,e=arguments[2],t=arguments[3],r=arguments[4]||0);const m=e.isCompressedTexture?e.mipmaps[r]:e.image;null!==i?(s=i.max.x-i.min.x,a=i.max.y-i.min.y,o=i.max.z-i.min.z,l=i.min.x,c=i.min.y,h=i.min.z):(s=m.width,a=m.height,o=m.depth,l=0,c=0,h=0),null!==n?(d=n.x,u=n.y,p=n.z):(d=0,u=0,p=0);const g=Ae.convert(t.format),f=Ae.convert(t.type);let A;if(t.isData3DTexture)te.setTexture3D(t,0),A=_e.TEXTURE_3D;else{if(!t.isDataArrayTexture&&!t.isCompressedArrayTexture)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");te.setTexture2DArray(t,0),A=_e.TEXTURE_2D_ARRAY}_e.pixelStorei(_e.UNPACK_FLIP_Y_WEBGL,t.flipY),_e.pixelStorei(_e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),_e.pixelStorei(_e.UNPACK_ALIGNMENT,t.unpackAlignment);const y=_e.getParameter(_e.UNPACK_ROW_LENGTH),v=_e.getParameter(_e.UNPACK_IMAGE_HEIGHT),_=_e.getParameter(_e.UNPACK_SKIP_PIXELS),b=_e.getParameter(_e.UNPACK_SKIP_ROWS),x=_e.getParameter(_e.UNPACK_SKIP_IMAGES);_e.pixelStorei(_e.UNPACK_ROW_LENGTH,m.width),_e.pixelStorei(_e.UNPACK_IMAGE_HEIGHT,m.height),_e.pixelStorei(_e.UNPACK_SKIP_PIXELS,l),_e.pixelStorei(_e.UNPACK_SKIP_ROWS,c),_e.pixelStorei(_e.UNPACK_SKIP_IMAGES,h),e.isDataTexture||e.isData3DTexture?_e.texSubImage3D(A,r,d,u,p,s,a,o,g,f,m.data):t.isCompressedArrayTexture?_e.compressedTexSubImage3D(A,r,d,u,p,s,a,o,g,m.data):_e.texSubImage3D(A,r,d,u,p,s,a,o,g,f,m),_e.pixelStorei(_e.UNPACK_ROW_LENGTH,y),_e.pixelStorei(_e.UNPACK_IMAGE_HEIGHT,v),_e.pixelStorei(_e.UNPACK_SKIP_PIXELS,_),_e.pixelStorei(_e.UNPACK_SKIP_ROWS,b),_e.pixelStorei(_e.UNPACK_SKIP_IMAGES,x),0===r&&t.generateMipmaps&&_e.generateMipmap(A),Z.unbindTexture()},this.initRenderTarget=function(e){void 0===ee.get(e).__webglFramebuffer&&te.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?te.setTextureCube(e,0):e.isData3DTexture?te.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?te.setTexture2DArray(e,0):te.setTexture2D(e,0),Z.unbindTexture()},this.resetState=function(){w=0,C=0,S=null,Z.reset(),ye.reset()},this.resetCurrentMaterial=function(){M=-1},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ti}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=e===Ft?"display-p3":"srgb",t.unpackColorSpace=Pi.workingColorSpace===kt?"display-p3":"srgb"}get useLegacyLights(){return this._useLegacyLights}set useLegacyLights(e){this._useLegacyLights=e}}class yl{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new mr(e),this.density=t}clone(){return new yl(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class vl{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new mr(e),this.near=t,this.far=i}clone(){return new vl(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class _l extends Zn{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 On,this.environmentIntensity=1,this.environmentRotation=new On,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class bl{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=$t,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=ci()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}get updateRange(){return Si("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,r=this.stride;n<r;n++)this.array[e+n]=t.array[i+n];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=ci()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(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 void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=ci()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(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 xl=new Xi;class wl{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++)xl.fromBufferAttribute(this,t),xl.applyMatrix4(e),this.setXYZ(t,xl.x,xl.y,xl.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)xl.fromBufferAttribute(this,t),xl.applyNormalMatrix(e),this.setXYZ(t,xl.x,xl.y,xl.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)xl.fromBufferAttribute(this,t),xl.transformDirection(e),this.setXYZ(t,xl.x,xl.y,xl.z);return this}getComponent(e,t){let i=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(i=pi(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=mi(i,this.array)),this.data.array[e*this.data.stride+this.offset+t]=i,this}setX(e,t){return this.normalized&&(t=mi(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=mi(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=mi(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=mi(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=pi(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=pi(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=pi(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=pi(t,this.array)),t}setXY(e,t,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=mi(t,this.array),i=mi(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=mi(t,this.array),i=mi(i,this.array),n=mi(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,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=mi(t,this.array),i=mi(i,this.array),n=mi(n,this.array),r=mi(r,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]=r,this}clone(e){if(void 0===e){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const i=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[i+t])}return new Mr(new this.array.constructor(e),this.itemSize,this.normalized)}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new wl(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const i=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[i+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(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 Cl extends Ar{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new mr(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 Sl;const Ml=new Xi,El=new Xi,Tl=new Xi,Il=new fi,Pl=new fi,Dl=new Sn,Rl=new Xi,Bl=new Xi,Ll=new Xi,Ol=new fi,Ul=new fi,Fl=new fi;class kl extends Zn{constructor(e=new Cl){if(super(),this.isSprite=!0,this.type="Sprite",void 0===Sl){Sl=new Fr;const e=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),t=new bl(e,5);Sl.setIndex([0,1,2,0,2,3]),Sl.setAttribute("position",new wl(t,3,0,!1)),Sl.setAttribute("uv",new wl(t,2,3,!1))}this.geometry=Sl,this.material=e,this.center=new fi(.5,.5)}raycast(e,t){null===e.camera&&console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),El.setFromMatrixScale(this.matrixWorld),Dl.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),Tl.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&!1===this.material.sizeAttenuation&&El.multiplyScalar(-Tl.z);const i=this.material.rotation;let n,r;0!==i&&(r=Math.cos(i),n=Math.sin(i));const s=this.center;Nl(Rl.set(-.5,-.5,0),Tl,s,El,n,r),Nl(Bl.set(.5,-.5,0),Tl,s,El,n,r),Nl(Ll.set(.5,.5,0),Tl,s,El,n,r),Ol.set(0,0),Ul.set(1,0),Fl.set(1,1);let a=e.ray.intersectTriangle(Rl,Bl,Ll,!1,Ml);if(null===a&&(Nl(Bl.set(-.5,.5,0),Tl,s,El,n,r),Ul.set(0,1),a=e.ray.intersectTriangle(Rl,Ll,Bl,!1,Ml),null===a))return;const o=e.ray.origin.distanceTo(Ml);o<e.near||o>e.far||t.push({distance:o,point:Ml.clone(),uv:cr.getInterpolation(Ml,Rl,Bl,Ll,Ol,Ul,Fl,new fi),face:null,object:this})}copy(e,t){return super.copy(e,t),void 0!==e.center&&this.center.copy(e.center),this.material=e.material,this}}function Nl(e,t,i,n,r,s){Il.subVectors(e,i).addScalar(.5).multiply(n),void 0!==r?(Pl.x=s*Il.x-r*Il.y,Pl.y=r*Il.x+s*Il.y):Pl.copy(Il),e.copy(t),e.x+=Pl.x,e.y+=Pl.y,e.applyMatrix4(Dl)}const jl=new Xi,zl=new Xi;class Gl extends Zn{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 e=0,i=t.length;e<i;e++){const i=t[e];this.addLevel(i.object.clone(),i.distance,i.hysteresis)}return this.autoUpdate=e.autoUpdate,this}addLevel(e,t=0,i=0){t=Math.abs(t);const n=this.levels;let r;for(r=0;r<n.length&&!(t<n[r].distance);r++);return n.splice(r,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 n=t[i].distance;if(t[i].object.visible&&(n-=n*t[i].hysteresis),e<n)break}return t[i-1].object}return null}raycast(e,t){if(this.levels.length>0){jl.setFromMatrixPosition(this.matrixWorld);const i=e.ray.origin.distanceTo(jl);this.getObjectForDistance(i).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){jl.setFromMatrixPosition(e.matrixWorld),zl.setFromMatrixPosition(this.matrixWorld);const i=jl.distanceTo(zl)/e.zoom;let n,r;for(t[0].object.visible=!0,n=1,r=t.length;n<r;n++){let e=t[n].distance;if(t[n].object.visible&&(e-=e*t[n].hysteresis),!(i>=e))break;t[n-1].object.visible=!1,t[n].object.visible=!0}for(this._currentLevel=n-1;n<r;n++)t[n].object.visible=!1}}toJSON(e){const t=super.toJSON(e);!1===this.autoUpdate&&(t.object.autoUpdate=!1),t.object.levels=[];const i=this.levels;for(let e=0,n=i.length;e<n;e++){const n=i[e];t.object.levels.push({object:n.object.uuid,distance:n.distance,hysteresis:n.hysteresis})}return t}}const Ql=new Xi,Vl=new Gi,Hl=new Gi,Wl=new Xi,ql=new Sn,Xl=new Xi,Yl=new fn,Kl=new Sn,Jl=new Cn;class Zl extends ts{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=le,this.bindMatrix=new Sn,this.bindMatrixInverse=new Sn,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const e=this.geometry;null===this.boundingBox&&(this.boundingBox=new Ji),this.boundingBox.makeEmpty();const t=e.getAttribute("position");for(let e=0;e<t.count;e++)this.getVertexPosition(e,Xl),this.boundingBox.expandByPoint(Xl)}computeBoundingSphere(){const e=this.geometry;null===this.boundingSphere&&(this.boundingSphere=new fn),this.boundingSphere.makeEmpty();const t=e.getAttribute("position");for(let e=0;e<t.count;e++)this.getVertexPosition(e,Xl),this.boundingSphere.expandByPoint(Xl)}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,null!==e.boundingBox&&(this.boundingBox=e.boundingBox.clone()),null!==e.boundingSphere&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){const i=this.material,n=this.matrixWorld;void 0!==i&&(null===this.boundingSphere&&this.computeBoundingSphere(),Yl.copy(this.boundingSphere),Yl.applyMatrix4(n),!1!==e.ray.intersectsSphere(Yl)&&(Kl.copy(n).invert(),Jl.copy(e.ray).applyMatrix4(Kl),(null===this.boundingBox||!1!==Jl.intersectsBox(this.boundingBox))&&this._computeIntersections(e,t,Jl)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,void 0===t&&(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 Gi,t=this.geometry.attributes.skinWeight;for(let i=0,n=t.count;i<n;i++){e.fromBufferAttribute(t,i);const n=1/e.manhattanLength();n!==1/0?e.multiplyScalar(n):e.set(1,0,0,0),t.setXYZW(i,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===le?this.bindMatrixInverse.copy(this.matrixWorld).invert():"detached"===this.bindMode?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){const i=this.skeleton,n=this.geometry;Vl.fromBufferAttribute(n.attributes.skinIndex,e),Hl.fromBufferAttribute(n.attributes.skinWeight,e),Ql.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let e=0;e<4;e++){const n=Hl.getComponent(e);if(0!==n){const r=Vl.getComponent(e);ql.multiplyMatrices(i.bones[r].matrixWorld,i.boneInverses[r]),t.addScaledVector(Wl.copy(Ql).applyMatrix4(ql),n)}}return t.applyMatrix4(this.bindMatrixInverse)}}class $l extends Zn{constructor(){super(),this.isBone=!0,this.type="Bone"}}class ec extends Ni{constructor(e=null,t=1,i=1,n,r,s,a,o,l=ye,c=ye,h,d){super(null,s,a,o,l,c,n,r,h,d),this.isDataTexture=!0,this.image={data:e,width:t,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const tc=new Sn,ic=new Sn;class nc{constructor(e=[],t=[]){this.uuid=ci(),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(16*e.length),0===t.length)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 e=0,t=this.bones.length;e<t;e++)this.boneInverses.push(new Sn)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){const t=new Sn;this.bones[e]&&t.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(t)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){const t=this.bones[e];t&&t.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){const t=this.bones[e];t&&(t.parent&&t.parent.isBone?(t.matrix.copy(t.parent.matrixWorld).invert(),t.matrix.multiply(t.matrixWorld)):t.matrix.copy(t.matrixWorld),t.matrix.decompose(t.position,t.quaternion,t.scale))}}update(){const e=this.bones,t=this.boneInverses,i=this.boneMatrices,n=this.boneTexture;for(let n=0,r=e.length;n<r;n++){const r=e[n]?e[n].matrixWorld:ic;tc.multiplyMatrices(r,t[n]),tc.toArray(i,16*n)}null!==n&&(n.needsUpdate=!0)}clone(){return new nc(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(4*this.bones.length);e=4*Math.ceil(e/4),e=Math.max(e,4);const t=new Float32Array(e*e*4);t.set(this.boneMatrices);const i=new ec(t,e,e,Ue,Pe);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 i=this.bones[t];if(i.name===e)return i}}dispose(){null!==this.boneTexture&&(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 n=e.bones[i];let r=t[n];void 0===r&&(console.warn("THREE.Skeleton: No bone found with UUID:",n),r=new $l),this.bones.push(r),this.boneInverses.push((new Sn).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,r=t.length;n<r;n++){const r=t[n];e.bones.push(r.uuid);const s=i[n];e.boneInverses.push(s.toArray())}return e}}class rc extends Mr{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 sc=new Sn,ac=new Sn,oc=[],lc=new Ji,cc=new Sn,hc=new ts,dc=new fn;class uc extends ts{constructor(e,t,i){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new rc(new Float32Array(16*i),16),this.instanceColor=null,this.morphTexture=null,this.sourceTrs=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let e=0;e<i;e++)this.setMatrixAt(e,cc)}computeBoundingBox(){const e=this.geometry,t=this.count;null===this.boundingBox&&(this.boundingBox=new Ji),null===e.boundingBox&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,sc),lc.copy(e.boundingBox).applyMatrix4(sc),this.boundingBox.union(lc)}computeBoundingSphere(){const e=this.geometry,t=this.count;null===this.boundingSphere&&(this.boundingSphere=new fn),null===e.boundingSphere&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,sc),dc.copy(e.boundingSphere).applyMatrix4(sc),this.boundingSphere.union(dc)}copy(e,t){return super.copy(e,t),e.isInstancedMesh?(this.instanceMatrix.copy(e.instanceMatrix),null!==e.morphTexture&&(this.morphTexture=e.morphTexture.clone()),null!==e.instanceColor&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,null!==e.boundingBox&&(this.boundingBox=e.boundingBox.clone()),null!==e.boundingSphere&&(this.boundingSphere=e.boundingSphere.clone()),this):this}getColorAt(e,t){t.fromArray(this.instanceColor.array,3*e)}getMatrixAt(e,t){t.fromArray(this.instanceMatrix.array,16*e)}getMorphAt(e,t){const i=t.morphTargetInfluences,n=this.morphTexture.source.data.data,r=e*(i.length+1)+1;for(let e=0;e<i.length;e++)i[e]=n[r+e]}raycast(e,t){const i=this.matrixWorld,n=this.count;if(hc.geometry=this.geometry,hc.material=this.material,void 0!==hc.material&&(null===this.boundingSphere&&this.computeBoundingSphere(),dc.copy(this.boundingSphere),dc.applyMatrix4(i),!1!==e.ray.intersectsSphere(dc)))for(let r=0;r<n;r++){this.getMatrixAt(r,sc),ac.multiplyMatrices(i,sc),hc.matrixWorld=ac,hc.raycast(e,oc);for(let e=0,i=oc.length;e<i;e++){const i=oc[e];i.instanceId=r,i.object=this,t.push(i)}oc.length=0}}setColorAt(e,t){null===this.instanceColor&&(this.instanceColor=new rc(new Float32Array(3*this.instanceMatrix.count).fill(1),3)),t.toArray(this.instanceColor.array,3*e)}setMatrixAt(e,t){t.toArray(this.instanceMatrix.array,16*e)}setMorphAt(e,t){const i=t.morphTargetInfluences,n=i.length+1;null===this.morphTexture&&(this.morphTexture=new ec(new Float32Array(n*this.count),n,this.count,Ne,Pe));const r=this.morphTexture.source.data.data;let s=0;for(let e=0;e<i.length;e++)s+=i[e];const a=this.geometry.morphTargetsRelative?1:1-s,o=n*e;r[o]=a,r.set(i,o+1)}updateMorphTargets(){}dispose(){return this.dispatchEvent({type:"dispose"}),null!==this.morphTexture&&(this.morphTexture.dispose(),this.morphTexture=null),this}}function pc(e,t){return e.z-t.z}function mc(e,t){return t.z-e.z}const gc=new Sn,fc=new Sn,Ac=new Sn,yc=new mr(1,1,1),vc=new Sn,_c=new Cs,bc=new Ji,xc=new fn,wc=new Xi,Cc=new Xi,Sc=new Xi,Mc=new class{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,t,i){const n=this.pool,r=this.list;this.index>=n.length&&n.push({start:-1,count:-1,z:-1,index:-1});const s=n[this.index];r.push(s),this.index++,s.start=e.start,s.count=e.count,s.z=t,s.index=i}reset(){this.list.length=0,this.index=0}},Ec=new ts,Tc=[];function Ic(e,t,i=0){const n=t.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==t.array.constructor){const r=e.count;for(let s=0;s<r;s++)for(let r=0;r<n;r++)t.setComponent(s+i,r,e.getComponent(s,r))}else t.array.set(e.array,i*n);t.needsUpdate=!0}class Pc extends ts{get maxInstanceCount(){return this._maxInstanceCount}constructor(e,t,i=2*t,n){super(new Fr,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(4*this._maxInstanceCount);e=4*Math.ceil(e/4),e=Math.max(e,4);const t=new Float32Array(e*e*4),i=new ec(t,e,e,Ue,Pe);this._matricesTexture=i}_initIndirectTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);const t=new Uint32Array(e*e),i=new ec(t,e,e,je,Ie);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 ec(t,e,e,Ue,Pe);i.colorSpace=Pi.workingColorSpace,this._colorsTexture=i}_initializeGeometry(e){const t=this.geometry,i=this._maxVertexCount,n=this._maxIndexCount;if(!1===this._geometryInitialized){for(const n in e.attributes){const r=e.getAttribute(n),{array:s,itemSize:a,normalized:o}=r,l=new s.constructor(i*a),c=new Mr(l,a,o);t.setAttribute(n,c)}if(null!==e.getIndex()){const e=i>65535?new Uint32Array(n):new Uint16Array(n);t.setIndex(new Mr(e,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),r=t.getAttribute(i);if(n.itemSize!==r.itemSize||n.normalized!==r.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Ji);const e=this.boundingBox,t=this._drawInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){if(!1===t[i].active)continue;const n=t[i].geometryIndex;this.getMatrixAt(i,gc),this.getBoundingBoxAt(n,bc).applyMatrix4(gc),e.union(bc)}}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new fn);const e=this.boundingSphere,t=this._drawInfo;e.makeEmpty();for(let i=0,n=t.length;i<n;i++){if(!1===t[i].active)continue;const n=t[i].geometryIndex;this.getMatrixAt(i,gc),this.getBoundingSphereAt(n,xc).applyMatrix4(gc),e.union(xc)}}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;Ac.toArray(n,16*t),i.needsUpdate=!0;const r=this._colorsTexture;return r&&(yc.toArray(r.image.data,4*t),r.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 r=null;const s=this._reservedRanges,a=this._drawRanges,o=this._bounds;0!==this._geometryCount&&(r=s[s.length-1]),n.vertexCount=-1===t?e.getAttribute("position").count:t,n.vertexStart=null===r?0:r.vertexStart+r.vertexCount;const l=e.getIndex(),c=null!==l;if(c&&(n.indexCount=-1===i?l.count:i,n.indexStart=null===r?0:r.indexStart+r.indexCount),-1!==n.indexStart&&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 h=this._geometryCount;return this._geometryCount++,s.push(n),a.push({start:c?n.indexStart:n.vertexStart,count:-1}),o.push({boxInitialized:!1,box:new Ji,sphereInitialized:!1,sphere:new fn}),this.setGeometryAt(h,e),h}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=null!==i.getIndex(),r=i.getIndex(),s=t.getIndex(),a=this._reservedRanges[e];if(n&&s.count>a.indexCount||t.attributes.position.count>a.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const o=a.vertexStart,l=a.vertexCount;for(const e in i.attributes){const n=t.getAttribute(e),r=i.getAttribute(e);Ic(n,r,o);const s=n.itemSize;for(let e=n.count,t=l;e<t;e++){const t=o+e;for(let e=0;e<s;e++)r.setComponent(t,e,0)}r.needsUpdate=!0,r.addUpdateRange(o*s,l*s)}if(n){const e=a.indexStart;for(let t=0;t<s.count;t++)r.setX(e+t,o+s.getX(t));for(let t=s.count,i=a.indexCount;t<i;t++)r.setX(e+t,o);r.needsUpdate=!0,r.addUpdateRange(e,a.indexCount)}const c=this._bounds[e];null!==t.boundingBox?(c.box.copy(t.boundingBox),c.boxInitialized=!0):c.boxInitialized=!1,null!==t.boundingSphere?(c.sphere.copy(t.boundingSphere),c.sphereInitialized=!0):c.sphereInitialized=!1;const h=this._drawRanges[e],d=t.getAttribute("position");return h.count=n?s.count:d.count,this._visibilityChanged=!0,e}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;const i=this._bounds[e],n=i.box,r=this.geometry;if(!1===i.boxInitialized){n.makeEmpty();const t=r.index,s=r.attributes.position,a=this._drawRanges[e];for(let e=a.start,i=a.start+a.count;e<i;e++){let i=e;t&&(i=t.getX(i)),n.expandByPoint(wc.fromBufferAttribute(s,i))}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,r=this.geometry;if(!1===i.sphereInitialized){n.makeEmpty(),this.getBoundingBoxAt(e,bc),bc.getCenter(n.center);const t=r.index,s=r.attributes.position,a=this._drawRanges[e];let o=0;for(let e=a.start,i=a.start+a.count;e<i;e++){let i=e;t&&(i=t.getX(i)),wc.fromBufferAttribute(s,i),o=Math.max(o,n.center.distanceToSquared(wc))}n.radius=Math.sqrt(o),i.sphereInitialized=!0}return t.copy(n),t}setMatrixAt(e,t){const i=this._drawInfo,n=this._matricesTexture,r=this._matricesTexture.image.data;return e>=i.length||!1===i[e].active||(t.toArray(r,16*e),n.needsUpdate=!0),this}getMatrixAt(e,t){const i=this._drawInfo,n=this._matricesTexture.image.data;return e>=i.length||!1===i[e].active?null:t.fromArray(n,16*e)}setColorAt(e,t){null===this._colorsTexture&&this._initColorsTexture();const i=this._colorsTexture,n=this._colorsTexture.image.data,r=this._drawInfo;return e>=r.length||!1===r[e].active||(t.toArray(n,4*e),i.needsUpdate=!0),this}getColorAt(e,t){const i=this._colorsTexture.image.data,n=this._drawInfo;return e>=n.length||!1===n[e].active?null:t.fromArray(i,4*e)}setVisibleAt(e,t){const i=this._drawInfo;return e>=i.length||!1===i[e].active||i[e].visible===t||(i[e].visible=t,this._visibilityChanged=!0),this}getVisibleAt(e){const t=this._drawInfo;return!(e>=t.length||!1===t[e].active)&&t[e].visible}raycast(e,t){const i=this._drawInfo,n=this._drawRanges,r=this.matrixWorld,s=this.geometry;Ec.material=this.material,Ec.geometry.index=s.index,Ec.geometry.attributes=s.attributes,null===Ec.geometry.boundingBox&&(Ec.geometry.boundingBox=new Ji),null===Ec.geometry.boundingSphere&&(Ec.geometry.boundingSphere=new fn);for(let s=0,a=i.length;s<a;s++){if(!i[s].visible||!i[s].active)continue;const a=i[s].geometryIndex,o=n[a];Ec.geometry.setDrawRange(o.start,o.count),this.getMatrixAt(s,Ec.matrixWorld).premultiply(r),this.getBoundingBoxAt(a,Ec.geometry.boundingBox),this.getBoundingSphereAt(a,Ec.geometry.boundingSphere),Ec.raycast(e,Tc);for(let e=0,i=Tc.length;e<i;e++){const i=Tc[e];i.object=this,i.batchId=s,t.push(i)}Tc.length=0}Ec.material=null,Ec.geometry.index=null,Ec.geometry.attributes={},Ec.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=null!==e.boundingBox?e.boundingBox.clone():null,this.boundingSphere=null!==e.boundingSphere?e.boundingSphere.clone():null,this._drawRanges=e._drawRanges.map(e=>({...e})),this._reservedRanges=e._reservedRanges.map(e=>({...e})),this._drawInfo=e._drawInfo.map(e=>({...e})),this._bounds=e._bounds.map(e=>({boxInitialized:e.boxInitialized,box:e.box.clone(),sphereInitialized:e.sphereInitialized,sphere:e.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(),null!==this._colorsTexture&&(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,null!==this._colorsTexture&&(this._colorsTexture.dispose(),this._colorsTexture=null),this}onBeforeRender(e,t,i,n,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const s=n.getIndex(),a=null===s?1:s.array.BYTES_PER_ELEMENT,o=this._drawInfo,l=this._multiDrawStarts,c=this._multiDrawCounts,h=this._drawRanges,d=this.perObjectFrustumCulled,u=this._indirectTexture,p=u.image.data;d&&(vc.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),_c.setFromProjectionMatrix(vc,e.coordinateSystem));let m=0;if(this.sortObjects){fc.copy(this.matrixWorld).invert(),wc.setFromMatrixPosition(i.matrixWorld).applyMatrix4(fc),Cc.set(0,0,-1).transformDirection(i.matrixWorld).transformDirection(fc);for(let e=0,t=o.length;e<t;e++)if(o[e].visible&&o[e].active){const t=o[e].geometryIndex;this.getMatrixAt(e,gc),this.getBoundingSphereAt(t,xc).applyMatrix4(gc);let i=!1;if(d&&(i=!_c.intersectsSphere(xc)),!i){const i=Sc.subVectors(xc.center,wc).dot(Cc);Mc.push(h[t],i,e)}}const e=Mc.list,t=this.customSort;null===t?e.sort(r.transparent?mc:pc):t.call(this,e,i);for(let t=0,i=e.length;t<i;t++){const i=e[t];l[m]=i.start*a,c[m]=i.count,p[m]=i.index,m++}Mc.reset()}else for(let e=0,t=o.length;e<t;e++)if(o[e].visible&&o[e].active){const t=o[e].geometryIndex;let i=!1;if(d&&(this.getMatrixAt(e,gc),this.getBoundingSphereAt(t,xc).applyMatrix4(gc),i=!_c.intersectsSphere(xc)),!i){const i=h[t];l[m]=i.start*a,c[m]=i.count,p[m]=e,m++}}u.needsUpdate=!0,this._multiDrawCount=m,this._visibilityChanged=!1}onBeforeShadow(e,t,i,n,r,s){this.onBeforeRender(e,null,n,r,s)}}class Dc extends Ar{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new mr(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 Rc=new Xi,Bc=new Xi,Lc=new Sn,Oc=new Cn,Uc=new fn,Fc=new Xi,kc=new Xi;class Nc extends Zn{constructor(e=new Fr,t=new Dc){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(null===e.index){const t=e.attributes.position,i=[0];for(let e=1,n=t.count;e<n;e++)Rc.fromBufferAttribute(t,e-1),Bc.fromBufferAttribute(t,e),i[e]=i[e-1],i[e]+=Rc.distanceTo(Bc);e.setAttribute("lineDistance",new Ir(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,r=e.params.Line.threshold,s=i.drawRange;if(null===i.boundingSphere&&i.computeBoundingSphere(),Uc.copy(i.boundingSphere),Uc.applyMatrix4(n),Uc.radius+=r,!1===e.ray.intersectsSphere(Uc))return;Lc.copy(n).invert(),Oc.copy(e.ray).applyMatrix4(Lc);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=this.isLineSegments?2:1,c=i.index,h=i.attributes.position;if(null!==c){const i=Math.max(0,s.start),n=Math.min(c.count,s.start+s.count);for(let r=i,s=n-1;r<s;r+=l){const i=c.getX(r),n=c.getX(r+1),s=jc(this,e,Oc,o,i,n);s&&t.push(s)}if(this.isLineLoop){const r=c.getX(n-1),s=c.getX(i),a=jc(this,e,Oc,o,r,s);a&&t.push(a)}}else{const i=Math.max(0,s.start),n=Math.min(h.count,s.start+s.count);for(let r=i,s=n-1;r<s;r+=l){const i=jc(this,e,Oc,o,r,r+1);i&&t.push(i)}if(this.isLineLoop){const r=jc(this,e,Oc,o,n-1,i);r&&t.push(r)}}}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const i=e[t[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=i.length;e<t;e++){const t=i[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}}function jc(e,t,i,n,r,s){const a=e.geometry.attributes.position;if(Rc.fromBufferAttribute(a,r),Bc.fromBufferAttribute(a,s),i.distanceSqToSegment(Rc,Bc,Fc,kc)>n)return;Fc.applyMatrix4(e.matrixWorld);const o=t.ray.origin.distanceTo(Fc);return o<t.near||o>t.far?void 0:{distance:o,point:kc.clone().applyMatrix4(e.matrixWorld),index:r,face:null,faceIndex:null,object:e}}const zc=new Xi,Gc=new Xi;class Qc extends Nc{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,i=[];for(let e=0,n=t.count;e<n;e+=2)zc.fromBufferAttribute(t,e),Gc.fromBufferAttribute(t,e+1),i[e]=0===e?0:i[e-1],i[e+1]=i[e]+zc.distanceTo(Gc);e.setAttribute("lineDistance",new Ir(i,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class Vc extends Nc{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}}class Hc extends Ar{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new mr(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 Wc=new Sn,qc=new Cn,Xc=new fn,Yc=new Xi;class Kc extends Zn{constructor(e=new Fr,t=new Hc){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,r=e.params.Points.threshold,s=i.drawRange;if(null===i.boundingSphere&&i.computeBoundingSphere(),Xc.copy(i.boundingSphere),Xc.applyMatrix4(n),Xc.radius+=r,!1===e.ray.intersectsSphere(Xc))return;Wc.copy(n).invert(),qc.copy(e.ray).applyMatrix4(Wc);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=i.index,c=i.attributes.position;if(null!==l){for(let i=Math.max(0,s.start),r=Math.min(l.count,s.start+s.count);i<r;i++){const r=l.getX(i);Yc.fromBufferAttribute(c,r),Jc(Yc,r,o,n,e,t,this)}}else{for(let i=Math.max(0,s.start),r=Math.min(c.count,s.start+s.count);i<r;i++)Yc.fromBufferAttribute(c,i),Jc(Yc,i,o,n,e,t,this)}}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const i=e[t[0]];if(void 0!==i){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=i.length;e<t;e++){const t=i[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}}function Jc(e,t,i,n,r,s,a){const o=qc.distanceSqToPoint(e);if(o<i){const i=new Xi;qc.closestPointToPoint(e,i),i.applyMatrix4(n);const l=r.ray.origin.distanceTo(i);if(l<r.near||l>r.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:i,index:t,face:null,object:a})}}class Zc extends Ni{constructor(e,t,i,n,r,s,a,o,l){super(e,t,i,n,r,s,a,o,l),this.isVideoTexture=!0,this.minFilter=void 0!==s?s:be,this.magFilter=void 0!==r?r:be,this.generateMipmaps=!1;const c=this;"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback(function t(){c.needsUpdate=!0,e.requestVideoFrameCallback(t)})}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 $c extends Ni{constructor(e,t,i,n,r,s,a,o,l,c,h,d){super(null,s,a,o,l,c,n,r,h,d),this.isCompressedTexture=!0,this.image={width:t,height:i},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}}class eh extends $c{constructor(e,t,i,n,r,s){super(e,t,i,r,s),this.isCompressedArrayTexture=!0,this.image.depth=n,this.wrapR=fe,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class th extends $c{constructor(e,t,i){super(void 0,e[0].width,e[0].height,t,i,he),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}}class ih extends Ni{constructor(e,t,i,n,r,s,a,o,l){super(e,t,i,n,r,s,a,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class nh{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),r=0;t.push(0);for(let s=1;s<=e;s++)i=this.getPoint(s/e),r+=i.distanceTo(n),t.push(r),n=i;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t){const i=this.getLengths();let n=0;const r=i.length;let s;s=t||e*i[r-1];let a,o=0,l=r-1;for(;o<=l;)if(n=Math.floor(o+(l-o)/2),a=i[n]-s,a<0)o=n+1;else{if(!(a>0)){l=n;break}l=n-1}if(n=l,i[n]===s)return n/(r-1);const c=i[n];return(n+(s-c)/(i[n+1]-c))/(r-1)}getTangent(e,t){let i=e-1e-4,n=e+1e-4;i<0&&(i=0),n>1&&(n=1);const r=this.getPoint(i),s=this.getPoint(n),a=t||(r.isVector2?new fi:new Xi);return a.copy(s).sub(r).normalize(),a}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t){const i=new Xi,n=[],r=[],s=[],a=new Xi,o=new Sn;for(let t=0;t<=e;t++){const i=t/e;n[t]=this.getTangentAt(i,new Xi)}r[0]=new Xi,s[0]=new Xi;let l=Number.MAX_VALUE;const c=Math.abs(n[0].x),h=Math.abs(n[0].y),d=Math.abs(n[0].z);c<=l&&(l=c,i.set(1,0,0)),h<=l&&(l=h,i.set(0,1,0)),d<=l&&i.set(0,0,1),a.crossVectors(n[0],i).normalize(),r[0].crossVectors(n[0],a),s[0].crossVectors(n[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),s[t]=s[t-1].clone(),a.crossVectors(n[t-1],n[t]),a.length()>Number.EPSILON){a.normalize();const e=Math.acos(hi(n[t-1].dot(n[t]),-1,1));r[t].applyMatrix4(o.makeRotationAxis(a,e))}s[t].crossVectors(n[t],r[t])}if(!0===t){let t=Math.acos(hi(r[0].dot(r[e]),-1,1));t/=e,n[0].dot(a.crossVectors(r[0],r[e]))>0&&(t=-t);for(let i=1;i<=e;i++)r[i].applyMatrix4(o.makeRotationAxis(n[i],t*i)),s[i].crossVectors(n[i],r[i])}return{tangents:n,normals:r,binormals:s}}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 rh extends nh{constructor(e=0,t=0,i=1,n=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=n,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(e,t=new fi){const i=t,n=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)<Number.EPSILON;for(;r<0;)r+=n;for(;r>n;)r-=n;r<Number.EPSILON&&(r=s?0:n),!0===this.aClockwise&&!s&&(r===n?r=-n:r-=n);const a=this.aStartAngle+e*r;let o=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(0!==this.aRotation){const e=Math.cos(this.aRotation),t=Math.sin(this.aRotation),i=o-this.aX,n=l-this.aY;o=i*e-n*t+this.aX,l=i*t+n*e+this.aY}return i.set(o,l)}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 sh extends rh{constructor(e,t,i,n,r,s){super(e,t,i,i,n,r,s),this.isArcCurve=!0,this.type="ArcCurve"}}function ah(){let e=0,t=0,i=0,n=0;function r(r,s,a,o){e=r,t=a,i=-3*r+3*s-2*a-o,n=2*r-2*s+a+o}return{initCatmullRom:function(e,t,i,n,s){r(t,i,s*(i-e),s*(n-t))},initNonuniformCatmullRom:function(e,t,i,n,s,a,o){let l=(t-e)/s-(i-e)/(s+a)+(i-t)/a,c=(i-t)/a-(n-t)/(a+o)+(n-i)/o;l*=a,c*=a,r(t,i,l,c)},calc:function(r){const s=r*r;return e+t*r+i*s+n*(s*r)}}}const oh=new Xi,lh=new ah,ch=new ah,hh=new ah;class dh extends nh{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 Xi){const i=t,n=this.points,r=n.length,s=(r-(this.closed?0:1))*e;let a,o,l=Math.floor(s),c=s-l;this.closed?l+=l>0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===c&&l===r-1&&(l=r-2,c=1),this.closed||l>0?a=n[(l-1)%r]:(oh.subVectors(n[0],n[1]).add(n[0]),a=oh);const h=n[l%r],d=n[(l+1)%r];if(this.closed||l+2<r?o=n[(l+2)%r]:(oh.subVectors(n[r-1],n[r-2]).add(n[r-1]),o=oh),"centripetal"===this.curveType||"chordal"===this.curveType){const e="chordal"===this.curveType?.5:.25;let t=Math.pow(a.distanceToSquared(h),e),i=Math.pow(h.distanceToSquared(d),e),n=Math.pow(d.distanceToSquared(o),e);i<1e-4&&(i=1),t<1e-4&&(t=i),n<1e-4&&(n=i),lh.initNonuniformCatmullRom(a.x,h.x,d.x,o.x,t,i,n),ch.initNonuniformCatmullRom(a.y,h.y,d.y,o.y,t,i,n),hh.initNonuniformCatmullRom(a.z,h.z,d.z,o.z,t,i,n)}else"catmullrom"===this.curveType&&(lh.initCatmullRom(a.x,h.x,d.x,o.x,this.tension),ch.initCatmullRom(a.y,h.y,d.y,o.y,this.tension),hh.initCatmullRom(a.z,h.z,d.z,o.z,this.tension));return i.set(lh.calc(c),ch.calc(c),hh.calc(c)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const i=e.points[t];this.points.push(i.clone())}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,i=this.points.length;t<i;t++){const i=this.points[t];e.points.push(i.toArray())}return e.closed=this.closed,e.curveType=this.curveType,e.tension=this.tension,e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const i=e.points[t];this.points.push((new Xi).fromArray(i))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}}function uh(e,t,i,n,r){const s=.5*(n-t),a=.5*(r-i),o=e*e;return(2*i-2*n+s+a)*(e*o)+(-3*i+3*n-2*s-a)*o+s*e+i}function ph(e,t,i,n){return function(e,t){const i=1-e;return i*i*t}(e,t)+function(e,t){return 2*(1-e)*e*t}(e,i)+function(e,t){return e*e*t}(e,n)}function mh(e,t,i,n,r){return function(e,t){const i=1-e;return i*i*i*t}(e,t)+function(e,t){const i=1-e;return 3*i*i*e*t}(e,i)+function(e,t){return 3*(1-e)*e*e*t}(e,n)+function(e,t){return e*e*e*t}(e,r)}class gh extends nh{constructor(e=new fi,t=new fi,i=new fi,n=new fi){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=i,this.v3=n}getPoint(e,t=new fi){const i=t,n=this.v0,r=this.v1,s=this.v2,a=this.v3;return i.set(mh(e,n.x,r.x,s.x,a.x),mh(e,n.y,r.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.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 fh extends nh{constructor(e=new Xi,t=new Xi,i=new Xi,n=new Xi){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=i,this.v3=n}getPoint(e,t=new Xi){const i=t,n=this.v0,r=this.v1,s=this.v2,a=this.v3;return i.set(mh(e,n.x,r.x,s.x,a.x),mh(e,n.y,r.y,s.y,a.y),mh(e,n.z,r.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.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 Ah extends nh{constructor(e=new fi,t=new fi){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new fi){const i=t;return 1===e?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 fi){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 yh extends nh{constructor(e=new Xi,t=new Xi){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new Xi){const i=t;return 1===e?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 Xi){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 vh extends nh{constructor(e=new fi,t=new fi,i=new fi){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=i}getPoint(e,t=new fi){const i=t,n=this.v0,r=this.v1,s=this.v2;return i.set(ph(e,n.x,r.x,s.x),ph(e,n.y,r.y,s.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 _h extends nh{constructor(e=new Xi,t=new Xi,i=new Xi){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=i}getPoint(e,t=new Xi){const i=t,n=this.v0,r=this.v1,s=this.v2;return i.set(ph(e,n.x,r.x,s.x),ph(e,n.y,r.y,s.y),ph(e,n.z,r.z,s.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 bh extends nh{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new fi){const i=t,n=this.points,r=(n.length-1)*e,s=Math.floor(r),a=r-s,o=n[0===s?s:s-1],l=n[s],c=n[s>n.length-2?n.length-1:s+1],h=n[s>n.length-3?n.length-1:s+2];return i.set(uh(a,o.x,l.x,c.x,h.x),uh(a,o.y,l.y,c.y,h.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const i=e.points[t];this.points.push(i.clone())}return this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,i=this.points.length;t<i;t++){const i=this.points[t];e.points.push(i.toArray())}return e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,i=e.points.length;t<i;t++){const i=e.points[t];this.points.push((new fi).fromArray(i))}return this}}var xh=Object.freeze({__proto__:null,ArcCurve:sh,CatmullRomCurve3:dh,CubicBezierCurve:gh,CubicBezierCurve3:fh,EllipseCurve:rh,LineCurve:Ah,LineCurve3:yh,QuadraticBezierCurve:vh,QuadraticBezierCurve3:_h,SplineCurve:bh});class wh extends nh{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=!0===e.isVector2?"LineCurve":"LineCurve3";this.curves.push(new xh[i](t,e))}return this}getPoint(e,t){const i=e*this.getLength(),n=this.getCurveLengths();let r=0;for(;r<n.length;){if(n[r]>=i){const e=n[r]-i,s=this.curves[r],a=s.getLength(),o=0===a?0:1-e/a;return s.getPointAt(o,t)}r++}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,r=this.curves;n<r.length;n++){const s=r[n],a=s.isEllipseCurve?2*e:s.isLineCurve||s.isLineCurve3?1:s.isSplineCurve?e*s.points.length:e,o=s.getPoints(a);for(let e=0;e<o.length;e++){const n=o[e];i&&i.equals(n)||(t.push(n),i=n)}}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 i=e.curves[t];this.curves.push(i.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 i=this.curves[t];e.curves.push(i.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 i=e.curves[t];this.curves.push((new xh[i.type]).fromJSON(i))}return this}}class Ch extends wh{constructor(e){super(),this.type="Path",this.currentPoint=new fi,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 Ah(this.currentPoint.clone(),new fi(e,t));return this.curves.push(i),this.currentPoint.set(e,t),this}quadraticCurveTo(e,t,i,n){const r=new vh(this.currentPoint.clone(),new fi(e,t),new fi(i,n));return this.curves.push(r),this.currentPoint.set(i,n),this}bezierCurveTo(e,t,i,n,r,s){const a=new gh(this.currentPoint.clone(),new fi(e,t),new fi(i,n),new fi(r,s));return this.curves.push(a),this.currentPoint.set(r,s),this}splineThru(e){const t=[this.currentPoint.clone()].concat(e),i=new bh(t);return this.curves.push(i),this.currentPoint.copy(e[e.length-1]),this}arc(e,t,i,n,r,s){const a=this.currentPoint.x,o=this.currentPoint.y;return this.absarc(e+a,t+o,i,n,r,s),this}absarc(e,t,i,n,r,s){return this.absellipse(e,t,i,i,n,r,s),this}ellipse(e,t,i,n,r,s,a,o){const l=this.currentPoint.x,c=this.currentPoint.y;return this.absellipse(e+l,t+c,i,n,r,s,a,o),this}absellipse(e,t,i,n,r,s,a,o){const l=new rh(e,t,i,n,r,s,a,o);if(this.curves.length>0){const e=l.getPoint(0);e.equals(this.currentPoint)||this.lineTo(e.x,e.y)}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),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 Sh extends Fr{constructor(e=[new fi(0,-.5),new fi(.5,0),new fi(0,.5)],t=12,i=0,n=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:i,phiLength:n},t=Math.floor(t),n=hi(n,0,2*Math.PI);const r=[],s=[],a=[],o=[],l=[],c=1/t,h=new Xi,d=new fi,u=new Xi,p=new Xi,m=new Xi;let g=0,f=0;for(let t=0;t<=e.length-1;t++)switch(t){case 0:g=e[t+1].x-e[t].x,f=e[t+1].y-e[t].y,u.x=1*f,u.y=-g,u.z=0*f,m.copy(u),u.normalize(),o.push(u.x,u.y,u.z);break;case e.length-1:o.push(m.x,m.y,m.z);break;default:g=e[t+1].x-e[t].x,f=e[t+1].y-e[t].y,u.x=1*f,u.y=-g,u.z=0*f,p.copy(u),u.x+=m.x,u.y+=m.y,u.z+=m.z,u.normalize(),o.push(u.x,u.y,u.z),m.copy(p)}for(let r=0;r<=t;r++){const u=i+r*c*n,p=Math.sin(u),m=Math.cos(u);for(let i=0;i<=e.length-1;i++){h.x=e[i].x*p,h.y=e[i].y,h.z=e[i].x*m,s.push(h.x,h.y,h.z),d.x=r/t,d.y=i/(e.length-1),a.push(d.x,d.y);const n=o[3*i+0]*p,c=o[3*i+1],u=o[3*i+0]*m;l.push(n,c,u)}}for(let i=0;i<t;i++)for(let t=0;t<e.length-1;t++){const n=t+i*e.length,s=n,a=n+e.length,o=n+e.length+1,l=n+1;r.push(s,a,l),r.push(o,l,a)}this.setIndex(r),this.setAttribute("position",new Ir(s,3)),this.setAttribute("uv",new Ir(a,2)),this.setAttribute("normal",new Ir(l,3))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Sh(e.points,e.segments,e.phiStart,e.phiLength)}}class Mh extends Sh{constructor(e=1,t=1,i=4,n=8){const r=new Ch;r.absarc(0,-t/2,e,1.5*Math.PI,0),r.absarc(0,t/2,e,0,.5*Math.PI),super(r.getPoints(i),n),this.type="CapsuleGeometry",this.parameters={radius:e,length:t,capSegments:i,radialSegments:n}}static fromJSON(e){return new Mh(e.radius,e.length,e.capSegments,e.radialSegments)}}class Eh extends Fr{constructor(e=1,t=32,i=0,n=2*Math.PI){super(),this.type="CircleGeometry",this.parameters={radius:e,segments:t,thetaStart:i,thetaLength:n},t=Math.max(3,t);const r=[],s=[],a=[],o=[],l=new Xi,c=new fi;s.push(0,0,0),a.push(0,0,1),o.push(.5,.5);for(let r=0,h=3;r<=t;r++,h+=3){const d=i+r/t*n;l.x=e*Math.cos(d),l.y=e*Math.sin(d),s.push(l.x,l.y,l.z),a.push(0,0,1),c.x=(s[h]/e+1)/2,c.y=(s[h+1]/e+1)/2,o.push(c.x,c.y)}for(let e=1;e<=t;e++)r.push(e,e+1,0);this.setIndex(r),this.setAttribute("position",new Ir(s,3)),this.setAttribute("normal",new Ir(a,3)),this.setAttribute("uv",new Ir(o,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Eh(e.radius,e.segments,e.thetaStart,e.thetaLength)}}class Th extends Fr{constructor(e=1,t=1,i=1,n=32,r=1,s=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:i,radialSegments:n,heightSegments:r,openEnded:s,thetaStart:a,thetaLength:o};const l=this;n=Math.floor(n),r=Math.floor(r);const c=[],h=[],d=[],u=[];let p=0;const m=[],g=i/2;let f=0;function A(i){const r=p,s=new fi,m=new Xi;let A=0;const y=!0===i?e:t,v=!0===i?1:-1;for(let e=1;e<=n;e++)h.push(0,g*v,0),d.push(0,v,0),u.push(.5,.5),p++;const _=p;for(let e=0;e<=n;e++){const t=e/n*o+a,i=Math.cos(t),r=Math.sin(t);m.x=y*r,m.y=g*v,m.z=y*i,h.push(m.x,m.y,m.z),d.push(0,v,0),s.x=.5*i+.5,s.y=.5*r*v+.5,u.push(s.x,s.y),p++}for(let e=0;e<n;e++){const t=r+e,n=_+e;!0===i?c.push(n,n+1,t):c.push(n+1,n,t),A+=3}l.addGroup(f,A,!0===i?1:2),f+=A}(function(){const s=new Xi,A=new Xi;let y=0;const v=(t-e)/i;for(let l=0;l<=r;l++){const c=[],f=l/r,y=f*(t-e)+e;for(let e=0;e<=n;e++){const t=e/n,r=t*o+a,l=Math.sin(r),m=Math.cos(r);A.x=y*l,A.y=-f*i+g,A.z=y*m,h.push(A.x,A.y,A.z),s.set(l,v,m).normalize(),d.push(s.x,s.y,s.z),u.push(t,1-f),c.push(p++)}m.push(c)}for(let e=0;e<n;e++)for(let t=0;t<r;t++){const i=m[t][e],n=m[t+1][e],r=m[t+1][e+1],s=m[t][e+1];c.push(i,n,s),c.push(n,r,s),y+=6}l.addGroup(f,y,0),f+=y})(),!1===s&&(e>0&&A(!0),t>0&&A(!1)),this.setIndex(c),this.setAttribute("position",new Ir(h,3)),this.setAttribute("normal",new Ir(d,3)),this.setAttribute("uv",new Ir(u,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Th(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Ih extends Th{constructor(e=1,t=1,i=32,n=1,r=!1,s=0,a=2*Math.PI){super(0,e,t,i,n,r,s,a),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:i,heightSegments:n,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(e){return new Ih(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Ph extends Fr{constructor(e=[],t=[],i=1,n=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:i,detail:n};const r=[],s=[];function a(e,t,i,n){const r=n+1,s=[];for(let n=0;n<=r;n++){s[n]=[];const a=e.clone().lerp(i,n/r),o=t.clone().lerp(i,n/r),l=r-n;for(let e=0;e<=l;e++)s[n][e]=0===e&&n===r?a:a.clone().lerp(o,e/l)}for(let e=0;e<r;e++)for(let t=0;t<2*(r-e)-1;t++){const i=Math.floor(t/2);t%2==0?(o(s[e][i+1]),o(s[e+1][i]),o(s[e][i])):(o(s[e][i+1]),o(s[e+1][i+1]),o(s[e+1][i]))}}function o(e){r.push(e.x,e.y,e.z)}function l(t,i){const n=3*t;i.x=e[n+0],i.y=e[n+1],i.z=e[n+2]}function c(e,t,i,n){n<0&&1===e.x&&(s[t]=e.x-1),0===i.x&&0===i.z&&(s[t]=n/2/Math.PI+.5)}function h(e){return Math.atan2(e.z,-e.x)}function d(e){return Math.atan2(-e.y,Math.sqrt(e.x*e.x+e.z*e.z))}(function(e){const i=new Xi,n=new Xi,r=new Xi;for(let s=0;s<t.length;s+=3)l(t[s+0],i),l(t[s+1],n),l(t[s+2],r),a(i,n,r,e)})(n),function(e){const t=new Xi;for(let i=0;i<r.length;i+=3)t.x=r[i+0],t.y=r[i+1],t.z=r[i+2],t.normalize().multiplyScalar(e),r[i+0]=t.x,r[i+1]=t.y,r[i+2]=t.z}(i),function(){const e=new Xi;for(let t=0;t<r.length;t+=3){e.x=r[t+0],e.y=r[t+1],e.z=r[t+2];const i=h(e)/2/Math.PI+.5,n=d(e)/Math.PI+.5;s.push(i,1-n)}(function(){const e=new Xi,t=new Xi,i=new Xi,n=new Xi,a=new fi,o=new fi,l=new fi;for(let d=0,u=0;d<r.length;d+=9,u+=6){e.set(r[d+0],r[d+1],r[d+2]),t.set(r[d+3],r[d+4],r[d+5]),i.set(r[d+6],r[d+7],r[d+8]),a.set(s[u+0],s[u+1]),o.set(s[u+2],s[u+3]),l.set(s[u+4],s[u+5]),n.copy(e).add(t).add(i).divideScalar(3);const p=h(n);c(a,u+0,e,p),c(o,u+2,t,p),c(l,u+4,i,p)}})(),function(){for(let e=0;e<s.length;e+=6){const t=s[e+0],i=s[e+2],n=s[e+4],r=Math.max(t,i,n),a=Math.min(t,i,n);r>.9&&a<.1&&(t<.2&&(s[e+0]+=1),i<.2&&(s[e+2]+=1),n<.2&&(s[e+4]+=1))}}()}(),this.setAttribute("position",new Ir(r,3)),this.setAttribute("normal",new Ir(r.slice(),3)),this.setAttribute("uv",new Ir(s,2)),0===n?this.computeVertexNormals():this.normalizeNormals()}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ph(e.vertices,e.indices,e.radius,e.details)}}class Dh extends Ph{constructor(e=1,t=0){const i=(1+Math.sqrt(5))/2,n=1/i;super([-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],[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],e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Dh(e.radius,e.detail)}}const Rh=new Xi,Bh=new Xi,Lh=new Xi,Oh=new cr;class Uh extends Fr{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},null!==e){const i=Math.pow(10,4),n=Math.cos(oi*t),r=e.getIndex(),s=e.getAttribute("position"),a=r?r.count:s.count,o=[0,0,0],l=["a","b","c"],c=new Array(3),h={},d=[];for(let e=0;e<a;e+=3){r?(o[0]=r.getX(e),o[1]=r.getX(e+1),o[2]=r.getX(e+2)):(o[0]=e,o[1]=e+1,o[2]=e+2);const{a:t,b:a,c:u}=Oh;if(t.fromBufferAttribute(s,o[0]),a.fromBufferAttribute(s,o[1]),u.fromBufferAttribute(s,o[2]),Oh.getNormal(Lh),c[0]=`${Math.round(t.x*i)},${Math.round(t.y*i)},${Math.round(t.z*i)}`,c[1]=`${Math.round(a.x*i)},${Math.round(a.y*i)},${Math.round(a.z*i)}`,c[2]=`${Math.round(u.x*i)},${Math.round(u.y*i)},${Math.round(u.z*i)}`,c[0]!==c[1]&&c[1]!==c[2]&&c[2]!==c[0])for(let e=0;e<3;e++){const t=(e+1)%3,i=c[e],r=c[t],s=Oh[l[e]],a=Oh[l[t]],u=`${i}_${r}`,p=`${r}_${i}`;p in h&&h[p]?(Lh.dot(h[p].normal)<=n&&(d.push(s.x,s.y,s.z),d.push(a.x,a.y,a.z)),h[p]=null):u in h||(h[u]={index0:o[e],index1:o[t],normal:Lh.clone()})}}for(const e in h)if(h[e]){const{index0:t,index1:i}=h[e];Rh.fromBufferAttribute(s,t),Bh.fromBufferAttribute(s,i),d.push(Rh.x,Rh.y,Rh.z),d.push(Bh.x,Bh.y,Bh.z)}this.setAttribute("position",new Ir(d,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}class Fh extends Ch{constructor(e){super(e),this.uuid=ci(),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 i=e.holes[t];this.holes.push(i.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 i=this.holes[t];e.holes.push(i.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 i=e.holes[t];this.holes.push((new Ch).fromJSON(i))}return this}}const kh=function(e,t,i=2){const n=t&&t.length,r=n?t[0]*i:e.length;let s=Nh(e,0,r,i,!0);const a=[];if(!s||s.next===s.prev)return a;let o,l,c,h,d,u,p;if(n&&(s=function(e,t,i,n){const r=[];let s,a,o,l,c;for(s=0,a=t.length;s<a;s++)o=t[s]*n,l=s<a-1?t[s+1]*n:e.length,c=Nh(e,o,l,n,!1),c===c.next&&(c.steiner=!0),r.push(Kh(c));for(r.sort(Wh),s=0;s<r.length;s++)i=qh(r[s],i);return i}(e,t,s,i)),e.length>80*i){o=c=e[0],l=h=e[1];for(let t=i;t<r;t+=i)d=e[t],u=e[t+1],d<o&&(o=d),u<l&&(l=u),d>c&&(c=d),u>h&&(h=u);p=Math.max(c-o,h-l),p=0!==p?32767/p:0}return zh(s,a,i,o,l,p,0),a};function Nh(e,t,i,n,r){let s,a;if(r===function(e,t,i,n){let r=0;for(let s=t,a=i-n;s<i;s+=n)r+=(e[a]-e[s])*(e[s+1]+e[a+1]),a=s;return r}(e,t,i,n)>0)for(s=t;s<i;s+=n)a=ad(s,e[s],e[s+1],a);else for(s=i-n;s>=t;s-=n)a=ad(s,e[s],e[s+1],a);return a&&ed(a,a.next)&&(od(a),a=a.next),a}function jh(e,t){if(!e)return e;t||(t=e);let i,n=e;do{if(i=!1,n.steiner||!ed(n,n.next)&&0!==$h(n.prev,n,n.next))n=n.next;else{if(od(n),n=t=n.prev,n===n.next)break;i=!0}}while(i||n!==t);return t}function zh(e,t,i,n,r,s,a){if(!e)return;!a&&s&&function(e,t,i,n){let r=e;do{0===r.z&&(r.z=Yh(r.x,r.y,t,i,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){let t,i,n,r,s,a,o,l,c=1;do{for(i=e,e=null,s=null,a=0;i;){for(a++,n=i,o=0,t=0;t<c&&(o++,n=n.nextZ,n);t++);for(l=c;o>0||l>0&&n;)0!==o&&(0===l||!n||i.z<=n.z)?(r=i,i=i.nextZ,o--):(r=n,n=n.nextZ,l--),s?s.nextZ=r:e=r,r.prevZ=s,s=r;i=n}s.nextZ=null,c*=2}while(a>1)}(r)}(e,n,r,s);let o,l,c=e;for(;e.prev!==e.next;)if(o=e.prev,l=e.next,s?Qh(e,n,r,s):Gh(e))t.push(o.i/i|0),t.push(e.i/i|0),t.push(l.i/i|0),od(e),e=l.next,c=l.next;else if((e=l)===c){a?1===a?zh(e=Vh(jh(e),t,i),t,i,n,r,s,2):2===a&&Hh(e,t,i,n,r,s):zh(jh(e),t,i,n,r,s,1);break}}function Gh(e){const t=e.prev,i=e,n=e.next;if($h(t,i,n)>=0)return!1;const r=t.x,s=i.x,a=n.x,o=t.y,l=i.y,c=n.y,h=r<s?r<a?r:a:s<a?s:a,d=o<l?o<c?o:c:l<c?l:c,u=r>s?r>a?r:a:s>a?s:a,p=o>l?o>c?o:c:l>c?l:c;let m=n.next;for(;m!==t;){if(m.x>=h&&m.x<=u&&m.y>=d&&m.y<=p&&Jh(r,o,s,l,a,c,m.x,m.y)&&$h(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Qh(e,t,i,n){const r=e.prev,s=e,a=e.next;if($h(r,s,a)>=0)return!1;const o=r.x,l=s.x,c=a.x,h=r.y,d=s.y,u=a.y,p=o<l?o<c?o:c:l<c?l:c,m=h<d?h<u?h:u:d<u?d:u,g=o>l?o>c?o:c:l>c?l:c,f=h>d?h>u?h:u:d>u?d:u,A=Yh(p,m,t,i,n),y=Yh(g,f,t,i,n);let v=e.prevZ,_=e.nextZ;for(;v&&v.z>=A&&_&&_.z<=y;){if(v.x>=p&&v.x<=g&&v.y>=m&&v.y<=f&&v!==r&&v!==a&&Jh(o,h,l,d,c,u,v.x,v.y)&&$h(v.prev,v,v.next)>=0||(v=v.prevZ,_.x>=p&&_.x<=g&&_.y>=m&&_.y<=f&&_!==r&&_!==a&&Jh(o,h,l,d,c,u,_.x,_.y)&&$h(_.prev,_,_.next)>=0))return!1;_=_.nextZ}for(;v&&v.z>=A;){if(v.x>=p&&v.x<=g&&v.y>=m&&v.y<=f&&v!==r&&v!==a&&Jh(o,h,l,d,c,u,v.x,v.y)&&$h(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;_&&_.z<=y;){if(_.x>=p&&_.x<=g&&_.y>=m&&_.y<=f&&_!==r&&_!==a&&Jh(o,h,l,d,c,u,_.x,_.y)&&$h(_.prev,_,_.next)>=0)return!1;_=_.nextZ}return!0}function Vh(e,t,i){let n=e;do{const r=n.prev,s=n.next.next;!ed(r,s)&&td(r,n,n.next,s)&&rd(r,s)&&rd(s,r)&&(t.push(r.i/i|0),t.push(n.i/i|0),t.push(s.i/i|0),od(n),od(n.next),n=e=s),n=n.next}while(n!==e);return jh(n)}function Hh(e,t,i,n,r,s){let a=e;do{let e=a.next.next;for(;e!==a.prev;){if(a.i!==e.i&&Zh(a,e)){let o=sd(a,e);return a=jh(a,a.next),o=jh(o,o.next),zh(a,t,i,n,r,s,0),void zh(o,t,i,n,r,s,0)}e=e.next}a=a.next}while(a!==e)}function Wh(e,t){return e.x-t.x}function qh(e,t){const i=function(e,t){let i,n=t,r=-1/0;const s=e.x,a=e.y;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){const e=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(e<=s&&e>r&&(r=e,i=n.x<n.next.x?n:n.next,e===s))return i}n=n.next}while(n!==t);if(!i)return null;const o=i,l=i.x,c=i.y;let h,d=1/0;n=i;do{s>=n.x&&n.x>=l&&s!==n.x&&Jh(a<c?s:r,a,l,c,a<c?r:s,a,n.x,n.y)&&(h=Math.abs(a-n.y)/(s-n.x),rd(n,e)&&(h<d||h===d&&(n.x>i.x||n.x===i.x&&Xh(i,n)))&&(i=n,d=h)),n=n.next}while(n!==o);return i}(e,t);if(!i)return t;const n=sd(i,e);return jh(n,n.next),jh(i,i.next)}function Xh(e,t){return $h(e.prev,e,t.prev)<0&&$h(t.next,e,e.next)<0}function Yh(e,t,i,n,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Kh(e){let t=e,i=e;do{(t.x<i.x||t.x===i.x&&t.y<i.y)&&(i=t),t=t.next}while(t!==e);return i}function Jh(e,t,i,n,r,s,a,o){return(r-a)*(t-o)>=(e-a)*(s-o)&&(e-a)*(n-o)>=(i-a)*(t-o)&&(i-a)*(s-o)>=(r-a)*(n-o)}function Zh(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&td(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(rd(e,t)&&rd(t,e)&&function(e,t){let i=e,n=!1;const r=(e.x+t.x)/2,s=(e.y+t.y)/2;do{i.y>s!=i.next.y>s&&i.next.y!==i.y&&r<(i.next.x-i.x)*(s-i.y)/(i.next.y-i.y)+i.x&&(n=!n),i=i.next}while(i!==e);return n}(e,t)&&($h(e.prev,e,t.prev)||$h(e,t.prev,t))||ed(e,t)&&$h(e.prev,e,e.next)>0&&$h(t.prev,t,t.next)>0)}function $h(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function ed(e,t){return e.x===t.x&&e.y===t.y}function td(e,t,i,n){const r=nd($h(e,t,i)),s=nd($h(e,t,n)),a=nd($h(i,n,e)),o=nd($h(i,n,t));return!!(r!==s&&a!==o||0===r&&id(e,i,t)||0===s&&id(e,n,t)||0===a&&id(i,e,n)||0===o&&id(i,t,n))}function id(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function nd(e){return e>0?1:e<0?-1:0}function rd(e,t){return $h(e.prev,e,e.next)<0?$h(e,t,e.next)>=0&&$h(e,e.prev,t)>=0:$h(e,t,e.prev)<0||$h(e,e.next,t)<0}function sd(e,t){const i=new ld(e.i,e.x,e.y),n=new ld(t.i,t.x,t.y),r=e.next,s=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,n.next=i,i.prev=n,s.next=n,n.prev=s,n}function ad(e,t,i,n){const r=new ld(e,t,i);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r}function od(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function ld(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class cd{static area(e){const t=e.length;let i=0;for(let n=t-1,r=0;r<t;n=r++)i+=e[n].x*e[r].y-e[r].x*e[n].y;return.5*i}static isClockWise(e){return cd.area(e)<0}static triangulateShape(e,t){const i=[],n=[],r=[];hd(e),dd(i,e);let s=e.length;t.forEach(hd);for(let e=0;e<t.length;e++)n.push(s),s+=t[e].length,dd(i,t[e]);const a=kh(i,n);for(let e=0;e<a.length;e+=3)r.push(a.slice(e,e+3));return r}}function hd(e){const t=e.length;t>2&&e[t-1].equals(e[0])&&e.pop()}function dd(e,t){for(let i=0;i<t.length;i++)e.push(t[i].x),e.push(t[i].y)}class ud extends Fr{constructor(e=new Fh([new fi(.5,.5),new fi(-.5,.5),new fi(-.5,-.5),new fi(.5,-.5)]),t={}){super(),this.type="ExtrudeGeometry",this.parameters={shapes:e,options:t},e=Array.isArray(e)?e:[e];const i=this,n=[],r=[];for(let t=0,i=e.length;t<i;t++){s(e[t])}function s(e){const s=[],a=void 0!==t.curveSegments?t.curveSegments:12,o=void 0!==t.steps?t.steps:1,l=void 0!==t.depth?t.depth:1;let c=void 0===t.bevelEnabled||t.bevelEnabled,h=void 0!==t.bevelThickness?t.bevelThickness:.2,d=void 0!==t.bevelSize?t.bevelSize:h-.1,u=void 0!==t.bevelOffset?t.bevelOffset:0,p=void 0!==t.bevelSegments?t.bevelSegments:3;const m=t.extrudePath,g=void 0!==t.UVGenerator?t.UVGenerator:pd;let f,A,y,v,_,b=!1;m&&(f=m.getSpacedPoints(o),b=!0,c=!1,A=m.computeFrenetFrames(o,!1),y=new Xi,v=new Xi,_=new Xi),c||(p=0,h=0,d=0,u=0);const x=e.extractPoints(a);let w=x.shape;const C=x.holes;if(!cd.isClockWise(w)){w=w.reverse();for(let e=0,t=C.length;e<t;e++){const t=C[e];cd.isClockWise(t)&&(C[e]=t.reverse())}}const S=cd.triangulateShape(w,C),M=w;for(let e=0,t=C.length;e<t;e++){const t=C[e];w=w.concat(t)}function E(e,t,i){return t||console.error("THREE.ExtrudeGeometry: vec does not exist"),e.clone().addScaledVector(t,i)}const T=w.length,I=S.length;function P(e,t,i){let n,r,s;const a=e.x-t.x,o=e.y-t.y,l=i.x-e.x,c=i.y-e.y,h=a*a+o*o,d=a*c-o*l;if(Math.abs(d)>Number.EPSILON){const d=Math.sqrt(h),u=Math.sqrt(l*l+c*c),p=t.x-o/d,m=t.y+a/d,g=((i.x-c/u-p)*c-(i.y+l/u-m)*l)/(a*c-o*l);n=p+a*g-e.x,r=m+o*g-e.y;const f=n*n+r*r;if(f<=2)return new fi(n,r);s=Math.sqrt(f/2)}else{let e=!1;a>Number.EPSILON?l>Number.EPSILON&&(e=!0):a<-Number.EPSILON?l<-Number.EPSILON&&(e=!0):Math.sign(o)===Math.sign(c)&&(e=!0),e?(n=-o,r=a,s=Math.sqrt(h)):(n=a,r=o,s=Math.sqrt(h/2))}return new fi(n/s,r/s)}const D=[];for(let e=0,t=M.length,i=t-1,n=e+1;e<t;e++,i++,n++)i===t&&(i=0),n===t&&(n=0),D[e]=P(M[e],M[i],M[n]);const R=[];let B,L=D.concat();for(let e=0,t=C.length;e<t;e++){const t=C[e];B=[];for(let e=0,i=t.length,n=i-1,r=e+1;e<i;e++,n++,r++)n===i&&(n=0),r===i&&(r=0),B[e]=P(t[e],t[n],t[r]);R.push(B),L=L.concat(B)}for(let e=0;e<p;e++){const t=e/p,i=h*Math.cos(t*Math.PI/2),n=d*Math.sin(t*Math.PI/2)+u;for(let e=0,t=M.length;e<t;e++){const t=E(M[e],D[e],n);F(t.x,t.y,-i)}for(let e=0,t=C.length;e<t;e++){const t=C[e];B=R[e];for(let e=0,r=t.length;e<r;e++){const r=E(t[e],B[e],n);F(r.x,r.y,-i)}}}const O=d+u;for(let e=0;e<T;e++){const t=c?E(w[e],L[e],O):w[e];b?(v.copy(A.normals[0]).multiplyScalar(t.x),y.copy(A.binormals[0]).multiplyScalar(t.y),_.copy(f[0]).add(v).add(y),F(_.x,_.y,_.z)):F(t.x,t.y,0)}for(let e=1;e<=o;e++)for(let t=0;t<T;t++){const i=c?E(w[t],L[t],O):w[t];b?(v.copy(A.normals[e]).multiplyScalar(i.x),y.copy(A.binormals[e]).multiplyScalar(i.y),_.copy(f[e]).add(v).add(y),F(_.x,_.y,_.z)):F(i.x,i.y,l/o*e)}for(let e=p-1;e>=0;e--){const t=e/p,i=h*Math.cos(t*Math.PI/2),n=d*Math.sin(t*Math.PI/2)+u;for(let e=0,t=M.length;e<t;e++){const t=E(M[e],D[e],n);F(t.x,t.y,l+i)}for(let e=0,t=C.length;e<t;e++){const t=C[e];B=R[e];for(let e=0,r=t.length;e<r;e++){const r=E(t[e],B[e],n);b?F(r.x,r.y+f[o-1].y,f[o-1].x+i):F(r.x,r.y,l+i)}}}function U(e,t){let i=e.length;for(;--i>=0;){const n=i;let r=i-1;r<0&&(r=e.length-1);for(let e=0,i=o+2*p;e<i;e++){const i=T*e,s=T*(e+1);N(t+n+i,t+r+i,t+r+s,t+n+s)}}}function F(e,t,i){s.push(e),s.push(t),s.push(i)}function k(e,t,r){j(e),j(t),j(r);const s=n.length/3,a=g.generateTopUV(i,n,s-3,s-2,s-1);z(a[0]),z(a[1]),z(a[2])}function N(e,t,r,s){j(e),j(t),j(s),j(t),j(r),j(s);const a=n.length/3,o=g.generateSideWallUV(i,n,a-6,a-3,a-2,a-1);z(o[0]),z(o[1]),z(o[3]),z(o[1]),z(o[2]),z(o[3])}function j(e){n.push(s[3*e+0]),n.push(s[3*e+1]),n.push(s[3*e+2])}function z(e){r.push(e.x),r.push(e.y)}(function(){const e=n.length/3;if(c){let e=0,t=T*e;for(let e=0;e<I;e++){const i=S[e];k(i[2]+t,i[1]+t,i[0]+t)}e=o+2*p,t=T*e;for(let e=0;e<I;e++){const i=S[e];k(i[0]+t,i[1]+t,i[2]+t)}}else{for(let e=0;e<I;e++){const t=S[e];k(t[2],t[1],t[0])}for(let e=0;e<I;e++){const t=S[e];k(t[0]+T*o,t[1]+T*o,t[2]+T*o)}}i.addGroup(e,n.length/3-e,0)})(),function(){const e=n.length/3;let t=0;U(M,t),t+=M.length;for(let e=0,i=C.length;e<i;e++){const i=C[e];U(i,t),t+=i.length}i.addGroup(e,n.length/3-e,1)}()}this.setAttribute("position",new Ir(n,3)),this.setAttribute("uv",new Ir(r,2)),this.computeVertexNormals()}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON();return function(e,t,i){if(i.shapes=[],Array.isArray(e))for(let t=0,n=e.length;t<n;t++){const n=e[t];i.shapes.push(n.uuid)}else i.shapes.push(e.uuid);return i.options=Object.assign({},t),void 0!==t.extrudePath&&(i.options.extrudePath=t.extrudePath.toJSON()),i}(this.parameters.shapes,this.parameters.options,e)}static fromJSON(e,t){const i=[];for(let n=0,r=e.shapes.length;n<r;n++){const r=t[e.shapes[n]];i.push(r)}const n=e.options.extrudePath;return void 0!==n&&(e.options.extrudePath=(new xh[n.type]).fromJSON(n)),new ud(i,e.options)}}const pd={generateTopUV:function(e,t,i,n,r){const s=t[3*i],a=t[3*i+1],o=t[3*n],l=t[3*n+1],c=t[3*r],h=t[3*r+1];return[new fi(s,a),new fi(o,l),new fi(c,h)]},generateSideWallUV:function(e,t,i,n,r,s){const a=t[3*i],o=t[3*i+1],l=t[3*i+2],c=t[3*n],h=t[3*n+1],d=t[3*n+2],u=t[3*r],p=t[3*r+1],m=t[3*r+2],g=t[3*s],f=t[3*s+1],A=t[3*s+2];return Math.abs(o-h)<Math.abs(a-c)?[new fi(a,1-l),new fi(c,1-d),new fi(u,1-m),new fi(g,1-A)]:[new fi(o,1-l),new fi(h,1-d),new fi(p,1-m),new fi(f,1-A)]}};class md extends Ph{constructor(e=1,t=0){const i=(1+Math.sqrt(5))/2;super([-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],[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],e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new md(e.radius,e.detail)}}class gd extends Ph{constructor(e=1,t=0){super([1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],e,t),this.type="OctahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new gd(e.radius,e.detail)}}class fd extends Fr{constructor(e=.5,t=1,i=32,n=1,r=0,s=2*Math.PI){super(),this.type="RingGeometry",this.parameters={innerRadius:e,outerRadius:t,thetaSegments:i,phiSegments:n,thetaStart:r,thetaLength:s},i=Math.max(3,i);const a=[],o=[],l=[],c=[];let h=e;const d=(t-e)/(n=Math.max(1,n)),u=new Xi,p=new fi;for(let e=0;e<=n;e++){for(let e=0;e<=i;e++){const n=r+e/i*s;u.x=h*Math.cos(n),u.y=h*Math.sin(n),o.push(u.x,u.y,u.z),l.push(0,0,1),p.x=(u.x/t+1)/2,p.y=(u.y/t+1)/2,c.push(p.x,p.y)}h+=d}for(let e=0;e<n;e++){const t=e*(i+1);for(let e=0;e<i;e++){const n=e+t,r=n,s=n+i+1,o=n+i+2,l=n+1;a.push(r,s,l),a.push(s,o,l)}}this.setIndex(a),this.setAttribute("position",new Ir(o,3)),this.setAttribute("normal",new Ir(l,3)),this.setAttribute("uv",new Ir(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new fd(e.innerRadius,e.outerRadius,e.thetaSegments,e.phiSegments,e.thetaStart,e.thetaLength)}}class Ad extends Fr{constructor(e=new Fh([new fi(0,.5),new fi(-.5,-.5),new fi(.5,-.5)]),t=12){super(),this.type="ShapeGeometry",this.parameters={shapes:e,curveSegments:t};const i=[],n=[],r=[],s=[];let a=0,o=0;if(!1===Array.isArray(e))l(e);else for(let t=0;t<e.length;t++)l(e[t]),this.addGroup(a,o,t),a+=o,o=0;function l(e){const a=n.length/3,l=e.extractPoints(t);let c=l.shape;const h=l.holes;!1===cd.isClockWise(c)&&(c=c.reverse());for(let e=0,t=h.length;e<t;e++){const t=h[e];!0===cd.isClockWise(t)&&(h[e]=t.reverse())}const d=cd.triangulateShape(c,h);for(let e=0,t=h.length;e<t;e++){const t=h[e];c=c.concat(t)}for(let e=0,t=c.length;e<t;e++){const t=c[e];n.push(t.x,t.y,0),r.push(0,0,1),s.push(t.x,t.y)}for(let e=0,t=d.length;e<t;e++){const t=d[e],n=t[0]+a,r=t[1]+a,s=t[2]+a;i.push(n,r,s),o+=3}}this.setIndex(i),this.setAttribute("position",new Ir(n,3)),this.setAttribute("normal",new Ir(r,3)),this.setAttribute("uv",new Ir(s,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON();return function(e,t){if(t.shapes=[],Array.isArray(e))for(let i=0,n=e.length;i<n;i++){const n=e[i];t.shapes.push(n.uuid)}else t.shapes.push(e.uuid);return t}(this.parameters.shapes,e)}static fromJSON(e,t){const i=[];for(let n=0,r=e.shapes.length;n<r;n++){const r=t[e.shapes[n]];i.push(r)}return new Ad(i,e.curveSegments)}}class yd extends Fr{constructor(e=1,t=32,i=16,n=0,r=2*Math.PI,s=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:i,phiStart:n,phiLength:r,thetaStart:s,thetaLength:a},t=Math.max(3,Math.floor(t)),i=Math.max(2,Math.floor(i));const o=Math.min(s+a,Math.PI);let l=0;const c=[],h=new Xi,d=new Xi,u=[],p=[],m=[],g=[];for(let u=0;u<=i;u++){const f=[],A=u/i;let y=0;0===u&&0===s?y=.5/t:u===i&&o===Math.PI&&(y=-.5/t);for(let i=0;i<=t;i++){const o=i/t;h.x=-e*Math.cos(n+o*r)*Math.sin(s+A*a),h.y=e*Math.cos(s+A*a),h.z=e*Math.sin(n+o*r)*Math.sin(s+A*a),p.push(h.x,h.y,h.z),d.copy(h).normalize(),m.push(d.x,d.y,d.z),g.push(o+y,1-A),f.push(l++)}c.push(f)}for(let e=0;e<i;e++)for(let n=0;n<t;n++){const t=c[e][n+1],r=c[e][n],a=c[e+1][n],l=c[e+1][n+1];(0!==e||s>0)&&u.push(t,r,l),(e!==i-1||o<Math.PI)&&u.push(r,a,l)}this.setIndex(u),this.setAttribute("position",new Ir(p,3)),this.setAttribute("normal",new Ir(m,3)),this.setAttribute("uv",new Ir(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new yd(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class vd extends Ph{constructor(e=1,t=0){super([1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],e,t),this.type="TetrahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new vd(e.radius,e.detail)}}class _d extends Fr{constructor(e=1,t=.4,i=12,n=48,r=2*Math.PI){super(),this.type="TorusGeometry",this.parameters={radius:e,tube:t,radialSegments:i,tubularSegments:n,arc:r},i=Math.floor(i),n=Math.floor(n);const s=[],a=[],o=[],l=[],c=new Xi,h=new Xi,d=new Xi;for(let s=0;s<=i;s++)for(let u=0;u<=n;u++){const p=u/n*r,m=s/i*Math.PI*2;h.x=(e+t*Math.cos(m))*Math.cos(p),h.y=(e+t*Math.cos(m))*Math.sin(p),h.z=t*Math.sin(m),a.push(h.x,h.y,h.z),c.x=e*Math.cos(p),c.y=e*Math.sin(p),d.subVectors(h,c).normalize(),o.push(d.x,d.y,d.z),l.push(u/n),l.push(s/i)}for(let e=1;e<=i;e++)for(let t=1;t<=n;t++){const i=(n+1)*e+t-1,r=(n+1)*(e-1)+t-1,a=(n+1)*(e-1)+t,o=(n+1)*e+t;s.push(i,r,o),s.push(r,a,o)}this.setIndex(s),this.setAttribute("position",new Ir(a,3)),this.setAttribute("normal",new Ir(o,3)),this.setAttribute("uv",new Ir(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new _d(e.radius,e.tube,e.radialSegments,e.tubularSegments,e.arc)}}class bd extends Fr{constructor(e=1,t=.4,i=64,n=8,r=2,s=3){super(),this.type="TorusKnotGeometry",this.parameters={radius:e,tube:t,tubularSegments:i,radialSegments:n,p:r,q:s},i=Math.floor(i),n=Math.floor(n);const a=[],o=[],l=[],c=[],h=new Xi,d=new Xi,u=new Xi,p=new Xi,m=new Xi,g=new Xi,f=new Xi;for(let a=0;a<=i;++a){const y=a/i*r*Math.PI*2;A(y,r,s,e,u),A(y+.01,r,s,e,p),g.subVectors(p,u),f.addVectors(p,u),m.crossVectors(g,f),f.crossVectors(m,g),m.normalize(),f.normalize();for(let e=0;e<=n;++e){const r=e/n*Math.PI*2,s=-t*Math.cos(r),p=t*Math.sin(r);h.x=u.x+(s*f.x+p*m.x),h.y=u.y+(s*f.y+p*m.y),h.z=u.z+(s*f.z+p*m.z),o.push(h.x,h.y,h.z),d.subVectors(h,u).normalize(),l.push(d.x,d.y,d.z),c.push(a/i),c.push(e/n)}}for(let e=1;e<=i;e++)for(let t=1;t<=n;t++){const i=(n+1)*(e-1)+(t-1),r=(n+1)*e+(t-1),s=(n+1)*e+t,o=(n+1)*(e-1)+t;a.push(i,r,o),a.push(r,s,o)}function A(e,t,i,n,r){const s=Math.cos(e),a=Math.sin(e),o=i/t*e,l=Math.cos(o);r.x=n*(2+l)*.5*s,r.y=n*(2+l)*a*.5,r.z=n*Math.sin(o)*.5}this.setIndex(a),this.setAttribute("position",new Ir(o,3)),this.setAttribute("normal",new Ir(l,3)),this.setAttribute("uv",new Ir(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new bd(e.radius,e.tube,e.tubularSegments,e.radialSegments,e.p,e.q)}}class xd extends Fr{constructor(e=new _h(new Xi(-1,-1,0),new Xi(-1,1,0),new Xi(1,1,0)),t=64,i=1,n=8,r=!1){super(),this.type="TubeGeometry",this.parameters={path:e,tubularSegments:t,radius:i,radialSegments:n,closed:r};const s=e.computeFrenetFrames(t,r);this.tangents=s.tangents,this.normals=s.normals,this.binormals=s.binormals;const a=new Xi,o=new Xi,l=new fi;let c=new Xi;const h=[],d=[],u=[],p=[];function m(r){c=e.getPointAt(r/t,c);const l=s.normals[r],u=s.binormals[r];for(let e=0;e<=n;e++){const t=e/n*Math.PI*2,r=Math.sin(t),s=-Math.cos(t);o.x=s*l.x+r*u.x,o.y=s*l.y+r*u.y,o.z=s*l.z+r*u.z,o.normalize(),d.push(o.x,o.y,o.z),a.x=c.x+i*o.x,a.y=c.y+i*o.y,a.z=c.z+i*o.z,h.push(a.x,a.y,a.z)}}(function(){for(let e=0;e<t;e++)m(e);m(!1===r?t:0),function(){for(let e=0;e<=t;e++)for(let i=0;i<=n;i++)l.x=e/t,l.y=i/n,u.push(l.x,l.y)}(),function(){for(let e=1;e<=t;e++)for(let t=1;t<=n;t++){const i=(n+1)*(e-1)+(t-1),r=(n+1)*e+(t-1),s=(n+1)*e+t,a=(n+1)*(e-1)+t;p.push(i,r,a),p.push(r,s,a)}}()})(),this.setIndex(p),this.setAttribute("position",new Ir(h,3)),this.setAttribute("normal",new Ir(d,3)),this.setAttribute("uv",new Ir(u,2))}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 xd((new xh[e.path.type]).fromJSON(e.path),e.tubularSegments,e.radius,e.radialSegments,e.closed)}}class wd extends Fr{constructor(e=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:e},null!==e){const t=[],i=new Set,n=new Xi,r=new Xi;if(null!==e.index){const s=e.attributes.position,a=e.index;let o=e.groups;0===o.length&&(o=[{start:0,count:a.count,materialIndex:0}]);for(let e=0,l=o.length;e<l;++e){const l=o[e],c=l.start;for(let e=c,o=c+l.count;e<o;e+=3)for(let o=0;o<3;o++){const l=a.getX(e+o),c=a.getX(e+(o+1)%3);n.fromBufferAttribute(s,l),r.fromBufferAttribute(s,c),!0===Cd(n,r,i)&&(t.push(n.x,n.y,n.z),t.push(r.x,r.y,r.z))}}}else{const s=e.attributes.position;for(let e=0,a=s.count/3;e<a;e++)for(let a=0;a<3;a++){const o=3*e+a,l=3*e+(a+1)%3;n.fromBufferAttribute(s,o),r.fromBufferAttribute(s,l),!0===Cd(n,r,i)&&(t.push(n.x,n.y,n.z),t.push(r.x,r.y,r.z))}}this.setAttribute("position",new Ir(t,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}function Cd(e,t,i){const n=`${e.x},${e.y},${e.z}-${t.x},${t.y},${t.z}`,r=`${t.x},${t.y},${t.z}-${e.x},${e.y},${e.z}`;return!0!==i.has(n)&&!0!==i.has(r)&&(i.add(n),i.add(r),!0)}var Sd=Object.freeze({__proto__:null,BoxGeometry:ns,CapsuleGeometry:Mh,CircleGeometry:Eh,ConeGeometry:Ih,CylinderGeometry:Th,DodecahedronGeometry:Dh,EdgesGeometry:Uh,ExtrudeGeometry:ud,IcosahedronGeometry:md,LatheGeometry:Sh,OctahedronGeometry:gd,PlaneGeometry:Es,PolyhedronGeometry:Ph,RingGeometry:fd,ShapeGeometry:Ad,SphereGeometry:yd,TetrahedronGeometry:vd,TorusGeometry:_d,TorusKnotGeometry:bd,TubeGeometry:xd,WireframeGeometry:wd});class Md extends Ar{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new mr(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 Ed extends ls{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Td extends Ar{constructor(e){super(),this.isMeshStandardMaterial=!0,this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new mr(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 mr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Rt,this.normalScale=new fi(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 On,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 Id extends Td{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 fi(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return hi(2.5*(this.ior-1)/(this.ior+1),0,2.5)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new mr(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 mr(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new mr(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 Pd extends Ar{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new mr(16777215),this.specular=new mr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new mr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Rt,this.normalScale=new fi(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new On,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Dd extends Ar{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new mr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new mr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Rt,this.normalScale=new fi(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 Rd extends Ar{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Rt,this.normalScale=new fi(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 Bd extends Ar{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new mr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new mr(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Rt,this.normalScale=new fi(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new On,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Ld extends Ar{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new mr(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Rt,this.normalScale=new fi(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 Od extends Dc{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 Ud(e,t,i){return!e||!i&&e.constructor===t?e:"number"==typeof t.BYTES_PER_ELEMENT?new t(e):Array.prototype.slice.call(e)}function Fd(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function kd(e){const t=e.length,i=new Array(t);for(let e=0;e!==t;++e)i[e]=e;return i.sort(function(t,i){return e[t]-e[i]}),i}function Nd(e,t,i){const n=e.length,r=new e.constructor(n);for(let s=0,a=0;a!==n;++s){const n=i[s]*t;for(let i=0;i!==t;++i)r[a++]=e[n+i]}return r}function jd(e,t,i,n){let r=1,s=e[0];for(;void 0!==s&&void 0===s[n];)s=e[r++];if(void 0===s)return;let a=s[n];if(void 0!==a)if(Array.isArray(a))do{a=s[n],void 0!==a&&(t.push(s.time),i.push.apply(i,a)),s=e[r++]}while(void 0!==s);else if(void 0!==a.toArray)do{a=s[n],void 0!==a&&(t.push(s.time),a.toArray(i,i.length)),s=e[r++]}while(void 0!==s);else do{a=s[n],void 0!==a&&(t.push(s.time),i.push(a)),s=e[r++]}while(void 0!==s)}const zd={convertArray:Ud,isTypedArray:Fd,getKeyframeOrder:kd,sortedArray:Nd,flattenJSON:jd,subclip:function(e,t,i,n,r=30){const s=e.clone();s.name=t;const a=[];for(let e=0;e<s.tracks.length;++e){const t=s.tracks[e],o=t.getValueSize(),l=[],c=[];for(let e=0;e<t.times.length;++e){const s=t.times[e]*r;if(!(s<i||s>=n)){l.push(t.times[e]);for(let i=0;i<o;++i)c.push(t.values[e*o+i])}}0!==l.length&&(t.times=Ud(l,t.times.constructor),t.values=Ud(c,t.values.constructor),a.push(t))}s.tracks=a;let o=1/0;for(let e=0;e<s.tracks.length;++e)o>s.tracks[e].times[0]&&(o=s.tracks[e].times[0]);for(let e=0;e<s.tracks.length;++e)s.tracks[e].shift(-1*o);return s.resetDuration(),s},makeClipAdditive:function(e,t=0,i=e,n=30){n<=0&&(n=30);const r=i.tracks.length,s=t/n;for(let t=0;t<r;++t){const n=i.tracks[t],r=n.ValueTypeName;if("bool"===r||"string"===r)continue;const a=e.tracks.find(function(e){return e.name===n.name&&e.ValueTypeName===r});if(void 0===a)continue;let o=0;const l=n.getValueSize();n.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(o=l/3);let c=0;const h=a.getValueSize();a.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(c=h/3);const d=n.times.length-1;let u;if(s<=n.times[0]){const e=o,t=l-o;u=n.values.slice(e,t)}else if(s>=n.times[d]){const e=d*l+o,t=e+l-o;u=n.values.slice(e,t)}else{const e=n.createInterpolant(),t=o,i=l-o;e.evaluate(s),u=e.resultBuffer.slice(t,i)}"quaternion"===r&&(new qi).fromArray(u).normalize().conjugate().toArray(u);const p=a.times.length;for(let e=0;e<p;++e){const t=e*h+c;if("quaternion"===r)qi.multiplyQuaternionsFlat(a.values,t,u,0,a.values,t);else{const e=h-2*c;for(let i=0;i<e;++i)a.values[t+i]-=u[i]}}}return e.blendMode=2501,e}};class Gd{constructor(e,t,i,n){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=void 0!==n?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],r=t[i-1];e:{t:{let s;i:{n:if(!(e<n)){for(let s=i+2;;){if(void 0===n){if(e<r)break n;return i=t.length,this._cachedIndex=i,this.copySampleValue_(i-1)}if(i===s)break;if(r=n,n=t[++i],e<n)break t}s=t.length;break i}if(!(e>=r)){const a=t[1];e<a&&(i=2,r=a);for(let s=i-2;;){if(void 0===r)return this._cachedIndex=0,this.copySampleValue_(0);if(i===s)break;if(n=r,r=t[--i-1],e>=r)break t}s=i,i=0;break i}break e}for(;i<s;){const n=i+s>>>1;e<t[n]?s=n:i=n+1}if(n=t[i],r=t[i-1],void 0===r)return this._cachedIndex=0,this.copySampleValue_(0);if(void 0===n)return i=t.length,this._cachedIndex=i,this.copySampleValue_(i-1)}this._cachedIndex=i,this.intervalChanged_(i,r,n)}return this.interpolate_(i,r,e,n)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){const t=this.resultBuffer,i=this.sampleValues,n=this.valueSize,r=e*n;for(let e=0;e!==n;++e)t[e]=i[r+e];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}}class Qd extends Gd{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:Mt,endingEnd:Mt}}intervalChanged_(e,t,i){const n=this.parameterPositions;let r=e-2,s=e+1,a=n[r],o=n[s];if(void 0===a)switch(this.getSettings_().endingStart){case Et:r=e,a=2*t-i;break;case Tt:r=n.length-2,a=t+n[r]-n[r+1];break;default:r=e,a=i}if(void 0===o)switch(this.getSettings_().endingEnd){case Et:s=e,o=2*i-t;break;case Tt:s=1,o=i+n[1]-n[0];break;default:s=e-1,o=t}const l=.5*(i-t),c=this.valueSize;this._weightPrev=l/(t-a),this._weightNext=l/(o-i),this._offsetPrev=r*c,this._offsetNext=s*c}interpolate_(e,t,i,n){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,l=o-a,c=this._offsetPrev,h=this._offsetNext,d=this._weightPrev,u=this._weightNext,p=(i-t)/(n-t),m=p*p,g=m*p,f=-d*g+2*d*m-d*p,A=(1+d)*g+(-1.5-2*d)*m+(-.5+d)*p+1,y=(-1-u)*g+(1.5+u)*m+.5*p,v=u*g-u*m;for(let e=0;e!==a;++e)r[e]=f*s[c+e]+A*s[l+e]+y*s[o+e]+v*s[h+e];return r}}class Vd extends Gd{constructor(e,t,i,n){super(e,t,i,n)}interpolate_(e,t,i,n){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,l=o-a,c=(i-t)/(n-t),h=1-c;for(let e=0;e!==a;++e)r[e]=s[l+e]*h+s[o+e]*c;return r}}class Hd extends Gd{constructor(e,t,i,n){super(e,t,i,n)}interpolate_(e){return this.copySampleValue_(e-1)}}class Wd{constructor(e,t,i,n){if(void 0===e)throw new Error("THREE.KeyframeTrack: track name is undefined");if(void 0===t||0===t.length)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=Ud(t,this.TimeBufferType),this.values=Ud(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:Ud(e.times,Array),values:Ud(e.values,Array)};const t=e.getInterpolation();t!==e.DefaultInterpolation&&(i.interpolation=t)}return i.type=e.ValueTypeName,i}InterpolantFactoryMethodDiscrete(e){return new Hd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Vd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Qd(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case wt:t=this.InterpolantFactoryMethodDiscrete;break;case Ct:t=this.InterpolantFactoryMethodLinear;break;case St:t=this.InterpolantFactoryMethodSmooth}if(void 0===t){const t="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(void 0===this.createInterpolant){if(e===this.DefaultInterpolation)throw new Error(t);this.setInterpolation(this.DefaultInterpolation)}return console.warn("THREE.KeyframeTrack:",t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return wt;case this.InterpolantFactoryMethodLinear:return Ct;case this.InterpolantFactoryMethodSmooth:return St}}getValueSize(){return this.values.length/this.times.length}shift(e){if(0!==e){const t=this.times;for(let i=0,n=t.length;i!==n;++i)t[i]+=e}return this}scale(e){if(1!==e){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 r=0,s=n-1;for(;r!==n&&i[r]<e;)++r;for(;-1!==s&&i[s]>t;)--s;if(++s,0!==r||s!==n){r>=s&&(s=Math.max(s,1),r=s-1);const e=this.getValueSize();this.times=i.slice(r,s),this.values=this.values.slice(r*e,s*e)}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,r=i.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let s=null;for(let t=0;t!==r;t++){const n=i[t];if("number"==typeof n&&isNaN(n)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,t,n),e=!1;break}if(null!==s&&s>n){console.error("THREE.KeyframeTrack: Out of order keys.",this,t,n,s),e=!1;break}s=n}if(void 0!==n&&Fd(n))for(let t=0,i=n.length;t!==i;++t){const i=n[t];if(isNaN(i)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,t,i),e=!1;break}}return e}optimize(){const e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),n=this.getInterpolation()===St,r=e.length-1;let s=1;for(let a=1;a<r;++a){let r=!1;const o=e[a];if(o!==e[a+1]&&(1!==a||o!==e[0]))if(n)r=!0;else{const e=a*i,n=e-i,s=e+i;for(let a=0;a!==i;++a){const i=t[e+a];if(i!==t[n+a]||i!==t[s+a]){r=!0;break}}}if(r){if(a!==s){e[s]=e[a];const n=a*i,r=s*i;for(let e=0;e!==i;++e)t[r+e]=t[n+e]}++s}}if(r>0){e[s]=e[r];for(let e=r*i,n=s*i,a=0;a!==i;++a)t[n+a]=t[e+a];++s}return s!==e.length?(this.times=e.slice(0,s),this.values=t.slice(0,s*i)):(this.times=e,this.values=t),this}clone(){const e=this.times.slice(),t=this.values.slice(),i=new(0,this.constructor)(this.name,e,t);return i.createInterpolant=this.createInterpolant,i}}Wd.prototype.TimeBufferType=Float32Array,Wd.prototype.ValueBufferType=Float32Array,Wd.prototype.DefaultInterpolation=Ct;class qd extends Wd{constructor(e,t,i){super(e,t,i)}}qd.prototype.ValueTypeName="bool",qd.prototype.ValueBufferType=Array,qd.prototype.DefaultInterpolation=wt,qd.prototype.InterpolantFactoryMethodLinear=void 0,qd.prototype.InterpolantFactoryMethodSmooth=void 0;class Xd extends Wd{}Xd.prototype.ValueTypeName="color";class Yd extends Wd{}Yd.prototype.ValueTypeName="number";class Kd extends Gd{constructor(e,t,i,n){super(e,t,i,n)}interpolate_(e,t,i,n){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(i-t)/(n-t);let l=e*a;for(let e=l+a;l!==e;l+=4)qi.slerpFlat(r,0,s,l-a,s,l,o);return r}}class Jd extends Wd{InterpolantFactoryMethodLinear(e){return new Kd(this.times,this.values,this.getValueSize(),e)}}Jd.prototype.ValueTypeName="quaternion",Jd.prototype.InterpolantFactoryMethodSmooth=void 0;class Zd extends Wd{constructor(e,t,i){super(e,t,i)}}Zd.prototype.ValueTypeName="string",Zd.prototype.ValueBufferType=Array,Zd.prototype.DefaultInterpolation=wt,Zd.prototype.InterpolantFactoryMethodLinear=void 0,Zd.prototype.InterpolantFactoryMethodSmooth=void 0;class $d extends Wd{}$d.prototype.ValueTypeName="vector";class eu{constructor(e="",t=-1,i=[],n=It){this.name=e,this.tracks=i,this.duration=t,this.blendMode=n,this.uuid=ci(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){const t=[],i=e.tracks,n=1/(e.fps||1);for(let e=0,r=i.length;e!==r;++e)t.push(tu(i[e]).scale(n));const r=new this(e.name,e.duration,t,e.blendMode);return r.uuid=e.uuid,r.userData=JSON.parse(e.userData||"{}"),r}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 e=0,n=i.length;e!==n;++e)t.push(Wd.toJSON(i[e]));return n}static CreateFromMorphTargetSequence(e,t,i,n){const r=t.length,s=[];for(let e=0;e<r;e++){let a=[],o=[];a.push((e+r-1)%r,e,(e+1)%r),o.push(0,1,0);const l=kd(a);a=Nd(a,1,l),o=Nd(o,1,l),!n&&0===a[0]&&(a.push(r),o.push(o[0])),s.push(new Yd(".morphTargetInfluences["+t[e].name+"]",a,o).scale(1/i))}return new this(e,-1,s)}static findByName(e,t){let i=e;if(!Array.isArray(e)){const t=e;i=t.geometry&&t.geometry.animations||t.animations}for(let e=0;e<i.length;e++)if(i[e].name===t)return i[e];return null}static CreateClipsFromMorphTargetSequences(e,t,i){const n={},r=/^([\w-]*?)([\d]+)$/;for(let t=0,i=e.length;t<i;t++){const i=e[t],s=i.name.match(r);if(s&&s.length>1){const e=s[1];let t=n[e];t||(n[e]=t=[]),t.push(i)}}const s=[];for(const e in n)s.push(this.CreateFromMorphTargetSequence(e,n[e],t,i));return s}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const i=function(e,t,i,n,r){if(0!==i.length){const s=[],a=[];jd(i,s,a,n),0!==s.length&&r.push(new e(t,s,a))}},n=[],r=e.name||"default",s=e.fps||30,a=e.blendMode;let o=e.length||-1;const l=e.hierarchy||[];for(let e=0;e<l.length;e++){const r=l[e].keys;if(r&&0!==r.length)if(r[0].morphTargets){const e={};let t;for(t=0;t<r.length;t++)if(r[t].morphTargets)for(let i=0;i<r[t].morphTargets.length;i++)e[r[t].morphTargets[i]]=-1;for(const i in e){const e=[],s=[];for(let n=0;n!==r[t].morphTargets.length;++n){const n=r[t];e.push(n.time),s.push(n.morphTarget===i?1:0)}n.push(new Yd(".morphTargetInfluence["+i+"]",e,s))}o=e.length*s}else{const s=".bones["+t[e].name+"]";i($d,s+".position",r,"pos",n),i(Jd,s+".quaternion",r,"rot",n),i($d,s+".scale",r,"scl",n)}}return 0===n.length?null:new this(r,o,n,a)}resetDuration(){let e=0;for(let t=0,i=this.tracks.length;t!==i;++t){const i=this.tracks[t];e=Math.max(e,i.times[i.times.length-1])}return this.duration=e,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 t=0;t<this.tracks.length;t++)e.push(this.tracks[t].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 tu(e){if(void 0===e.type)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const t=function(e){switch(e.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return Yd;case"vector":case"vector2":case"vector3":case"vector4":return $d;case"color":return Xd;case"quaternion":return Jd;case"bool":case"boolean":return qd;case"string":return Zd}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}(e.type);if(void 0===e.times){const t=[],i=[];jd(e.keys,t,i,"value"),e.times=t,e.values=i}return void 0!==t.parse?t.parse(e):new t(e.name,e.times,e.values,e.interpolation)}const iu={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e,t){return!1===this.enabled?t?Promise.resolve():void 0:t?Promise.resolve(this.files[e]):this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class nu{constructor(e,t,i){const n=this;let r,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i,this.itemStart=function(e){o++,!1===s&&void 0!==n.onStart&&n.onStart(e,a,o),s=!0},this.itemEnd=function(e){a++,void 0!==n.onProgress&&n.onProgress(e,a,o),a===o&&(s=!1,void 0!==n.onLoad&&n.onLoad())},this.itemError=function(e){void 0!==n.onError&&n.onError(e)},this.resolveURL=function(e){return r?r(e):e},this.setURLModifier=function(e){return r=e,this},this.addHandler=function(e,t){return l.push(e,t),this},this.removeHandler=function(e){const t=l.indexOf(e);return-1!==t&&l.splice(t,2),this},this.getHandler=function(e){for(let t=0,i=l.length;t<i;t+=2){const i=l[t],n=l[t+1];if(i.global&&(i.lastIndex=0),i.test(e))return n}return null}}}const ru=new nu;class su{constructor(e){this.manager=void 0!==e?e:ru,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const i=this;return new Promise(function(n,r){i.load(e,n,t,r)})}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}}su.DEFAULT_MATERIAL_NAME="__DEFAULT";const au={};class ou extends Error{constructor(e,t){super(e),this.response=t}}class lu extends su{constructor(e){super(e),this.responseType="text",this.useCache=!0}load(e,t,i,n){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e),(this.useCache?iu.get(e,this.responseType,this.mimeType):Promise.resolve(void 0)).then(r=>{if(void 0!==r)return this.manager.itemStart(e),setTimeout(()=>{t&&t(r),this.manager.itemEnd(e)},0),r;if(void 0!==au[e])return void au[e].push({onLoad:t,onProgress:i,onError:n});au[e]=[],au[e].push({onLoad:t,onProgress:i,onError:n});const s=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(s).then(t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||void 0===t.body||void 0===t.body.getReader)return t;const i=au[e],n=t.body.getReader(),r=t.headers.get("X-File-Size")||t.headers.get("Content-Length"),s=r?parseInt(r):0,a=0!==s;let o=0;const l=new ReadableStream({start(e){!function t(){n.read().then(({done:n,value:r})=>{if(n)e.close();else{o+=r.byteLength;const n=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:s});for(let e=0,t=i.length;e<t;e++){const t=i[e];t.onProgress&&t.onProgress(n)}e.enqueue(r),t()}},t=>{e.error(t)})}()}});return new Response(l)}throw new ou(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)}).then(e=>{switch(o){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then(e=>(new DOMParser).parseFromString(e,a));case"json":return e.json();default:if(void 0===a)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(a),i=t&&t[1]?t[1].toLowerCase():void 0,n=new TextDecoder(i);return e.arrayBuffer().then(e=>n.decode(e))}}}).then(t=>{this.useCache&&iu.add(e,t,this.responseType);const i=au[e];delete au[e];for(let e=0,n=i.length;e<n;e++){const n=i[e];n.onLoad&&n.onLoad(t)}}).catch(t=>{const i=au[e];if(void 0===i)throw this.manager.itemError(e),t;delete au[e];for(let e=0,n=i.length;e<n;e++){const n=i[e];n.onError&&n.onError(t)}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 cu extends su{constructor(e){super(e)}load(e,t,i,n){const r=this,s=[],a=new $c,o=new lu(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(r.withCredentials);let l=0;function c(c){o.load(e[c],function(e){const i=r.parse(e,!0);s[c]={width:i.width,height:i.height,format:i.format,mipmaps:i.mipmaps},l+=1,6===l&&(1===i.mipmapCount&&(a.minFilter=be),a.image=s,a.format=i.format,a.needsUpdate=!0,t&&t(a))},i,n)}if(Array.isArray(e))for(let t=0,i=e.length;t<i;++t)c(t);else o.load(e,function(e){const i=r.parse(e,!0);if(i.isCubemap){const e=i.mipmaps.length/i.mipmapCount;for(let t=0;t<e;t++){s[t]={mipmaps:[]};for(let e=0;e<i.mipmapCount;e++)s[t].mipmaps.push(i.mipmaps[t*i.mipmapCount+e]),s[t].format=i.format,s[t].width=i.width,s[t].height=i.height}a.image=s}else a.image.width=i.width,a.image.height=i.height,a.mipmaps=i.mipmaps;1===i.mipmapCount&&(a.minFilter=be),a.format=i.format,a.needsUpdate=!0,t&&t(a)},i,n);return a}}class hu extends su{constructor(e){super(e)}load(e,t,i,n){const r=e;void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const s=this,a=iu.get(e);if(void 0!==a)return s.manager.itemStart(e),setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0),a;const o=xi("img");function l(){h(),iu.add(e,this),t&&t(this),s.manager.itemEnd(e)}function c(t){h(),n&&n(t),s.manager.itemError(e),s.manager.itemEnd(e)}function h(){o.removeEventListener("load",l,!1),o.removeEventListener("error",c,!1)}return o.addEventListener("load",l,!1),o.addEventListener("error",c,!1),"data:"!==e.slice(0,5)&&void 0!==this.crossOrigin&&(o.crossOrigin=this.crossOrigin),s.manager.itemStart(e),iu.get(e,"blob").then(t=>{if(void 0!==t&&!t.type.startsWith("text/plain"))return t.type||(e.endsWith(".svg")||e.startsWith("data:image/svg"))&&(t=new Blob([t],{type:"image/svg+xml"})),void(o.src=URL.createObjectURL(t));const s=new lu(this.manager);s.useCache=!1,s.setPath(this.path),s.setCrossOrigin(this.crossOrigin),s.setResponseType("blob"),s.load(r,function(t){t.type||(e.endsWith(".svg")||e.startsWith("data:image/svg"))&&(t=new Blob([t],{type:"image/svg+xml"})),iu.add(e,t,"blob"),o.src=URL.createObjectURL(t)},i,e=>{h(),n&&n(e)})}),o}}class du extends su{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new ec,a=new lu(this.manager);return a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setPath(this.path),a.setWithCredentials(r.withCredentials),a.load(e,function(e){let i;try{i=r.parse(e)}catch(e){if(void 0===n)return void console.error(e);n(e)}void 0!==i.image?s.image=i.image:void 0!==i.data&&(s.image.width=i.width,s.image.height=i.height,s.image.data=i.data,s.image.complete=!0),s.wrapS=void 0!==i.wrapS?i.wrapS:fe,s.wrapT=void 0!==i.wrapT?i.wrapT:fe,s.magFilter=void 0!==i.magFilter?i.magFilter:be,s.minFilter=void 0!==i.minFilter?i.minFilter:be,s.anisotropy=void 0!==i.anisotropy?i.anisotropy:1,void 0!==i.colorSpace&&(s.colorSpace=i.colorSpace),void 0!==i.flipY&&(s.flipY=i.flipY),void 0!==i.format&&(s.format=i.format),void 0!==i.type&&(s.type=i.type),void 0!==i.mipmaps&&(s.mipmaps=i.mipmaps,s.minFilter=we),1===i.mipmapCount&&(s.minFilter=be),void 0!==i.generateMipmaps&&(s.generateMipmaps=i.generateMipmaps),s.needsUpdate=!0,t&&t(s,i)},i,n),s}}class uu extends su{constructor(e){super(e)}load(e,t,i,n){const r=new Ni,s=new hu(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(i){r.image=i,r.needsUpdate=!0,e.startsWith("blob:")||(r.userData.rootPath=s.path+e),void 0!==t&&t(r)},i,function(e){r.image instanceof ImageData&&(r.needsUpdate=!0),void 0!==n&&n(e)}),r}}class pu extends Zn{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new mr(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,void 0!==this.groundColor&&(t.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(t.object.distance=this.distance),void 0!==this.angle&&(t.object.angle=this.angle),void 0!==this.decay&&(t.object.decay=this.decay),void 0!==this.penumbra&&(t.object.penumbra=this.penumbra),void 0!==this.shadow&&(t.object.shadow=this.shadow.toJSON()),void 0!==this.target&&(t.object.target=this.target.uuid),t}}class mu extends pu{constructor(e,t,i){super(e,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Zn.DEFAULT_UP),this.updateMatrix(),this.groundColor=new mr(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}const gu=new Sn,fu=new Xi,Au=new Xi;class yu{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new fi(512,512),this.map=null,this.mapPass=null,this.matrix=new Sn,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Cs,this._frameExtents=new fi(1,1),this._viewportCount=1,this._viewports=[new Gi(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,i=this.matrix;fu.setFromMatrixPosition(e.matrixWorld),t.position.copy(fu),Au.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Au),t.updateMatrixWorld(),gu.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(gu),i.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),i.multiply(gu)}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 1!==this.intensity&&(e.intensity=this.intensity),0!==this.bias&&(e.bias=this.bias),0!==this.normalBias&&(e.normalBias=this.normalBias),1!==this.radius&&(e.radius=this.radius),(512!==this.mapSize.x||512!==this.mapSize.y)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class vu extends yu{constructor(){super(new ps(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){const t=this.camera,i=2*li*e.angle*this.focus,n=this.mapSize.width/this.mapSize.height,r=e.distance||t.far;(i!==t.fov||n!==t.aspect||r!==t.far)&&(t.fov=i,t.aspect=n,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class _u extends pu{constructor(e,t,i=0,n=Math.PI/3,r=0,s=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Zn.DEFAULT_UP),this.updateMatrix(),this.target=new Zn,this.distance=i,this.angle=n,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new vu}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 bu=new Sn,xu=new Xi,wu=new Xi;class Cu extends yu{constructor(){super(new ps(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new fi(4,2),this._viewportCount=6,this._viewports=[new Gi(2,1,1,1),new Gi(0,1,1,1),new Gi(3,1,1,1),new Gi(1,1,1,1),new Gi(3,0,1,1),new Gi(1,0,1,1)],this._cubeDirections=[new Xi(1,0,0),new Xi(-1,0,0),new Xi(0,0,1),new Xi(0,0,-1),new Xi(0,1,0),new Xi(0,-1,0)],this._cubeUps=[new Xi(0,1,0),new Xi(0,1,0),new Xi(0,1,0),new Xi(0,1,0),new Xi(0,0,1),new Xi(0,0,-1)]}updateMatrices(e,t=0){const i=this.camera,n=this.matrix,r=e.distance||i.far;r!==i.far&&(i.far=r,i.updateProjectionMatrix()),xu.setFromMatrixPosition(e.matrixWorld),i.position.copy(xu),wu.copy(i.position),wu.add(this._cubeDirections[t]),i.up.copy(this._cubeUps[t]),i.lookAt(wu),i.updateMatrixWorld(),n.makeTranslation(-xu.x,-xu.y,-xu.z),bu.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),this._frustum.setFromProjectionMatrix(bu)}}class Su extends pu{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 Cu}get power(){return 4*this.intensity*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 Mu extends yu{constructor(){super(new zs(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Eu extends pu{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Zn.DEFAULT_UP),this.updateMatrix(),this.target=new Zn,this.shadow=new Mu}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class Tu extends pu{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Iu extends pu{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 Pu{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new Xi)}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,r=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.282095),t.addScaledVector(s[1],.488603*n),t.addScaledVector(s[2],.488603*r),t.addScaledVector(s[3],.488603*i),t.addScaledVector(s[4],i*n*1.092548),t.addScaledVector(s[5],n*r*1.092548),t.addScaledVector(s[6],.315392*(3*r*r-1)),t.addScaledVector(s[7],i*r*1.092548),t.addScaledVector(s[8],.546274*(i*i-n*n)),t}getIrradianceAt(e,t){const i=e.x,n=e.y,r=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.886227),t.addScaledVector(s[1],1.023328*n),t.addScaledVector(s[2],1.023328*r),t.addScaledVector(s[3],1.023328*i),t.addScaledVector(s[4],.858086*i*n),t.addScaledVector(s[5],.858086*n*r),t.addScaledVector(s[6],.743125*r*r-.247708),t.addScaledVector(s[7],.858086*i*r),t.addScaledVector(s[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+3*n);return this}toArray(e=[],t=0){const i=this.coefficients;for(let n=0;n<9;n++)i[n].toArray(e,t+3*n);return e}static getBasisAt(e,t){const i=e.x,n=e.y,r=e.z;t[0]=.282095,t[1]=.488603*n,t[2]=.488603*r,t[3]=.488603*i,t[4]=1.092548*i*n,t[5]=1.092548*n*r,t[6]=.315392*(3*r*r-1),t[7]=1.092548*i*r,t[8]=.546274*(i*i-n*n)}}class Du extends pu{constructor(e=new Pu,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 Ru extends su{constructor(e){super(e),this.textures={}}load(e,t,i,n){const r=this,s=new lu(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(e,function(i){try{t(r.parse(JSON.parse(i)))}catch(t){n?n(t):console.error(t),r.manager.itemError(e)}},i,n)}parse(e){const t=this.textures;function i(e){return void 0===t[e]&&console.warn("THREE.MaterialLoader: Undefined texture",e),t[e]}const n=e.metadata&&e.metadata.version<=4.5?Ut:void 0,r=Ru.createMaterialFromType(e.type);if(void 0!==e.uuid&&(r.uuid=e.uuid),void 0!==e.name&&(r.name=e.name),void 0!==e.color&&void 0!==r.color&&r.color.setHex(e.color,n),void 0!==e.roughness&&(r.roughness=e.roughness),void 0!==e.metalness&&(r.metalness=e.metalness),void 0!==e.sheen&&(r.sheen=e.sheen),void 0!==e.sheenColor&&(r.sheenColor=(new mr).setHex(e.sheenColor,n)),void 0!==e.sheenRoughness&&(r.sheenRoughness=e.sheenRoughness),void 0!==e.emissive&&void 0!==r.emissive&&r.emissive.setHex(e.emissive,n),void 0!==e.specular&&void 0!==r.specular&&r.specular.setHex(e.specular,n),void 0!==e.specularIntensity&&(r.specularIntensity=e.specularIntensity),void 0!==e.specularColor&&void 0!==r.specularColor&&r.specularColor.setHex(e.specularColor,n),void 0!==e.shininess&&(r.shininess=e.shininess),void 0!==e.clearcoat&&(r.clearcoat=e.clearcoat),void 0!==e.clearcoatRoughness&&(r.clearcoatRoughness=e.clearcoatRoughness),void 0!==e.dispersion&&(r.dispersion=e.dispersion),void 0!==e.iridescence&&(r.iridescence=e.iridescence),void 0!==e.iridescenceIOR&&(r.iridescenceIOR=e.iridescenceIOR),void 0!==e.iridescenceThicknessRange&&(r.iridescenceThicknessRange=e.iridescenceThicknessRange),void 0!==e.transmission&&(r.transmission=e.transmission),void 0!==e.thickness&&(r.thickness=e.thickness),void 0!==e.attenuationDistance&&(r.attenuationDistance=e.attenuationDistance),void 0!==e.attenuationColor&&void 0!==r.attenuationColor&&r.attenuationColor.setHex(e.attenuationColor,n),void 0!==e.anisotropy&&(r.anisotropy=e.anisotropy),void 0!==e.anisotropyRotation&&(r.anisotropyRotation=e.anisotropyRotation),void 0!==e.fog&&(r.fog=e.fog),void 0!==e.flatShading&&(r.flatShading=e.flatShading),void 0!==e.blending&&(r.blending=e.blending),void 0!==e.combine&&(r.combine=e.combine),void 0!==e.side&&(r.side=e.side),void 0!==e.shadowSide&&(r.shadowSide=e.shadowSide),void 0!==e.opacity&&(r.opacity=e.opacity),void 0!==e.transparent&&(r.transparent=e.transparent),void 0!==e.alphaTest&&(r.alphaTest=e.alphaTest),void 0!==e.alphaHash&&(r.alphaHash=e.alphaHash),void 0!==e.depthFunc&&(r.depthFunc=e.depthFunc),void 0!==e.depthTest&&(r.depthTest=e.depthTest),void 0!==e.depthWrite&&(r.depthWrite=e.depthWrite),void 0!==e.colorWrite&&(r.colorWrite=e.colorWrite),void 0!==e.blendSrc&&(r.blendSrc=e.blendSrc),void 0!==e.blendDst&&(r.blendDst=e.blendDst),void 0!==e.blendEquation&&(r.blendEquation=e.blendEquation),void 0!==e.blendSrcAlpha&&(r.blendSrcAlpha=e.blendSrcAlpha),void 0!==e.blendDstAlpha&&(r.blendDstAlpha=e.blendDstAlpha),void 0!==e.blendEquationAlpha&&(r.blendEquationAlpha=e.blendEquationAlpha),void 0!==e.blendColor&&void 0!==r.blendColor&&r.blendColor.setHex(e.blendColor),void 0!==e.blendAlpha&&(r.blendAlpha=e.blendAlpha),void 0!==e.stencilWriteMask&&(r.stencilWriteMask=e.stencilWriteMask),void 0!==e.stencilFunc&&(r.stencilFunc=e.stencilFunc),void 0!==e.stencilRef&&(r.stencilRef=e.stencilRef),void 0!==e.stencilFuncMask&&(r.stencilFuncMask=e.stencilFuncMask),void 0!==e.stencilFail&&(r.stencilFail=e.stencilFail),void 0!==e.stencilZFail&&(r.stencilZFail=e.stencilZFail),void 0!==e.stencilZPass&&(r.stencilZPass=e.stencilZPass),void 0!==e.stencilWrite&&(r.stencilWrite=e.stencilWrite),void 0!==e.wireframe&&(r.wireframe=e.wireframe),void 0!==e.wireframeLinewidth&&(r.wireframeLinewidth=e.wireframeLinewidth),void 0!==e.wireframeLinecap&&(r.wireframeLinecap=e.wireframeLinecap),void 0!==e.wireframeLinejoin&&(r.wireframeLinejoin=e.wireframeLinejoin),void 0!==e.rotation&&(r.rotation=e.rotation),void 0!==e.linewidth&&(r.linewidth=e.linewidth),void 0!==e.dashSize&&(r.dashSize=e.dashSize),void 0!==e.gapSize&&(r.gapSize=e.gapSize),void 0!==e.scale&&(r.scale=e.scale),void 0!==e.polygonOffset&&(r.polygonOffset=e.polygonOffset),void 0!==e.polygonOffsetFactor&&(r.polygonOffsetFactor=e.polygonOffsetFactor),void 0!==e.polygonOffsetUnits&&(r.polygonOffsetUnits=e.polygonOffsetUnits),void 0!==e.dithering&&(r.dithering=e.dithering),void 0!==e.alphaToCoverage&&(r.alphaToCoverage=e.alphaToCoverage),void 0!==e.premultipliedAlpha&&(r.premultipliedAlpha=e.premultipliedAlpha),void 0!==e.forceSinglePass&&(r.forceSinglePass=e.forceSinglePass),void 0!==e.visible&&(r.visible=e.visible),void 0!==e.toneMapped&&(r.toneMapped=e.toneMapped),void 0!==e.userData&&(r.userData=e.userData),void 0!==e.vertexColors&&("number"==typeof e.vertexColors?r.vertexColors=e.vertexColors>0:r.vertexColors=e.vertexColors),void 0!==e.uniforms)for(const t in e.uniforms){const s=e.uniforms[t];switch(r.uniforms[t]={},s.type){case"t":r.uniforms[t].value=i(s.value);break;case"c":r.uniforms[t].value=(new mr).setHex(s.value,n);break;case"v2":r.uniforms[t].value=(new fi).fromArray(s.value);break;case"v3":r.uniforms[t].value=(new Xi).fromArray(s.value);break;case"v4":r.uniforms[t].value=(new Gi).fromArray(s.value);break;case"m3":r.uniforms[t].value=(new Ai).fromArray(s.value);break;case"m4":r.uniforms[t].value=(new Sn).fromArray(s.value);break;default:r.uniforms[t].value=s.value}}if(void 0!==e.defines&&(r.defines=e.defines),void 0!==e.vertexShader&&(r.vertexShader=e.vertexShader),void 0!==e.fragmentShader&&(r.fragmentShader=e.fragmentShader),void 0!==e.glslVersion&&(r.glslVersion=e.glslVersion),void 0!==e.extensions)for(const t in e.extensions)r.extensions[t]=e.extensions[t];if(void 0!==e.lights&&(r.lights=e.lights),void 0!==e.clipping&&(r.clipping=e.clipping),void 0!==e.size&&(r.size=e.size),void 0!==e.sizeAttenuation&&(r.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(r.map=i(e.map)),void 0!==e.matcap&&(r.matcap=i(e.matcap)),void 0!==e.alphaMap&&(r.alphaMap=i(e.alphaMap)),void 0!==e.bumpMap&&(r.bumpMap=i(e.bumpMap)),void 0!==e.bumpScale&&(r.bumpScale=e.bumpScale),void 0!==e.normalMap&&(r.normalMap=i(e.normalMap)),void 0!==e.normalMapType&&(r.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),r.normalScale=(new fi).fromArray(t)}return void 0!==e.displacementMap&&(r.displacementMap=i(e.displacementMap)),void 0!==e.displacementScale&&(r.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(r.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(r.roughnessMap=i(e.roughnessMap)),void 0!==e.metalnessMap&&(r.metalnessMap=i(e.metalnessMap)),void 0!==e.emissiveMap&&(r.emissiveMap=i(e.emissiveMap)),void 0!==e.emissiveIntensity&&(r.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(r.specularMap=i(e.specularMap)),void 0!==e.specularIntensityMap&&(r.specularIntensityMap=i(e.specularIntensityMap)),void 0!==e.specularColorMap&&(r.specularColorMap=i(e.specularColorMap)),void 0!==e.envMap&&(r.envMap=i(e.envMap)),void 0!==e.envMapRotation&&r.envMapRotation.fromArray(e.envMapRotation),void 0!==e.envMapIntensity&&(r.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(r.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(r.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(r.lightMap=i(e.lightMap)),void 0!==e.lightMapIntensity&&(r.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(r.aoMap=i(e.aoMap)),void 0!==e.aoMapIntensity&&(r.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(r.gradientMap=i(e.gradientMap)),void 0!==e.clearcoatMap&&(r.clearcoatMap=i(e.clearcoatMap)),void 0!==e.clearcoatRoughnessMap&&(r.clearcoatRoughnessMap=i(e.clearcoatRoughnessMap)),void 0!==e.clearcoatNormalMap&&(r.clearcoatNormalMap=i(e.clearcoatNormalMap)),void 0!==e.clearcoatNormalScale&&(r.clearcoatNormalScale=(new fi).fromArray(e.clearcoatNormalScale)),void 0!==e.iridescenceMap&&(r.iridescenceMap=i(e.iridescenceMap)),void 0!==e.iridescenceThicknessMap&&(r.iridescenceThicknessMap=i(e.iridescenceThicknessMap)),void 0!==e.transmissionMap&&(r.transmissionMap=i(e.transmissionMap)),void 0!==e.thicknessMap&&(r.thicknessMap=i(e.thicknessMap)),void 0!==e.anisotropyMap&&(r.anisotropyMap=i(e.anisotropyMap)),void 0!==e.sheenColorMap&&(r.sheenColorMap=i(e.sheenColorMap)),void 0!==e.sheenRoughnessMap&&(r.sheenRoughnessMap=i(e.sheenRoughnessMap)),r}setTextures(e){return this.textures=e,this}static createMaterialFromType(e){return new{ShadowMaterial:Md,SpriteMaterial:Cl,RawShaderMaterial:Ed,ShaderMaterial:ls,PointsMaterial:Hc,MeshPhysicalMaterial:Id,MeshStandardMaterial:Td,MeshPhongMaterial:Pd,MeshToonMaterial:Dd,MeshNormalMaterial:Rd,MeshLambertMaterial:Bd,MeshDepthMaterial:el,MeshDistanceMaterial:tl,MeshBasicMaterial:vr,MeshMatcapMaterial:Ld,LineDashedMaterial:Od,LineBasicMaterial:Dc,Material:Ar}[e]}}class Bu{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-1===t?"./":e.slice(0,t+1)}static resolveURL(e,t){if("string"!=typeof e||""===e)return"";if("/"===e[0]){if(!/^https?:\/\//i.test(t))return e;t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")}return/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e}}class Lu extends Fr{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 Ou extends su{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new lu(r.manager);s.setPath(r.path),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(e,function(i){try{t(r.parse(JSON.parse(i)))}catch(t){n?n(t):console.error(t),r.manager.itemError(e)}},i,n)}parse(e){const t={},i={};function n(e,n){if(void 0!==t[n])return t[n];const r=e.interleavedBuffers[n],s=function(e,t){if(void 0!==i[t])return i[t];const n=e.arrayBuffers[t],r=new Uint32Array(n).buffer;return i[t]=r,r}(e,r.buffer),a=bi(r.type,s),o=new bl(a,r.stride);return o.uuid=r.uuid,t[n]=o,o}const r=e.isInstancedBufferGeometry?new Lu:new Fr,s=e.data.index;if(void 0!==s){const e=bi(s.type,s.array);r.setIndex(new Mr(e,1))}const a=e.data.attributes;for(const t in a){const i=a[t];let s;if(i.isInterleavedBufferAttribute){const t=n(e.data,i.data);s=new wl(t,i.itemSize,i.offset,i.normalized)}else{const e=bi(i.type,i.array);s=new(i.isInstancedBufferAttribute?rc:Mr)(e,i.itemSize,i.normalized)}void 0!==i.name&&(s.name=i.name),void 0!==i.usage&&s.setUsage(i.usage),r.setAttribute(t,s)}const o=e.data.morphAttributes;if(o)for(const t in o){const i=o[t],s=[];for(let t=0,r=i.length;t<r;t++){const r=i[t];let a;if(r.isInterleavedBufferAttribute){const t=n(e.data,r.data);a=new wl(t,r.itemSize,r.offset,r.normalized)}else{const e=bi(r.type,r.array);a=new Mr(e,r.itemSize,r.normalized)}void 0!==r.name&&(a.name=r.name),s.push(a)}r.morphAttributes[t]=s}e.data.morphTargetsRelative&&(r.morphTargetsRelative=!0);const l=e.data.groups||e.data.drawcalls||e.data.offsets;if(void 0!==l)for(let e=0,t=l.length;e!==t;++e){const t=l[e];r.addGroup(t.start,t.count,t.materialIndex)}const c=e.data.boundingSphere;if(void 0!==c){const e=new Xi;void 0!==c.center&&e.fromArray(c.center),r.boundingSphere=new fn(e,c.radius)}return e.name&&(r.name=e.name),e.userData&&(r.userData=e.userData),r}}class Uu extends su{constructor(e){super(e)}load(e,t,i,n){const r=this,s=""===this.path?Bu.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||s;const a=new lu(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(i){let s=null;try{s=JSON.parse(i)}catch(t){return void 0!==n&&n(t),void console.error("THREE:ObjectLoader: Can't parse "+e+".",t.message)}const a=s.metadata;if(void 0===a||void 0===a.type||"geometry"===a.type.toLowerCase())return void 0!==n&&n(new Error("THREE.ObjectLoader: Can't load "+e)),void console.error("THREE.ObjectLoader: Can't load "+e);r.parse(s,t)},i,n)}async loadAsync(e,t){const i=""===this.path?Bu.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||i;const n=new lu(this.manager);n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials);const r=await n.loadAsync(e,t),s=JSON.parse(r),a=s.metadata;if(void 0===a||void 0===a.type||"geometry"===a.type.toLowerCase())throw new Error("THREE.ObjectLoader: Can't load "+e);return await this.parseAsync(s)}parse(e,t){const i=this.parseAnimations(e.animations),n=this.parseShapes(e.shapes),r=this.parseGeometries(e.geometries,n),s=this.parseImages(e.images,function(){void 0!==t&&t(l)}),a=this.parseTextures(e.textures,s),o=this.parseMaterials(e.materials,a),l=this.parseObject(e.object,r,o,a,i),c=this.parseSkeletons(e.skeletons,l);if(this.bindSkeletons(l,c),this.bindLightTargets(l),void 0!==t){let e=!1;for(const t in s)if(s[t].data instanceof HTMLImageElement){e=!0;break}!1===e&&t(l)}return l}async parseAsync(e){const t=this.parseAnimations(e.animations),i=this.parseShapes(e.shapes),n=this.parseGeometries(e.geometries,i),r=await this.parseImagesAsync(e.images),s=this.parseTextures(e.textures,r),a=this.parseMaterials(e.materials,s),o=this.parseObject(e.object,n,a,s,t),l=this.parseSkeletons(e.skeletons,o);return this.bindSkeletons(o,l),this.bindLightTargets(o),o}parseShapes(e){const t={};if(void 0!==e)for(let i=0,n=e.length;i<n;i++){const n=(new Fh).fromJSON(e[i]);t[n.uuid]=n}return t}parseSkeletons(e,t){const i={},n={};if(t.traverse(function(e){e.isBone&&(n[e.uuid]=e)}),void 0!==e)for(let t=0,r=e.length;t<r;t++){const r=(new nc).fromJSON(e[t],n);i[r.uuid]=r}return i}parseGeometries(e,t){const i={};if(void 0!==e){const n=new Ou;for(let r=0,s=e.length;r<s;r++){let s;const a=e[r];switch(a.type){case"BufferGeometry":case"InstancedBufferGeometry":s=n.parse(a);break;default:a.type in Sd?s=Sd[a.type].fromJSON(a,t):console.warn(`THREE.ObjectLoader: Unsupported geometry type "${a.type}"`)}s.uuid=a.uuid,void 0!==a.name&&(s.name=a.name),void 0!==a.userData&&(s.userData=a.userData),i[a.uuid]=s}}return i}parseMaterials(e,t){const i={},n={};if(void 0!==e){const r=new Ru;r.setTextures(t);for(let t=0,s=e.length;t<s;t++){const s=e[t];void 0===i[s.uuid]&&(i[s.uuid]=r.parse(s)),n[s.uuid]=i[s.uuid]}}return n}parseAnimations(e){const t={};if(void 0!==e)for(let i=0;i<e.length;i++){const n=e[i],r=eu.parse(n);t[r.uuid]=r}return t}parseImages(e,t){const i=this,n={};let r;function s(e){if("string"==typeof e){const t=e;return function(e){return i.manager.itemStart(e),r.load(e,function(){i.manager.itemEnd(e)},void 0,function(){i.manager.itemError(e),i.manager.itemEnd(e)})}(/^(\/\/)|([a-z]+:(\/\/)?)/i.test(t)?t:i.resourcePath+t)}return e.data?{data:bi(e.type,e.data),width:e.width,height:e.height,complete:!0}:null}if(void 0!==e&&e.length>0){const i=new nu(t);r=new hu(i),r.setCrossOrigin(this.crossOrigin);for(let t=0,i=e.length;t<i;t++){const i=e[t],r=i.url;if(Array.isArray(r)){const e=[];for(let t=0,i=r.length;t<i;t++){const i=s(r[t]);null!==i&&(i instanceof HTMLImageElement?e.push(i):e.push(new ec(i.data,i.width,i.height)))}n[i.uuid]=new Ui(e)}else{const e=s(i.url);n[i.uuid]=new Ui(e)}}}return n}async parseImagesAsync(e){const t=this,i={};let n;async function r(e){if("string"==typeof e){const i=e,r=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(i)?i:t.resourcePath+i;return await n.loadAsync(r)}return e.data?{data:bi(e.type,e.data),width:e.width,height:e.height,complete:!0}:null}if(void 0!==e&&e.length>0){n=new hu(this.manager),n.setCrossOrigin(this.crossOrigin);for(let t=0,n=e.length;t<n;t++){const n=e[t],s=n.url;if(Array.isArray(s)){const e=[];for(let t=0,i=s.length;t<i;t++){const i=s[t],n=await r(i);null!==n&&(n instanceof HTMLImageElement?e.push(n):e.push(new ec(n.data,n.width,n.height)))}i[n.uuid]=new Ui(e)}else{const e=await r(n.url);i[n.uuid]=new Ui(e)}}}return i}parseTextures(e,t){function i(e,t){return"number"==typeof e?e:(console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",e),t[e])}const n={};if(void 0!==e)for(let r=0,s=e.length;r<s;r++){const s=e[r];void 0===s.image&&console.warn('THREE.ObjectLoader: No "image" specified for',s.uuid),void 0===t[s.image]&&console.warn("THREE.ObjectLoader: Undefined image",s.image);const a=t[s.image],o=a?a.data:void 0;let l;Array.isArray(o)?(l=new fs,6===o.length&&(l.needsUpdate=!0)):(l=o&&o.data?new ec:new Ni,o&&o.complete&&(l.needsUpdate=!0)),l.source=a,l.uuid=s.uuid,void 0!==s.name&&(l.name=s.name),void 0!==s.mapping&&(l.mapping=i(s.mapping,Fu)),void 0!==s.channel&&(l.channel=s.channel),void 0!==s.offset&&l.offset.fromArray(s.offset),void 0!==s.repeat&&l.repeat.fromArray(s.repeat),void 0!==s.center&&l.center.fromArray(s.center),void 0!==s.rotation&&(l.rotation=s.rotation),void 0!==s.wrap&&(l.wrapS=i(s.wrap[0],ku),l.wrapT=i(s.wrap[1],ku)),void 0!==s.format&&(l.format=s.format),void 0!==s.internalFormat&&(l.internalFormat=s.internalFormat),void 0!==s.type&&(l.type=s.type),void 0!==s.colorSpace?l.colorSpace=s.colorSpace:void 0!==s.encoding&&(l.encoding=s.encoding),void 0!==s.minFilter&&(l.minFilter=i(s.minFilter,Nu)),void 0!==s.magFilter&&(l.magFilter=i(s.magFilter,Nu)),void 0!==s.anisotropy&&(l.anisotropy=s.anisotropy),void 0!==s.flipY&&(l.flipY=s.flipY),void 0!==s.generateMipmaps&&(l.generateMipmaps=s.generateMipmaps),void 0!==s.premultiplyAlpha&&(l.premultiplyAlpha=s.premultiplyAlpha),void 0!==s.unpackAlignment&&(l.unpackAlignment=s.unpackAlignment),void 0!==s.compareFunction&&(l.compareFunction=s.compareFunction),void 0!==s.userData&&(l.userData=s.userData),n[s.uuid]=l}return n}parseObject(e,t,i,n,r){let s;const a=e.metadata&&e.metadata.version<=4.5?Ut:void 0;function o(e){return void 0===t[e]&&console.warn("THREE.ObjectLoader: Undefined geometry",e),t[e]}function l(e){if(void 0!==e){if(Array.isArray(e)){const t=[];for(let n=0,r=e.length;n<r;n++){const r=e[n];void 0===i[r]&&console.warn("THREE.ObjectLoader: Undefined material",r),t.push(i[r])}return t}return void 0===i[e]&&console.warn("THREE.ObjectLoader: Undefined material",e),i[e]}}function c(e){return void 0===n[e]&&console.warn("THREE.ObjectLoader: Undefined texture",e),n[e]}let h,d;switch(e.type){case"Scene":s=new _l,void 0!==e.background&&(Number.isInteger(e.background)?s.background=(new mr).setHex(e.background,a):s.background=c(e.background)),void 0!==e.environment&&(s.environment=c(e.environment)),void 0!==e.fog&&("Fog"===e.fog.type?s.fog=new vl(e.fog.color,e.fog.near,e.fog.far):"FogExp2"===e.fog.type&&(s.fog=new yl(e.fog.color,e.fog.density)),""!==e.fog.name&&(s.fog.name=e.fog.name)),void 0!==e.backgroundBlurriness&&(s.backgroundBlurriness=e.backgroundBlurriness),void 0!==e.backgroundIntensity&&(s.backgroundIntensity=e.backgroundIntensity),void 0!==e.backgroundRotation&&s.backgroundRotation.fromArray(e.backgroundRotation),void 0!==e.environmentIntensity&&(s.environmentIntensity=e.environmentIntensity),void 0!==e.environmentRotation&&s.environmentRotation.fromArray(e.environmentRotation);break;case"PerspectiveCamera":s=new ps(e.fov,e.aspect,e.near,e.far),void 0!==e.focus&&(s.focus=e.focus),void 0!==e.zoom&&(s.zoom=e.zoom),void 0!==e.filmGauge&&(s.filmGauge=e.filmGauge),void 0!==e.filmOffset&&(s.filmOffset=e.filmOffset),void 0!==e.view&&(s.view=Object.assign({},e.view));break;case"OrthographicCamera":s=new zs(e.left,e.right,e.top,e.bottom,e.near,e.far),void 0!==e.zoom&&(s.zoom=e.zoom),void 0!==e.view&&(s.view=Object.assign({},e.view));break;case"AmbientLight":s=new Tu(e.color,e.intensity);break;case"DirectionalLight":s=new Eu(e.color,e.intensity),s.target=e.target||"";break;case"PointLight":s=new Su(e.color,e.intensity,e.distance,e.decay);break;case"RectAreaLight":s=new Iu(e.color,e.intensity,e.width,e.height);break;case"SpotLight":s=new _u(e.color,e.intensity,e.distance,e.angle,e.penumbra,e.decay),s.target=e.target||"";break;case"HemisphereLight":s=new mu(e.color,e.groundColor,e.intensity);break;case"LightProbe":s=(new Du).fromJSON(e);break;case"SkinnedMesh":h=o(e.geometry),d=l(e.material),s=new Zl(h,d),void 0!==e.bindMode&&(s.bindMode=e.bindMode),void 0!==e.bindMatrix&&s.bindMatrix.fromArray(e.bindMatrix),void 0!==e.skeleton&&(s.skeleton=e.skeleton);break;case"Mesh":h=o(e.geometry),d=l(e.material),s=new ts(h,d);break;case"InstancedMesh":h=o(e.geometry),d=l(e.material);const t=e.count,i=e.instanceMatrix,n=e.instanceColor;s=new uc(h,d,t),s.instanceMatrix=new rc(new Float32Array(i.array),16),void 0!==n&&(s.instanceColor=new rc(new Float32Array(n.array),n.itemSize));break;case"BatchedMesh":h=o(e.geometry),d=l(e.material),s=new Pc(e.maxInstanceCount,e.maxVertexCount,e.maxIndexCount,d),s.geometry=h,s.perObjectFrustumCulled=e.perObjectFrustumCulled,s.sortObjects=e.sortObjects,s._drawRanges=e.drawRanges,s._reservedRanges=e.reservedRanges,s._visibility=e.visibility,s._active=e.active,s._bounds=e.bounds.map(e=>{const t=new Ji;t.min.fromArray(e.boxMin),t.max.fromArray(e.boxMax);const i=new fn;return i.radius=e.sphereRadius,i.center.fromArray(e.sphereCenter),{boxInitialized:e.boxInitialized,box:t,sphereInitialized:e.sphereInitialized,sphere:i}}),s._maxInstanceCount=e.maxInstanceCount,s._maxVertexCount=e.maxVertexCount,s._maxIndexCount=e.maxIndexCount,s._geometryInitialized=e.geometryInitialized,s._geometryCount=e.geometryCount,s._matricesTexture=c(e.matricesTexture.uuid),void 0!==e.colorsTexture&&(s._colorsTexture=c(e.colorsTexture.uuid));break;case"LOD":s=new Gl;break;case"Line":s=new Nc(o(e.geometry),l(e.material));break;case"LineLoop":s=new Vc(o(e.geometry),l(e.material));break;case"LineSegments":s=new Qc(o(e.geometry),l(e.material));break;case"PointCloud":case"Points":s=new Kc(o(e.geometry),l(e.material));break;case"Sprite":s=new kl(l(e.material));break;case"Group":s=new ll;break;case"Bone":s=new $l;break;default:s=new Zn}if(s.uuid=e.uuid,void 0!==e.name&&(s.name=e.name),void 0!==e.matrix?(s.matrix.fromArray(e.matrix),void 0!==e.matrixAutoUpdate&&(s.matrixAutoUpdate=e.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(void 0!==e.position&&s.position.fromArray(e.position),void 0!==e.rotation&&s.rotation.fromArray(e.rotation),void 0!==e.quaternion&&s.quaternion.fromArray(e.quaternion),void 0!==e.scale&&s.scale.fromArray(e.scale)),void 0!==e.up&&s.up.fromArray(e.up),void 0!==e.castShadow&&(s.castShadow=e.castShadow),void 0!==e.receiveShadow&&(s.receiveShadow=e.receiveShadow),e.shadow&&(void 0!==e.shadow.intensity&&(s.shadow.intensity=e.shadow.intensity),void 0!==e.shadow.bias&&(s.shadow.bias=e.shadow.bias),void 0!==e.shadow.normalBias&&(s.shadow.normalBias=e.shadow.normalBias),void 0!==e.shadow.radius&&(s.shadow.radius=e.shadow.radius),void 0!==e.shadow.mapSize&&s.shadow.mapSize.fromArray(e.shadow.mapSize),void 0!==e.shadow.camera&&(s.shadow.camera=this.parseObject(e.shadow.camera))),void 0!==e.visible&&(s.visible=e.visible),void 0!==e.frustumCulled&&(s.frustumCulled=e.frustumCulled),void 0!==e.renderOrder&&(s.renderOrder=e.renderOrder),void 0!==e.userData&&(s.userData=e.userData),void 0!==e.layers&&(s.layers.mask=e.layers),void 0!==e.children){const a=e.children;for(let e=0;e<a.length;e++)s.add(this.parseObject(a[e],t,i,n,r))}if(void 0!==e.animations){const t=e.animations;for(let e=0;e<t.length;e++){const i=t[e];s.animations.push(r[i])}}if("LOD"===e.type){void 0!==e.autoUpdate&&(s.autoUpdate=e.autoUpdate);const t=e.levels;for(let e=0;e<t.length;e++){const i=t[e],n=s.getObjectByProperty("uuid",i.object);void 0!==n&&s.addLevel(n,i.distance,i.hysteresis)}}return s}bindSkeletons(e,t){0!==Object.keys(t).length&&e.traverse(function(e){if(!0===e.isSkinnedMesh&&void 0!==e.skeleton){const i=t[e.skeleton];void 0===i?console.warn("THREE.ObjectLoader: No skeleton found with UUID:",e.skeleton):e.bind(i,e.bindMatrix)}})}bindLightTargets(e){e.traverse(function(t){if(t.isDirectionalLight||t.isSpotLight){const i=t.target,n=e.getObjectByProperty("uuid",i);t.target=void 0!==n?n:new Zn}})}}const Fu={UVMapping:ce,CubeReflectionMapping:he,CubeRefractionMapping:de,EquirectangularReflectionMapping:ue,EquirectangularRefractionMapping:pe,CubeUVReflectionMapping:me},ku={RepeatWrapping:ge,ClampToEdgeWrapping:fe,MirroredRepeatWrapping:Ae},Nu={NearestFilter:ye,NearestMipmapNearestFilter:ve,NearestMipmapLinearFilter:_e,LinearFilter:be,LinearMipmapNearestFilter:xe,LinearMipmapLinearFilter:we};class ju extends su{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){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,s=iu.get(e);if(void 0!==s)return r.manager.itemStart(e),s.then?void s.then(i=>{t&&t(i),r.manager.itemEnd(e)}).catch(e=>{n&&n(e)}):(setTimeout(function(){t&&t(s),r.manager.itemEnd(e)},0),s);const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader;const o=fetch(e,a).then(function(e){return e.blob()}).then(function(t){return iu.add(e,t,"blob"),createImageBitmap(t,Object.assign(r.options,{colorSpaceConversion:"none"}))}).then(function(i){return iu.add(e,i),t&&t(i),r.manager.itemEnd(e),i}).catch(function(t){n&&n(t),iu.remove(e),r.manager.itemError(e),r.manager.itemEnd(e)});iu.add(e,o),r.manager.itemStart(e)}}let zu;class Gu{static getContext(){return void 0===zu&&(zu=new(window.AudioContext||window.webkitAudioContext)),zu}static setContext(e){zu=e}}const Qu=new Sn,Vu=new Sn,Hu=new Sn;class Wu{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=qu(),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=qu();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function qu(){return(typeof performance>"u"?Date:performance).now()}const Xu=new Xi,Yu=new qi,Ku=new Xi,Ju=new Xi;class Zu extends Zn{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(!0===this.isPlaying)return void console.warn("THREE.Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void console.warn("THREE.Audio: this Audio has no playback control.");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(!1!==this.hasPlaybackControl)return!0===this.isPlaying&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,!0===this.loop&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this;console.warn("THREE.Audio: this Audio has no playback control.")}stop(){if(!1!==this.hasPlaybackControl)return this._progress=0,null!==this.source&&(this.source.stop(),this.source.onended=null),this.isPlaying=!1,this;console.warn("THREE.Audio: this Audio has no playback control.")}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(!1!==this._connected){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=[]),!0===this._connected?(this.disconnect(),this.filters=e.slice(),this.connect()):this.filters=e.slice(),this}setDetune(e){return this.detune=e,!0===this.isPlaying&&void 0!==this.source.detune&&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(!1!==this.hasPlaybackControl)return this.playbackRate=e,!0===this.isPlaying&&this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,.01),this;console.warn("THREE.Audio: this Audio has no playback control.")}getPlaybackRate(){return this.playbackRate}onEnded(){this.isPlaying=!1}getLoop(){return!1===this.hasPlaybackControl?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop}setLoop(e){if(!1!==this.hasPlaybackControl)return this.loop=e,!0===this.isPlaying&&(this.source.loop=this.loop),this;console.warn("THREE.Audio: this Audio has no playback control.")}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 $u=new Xi,ep=new qi,tp=new Xi,ip=new Xi;class np{constructor(e,t,i){let n,r,s;switch(this.binding=e,this.valueSize=i,t){case"quaternion":n=this._slerp,r=this._slerpAdditive,s=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(6*i),this._workIndex=5;break;case"string":case"bool":n=this._select,r=this._select,s=this._setAdditiveIdentityOther,this.buffer=new Array(5*i);break;default:n=this._lerp,r=this._lerpAdditive,s=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(5*i)}this._mixBufferRegion=n,this._mixBufferRegionAdditive=r,this._setIdentity=s,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,r=e*n+n;let s=this.cumulativeWeight;if(0===s){for(let e=0;e!==n;++e)i[r+e]=i[e];s=t}else{s+=t;const e=t/s;this._mixBufferRegion(i,r,0,e,n)}this.cumulativeWeight=s}accumulateAdditive(e){const t=this.buffer,i=this.valueSize,n=i*this._addIndex;0===this.cumulativeWeightAdditive&&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,r=this.cumulativeWeight,s=this.cumulativeWeightAdditive,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,r<1){const e=t*this._origIndex;this._mixBufferRegion(i,n,e,1-r,t)}s>0&&this._mixBufferRegionAdditive(i,n,this._addIndex*t,1,t);for(let e=t,r=t+t;e!==r;++e)if(i[e]!==i[e+t]){a.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 e=i,r=n;e!==r;++e)t[e]=t[n+e%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const e=3*this.valueSize;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,r){if(n>=.5)for(let n=0;n!==r;++n)e[t+n]=e[i+n]}_slerp(e,t,i,n){qi.slerpFlat(e,t,e,t,e,i,n)}_slerpAdditive(e,t,i,n,r){const s=this._workIndex*r;qi.multiplyQuaternionsFlat(e,s,e,t,e,i),qi.slerpFlat(e,t,e,t,e,s,n)}_lerp(e,t,i,n,r){const s=1-n;for(let a=0;a!==r;++a){const r=t+a;e[r]=e[r]*s+e[i+a]*n}}_lerpAdditive(e,t,i,n,r){for(let s=0;s!==r;++s){const r=t+s;e[r]=e[r]+e[i+s]*n}}}const rp="\\[\\]\\.:\\/",sp=new RegExp("["+rp+"]","g"),ap="[^"+rp+"]",op="[^"+rp.replace("\\.","")+"]",lp=/((?:WC+[\/:])*)/.source.replace("WC",ap),cp=/(WCOD+)?/.source.replace("WCOD",op),hp=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",ap),dp=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",ap),up=new RegExp("^"+lp+cp+hp+dp+"$"),pp=["material","materials","bones","map"];class mp{constructor(e,t,i){this.path=t,this.parsedPath=i||mp.parseTrackName(t),this.node=mp.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 mp.Composite(e,t,i):new mp(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(sp,"")}static parseTrackName(e){const t=up.exec(e);if(null===t)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(void 0!==n&&-1!==n){const e=i.nodeName.substring(n+1);-1!==pp.indexOf(e)&&(i.nodeName=i.nodeName.substring(0,n),i.objectName=e)}if(null===i.propertyName||0===i.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(void 0===t||""===t||"."===t||-1===t||t===e.name||t===e.uuid)return e;if(e.skeleton){const i=e.skeleton.getBoneByName(t);if(void 0!==i)return i}if(e.children){const i=function(e){for(let n=0;n<e.length;n++){const r=e[n];if(r.name===t||r.uuid===t)return r;const s=i(r.children);if(s)return s}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,r=i.length;n!==r;++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,r=i.length;n!==r;++n)i[n]=e[t++]}_setValue_array_setNeedsUpdate(e,t){const i=this.resolvedProperty;for(let n=0,r=i.length;n!==r;++n)i[n]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){const i=this.resolvedProperty;for(let n=0,r=i.length;n!==r;++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 r=t.propertyIndex;if(e||(e=mp.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e)return void console.warn("THREE.PropertyBinding: No target node found for track: "+this.path+".");if(i){let n=t.objectIndex;switch(i){case"materials":if(!e.material)return void console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);if(!e.material.materials)return void console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);e=e.material.materials;break;case"bones":if(!e.skeleton)return void console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);e=e.skeleton.bones;for(let t=0;t<e.length;t++)if(e[t].name===n){n=t;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material)return void console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);if(!e.material.map)return void console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);e=e.material.map;break;default:if(void 0===e[i])return void console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);e=e[i]}if(void 0!==n){if(void 0===e[n])return void console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);e=e[n]}}const s=e[n];if(void 0===s){const i=t.nodeName;return void console.error("THREE.PropertyBinding: Trying to update property for track: "+i+"."+n+" but it wasn't found.",e)}let a=this.Versioning.None;this.targetObject=e,void 0!==e.needsUpdate?a=this.Versioning.NeedsUpdate:void 0!==e.matrixWorldNeedsUpdate&&(a=this.Versioning.MatrixWorldNeedsUpdate);let o=this.BindingType.Direct;if(void 0!==r){if("morphTargetInfluences"===n){if(!e.geometry)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);if(!e.geometry.morphAttributes)return void console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);void 0!==e.morphTargetDictionary[r]&&(r=e.morphTargetDictionary[r])}o=this.BindingType.ArrayElement,this.resolvedProperty=s,this.propertyIndex=r}else void 0!==s.fromArray&&void 0!==s.toArray?(o=this.BindingType.HasFromToArray,this.resolvedProperty=s):Array.isArray(s)?(o=this.BindingType.EntireArray,this.resolvedProperty=s):this.propertyName=n;this.getValue=this.GetterByBindingType[o],this.setValue=this.SetterByBindingTypeAndVersioning[o][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}mp.Composite=class{constructor(e,t,i){const n=i||mp.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];void 0!==n&&n.getValue(e,t)}setValue(e,t){const i=this._bindings;for(let n=this._targetGroup.nCachedObjects_,r=i.length;n!==r;++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()}},mp.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},mp.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},mp.prototype.GetterByBindingType=[mp.prototype._getValue_direct,mp.prototype._getValue_array,mp.prototype._getValue_arrayElement,mp.prototype._getValue_toArray],mp.prototype.SetterByBindingTypeAndVersioning=[[mp.prototype._setValue_direct,mp.prototype._setValue_direct_setNeedsUpdate,mp.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[mp.prototype._setValue_array,mp.prototype._setValue_array_setNeedsUpdate,mp.prototype._setValue_array_setMatrixWorldNeedsUpdate],[mp.prototype._setValue_arrayElement,mp.prototype._setValue_arrayElement_setNeedsUpdate,mp.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[mp.prototype._setValue_fromArray,mp.prototype._setValue_fromArray_setNeedsUpdate,mp.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class gp{constructor(e,t,i=null,n=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=i,this.blendMode=n;const r=t.tracks,s=r.length,a=new Array(s),o={endingStart:Mt,endingEnd:Mt};for(let e=0;e!==s;++e){const t=r[e].createInterpolant(null);a[e]=t,t.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=xt,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&&0!==this.timeScale&&null===this._startTime&&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 i=this._clip.duration,n=e._clip.duration,r=n/i,s=i/n;e.warp(1,r,t),this.warp(s,1,t)}return this}crossFadeTo(e,t,i){return e.crossFadeFrom(this,t,i)}stopFading(){const e=this._weightInterpolant;return null!==e&&(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,r=n.time,s=this.timeScale;let a=this._timeScaleInterpolant;null===a&&(a=n._lendControlInterpolant(),this._timeScaleInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=r,o[1]=r+i,l[0]=e/s,l[1]=t/s,this}stopWarping(){const e=this._timeScaleInterpolant;return null!==e&&(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)return void this._updateWeight(e);const r=this._startTime;if(null!==r){const n=(e-r)*i;n<0||0===i?t=0:(this._startTime=null,t=i*n)}t*=this._updateTimeScale(e);const s=this._updateTime(t),a=this._updateWeight(e);if(a>0){const e=this._interpolants,t=this._propertyBindings;if(2501===this.blendMode)for(let i=0,n=e.length;i!==n;++i)e[i].evaluate(s),t[i].accumulateAdditive(a);else for(let i=0,r=e.length;i!==r;++i)e[i].evaluate(s),t[i].accumulate(n,a)}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;const i=this._weightInterpolant;if(null!==i){const n=i.evaluate(e)[0];t*=n,e>i.parameterPositions[1]&&(this.stopFading(),0===n&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;const i=this._timeScaleInterpolant;if(null!==i){t*=i.evaluate(e)[0],e>i.parameterPositions[1]&&(this.stopWarping(),0===t?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,r=this._loopCount;const s=2202===i;if(0===e)return-1===r||!s||1&~r?n:t-n;if(i===bt){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(n>=t)n=t;else{if(!(n<0)){this.time=n;break e}n=0}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(-1===r&&(e>=0?(r=0,this._setEndings(!0,0===this.repetitions,s)):this._setEndings(0===this.repetitions,!0,s)),n>=t||n<0){const i=Math.floor(n/t);n-=t*i,r+=Math.abs(i);const a=this.repetitions-r;if(a<=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(1===a){const t=e<0;this._setEndings(t,!t,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=n,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:i})}}else this.time=n;if(s&&!(1&~r))return t-n}return n}_setEndings(e,t,i){const n=this._interpolantSettings;i?(n.endingStart=Et,n.endingEnd=Et):(n.endingStart=e?this.zeroSlopeAtStart?Et:Mt:Tt,n.endingEnd=t?this.zeroSlopeAtEnd?Et:Mt:Tt)}_scheduleFading(e,t,i){const n=this._mixer,r=n.time;let s=this._weightInterpolant;null===s&&(s=n._lendControlInterpolant(),this._weightInterpolant=s);const a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=t,a[1]=r+e,o[1]=i,this}}const fp=new Float32Array(1);class Ap extends ri{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,r=n.length,s=e._propertyBindings,a=e._interpolants,o=i.uuid,l=this._bindingsByRootAndName;let c=l[o];void 0===c&&(c={},l[o]=c);for(let e=0;e!==r;++e){const r=n[e],l=r.name;let h=c[l];if(void 0!==h)++h.referenceCount,s[e]=h;else{if(h=s[e],void 0!==h){null===h._cacheIndex&&(++h.referenceCount,this._addInactiveBinding(h,o,l));continue}const n=t&&t._propertyBindings[e].binding.parsedPath;h=new np(mp.create(i,l,n),r.ValueTypeName,r.getValueSize()),++h.referenceCount,this._addInactiveBinding(h,o,l),s[e]=h}a[e].resultBuffer=h.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(null===e._cacheIndex){const t=(e._localRoot||this._root).uuid,i=e._clip.uuid,n=this._actionsByClip[i];this._bindAction(e,n&&n.knownActions[0]),this._addInactiveAction(e,i,t)}const t=e._propertyBindings;for(let e=0,i=t.length;e!==i;++e){const i=t[e];0===i.useCount++&&(this._lendBinding(i),i.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){const t=e._propertyBindings;for(let e=0,i=t.length;e!==i;++e){const i=t[e];0===--i.useCount&&(i.restoreOriginalState(),this._takeBackBinding(i))}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 null!==t&&t<this._nActiveActions}_addInactiveAction(e,t,i){const n=this._actions,r=this._actionsByClip;let s=r[t];if(void 0===s)s={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,r[t]=s;else{const t=s.knownActions;e._byClipCacheIndex=t.length,t.push(e)}e._cacheIndex=n.length,n.push(e),s.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 r=e._clip.uuid,s=this._actionsByClip,a=s[r],o=a.knownActions,l=o[o.length-1],c=e._byClipCacheIndex;l._byClipCacheIndex=c,o[c]=l,o.pop(),e._byClipCacheIndex=null;delete a.actionByRoot[(e._localRoot||this._root).uuid],0===o.length&&delete s[r],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){const t=e._propertyBindings;for(let e=0,i=t.length;e!==i;++e){const i=t[e];0===--i.referenceCount&&this._removeInactiveBinding(i)}}_lendAction(e){const t=this._actions,i=e._cacheIndex,n=this._nActiveActions++,r=t[n];e._cacheIndex=n,t[n]=e,r._cacheIndex=i,t[i]=r}_takeBackAction(e){const t=this._actions,i=e._cacheIndex,n=--this._nActiveActions,r=t[n];e._cacheIndex=n,t[n]=e,r._cacheIndex=i,t[i]=r}_addInactiveBinding(e,t,i){const n=this._bindingsByRootAndName,r=this._bindings;let s=n[t];void 0===s&&(s={},n[t]=s),s[i]=e,e._cacheIndex=r.length,r.push(e)}_removeInactiveBinding(e){const t=this._bindings,i=e.binding,n=i.rootNode.uuid,r=i.path,s=this._bindingsByRootAndName,a=s[n],o=t[t.length-1],l=e._cacheIndex;o._cacheIndex=l,t[l]=o,t.pop(),delete a[r],0===Object.keys(a).length&&delete s[n]}_lendBinding(e){const t=this._bindings,i=e._cacheIndex,n=this._nActiveBindings++,r=t[n];e._cacheIndex=n,t[n]=e,r._cacheIndex=i,t[i]=r}_takeBackBinding(e){const t=this._bindings,i=e._cacheIndex,n=--this._nActiveBindings,r=t[n];e._cacheIndex=n,t[n]=e,r._cacheIndex=i,t[i]=r}_lendControlInterpolant(){const e=this._controlInterpolants,t=this._nActiveControlInterpolants++;let i=e[t];return void 0===i&&(i=new Vd(new Float32Array(2),new Float32Array(2),1,fp),i.__cacheIndex=t,e[t]=i),i}_takeBackControlInterpolant(e){const t=this._controlInterpolants,i=e.__cacheIndex,n=--this._nActiveControlInterpolants,r=t[n];e.__cacheIndex=n,t[n]=e,r.__cacheIndex=i,t[i]=r}clipAction(e,t,i){const n=t||this._root,r=n.uuid;let s="string"==typeof e?eu.findByName(n,e):e;const a=null!==s?s.uuid:e,o=this._actionsByClip[a];let l=null;if(void 0===i&&(i=null!==s?s.blendMode:It),void 0!==o){const e=o.actionByRoot[r];if(void 0!==e&&e.blendMode===i)return e;l=o.knownActions[0],null===s&&(s=l._clip)}if(null===s)return null;const c=new gp(this,s,t,i);return this._bindAction(c,l),this._addInactiveAction(c,a,r),c}existingAction(e,t){const i=t||this._root,n=i.uuid,r="string"==typeof e?eu.findByName(i,e):e,s=r?r.uuid:e,a=this._actionsByClip[s];return void 0!==a&&a.actionByRoot[n]||null}stopAllAction(){const e=this._actions;for(let t=this._nActiveActions-1;t>=0;--t)e[t].stop();return this}update(e){e*=this.timeScale;const t=this._actions,i=this._nActiveActions,n=this.time+=e,r=Math.sign(e),s=this._accuIndex^=1;for(let a=0;a!==i;++a)t[a]._update(n,e,r,s);const a=this._bindings,o=this._nActiveBindings;for(let e=0;e!==o;++e)a[e].apply(s);return this}setTime(e){this.time=0;for(let e=0;e<this._actions.length;e++)this._actions[e].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){const t=this._actions,i=e.uuid,n=this._actionsByClip,r=n[i];if(void 0!==r){const e=r.knownActions;for(let i=0,n=e.length;i!==n;++i){const n=e[i];this._deactivateAction(n);const r=n._cacheIndex,s=t[t.length-1];n._cacheIndex=null,n._byClipCacheIndex=null,s._cacheIndex=r,t[r]=s,t.pop(),this._removeInactiveBindingsForAction(n)}delete n[i]}}uncacheRoot(e){const t=e.uuid,i=this._actionsByClip;for(const e in i){const n=i[e].actionByRoot[t];void 0!==n&&(this._deactivateAction(n),this._removeInactiveAction(n))}const n=this._bindingsByRootAndName[t];if(void 0!==n)for(const e in n){const t=n[e];t.restoreOriginalState(),this._removeInactiveBinding(t)}}uncacheAction(e,t){const i=this.existingAction(e,t);null!==i&&(this._deactivateAction(i),this._removeInactiveAction(i))}}class yp{constructor(e){this.value=e}clone(){return new yp(void 0===this.value.clone?this.value:this.value.clone())}}let vp=0;class _p extends bl{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}}const bp=new Sn;class xp{constructor(e,t,i=0,n=1/0){this.ray=new Cn(e,t),this.near=i,this.far=n,this.camera=null,this.layers=new Un,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 bp.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(bp),this}intersectObject(e,t=!0,i=[]){return Cp(e,this,i,t),i.sort(wp),i}intersectObjects(e,t=!0,i=[]){for(let n=0,r=e.length;n<r;n++)Cp(e[n],this,i,t);return i.sort(wp),i}}function wp(e,t){return e.distance-t.distance}function Cp(e,t,i,n){let r=!0;if(e.layers.test(t.layers)&&!1===e.raycast(t,i)&&(r=!1),!0===r&&!0===n){const n=e.children;for(let e=0,r=n.length;e<r;e++)Cp(n[e],t,i,!0)}}class Sp{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),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,i),this.phi=Math.acos(hi(t/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}}class Mp{constructor(e,t,i,n){Mp.prototype.isMatrix2=!0,this.elements=[1,0,0,1],void 0!==e&&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 r=this.elements;return r[0]=e,r[2]=t,r[1]=i,r[3]=n,this}}const Ep=new fi;class Tp{constructor(e=new fi(1/0,1/0),t=new fi(-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=Ep.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,Ep).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 Ip=new Xi,Pp=new Xi;class Dp{constructor(e=new Xi,t=new Xi){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){Ip.subVectors(e,this.start),Pp.subVectors(this.end,this.start);const i=Pp.dot(Pp);let n=Pp.dot(Ip)/i;return t&&(n=hi(n,0,1)),n}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 Rp=new Xi;const Bp=new Xi,Lp=new Sn,Op=new Sn;function Up(e){const t=[];!0===e.isBone&&t.push(e);for(let i=0;i<e.children.length;i++)t.push.apply(t,Up(e.children[i]));return t}const Fp=new Xi,kp=new mr,Np=new mr;const jp=new Xi,zp=new Xi,Gp=new Xi;const Qp=new Xi,Vp=new cs;function Hp(e,t,i,n,r,s,a){Qp.set(r,s,a).unproject(n);const o=t[e];if(void 0!==o){const e=i.getAttribute("position");for(let t=0,i=o.length;t<i;t++)e.setXYZ(o[t],Qp.x,Qp.y,Qp.z)}}const Wp=new Ji;const qp=new Xi;let Xp,Yp;class Kp extends ri{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 Jp=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;void 0===i[e]&&(i[e]=[]),i[e].includes(t)||i[e].push(t)}hasEventListener(e,t){const i=this._eventListeners;return void 0!==i[e]&&i[e].includes(t)}removeEventListener(e,t){const i=this._eventListeners[e];if(void 0!==i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}dispatchEvent(e){const t=this._eventListeners[e.type];if(void 0!==t){e.target=this;const i=t.slice(0);for(let t=0,n=i.length;t<n;t++)i[t].call(this,e)}}};async function Zp(e){return new Promise(t=>setTimeout(t,Math.max(0,e)))}function $p(){return(typeof performance>"u"?Date:performance).now()}class em extends Jp{constructor(){super(...arguments),this._onPointerDown=e=>{if(0!==e.button||!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=$p();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=$p();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:$p()},e.buttons%2==0&&this._onPointerUp(e)},this._onPointerUp=e=>{if(0!==e.button||!this._pointerDown||!this._element)return;const t=e.clientX/this._element.clientWidth*2-1,i=-e.clientY/this._element.clientHeight*2+1,n=$p();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,r;null==(e=this._element)||e.removeEventListener("pointerdown",this._onPointerDown),null==(t=this._element)||t.removeEventListener("pointermove",this._onPointerMove),null==(i=this._element)||i.removeEventListener("pointerup",this._onPointerUp),null==(n=this._element)||n.removeEventListener("pointercancel",this._onPointerUp),null==(r=this._element)||r.removeEventListener("pointerout",this._onPointerUp)}_addElement(){var e,t,i,n,r;null==(e=this._element)||e.addEventListener("pointerdown",this._onPointerDown),null==(t=this._element)||t.addEventListener("pointermove",this._onPointerMove),null==(i=this._element)||i.addEventListener("pointerup",this._onPointerUp),null==(n=this._element)||n.addEventListener("pointercancel",this._onPointerUp),null==(r=this._element)||r.addEventListener("pointerout",this._onPointerUp)}dispose(){this.element=void 0}}class tm{constructor(e){this.options={limit:500,debug:!1,bindHotKeys:!1},this.enabled=!0,this.presets={},this._keyDown=e=>{if(!this.enabled)return;const t=e.ctrlKey||e.metaKey;"KeyZ"===e.code&&t&&!e.shiftKey?this.undo():("KeyZ"===e.code&&t&&e.shiftKey||"KeyY"===e.code&&e.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("function"==typeof t)return t(e);throw console.error(e,t,this.presets),new Error("Preset command not found")}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..."),1===e?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||"number"!=typeof e)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 im=class e{constructor(t=e.DECAY_MILLISECONDS){this.velocity=0,this.naturalFrequency=0,this.setDecayTime(t)}setDecayTime(t){this.naturalFrequency=1/Math.max(e.MIN_DECAY_MILLISECONDS,t)}update(e,t,i,n){const r=2e-4*this.naturalFrequency;if(null==e||0===n||e===t&&0===this.velocity)return t;if(i<0)return e;const s=e-t,a=this.velocity+this.naturalFrequency*s,o=s+i*a,l=Math.exp(-this.naturalFrequency*i),c=(a-this.naturalFrequency*o)*l,h=-this.naturalFrequency*(c+a*l);return Math.abs(c)<r*Math.abs(n)&&h*s>=0?(this.velocity=0,t):(this.velocity=c,t+o*l)}};im.SETTLING_TIME=1e4,im.MIN_DECAY_MILLISECONDS=.001,im.DECAY_MILLISECONDS=50;let nm=im;function rm(){const e=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");return e.style.display="block",e}function sm({innerHTML:e="",id:t,classList:i,addToBody:n=!0,elementTag:r="div"}){const s=document.createElement(r);return t&&(s.id=t),s.innerHTML=e,i&&s.classList.add(...i),n&&document.body.appendChild(s),s}async function am(e){return new Promise((t,i)=>{const n=new Image;n.onload=()=>t(n),n.onerror=i,n.crossOrigin="anonymous",n.decoding="sync",n.src=e})}function om(e,t=document.head){const i=document.createElement("style");return i.type="text/css",i.innerText=e,t?.appendChild(i),i}function lm(e,t){(t=t??document.createElement("script")).type=e.type||"text/javascript",t.text=e.text;for(let i=0;i<e.attributes.length;i++){const n=e.attributes[i];t.setAttribute(n.name,n.value)}return t}function cm(e){if(!window)return console.warn("window is required"),"";let t="";const i=new Uint8Array(e),n=i.byteLength;for(let e=0;e<n;e++)t+=String.fromCharCode(i[e]);return window.btoa(t)}function hm(e){if(!window)return console.warn("window is required"),new Uint8Array(0);const t=window.atob(e),i=t.length,n=new Uint8Array(i);for(let e=0;e<i;e++)n[e]=t.charCodeAt(e);return n.buffer}const dm={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function um(e,t){return new dm[e](t)}function pm(e){return e.replace(/\w\S*/g,function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()})}function mm(e){if(!e||""===e||e.match(/__MACOSX\/.*\._/))return"";const t=(e=e.replace(/\?.*$/,"")).split(/[\\/]/).pop()??"",i=t.lastIndexOf(".");return""===t||i<1?"":t.slice(i+1)}function gm(e){return RegExp.escape?RegExp.escape(e):e.replace(/[.*+?^${}()|[\]/\\=!:]/g,"\\$&")}function fm(e,t,i){return e.replace(new RegExp(gm(t),"g"),i)}function Am(e){return e.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 ym=(e,...t)=>String.raw({raw:e},...t),vm=(e,...t)=>String.raw({raw:e},...t),_m=(e,...t)=>{let i=String.raw({raw:e},...t);return i=fm(i,"%","%25"),i=fm(i,"> <","><"),i=fm(i,"; }",";}"),i=fm(i,"<","%3c"),i=fm(i,">","%3e"),i=fm(i,'"',"'"),i=fm(i,"#","%23"),i=fm(i,"{","%7b"),i=fm(i,"}","%7d"),i=fm(i,"|","%7c"),i=fm(i,"^","%5e"),i=fm(i,"`","%60"),i=fm(i,"@","%40"),i=fm(i,"&","&amp;"),i=fm(i,"\n","%0A"),"data:image/svg+xml;charset=UTF-8,"+i};function bm(e,t){const i=window.URL.createObjectURL(e),n=document.createElement("a");n.style.display="none",n.href=i,n.download=t,document.body.appendChild(n),n.click(),setTimeout(()=>{document.body.removeChild(n),window.URL.revokeObjectURL(i)},1e3)}async function xm(e){return new Promise((t,i)=>{const n=new FileReader;n.onload=e=>t(n.result),n.onerror=e=>i(n.error),n.onabort=e=>i(new Error("Read aborted")),n.readAsDataURL(e)})}function wm(e,t){return bm(e,t??e.name)}async function Cm(e=!1,t=!1,i){const n=document.createElement("input");n.type="file",n.multiple=e,n.accept=i||"*",n.webkitdirectory=t,n.style.display="none",document.body.appendChild(n),n.click();const r=await new Promise(e=>{n.onchange=t=>{e(Array.from(n.files||[]))}});return document.body.removeChild(n),r}function Sm(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}function Mm(e,t){let i;do{i=Object.getOwnPropertyDescriptor(e,t)}while(!i&&(e=Object.getPrototypeOf(e)));return i}function Em(e,t,i=!0,n=!1){const r=Mm(e,t);return!(null==r||!r.set)||i&&!1!==r?.writable&&void 0===r?.get||n&&!r}function Tm(e,t,i,n=!0,r=!1){return!(!e||!Em(e,t,n,r))&&(e[t]=i,!0)}function Im(e,...t){return"function"==typeof e&&(e=e(...t)),e}function Pm(e,t,i){for(const n of i){const i=e[n];void 0!==i&&Tm(t,n,i,!0)}return t}function Dm(e,t){for(const i of t)if(!e.includes(i))return!1;return!0}function Rm(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1}function Bm(e,t){return function(...i){return e(...i),t&&t.call(this,...i)}}function Lm(e,t,i=!1){for("string"==typeof e&&(e=e.split("."));e.length>0;){if(!t)return t;const n=e.splice(0,1)[0];if(!(n.length<1))if(Array.isArray(t))t=t[parseInt(n)];else{if("object"!=typeof t||!(n in t)){if(i)throw new Error("invalid access, check "+n+" in "+t);return}t=t[n]}}return t}function Om(e,t){return Object.hasOwn?Object.hasOwn(e,t):e.hasOwnProperty(t)}function Um(e,t,i=!0){const n=i?e:{},r=Object.keys(e);for(const i of r)n[i]=t(e[i],i);return n}function Fm(e,t){return Object.fromEntries(Object.entries(e).map(e=>t(e)))}const km={priority:1/0,type:"Object",serialize:(e,t)=>Fm(e,([e,i])=>[e,jm.Serialize(i,t,!1)]),deserialize:(e,t,i)=>Object.assign(t||{},Fm(e,([e,n])=>[e,jm.Deserialize(n,t?.[e],i,!1)])),isType:e=>(e.constructor||Object)===Object},Nm=class e{static GetSerializer(t){return e.Serializers.find(e=>e.isType(t))}static RegisterSerializer(...t){for(const i of t){const t=i.priority??1e10,n=Rm(e.Serializers,e=>void 0!==e.priority&&e.priority<t);n>=0?e.Serializers.splice(n+1,0,i):e.Serializers.push(i)}}static UnregisterSerializer(...t){for(const i of t){const t=e.Serializers.indexOf(i);t>=0&&e.Serializers.splice(t,1)}}static Serialize(t,i,n=!1){if("function"==typeof t)return;if(!n){const n=e.GetSerializer(t);if(n)return n.serialize(t,i);if("function"==typeof t.toJSON){const e=t.toJSON(i,!0);return t.serializableClassId&&e&&(e.serializableClassId=t.serializableClassId),e}}let r=t.constructor??Object;const s={};for(;r&&r!==Object;){const n=e.TypeMap.get(r)??[];for(const[r,a]of n)s[r]=e.Serialize(t[a],i,!1);r=Object.getPrototypeOf(r)}return t.serializableClassId&&(s.serializableClassId=t.serializableClassId),s}static Deserialize(t,i,n,r=!1){if(void 0===t||i===t)return i;if(t&&"object"==typeof t&&(t.constructor||Object)===Object&&t.resource&&"string"==typeof t.resource&&t.uuid){const e=n?.[t.resource];if(!e)return console.warn(`Serialization: Resource ${t.resource} not found`),i;const r=t.uuid,s=e[r];if(!s)return console.warn(`Serialization: Resource ${t.resource} with uuid ${r} not found`),i;if("object"==typeof(t=s)&&(t.__useCount=t.__useCount?t.__useCount+1:1),i===t)return i;if(t&&"object"==typeof t){if((t.constructor||Object)!==Object){if(i){if(i.uuid&&i.uuid===r){if("function"==typeof i.copy&&!0===i.copyOnDeserialize)return i.copy(t),i;console.warn("Serialization: replacing object",i,"with deserialized resource",t)}else if(!i.uuid&&"function"==typeof i.copy&&!0===i.copyOnDeserialize)return i.copy(t),i;return t}return t}console.error("Serialization: during Deserialize, meta should only have class instances, not js objects",t,i,n)}}if(t&&"object"==typeof t&&(t.constructor||Object)!==Object&&!Array.isArray(t)&&!t.serializableClassId){if(t instanceof Blob)return t;console.warn("Serialization: Data might already be deserialized. It will be cloned, or copied to source",t,"source",i,t.constructor,t.constructor!==Object)}if(t&&"object"==typeof t){const n=n=>{const r=e.SerializableClasses.get(n);r&&(i=r.DataInConstructor?new r(t):new r)};t.serializableClassId&&(!i||i.serializableClassId!==t.serializableClassId)&&n(t.serializableClassId),t.type&&(!i||i.type!==t.type)&&n(t.type),!Array.isArray(i)&&Array.isArray(t)?i=[]:"object"!=typeof i&&(t.constructor||Object)===Object&&(i={})}if("function"==typeof i)return console.error("Serialization: Cannot deserialize into a function",i,t),i;if(!r){const r=e.GetSerializer(t);if(r&&r!==km)return r.deserialize(t,i,n)}if(!t||null==i||"object"!=typeof i)return t;if(!r&&"function"==typeof i?.fromJSON)return i.fromJSON(t,n,!0),i;let s=i.constructor??Object;if(s===Object)return km.deserialize(t,i,n);for(;s&&s!==Object;){const r=e.TypeMap.get(s)??[];for(const[s,a]of r){const r=i[a],o=e.Deserialize(t[s],r,n,!1);o!==r&&Tm(i,a,o,!0)}s=Object.getPrototypeOf(s)}return i}};Nm.TypeMap=new WeakMap,Nm.SerializableClasses=new Map,Nm.Serializers=[{priority:0,type:"Array",isType:e=>Array.isArray(e),serialize:(e,t)=>e.map(e=>Nm.Serialize(e,t,!1)),deserialize:(e,t,i)=>{const n=e.length;Array.isArray(t)||(t=[]);for(let r=0;r<n;r++){const n=e[r],s=t.length>r?Nm.Deserialize(n,t[r],i,!1):Nm.Deserialize(n,void 0,i,!1);t.length<=r?t.push(s):t[r]=s}return t}},{priority:0,isType:e=>!e||"object"!=typeof e,serialize:e=>{if(e&&"number"==typeof e){if(e===1/0)return"Infinity";if(e===-1/0)return"-Infinity";if(isNaN(e))return"NaN"}return e},deserialize:(e,t)=>{if("number"==typeof t){if("Infinity"===e)return 1/0;if("-Infinity"===e)return-1/0;if("NaN"===e)return NaN;if("number"==typeof e||!e)return e}return e}},km];let jm=Nm;const zm=class e{static callFunction(t,i,n=[]){if(!i)return t(...n);if(t.name&&i[t.name]===t)return t.call(i,...n);e.methodMap.has(i)||e.methodMap.set(i,new WeakMap);const r=e.methodMap.get(i);if(!r.has(t)){let e=i;for(;e;){const s=Object.values(Object.getOwnPropertyDescriptors(e));for(let e of s)if(e.value===t)return r.set(t,!0),t.call(i,...n);e=Object.getPrototypeOf(e)}r.set(t,!1)}return r.get(t)?t.call(i,...n):t(...n)}};zm.methodMap=new WeakMap;let Gm=zm;function Qm(e,t="param"){if(!e)throw new Error("onChange: fnKey is undefined, make sure the function exists or provide a string");return(i,n,r)=>{const s={get(){return this[`_oc_${n}`]},set(i){var r;const s=this[`_oc_${n}`];if(s===i)return;this[`_oc_${n}`]=i;const a="param"===t?[n,i,s,this]:"object"===t?[{key:n,value:i,oldValue:s,target:this}]:[];"string"==typeof e?null==(r=this[e])||r.call(this,...a):"function"==typeof e&&Gm.callFunction(e,this,a)}};if(r)return Om(r,"value")&&delete r.value,Om(r,"writable")&&delete r.writable,Om(r,"initializer")&&delete r.initializer,Object.assign(r,s);Object.defineProperty(i,n,s)}}function Vm(e,t="void"){if(!e)throw new Error("onChange: fnKey is undefined, make sure the function exists or provide a string");return Qm(e,t)}function Hm(e,t="object"){if(!e)throw new Error("onChange: fnKey is undefined, make sure the function exists or provide a string");return Qm(e,t)}function Wm(e){return Qm((t,i,n,r)=>{if(!r.dispatchEvent)throw new Error("onChangeDispatchEvent: target does not have dispatchEvent");r.dispatchEvent({type:e||`${t}-changed`,detail:{key:t,value:i,oldValue:n}})},"param")}function qm(e){return(t,i)=>{const n=t.constructor;if(n===Object)throw new Error("All properties in an object are serialized by default");jm.TypeMap.has(n)||jm.TypeMap.set(n,[]),jm.TypeMap.get(n).push([e||i,i])}}function Xm(e){return t=>(t.prototype.serializableClassId=e,jm.SerializableClasses.set(e,t),t)}async function Ym(e,t,i,n=12){const r="string"==typeof t?(new TextEncoder).encode(t):t,s=await crypto.subtle.digest("SHA-256",r),a=crypto.getRandomValues(new Uint8Array(n)),o=Array.from(a).map(e=>String.fromCharCode(e)).join(""),l={name:"AES-GCM",iv:a},c=await crypto.subtle.importKey("raw",s,l,!1,["encrypt"]),h="string"==typeof e?(new TextEncoder).encode(e):e,d=await crypto.subtle.encrypt(l,c,h),u=new Uint8Array(d),p=Array.from(u),m=p.map(e=>String.fromCharCode(e)).join(""),g=i?"string"==typeof i?i:(new TextDecoder).decode(i):"",f=i?"string"==typeof i?(new TextEncoder).encode(i):Array.from(i):[];return"string"==typeof e?g+o+m:new Uint8Array([...f,...a,...p])}async function Km(e,t,i=12){const n="string"==typeof t?(new TextEncoder).encode(t):t,r=await crypto.subtle.digest("SHA-256",n),s=e.slice(0,i),a={name:"AES-GCM",iv:"string"==typeof s?new Uint8Array(Array.from(s).map(e=>e.charCodeAt(0))):s},o=await crypto.subtle.importKey("raw",r,a,!1,["decrypt"]),l=e.slice(i),c="string"==typeof l?new Uint8Array(Array.from(l).map(e=>e.charCodeAt(0))):l;try{const t=await crypto.subtle.decrypt(a,o,c);return"string"==typeof e?(new TextDecoder).decode(t):new Uint8Array(t)}catch{throw new Error("Decrypt failed")}}function Jm(e,t=8192,i=!1){var n;const r=e.width||e.videoWidth,s=e.height||e.videoHeight;if(!r||!s)throw new Error("Invalid bitmap");const a=document.createElement("canvas");a.width=Math.min(t,r),a.height=Math.floor(1+a.width*s/r);const o=e instanceof ImageBitmap,l=o&&i&&Math.abs(a.width-r)<.5?a.getContext("bitmaprenderer"):void 0;return l?l.transferFromImageBitmap(e):null==(n=a.getContext("2d"))||n.drawImage(e,0,0,a.width,a.height),o&&i&&e.close(),a}function Zm(e,t=8192,i=!1,n="image/png"){if(!e.width&&!e.videoWidth||!e.height&&!e.videoHeight)return"";const r=Jm(e,t,!1),s=r.toDataURL(n);return r.remove(),i&&e instanceof ImageBitmap&&e.close(),s}async function $m(e){return new Promise((t,i)=>{const n=new Image;n.addEventListener("load",()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const r=e.getContext("2d");if(!r)return void i(new Error("Could not get 2d context"));r.drawImage(n,0,0,e.width,e.height);const s=r.getImageData(0,0,e.width,e.height);t(s),e.remove(),n.remove()},!1),n.addEventListener("error",e=>{n.remove(),i(e)},!1),n.src=e})}function eg(e,{backgroundColor:t="",scale:i=1,width:n=512,height:r=512}){const s=document.createElement("canvas"),a=s.getContext("2d"),o=i,l=n,c=r;return s.width=l*o,s.height=c*o,s.style.width=`${l}`,s.style.height=`${c}`,t?.length>0&&(a.fillStyle=t,a.fillRect(0,0,s.width,s.height)),a.drawImage(e,0,0,s.width,s.height),s}function tg(e){const t=document.createElement("canvas");t.width=e.width||e.videoWidth||1,t.height=e.height||e.videoHeight||1;const i=t.getContext("2d");if(!i)throw new Error("Unable to get 2d context");return i.translate(0,e.height||e.videoHeight||1),i.scale(1,-1),i.drawImage(e,0,0),t}const ig=e=>`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${e}'/%3E%3C/svg%3E%0A`,ng=async(e,t)=>eg(await am(e),t),rg=async(e,t)=>await ng(e,t).then(e=>e.toDataURL("image/png")),sg=async e=>xm(await(await fetch(e)).blob());async function ag(e,t=sg){const i=e.match(/(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)/g);if(i)for(const n of i){const i=await t(n);e=e.replace(n,i)}return e}function og(e,t,{width:i,height:n},r=!0){const s=`\n<svg viewBox="0 0 ${i} ${n}" xmlns="http://www.w3.org/2000/svg">\n    <style>\n    ${t}\n    </style>\n    <foreignObject x="0" y="0" width="100%" height="100%">\n        <div xmlns="http://www.w3.org/1999/xhtml" style="height: 100%; width: 100%; position: absolute: top:0; left:0">\n            ${e}\n        </div>\n    </foreignObject>\n</svg>\n    `;return r?_m(s):s}function lg(e,t){return Math.abs(e)>Math.abs(t)?e:t}function cg(e,t,i){return e&~(1<<t)|(i?1:0)<<t}function hg(){const e=(e,t)=>e.toString(16).padStart(t,"0"),t=crypto.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const i=new DataView(t.buffer);return`${e(i.getUint32(0),8)}-${e(i.getUint16(4),4)}-${e(i.getUint16(6),4)}-${e(i.getUint16(8),4)}-${e(i.getUint32(10),8)}${e(i.getUint16(14),4)}`}function dg(e,t=null){var i;return null!=(i=window?.location)&&i.href?new URL(window.location.href).searchParams.get(e)??t:t}const ug={alert:async e=>window.alert(e),prompt:async(e,t,i)=>window.prompt(e,t),confirm:async e=>window.confirm(e),confirmSync:e=>window.confirm(e)};let pg=null;function mg(e){return function(e){return e.replace(/((https?:\/\/|www\.)[^\s<]+)/g,e=>{let t=e;return t.startsWith("http")||(t="https://"+t),`<a href="${t}" target="_blank" rel="noopener noreferrer" class="dialog-link"><span class="dialog-link-text">${Am(e)}</span></a>`})}(Am(e)).replace(/\n/g,"<br>")}function gg(e){return`\n${e.title?`<div class="dialog-title">${Am(e.title)}</div>`:""}\n<div class="dialog-message">${mg(e.message)}</div>\n`}const fg=e=>`\n<div class="dialog-content">\n${gg(e)}\n</div>\n<div class="dialog-footer">\n    ${e.ok&&`<button class="dialog-button dialog-ok">${Am(e.ok)}</button>`||""}\n</div>\n`,Ag=e=>`\n<div class="dialog-content">\n${gg(e)}\n</div>\n<div class="dialog-footer">\n    ${e.cancel&&`<button class="dialog-button dialog-cancel">${Am(e.cancel)}</button>`||""}\n    ${e.ok&&`<button class="dialog-button dialog-ok">${Am(e.ok)}</button>`||""}\n</div>\n`,yg=e=>`\n<div class="dialog-content">\n    ${gg(e)}\n    <input class="dialog-input" type="text" value="${e.defaultValue??""}" style="margin-top:0.5rem;"/>\n</div>\n<div class="dialog-footer">\n    ${e.cancel&&`<button class="dialog-button dialog-cancel">${Am(e.cancel)}</button>`||""}\n    ${e.ok&&`<button class="dialog-button dialog-ok">${Am(e.ok)}</button>`||""}\n</div>\n`;function vg(e,{message:t,...i}){pg||(pg=document.createElement("style"),pg.textContent='.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}',document.head.appendChild(pg));const n=document.createElement("div"),r=t?.split(":")[0];return r&&t&&(t=t.replace(r+":","").trim()),n.innerHTML=e({...i,message:t,title:r}),n.classList.add("dialog-container"),document.body.appendChild(n),n}const _g={alert:async e=>{const t=vg(fg,{message:e||"Alert",ok:"Okay"});return new Promise(e=>{const i=t.querySelector(".dialog-ok"),n=e=>{("Enter"===e.key||"Escape"===e.key)&&(e.preventDefault(),i?.click())};window.addEventListener("keydown",n),i?.addEventListener("click",()=>{window.removeEventListener("keydown",n),document.body.removeChild(t),e()}),i?.focus()})},prompt:async(e,t,i=!0)=>{const n=vg(yg,{message:e||"Enter some text",ok:"OK",cancel:i?"Cancel":void 0,defaultValue:t});return new Promise(e=>{const t=n.querySelector(".dialog-ok"),i=n.querySelector(".dialog-cancel"),r=n.querySelector(".dialog-input");r.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),t?.click())});const s=e=>{"Escape"===e.key&&i&&(e.preventDefault(),i?.click())},a=()=>{window.removeEventListener("keydown",s),document.body.removeChild(n)};window.addEventListener("keydown",s),t?.addEventListener("click",()=>{const t=r.value;a(),e(t)}),i?.addEventListener("click",()=>{a(),e(null)}),r?.focus(),r?.select()})},confirm:async e=>{const t=vg(Ag,{message:e||"Are you sure?",ok:"Yes",cancel:"No"});return new Promise(e=>{const i=t.querySelector(".dialog-ok"),n=t.querySelector(".dialog-cancel"),r=e=>{"Escape"===e.key&&n&&(e.preventDefault(),n.click())},s=()=>{window.removeEventListener("keydown",r),document.body.removeChild(t)};window.addEventListener("keydown",r),i?.addEventListener("click",()=>{s(),e(!0)}),n?.addEventListener("click",()=>{s(),e(!1)}),n?.focus()})},confirmSync:e=>window.confirm(e)};function bg(e){return null===e||"object"!=typeof e?e:Array.isArray(e)?e.map(bg):e._ui_isPrimitive||"function"!=typeof e.clone||!1===e._ui_primitiveClone?e:e.clone()}function xg(e,t){return null===e||"object"!=typeof e||null===t||"object"!=typeof t?e===t:Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every((e,i)=>xg(e,t[i])):e._ui_isPrimitive||"function"!=typeof e.equals||!1===e._ui_primitiveEquals?e===t:!!e.equals(t)}function wg(e,t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){if(e&&Array.isArray(e)){if(e.length<t.length){for(let i=0;i<e.length;i++)e[i]=wg(e[i],t[i]);for(let i=e.length;i<t.length;i++)e.push(bg(t[i]))}else{for(let i=0;i<t.length;i++)e[i]=wg(e[i],t[i]);e.length=t.length}return e}return bg(t)}return t._ui_isPrimitive||"function"!=typeof t.copy||!1===t._ui_primitiveCopy?t:!e||"object"!=typeof e||Array.isArray(e)||e._ui_isPrimitive||"function"!=typeof e.copy||!1===e._ui_primitiveCopy?bg(t):(e.copy(t),e)}function Cg(e,t,i,n=2e3){if(!e||!e.enabled)return;const r=t;if(r.type!==i)return e.record(t);const s=e.peek();let a=!!s&&s.type===i&&s.uid===r.uid;if(a){const t=s;!t.final&&r.time-t.time<n?(r.lastVal=t.lastVal,r.val=bg(r.val),e.replaceLast(r)):a=!1}a||xg(r.lastVal,r.val)||(r.val=bg(r.val),e.record(r))}function Sg(e,t,i,n,r,s,a=!0,o=2e3,l=!1,c){const[h,d]=t,u=n.lastValue??h?.[d];let p=!1;const m=n.last??!0,g=xg(u,i),f=bg(u);p=g?!m:!h||wg(u,i)!==u&&!Tm(h,d,i,!0,!0);const A=!p&&(m||!g);return a&&A&&e&&Cg(e,{type:s,lastVal:f,val:i,final:m,props:n,time:Date.now(),uid:r,binding:l?t:void 0,onUndoRedo:c},s,o),{last:m,value:i,lastValue:f,undoable:A}}function Mg(e,t){let i,n=e;for(;!i&&n;)n=Object.getPrototypeOf(n),n&&(i=Object.getOwnPropertyDescriptor(n,t));return{proto:n,protoDesc:i}}function Eg(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:")||e.startsWith("asset://")||e.startsWith("/")||e.startsWith("//")}const Tg={simpleCameraHelpers:"#ifndef SIMPLE_CAMERA_HELPERS\n#define SIMPLE_CAMERA_HELPERS\n#ifndef USE_TRANSMISSION\nuniform mat4 projectionMatrix;\n#endif\nvec3 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);}\n#endif\n",cameraHelpers:"#ifndef BASIC_CAMERA_HELPERS\n#define BASIC_CAMERA_HELPERS\nuniform mat4 projection;uniform vec2 cameraNearFar;uniform vec3 cameraPositionWorld;\n#ifndef THREE_PACKING_INCLUDED\n#define THREE_PACKING_INCLUDED\n#include <packing>\n#endif\nfloat 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){\n#if PERSPECTIVE_CAMERA == 1\nreturn perspectiveDepthToViewZ(depth,cameraNearFar.x,cameraNearFar.y);\n#else\nreturn orthographicDepthToViewZ(depth,cameraNearFar.x,cameraNearFar.y);\n#endif\n}\n#endif\n",randomHelpers:"#ifndef BASIC_RANDOM_HELPERS\n#define BASIC_RANDOM_HELPERS\nfloat 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);}\n#endif\n",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\n#define VORONOI_HELPER\nfloat 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;}\n#endif\n"},Ig=class{};Ig.Map=new WeakMap;let Pg=Ig;function Dg(e,t,i,n,r=!0){n=void 0!==n?n:e[t],i=i??t+"";const s=n?.uiConfig;let a;if(s)a=s;else{const s=function(e){return null==e?null:Array.isArray(e)?"folder":"boolean"==typeof e?"checkbox":"number"==typeof e?"number":"string"==typeof e?"input":"function"==typeof e?"button":"number"==typeof e.x?"vec":"number"==typeof e.r?"color":e.isTexture?"image":"object"==typeof e?"folder":null}(n);"folder"===s?a=Bg(i,n,{},"folder",r,t+""):s&&(a={type:s,label:i,property:[e,t],propertyKey:t+""})}return a&&!a.label&&(a.label=i),a}function Rg(e){if(!e)return[];let t=e.constructor||Object;t===Array&&(t=Object);const i=[],n=[];for(;t&&t!==Object;)n.push(t),t=Object.getPrototypeOf(t);if(!n.length||Array.isArray(e)){const t="object"==typeof e?Object.keys(e):Array.isArray(e)?e.map((e,t)=>t):[];for(const n of t){const t=e[n];if(null==t)continue;const r=Dg(e,n,n+"",t,!0);r&&i.push(r)}}return n.reverse().forEach(t=>{Pg.Map.get(t)?.forEach(({params:t,propKey:n,uiType:r})=>{let s;if(r||(s=()=>Dg(e,n)),s||(s={property:[e,n],type:r||"input"}),t){const i="function"==typeof t.params?t.params(e):t.params||{},n={...t};if(delete n.params,"function"==typeof s){const e=s;s=()=>{const t=e();return t&&Object.assign(t,{...n,...i})}}else Object.assign(s,{...n,...i})}i.push(s)})}),i}function Bg(e,t,i={},n="folder",r=!1,s){return{type:n,label:e,children:r?[()=>Rg(t)]:Rg(t),uuid:hg(),propertyKey:s,...i}}function Lg(e,t){return function(e){return(t,i)=>{const n=t.constructor;if(n===Object)throw new Error("Not possible to use uiConfig decorator on an object, use class instead");Pg.Map.has(n)||Pg.Map.set(n,[]),e(t,i,Pg.Map.get(n))}}((i,n,r)=>{const s=r.findIndex(e=>e.propKey===n);if(!(s&&s<0))throw new Error(`Property ${n} already has a uiConfig decorator`);r.push({params:t||{},propKey:n,uiType:e})})}function Og(e,t,i="panel"){return n=>class extends n{constructor(){super(...arguments),this.uiConfig=Bg(e,this,t||{},i)}}}function Ug(e,t){return Lg("monitor",{label:e,params:t})}function Fg(e,t,i,n){return Lg("slider",{label:e,bounds:t,stepSize:i,params:n})}function kg(e,t,i,n){return Lg("vec",{label:e,bounds:t,stepSize:i,params:n})}function Ng(e,t,i){return Array.isArray(t)&&"string"==typeof t[0]&&(t=t.map(e=>({label:e,value:e}))),Lg("dropdown",{label:e,children:t,params:i})}function jg(e,t){return Lg("button",{label:e,params:t})}function zg(e,t){return Lg("input",{label:e,params:t})}function Gg(e,t){return Lg("number",{label:e,params:t})}function Qg(e,t){return Lg("color",{label:e,params:t})}function Vg(e,t){return Lg("image",{label:e,params:t})}function Hg(e,t){return Lg("checkbox",{label:e,params:t})}function Wg(e,t){return Og(e,t,"panel")}function qg(e,t){return Og(e,t,"folder")}const Xg="UiConfigMethods_set",Yg="UiConfigMethods_action",Kg=class e{constructor(e){this._renderer=e,this.undoEditingWaitTime=2e3,this.undoPresets={[Xg]:e=>{const t=()=>{e.onUndoRedo&&e.onUndoRedo(e),e.uid.uiRefresh?.(!1)};return{undo:()=>{this.setValue(e.uid,e.lastVal,e.props,void 0,!1).then(t)},redo:()=>{this.setValue(e.uid,e.val,e.props,void 0,!1).then(t)}}},[Yg]:e=>{const t=()=>{e.onUndoRedo&&e.onUndoRedo(e),e.uid.uiRefresh?.(!1)};return{undo:async()=>{await e.undo.call(e.target,...e.args),t()},redo:async()=>{await e.redo.call(e.target,...e.args),t()}}}}}recordUndo(e){Cg(this._renderer.undoManager,e,Xg,this.undoEditingWaitTime)}async performAction(t,i,n,r,s){return e.PerformAction(t,i,n,r,s,this._renderer.undoManager,this.undoEditingWaitTime)}getValue(t,i,n=!0){return e.GetValue(t,i,n)}async setValue(t,i,n,r,s=!0){return e.SetValue(t,i,n,r,s,this._renderer,this._renderer.undoManager,this.undoEditingWaitTime)}async dispatchOnChange(t,i){return this.runAtEvent(t,()=>e.DispatchOnChangeSync(t,i))}async clickButton(t,i){return this.runAtEvent(t,async()=>{const n=e.GetBinding(t,!1),r=n[0],s=n[1],a=!1===Im(t.sendArgs,t)?[]:i?.args??[],o=[];if(r){const e=r[s]??r.value;"function"==typeof e?o.push([e,r]):e&&console.warn("Invalid action type for button",e)}"function"==typeof t.onClick&&o.push([t.onClick,t]);for(const[e,i]of o)await this.performAction(i,e,a,t);await this.dispatchOnChange(t,{})})}async runAtEvent(t,i){return e.RunAtEvent(t,i,this._renderer)}static async RunAtEvent(e,t,i){const n=Im(e.dispatchMode,e)??this.DefaultDispatchMode;return"immediate"!==n&&i?new Promise(e=>{const r=async()=>{i.removeEventListener(n,r),e(await t())};i.addEventListener(n,r)}):t()}static GetBinding(e,t=!0){let i=Im(e.property,e);const n=Im(e.path,e);if(void 0===i&&Object.hasOwn(e,"value")&&(i=[e,"value"]),void 0===i&&t&&(i=Im(e.parentProperty,e)),!i||"object"!=typeof i[0]||!i[1])return[void 0,""];if("string"==typeof i[1]&&n&&n.length&&(i=[i[0],i[1]+"."+n]),"string"==typeof i[1]&&i[1].includes(".")){const t=i[1].split(".");let n=i[0];const r=t.pop()||"";for(const r of t)if(n=Array.isArray(n)?n[parseInt(r)]:n[r],!n)return console.warn("Cannot determine property, invalid property path",e,i),[void 0,""];i=[n,r]}return Array.isArray(i[0])&&"string"==typeof i[1]&&(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,r]=this.GetBinding(e);if(!n)return;const s=n[r];return void 0!==t&&void 0!==s?xg(t,s)&&!i?void 0:wg(t,s):bg(s)}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];"function"==typeof e.onChange?e.onChange(...n):Array.isArray(e.onChange)?e.onChange.flat().forEach(e=>"function"==typeof e&&e?.(...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){Cg(t,e,Xg,i)}static async PerformAction(e,t,i,n,r,s,a){const o=()=>void 0===e?t(...i):t.call(e,...i);let l=await o();const c="function"==typeof l?l:l?.undo?.bind(l),h="function"!=typeof l?l?.action?.bind(l):null,d="function"==typeof l?o:l?.redo?.bind(l)??h;"function"==typeof h&&(l=await h()),"function"==typeof c&&this.RecordUndo({type:"UiConfigMethods_action",uid:n,target:e,undo:c,redo:d,args:i,onUndoRedo:r},s,a)}static async SetValue(e,t,i,n,r=!0,s,a,o){return this.RunAtEvent(e,()=>{const s=this.GetBinding(e),l=Sg(a,s,t,i,e,Xg,r,o,!1,void 0);return!(!l.undoable&&!n)&&(this.DispatchOnChangeSync(e,{...i,...l}),!0)},s)}static GetLabel(e){return(Im(e.label,e)??this.GetBinding(e)?.[1])+""}static GetChildren(e){return(Im(e.children,e)??[]).map(t=>Im(t,e)).flat(2).filter(e=>e)}static InitUiConfig(e){e&&(e.type||(console.warn("No type for config",e),e.type="input"),e.uuid||(e.uuid=hg()),void 0===e.property&&(e.binding?e.property=e.binding:void 0===e.value?(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=Im(e.bounds),n=(i?.length??0)>=2?i[1]:t?1/0:1,r=(i?.length??0)>=1?i[0]:t?-1/0:0;return{min:r,max:n,step:Im(e.stepSize)||(t?.01:Math.pow(10,Math.floor(Math.log10((n-r)/100))))}}static GetBaseProps(e){return{hidden:Im(e.hidden)??!1,disabled:Im(e.disabled)??!1,readOnly:Im(e.readOnly)??!1}}getBinding(t,i=!0){return e.GetBinding(t,i)}getRawValue(t){return e.GetRawValue(t)}getLabel(t){return e.GetLabel(t)}getChildren(t){return e.GetChildren(t)}initUiConfig(t){return e.InitUiConfig(t)}getBounds(t,i=!1){return e.GetBounds(t,i)}getBaseProps(t){return e.GetBaseProps(t)}dispatchOnChangeSync(t,i,...n){e.DispatchOnChangeSync(t,i,...n)}};Kg.DefaultDispatchMode="immediate";let Jg=Kg;class Zg extends Jp{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 Jg(this),this.undoManager=!1===i?void 0:i||new tm({bindHotKeys:!0,limit:1e3,debug:null!==dg("debugUndo")}),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(){null===this._rafId&&(this._rafId=requestAnimationFrame(this.raf))}stop(){null!==this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=null)}refreshQueue(e){const t=this._refreshQueue[e],i=[],n=$p(),r=n-this._lastModeTime[e];t.forEach(e=>{e[1]>.001?(e[1]-=r,i.push(e)):this._refreshUiConfigObject(e[0])}),this._refreshQueue[e]=i,this._lastModeTime[e]=n}_addToRefreshQueue(e,t,i){const n=t.uuid,r=this._refreshQueue[e],s=r.find(e=>e[2]===n);s?s[1]=Math.max(s[1],i):r.push([t,i,n]),this._refreshQueue[e]=r}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 r=i?this._flattenUiConfig(t):[t];for(const t of r)"immediate"===e?Zp(n).then(()=>this._refreshUiConfigObject(t)):this._addToRefreshQueue(e,t,n)}_flattenUiConfig(e,t){return t=t??[],!e||!e.uiRef||(t.push(e),"function"==typeof e.children)||e.children?.forEach(e=>{"function"!=typeof e&&e&&(Array.isArray(e)?e.forEach(e=>t=this._flattenUiConfig(e,t)):t=this._flattenUiConfig(e,t))}),t}}var $g=Object.defineProperty,ef=Object.getOwnPropertyDescriptor,tf=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?ef(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&$g(t,i,s),s};e.ViewerTimeline=class extends ri{constructor(){super(...arguments),this._time=0,this.delta=0,this.endTime=2,this.resetOnEnd=!0,this.stopOnEnd=!1,this.running=!1,this._clock=new Wu(!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)return this.delta=this._clock.getDelta(),void(this._time=this._clock.elapsedTime);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"})):void 0!==t&&0===t?(this.delta=0,this._time=this._clock.elapsedTime):(void 0===t||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"})}},tf([zg("Time",{readOnly:!0})],e.ViewerTimeline.prototype,"time",1),tf([zg("Delta",{readOnly:!0})],e.ViewerTimeline.prototype,"delta",2),tf([zg("Max Time"),qm(),Wm("endTimeChanged")],e.ViewerTimeline.prototype,"endTime",2),tf([Hg("Reset on End"),qm(),Wm("resetOnEndChanged")],e.ViewerTimeline.prototype,"resetOnEnd",2),tf([Hg("Stop on End"),qm(),Wm("stopOnEndChanged")],e.ViewerTimeline.prototype,"stopOnEnd",2),tf([zg("Running",{readOnly:!0})],e.ViewerTimeline.prototype,"running",2),tf([jg("Start")],e.ViewerTimeline.prototype,"start",1),tf([jg("Stop")],e.ViewerTimeline.prototype,"stop",1),tf([jg("Reset")],e.ViewerTimeline.prototype,"reset",1),e.ViewerTimeline=tf([Xm("ViewerTimeline"),qg("Timeline")],e.ViewerTimeline);var nf,rf={exports:{}};var sf,af=(nf||(nf=1,rf.exports=((sf=function(){function e(e){return n.appendChild(e.dom),e}function t(e){for(var t=0;t<n.children.length;t++)n.children[t].style.display=t===e?"block":"none";i=e}var i=0,n=document.createElement("div");n.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",n.addEventListener("click",function(e){e.preventDefault(),t(++i%n.children.length)},!1);var r=(performance||Date).now(),s=r,a=0,o=e(new sf.Panel("FPS","#0ff","#002")),l=e(new sf.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var c=e(new sf.Panel("MB","#f08","#201"));return t(0),{REVISION:16,dom:n,addPanel:e,showPanel:t,begin:function(){r=(performance||Date).now()},end:function(){a++;var e=(performance||Date).now();if(l.update(e-r,200),e>s+1e3&&(o.update(1e3*a/(e-s),100),s=e,a=0,c)){var t=performance.memory;c.update(t.usedJSHeapSize/1048576,t.jsHeapSizeLimit/1048576)}return e},update:function(){r=this.end()},domElement:n,setMode:t}}).Panel=function(e,t,i){var n=1/0,r=0,s=Math.round,a=s(window.devicePixelRatio||1),o=80*a,l=48*a,c=3*a,h=2*a,d=3*a,u=15*a,p=74*a,m=30*a,g=document.createElement("canvas");g.width=o,g.height=l,g.style.cssText="width:80px;height:48px";var f=g.getContext("2d");return f.font="bold "+9*a+"px Helvetica,Arial,sans-serif",f.textBaseline="top",f.fillStyle=i,f.fillRect(0,0,o,l),f.fillStyle=t,f.fillText(e,c,h),f.fillRect(d,u,p,m),f.fillStyle=i,f.globalAlpha=.9,f.fillRect(d,u,p,m),{dom:g,update:function(l,A){n=Math.min(n,l),r=Math.max(r,l),f.fillStyle=i,f.globalAlpha=1,f.fillRect(0,0,o,u),f.fillStyle=t,f.fillText(s(l)+" "+e+" ("+s(n)+"-"+s(r)+")",c,h),f.drawImage(g,d+a,u,p-a,m,d,u,p-a,m),f.fillRect(d+p-a,u,a,m),f.fillStyle=i,f.globalAlpha=.9,f.fillRect(d+p-a,u,a,s((1-l/A)*m))}}},sf)),rf.exports);const of=(lf=af)&&lf.__esModule&&Object.prototype.hasOwnProperty.call(lf,"default")?lf.default:lf;var lf;class cf{constructor(e){this._stats=new of,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 hf=class{static _initialize(){this._inited=!0,document.addEventListener("pointerdown",e=>{this.Element&&!this.Element.contains(e.target)&&0===e.button&&this.Remove()})}static Create(e,t,i,n=!0,r=!0){this._inited||this._initialize(),this.Element&&this.Remove();const s=document.createElement("div");s.id="customContextMenu",s.style.top=i+"px",s.style.left=t+"px",s.innerHTML="<style>.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}</style>";for(const[t,i]of Object.entries(e)){const e=document.createElement("div");e.classList.add("customContextMenuItems"),e.textContent=t,s.appendChild(e),e.onclick=async()=>{await i(),r&&this.Remove()}}return this.Element=s,n&&document.body.appendChild(s),s}static Remove(){this.Element?.remove(),this.Element=void 0}};hf.Element=void 0,hf._inited=!1;let df=hf;const uf=class e{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(([e,t])=>t&&this.on(e,t))}on(e,t){return this._listeners[e].push(t),this}_emit(e,t){return this._listeners[e].forEach(e=>e(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(t){t.stopPropagation(),t.preventDefault(),this._emit("dropstart");const i=Array.from(t.dataTransfer?.files||[]),n=Array.from(t.dataTransfer?.items||[]);if(0!==i.length||0!==n.length){if(e.USE_DATA_TRANSFER_ITEMS&&n.length>0){const e=n.map(e=>e.webkitGetAsEntry());return void this._loadNextEntry(new Map,e,t)}this._emit("drop",{nativeEvent:t,files:new Map(i.map(e=>(e.filePath=e.name,[e.filePath,e])))})}else this._fail("Required drag-and-drop APIs are not supported in this browser.")}_onDragover(e){e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy")}_onSelect(e){if(!this._inputEl)return void console.warn("Invalid Dropzone event ",e);this._emit("dropstart");const t=[].slice.call(this._inputEl.files??new FileList),i=new Map;t.forEach(e=>{e.filePath=e.webkitRelativePath||e.name,i.set(e.filePath,e)}),this._emit("drop",{files:i,nativeEvent:e})}_loadNextEntry(e,t,i){const n=t.pop();if(n)if(n.isFile)n.file(r=>{r.filePath=n.fullPath,e.set(n.fullPath,r),this._loadNextEntry(e,t,i)},e=>console.error("Could not load file: %s",n.fullPath,e,"Try setting Dropzone.USE_DATA_TRANSFER_ITEMS to false."));else if(n.isDirectory){const r=n.createReader(),s=n=>{n.length?(t=t.concat(n),r.readEntries(s)):this._loadNextEntry(e,t,i)};r.readEntries(s)}else console.warn("Unknown asset type: "+n.fullPath),this._loadNextEntry(e,t,i);else this._emit("drop",{files:e,nativeEvent:i})}_fail(e){this._emit("droperror",{message:e})}};uf.USE_DATA_TRANSFER_ITEMS=!0;let pf=uf;const mf={type:"change"},gf={type:"start"},ff={type:"end"},Af=new Cn,yf=new bs,vf=Math.cos(70*gi.DEG2RAD),_f=new Xi,bf=new Sp,xf=new Xi,wf=2*Math.PI,Cf=-1,Sf=0,Mf=1,Ef=2,Tf=3,If=4,Pf=5,Df=6,Rf=1e-6;class Bf extends Kp{constructor(e,t=null){super(e,t),this.state=Cf,this.enabled=!0,this.target=new Xi,this.cursor=new Xi,this.minDistance=1e-5,this.maxDistance=1/0,this.autoPushTarget=!0,this.autoPullTarget=!0,this.clampMax=new Xi(1/0,1/0,1/0),this.clampMin=new Xi(-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:p,MIDDLE:m,RIGHT:g},this.touches={ONE:f,TWO:y},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new Xi,this._lastQuaternion=new qi,this._lastTargetPosition=new Xi,this._quat=(new qi).setFromUnitVectors(e.up,new Xi(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Sp,this._sphericalDelta=new Sp(0),this._scale=1,this._panOffset=new Xi,this._rotateStart=new fi,this._rotateEnd=new fi,this._rotateDelta=new fi,this._panStart=new fi,this._panEnd=new fi,this._panDelta=new fi,this._dollyStart=new fi,this._dollyEnd=new fi,this._dollyDelta=new fi,this._dollyDirection=new Xi,this._mouse=new fi,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Of.bind(this),this._onPointerDown=Lf.bind(this),this._onPointerUp=Uf.bind(this),this._onContextMenu=Qf.bind(this),this._onMouseWheel=Nf.bind(this),this._onKeyDown=jf.bind(this),this._onTouchStart=zf.bind(this),this._onTouchMove=Gf.bind(this),this._onMouseDown=Ff.bind(this),this._onMouseMove=kf.bind(this),this._interceptControlDown=Vf.bind(this),this._interceptControlUp=Hf.bind(this),this._lastUpdateTime=0,null!==this.domElement&&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(){null!==this._domElementKeyEvents&&(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(mf),this.update(),this.state=Cf}update(e=null){if(this.throttleUpdate&&this.throttleUpdate>=1&&Date.now()-this._lastUpdateTime<1e3/this.throttleUpdate)return;const t=this.object.position;_f.copy(t).sub(this.target),_f.applyQuaternion(this._quat),this._spherical.setFromVector3(_f),bf.copy(this._spherical),xf.copy(this.target),this.autoRotate&&this.state===Cf&&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+=wf:i>Math.PI&&(i-=wf),n<-Math.PI?n+=wf:n>Math.PI&&(n-=wf),this._spherical.theta=i<=n?Math.max(i,Math.min(n,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(),!0===this.enableDamping?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=0,s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const e=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&&(r=this.minDistance-this._spherical.radius),this.autoPullTarget&&this._spherical.radius>this.maxDistance&&(r=this.maxDistance-this._spherical.radius),this._spherical.radius=this._clampDistance(this._spherical.radius),s=e!=this._spherical.radius}(0!==r||!this.target.equals(xf)||this._spherical.radius!==bf.radius||this._spherical.phi!==bf.phi||this._spherical.theta!==bf.theta)&&(_f.setFromSpherical(this._spherical),_f.applyQuaternion(this._quatInverse),t.copy(this.target).add(_f),this.target.add(_f.normalize().multiplyScalar(-r))),t.clamp(this.clampMin,this.clampMax),this.target.clamp(this.clampMin,this.clampMax),this.object.lookAt(this.target);let a=!1;if(!0===this.enableDamping&&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),a=!0):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let e=null;if(this.object.isPerspectiveCamera){const t=this._spherical.radius;e=this._spherical.radius*this._scale,e=this._clampDistance(e);const i=t-e;this.object.position.addScaledVector(this._dollyDirection,i),this.object.updateMatrixWorld(),s=!!i}else if(this.object.isOrthographicCamera){const t=new Xi(this._mouse.x,this._mouse.y,0);t.unproject(this.object);const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=i!==this.object.zoom;const n=new Xi(this._mouse.x,this._mouse.y,0);n.unproject(this.object),this.object.position.sub(n).add(t),this.object.updateMatrixWorld(),e=this._spherical.radius}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==e&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position):(Af.origin.copy(this.object.position),Af.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Af.direction))<vf?this.object.lookAt(this.target):(yf.setFromNormalAndCoplanarPoint(this.object.up,this.target),Af.intersectPlane(yf,this.target))))}else if(this.object.isOrthographicCamera){const e=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),e!==this.object.zoom&&(this.object.updateProjectionMatrix(),s=!0)}return this._scale=1,this._performCursorZoom=!1,!!(s||a||this._lastPosition.distanceToSquared(this.object.position)>Rf||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Rf||this._lastTargetPosition.distanceToSquared(this.target)>Rf)&&(this.dispatchEvent(mf),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}stopDamping(){this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)}_getAutoRotationAngle(e){return null!==e?wf/60*this.autoRotateSpeed*e:wf/60/60*this.autoRotateSpeed}_getZoomScale(e){return!this.enableDamping||this.zoomToCursor||this.object.isOrthographicCamera?Math.pow(.95,this.zoomSpeed):1}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){_f.setFromMatrixColumn(t,0),_f.multiplyScalar(-e),this._panOffset.add(_f)}_panUp(e,t){!0===this.screenSpacePanning?_f.setFromMatrixColumn(t,1):(_f.setFromMatrixColumn(t,0),_f.crossVectors(this.object.up,_f)),_f.multiplyScalar(e),this._panOffset.add(_f)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const n=this.object.position;_f.copy(n).sub(this.target);let r=_f.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/i.clientHeight,this.object.matrix),this._panUp(2*t*r/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,r=t-i.top,s=i.width,a=i.height;this._mouse.x=n/s*2-1,this._mouse.y=-r/a*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.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(wf*this._rotateDelta.x/t.clientHeight),this._rotateUp(wf*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+=1*e.deltaY;break;case 1:t+=.4*e.deltaY;break;default:t+=.01*e.deltaY}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(wf*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(-wf*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(wf*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(-wf*this.rotateSpeed/this.domElement.clientHeight):this._pan(-this.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(1===this._pointers.length)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._rotateStart.set(i,n)}}_handleTouchStartPan(e){if(1===this._pointers.length)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,r=Math.sqrt(i*i+n*n);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);this._rotateEnd.set(i,n)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(wf*this._rotateDelta.x/t.clientHeight),this._rotateUp(wf*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),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,r=Math.sqrt(i*i+n*n);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,6*this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const s=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(s,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return void this._pointers.splice(t,1)}_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];void 0===t&&(t=new fi,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}return e.ctrlKey&&!this._controlActive&&(i.deltaY*=10),i}rotateUp(e){this._rotateUp(e)}rotateLeft(e){this._rotateLeft(e)}}function Lf(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(e)&&(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e)))}function Of(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):e.buttons?this._onMouseMove(e):this._onPointerUp(e))}function Uf(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(ff),this.state=Cf;break;case 1:const t=this._pointers[0],i=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:i.x,pageY:i.y})}}function Ff(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case m:if(!1===this.enableZoom)return;this._handleMouseDownDolly(e),this.state=Mf;break;case p:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=Ef}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=Sf}break;case g:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=Sf}else{if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=Ef}break;default:this.state=Cf}this.state!==Cf&&this.dispatchEvent(gf)}function kf(e){switch(this.state){case Sf:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case Mf:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case Ef:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function Nf(e){!1===this.enabled||!1===this.enableZoom||this.state!==Cf||(e.preventDefault(),this.dispatchEvent(gf),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(ff))}function jf(e){!1===this.enabled||!1===this.enablePan||this._handleKeyDown(e)}function zf(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case f:if(!1===this.enableRotate)return;this._handleTouchStartRotate(e),this.state=Tf;break;case A:if(!1===this.enablePan)return;this._handleTouchStartPan(e),this.state=If;break;default:this.state=Cf}break;case 2:switch(this.touches.TWO){case y:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(e),this.state=Pf;break;case v:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(e),this.state=Df;break;default:this.state=Cf}break;default:this.state=Cf}this.state!==Cf&&this.dispatchEvent(gf)}function Gf(e){switch(this._trackPointer(e),this.state){case Tf:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case If:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case Pf:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case Df:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=Cf}}function Qf(e){!1!==this.enabled&&e.preventDefault()}function Vf(e){"Control"===e.key&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function Hf(e){"Control"===e.key&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}var Wf=Object.defineProperty,qf=Object.getOwnPropertyDescriptor,Xf=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?qf(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&Wf(t,i,s),s};e.OrbitControls3=class extends Bf{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 Xi(-1e6,-1e6,-1e6),this.clampMax=new Xi(1e6,1e6,1e6),this.screenSpacePanning=!0,this.keyPanSpeed=7,this.throttleUpdate=60}},Xf([qm()],e.OrbitControls3.prototype,"type",2),Xf([Hg()],e.OrbitControls3.prototype,"enabled",2),Xf([Hg(),qm()],e.OrbitControls3.prototype,"dollyZoom",2),Xf([Hg(),qm()],e.OrbitControls3.prototype,"zoomToCursor",2),Xf([Hg(),qm()],e.OrbitControls3.prototype,"enableDamping",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"dampingFactor",2),Xf([Hg(),qm()],e.OrbitControls3.prototype,"autoRotate",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"autoRotateSpeed",2),Xf([Hg(),qm()],e.OrbitControls3.prototype,"enableZoom",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"zoomSpeed",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"maxZoomSpeed",2),Xf([Hg(),qm()],e.OrbitControls3.prototype,"enableRotate",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"rotateSpeed",2),Xf([Hg(),qm()],e.OrbitControls3.prototype,"enablePan",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"panSpeed",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"autoPushTarget",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"autoPullTarget",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"minDistance",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"maxDistance",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"minZoom",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"maxZoom",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"minPolarAngle",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"maxPolarAngle",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"minAzimuthAngle",2),Xf([zg(),qm()],e.OrbitControls3.prototype,"maxAzimuthAngle",2),Xf([kg(),qm()],e.OrbitControls3.prototype,"clampMin",2),Xf([kg(),qm()],e.OrbitControls3.prototype,"clampMax",2),Xf([qm()],e.OrbitControls3.prototype,"screenSpacePanning",2),Xf([qm()],e.OrbitControls3.prototype,"keyPanSpeed",2),e.OrbitControls3=Xf([Wg("Orbit Controls")],e.OrbitControls3);const Yf=new xp;Yf.params.Line2={threshold:.01};const Kf=new Xi,Jf=new Xi,Zf=new qi,$f={X:new Xi(1,0,0),Y:new Xi(0,1,0),Z:new Xi(0,0,1)},eA={type:"change"},tA={type:"mouseDown",mode:null},iA={type:"mouseUp",mode:null},nA={type:"objectChange"};class rA extends Zn{constructor(e,t){super(),void 0===t&&(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 SA;this._gizmo=i,this.add(i);const n=new MA;this._plane=n,this.add(n);const r=this;function s(e,t){let s=t;Object.defineProperty(r,e,{get:function(){return void 0!==s?s:t},set:function(t){s!==t&&(!r.lockProps||!r.lockProps.includes(e))&&(s=t,n[e]=t,i[e]=t,r.dispatchEvent({type:e+"-changed",value:t}),r.dispatchEvent(eA))}}),r[e]=t,n[e]=t,i[e]=t}s("camera",e),s("object",void 0),s("enabled",!0),s("axis",null),s("mode","translate"),s("translationSnap",null),s("rotationSnap",null),s("scaleSnap",null),s("space","world"),s("size",1),s("dragging",!1),s("showX",!0),s("showY",!0),s("showZ",!0);const a=new Xi,o=new Xi,l=new qi,c=new qi,h=new Xi,d=new qi,u=new Xi,p=new Xi,m=new Xi,g=new Xi;s("worldPosition",a),s("worldPositionStart",o),s("worldQuaternion",l),s("worldQuaternionStart",c),s("cameraPosition",h),s("cameraQuaternion",d),s("pointStart",u),s("pointEnd",p),s("rotationAxis",m),s("rotationAngle",0),s("eye",g),this._offset=new Xi,this._startNorm=new Xi,this._endNorm=new Xi,this._cameraScale=new Xi,this._parentPosition=new Xi,this._parentQuaternion=new qi,this._parentQuaternionInv=new qi,this._parentScale=new Xi,this._worldScaleStart=new Xi,this._worldQuaternionInv=new qi,this._worldScale=new Xi,this._positionStart=new Xi,this._quaternionStart=new qi,this._scaleStart=new Xi,this._getPointer=sA.bind(this),this._onPointerDown=oA.bind(this),this._onPointerHover=aA.bind(this),this._onPointerMove=lA.bind(this),this._onPointerUp=cA.bind(this),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp)}updateMatrixWorld(){void 0!==this.object&&(this.object.updateMatrixWorld(),null===this.object.parent?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(void 0===this.object||!0===this.dragging)return;null!==e&&Yf.setFromCamera(e,this.camera);const t=hA(this._gizmo.picker[this.mode],Yf);this.axis=t?t.object.name:null}pointerDown(e){if(void 0!==this.object&&!0!==this.dragging&&(null==e||0===e.button)&&null!==this.axis){null!==e&&Yf.setFromCamera(e,this.camera);const t=hA(this._plane,Yf,!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,tA.mode=this.mode,this.dispatchEvent(tA)}}pointerMove(e){const t=this.axis,i=this.mode,n=this.object,r=n&&n.userData&&n.userData.isMultiSelectDummy;let s=r?"world":this.space;if("scale"!==i||r?("E"===t||"XYZE"===t||"XYZ"===t)&&(s="world"):s="local",void 0===n||null===t||!1===this.dragging||null!==e&&-1!==e.button)return;null!==e&&Yf.setFromCamera(e,this.camera);const a=hA(this._plane,Yf,!0);if(a){if(this.pointEnd.copy(a.point).sub(this.worldPositionStart),"translate"===i)this._offset.copy(this.pointEnd).sub(this.pointStart),"local"===s&&"XYZ"!==t&&this._offset.applyQuaternion(this._worldQuaternionInv),-1===t.indexOf("X")&&(this._offset.x=0),-1===t.indexOf("Y")&&(this._offset.y=0),-1===t.indexOf("Z")&&(this._offset.z=0),"local"===s&&"XYZ"!==t?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&&("local"===s&&(n.position.applyQuaternion(Zf.copy(this._quaternionStart).invert()),-1!==t.search("X")&&(n.position.x=Math.round(n.position.x/this.translationSnap)*this.translationSnap),-1!==t.search("Y")&&(n.position.y=Math.round(n.position.y/this.translationSnap)*this.translationSnap),-1!==t.search("Z")&&(n.position.z=Math.round(n.position.z/this.translationSnap)*this.translationSnap),n.position.applyQuaternion(this._quaternionStart)),"world"===s&&(n.parent&&n.position.add(Kf.setFromMatrixPosition(n.parent.matrixWorld)),-1!==t.search("X")&&(n.position.x=Math.round(n.position.x/this.translationSnap)*this.translationSnap),-1!==t.search("Y")&&(n.position.y=Math.round(n.position.y/this.translationSnap)*this.translationSnap),-1!==t.search("Z")&&(n.position.z=Math.round(n.position.z/this.translationSnap)*this.translationSnap),n.parent&&n.position.sub(Kf.setFromMatrixPosition(n.parent.matrixWorld))));else if("scale"===i){if(-1!==t.search("XYZ")){let e=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(e*=-1),Jf.set(e,e,e)}else Kf.copy(this.pointStart),Jf.copy(this.pointEnd),Kf.applyQuaternion(this._worldQuaternionInv),Jf.applyQuaternion(this._worldQuaternionInv),Jf.divide(Kf),-1===t.search("X")&&(Jf.x=1),-1===t.search("Y")&&(Jf.y=1),-1===t.search("Z")&&(Jf.z=1);n.scale.copy(this._scaleStart).multiply(Jf),this.scaleSnap&&(-1!==t.search("X")&&(n.scale.x=Math.round(n.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),-1!==t.search("Y")&&(n.scale.y=Math.round(n.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),-1!==t.search("Z")&&(n.scale.z=Math.round(n.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if("rotate"===i){this._offset.copy(this.pointEnd).sub(this.pointStart);const e=20/this.worldPosition.distanceTo(Kf.setFromMatrixPosition(this.camera.matrixWorld));let i=!1;"XYZE"===t?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(Kf.copy(this.rotationAxis).cross(this.eye))*e):("X"===t||"Y"===t||"Z"===t)&&(this.rotationAxis.copy($f[t]),Kf.copy($f[t]),"local"===s&&Kf.applyQuaternion(this.worldQuaternion),Kf.cross(this.eye),0===Kf.length()?i=!0:this.rotationAngle=this._offset.dot(Kf.normalize())*e),("E"===t||i)&&(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),"local"===s&&"E"!==t&&"XYZE"!==t?(n.quaternion.copy(this._quaternionStart),n.quaternion.multiply(Zf.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),n.quaternion.copy(Zf.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),n.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(eA),this.dispatchEvent(nA)}}pointerUp(e){null!==e&&0!==e.button||(this.dragging&&null!==this.axis&&(iA.mode=this.mode,this.dispatchEvent(iA)),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(eA),this.dispatchEvent(nA),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Yf}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}}function sA(e){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:e.button,buttons:e.buttons};{const t=this.domElement.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*2-1,y:-(e.clientY-t.top)/t.height*2+1,button:e.button,buttons:e.buttons}}}function aA(e){if(this.enabled)switch(e.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(e))}}function oA(e){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(e)),this.pointerDown(this._getPointer(e)))}function lA(e){this.enabled&&this.pointerMove(this._getPointer(e))}function cA(e){this.enabled&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(e)))}function hA(e,t,i){const n=t.intersectObject(e,!0);for(let e=0;e<n.length;e++)if(n[e].object.visible||i)return n[e];return!1}rA.ObjectConstructors={MeshBasicMaterial:vr,LineBasicMaterial:Dc};const dA=new On,uA=new Xi(0,1,0),pA=new Xi(0,0,0),mA=new Sn,gA=new qi,fA=new qi,AA=new Xi,yA=new Sn,vA=new Xi(1,0,0),_A=new Xi(0,1,0),bA=new Xi(0,0,1),xA=new Xi,wA=new Xi,CA=new Xi;class SA extends Zn{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new rA.ObjectConstructors.MeshBasicMaterial({allowOverride:!1,depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new rA.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 r=e.clone();r.color.setHex(15663205),r.opacity=.95;const s=e.clone();s.color.setHex(2014720),s.opacity=.95;const a=e.clone();a.color.setHex(37885),a.opacity=.95;const o=e.clone();o.color.setHex(16618689),o.__color=r.color.getHex();const l=e.clone();l.color.setHex(12516474),l.__color=s.color.getHex();const c=e.clone();c.color.setHex(11397372),c.__color=a.color.getHex();const h=e.clone();h.color.setHex(15663205),h.opacity=.75;const d=e.clone();d.color.setHex(2014720),d.opacity=.75;const u=e.clone();u.color.setHex(37885),u.opacity=.75;const p=e.clone();p.color.setHex(12893629),p.opacity=.75;const m=e.clone();m.color.setHex(16777051),m.opacity=.25;const g=e.clone();g.color.setHex(7895160),g.opacity=.75;const f=new Th(0,.04,.1,12);f.translate(0,.05,0);const A=new ns(.08,.08,.08);A.translate(0,.04,0);const y=new Fr;y.setAttribute("position",new Ir([0,0,0,1,0,0],3));const v=new Th(.0075,.0075,.5,3);function _(e,t){const i=new _d(e,.0075,3,64,t*Math.PI*2);return i.rotateY(Math.PI/2),i.rotateX(Math.PI/2),i}function b(e,t){const i=new _d(e,.1,4,24,t*Math.PI*2);return i.rotateY(Math.PI/2),i.rotateX(Math.PI/2),i}v.translate(0,.25,0);const x={X:[[new ts(f,o),[.5,0,0],[0,0,-Math.PI/2]],[new ts(v,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new ts(f,l),[0,.5,0]],[new ts(v,s)]],Z:[[new ts(f,c),[0,0,.5],[Math.PI/2,0,0]],[new ts(v,a),null,[Math.PI/2,0,0]]],XYZ:[[new ts(new gd(.1,2),p.clone()),[0,0,0]]],XY:[[new ts(new ns(.2,.2,.01),u.clone()),[.2,.2,0]]],YZ:[[new ts(new ns(.2,.2,.01),h.clone()),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new ts(new ns(.2,.2,.01),d.clone()),[.2,0,.2],[-Math.PI/2,0,0]]]},w={X:[[new ts(new Th(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]]],Y:[[new ts(new Th(.2,0,.6,4),i),[0,.3,0]]],Z:[[new ts(new Th(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]]],XYZ:[[new ts(new gd(.2,0),i)]],XY:[[new ts(new ns(.25,.25,.01),i),[.2,.2,0]]],YZ:[[new ts(new ns(.25,.25,.01),i),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new ts(new ns(.25,.25,.01),i),[.2,0,.2],[-Math.PI/2,0,0]]]},C={START:[[new ts(new gd(.01,2),n),null,null,null,"helper"]],END:[[new ts(new gd(.01,2),n),null,null,null,"helper"]],DELTA:[[new Nc(function(){const e=new Fr;return e.setAttribute("position",new Ir([0,0,0,1,1,1],3)),e}(),n),null,null,null,"helper"]],X:[[new Nc(y,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Nc(y,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Nc(y,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},S={XYZE:[[new ts(new yd(.1,10,8),p)],[new ts(_(.5,1),g),null,[0,Math.PI/2,0]]],X:[[new ts(_(.5,.5),r)],[new ts(v,r),[0,0,0],[0,0,-Math.PI/2]],[new ts(f.clone().translate(.5,0,0),o),[0,0,0],[-Math.PI/2,-Math.PI/2,-Math.PI/2]]],Y:[[new ts(_(.5,.5),s),null,[0,0,-Math.PI/2]],[new ts(v,s)],[new ts(f.clone().rotateZ(-Math.PI/2).translate(0,.5,0),l),[0,0,0],[Math.PI/2,0,0]]],Z:[[new ts(_(.5,.5),a),null,[0,Math.PI/2,0]],[new ts(v,a),null,[Math.PI/2,0,0]],[new ts(f.clone().rotateZ(-Math.PI).translate(0,0,.5),c),[0,0,0],[0,Math.PI/2,0]]]},M={AXIS:[[new Nc(y,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},E={XYZE:[[new ts(new yd(.25,10,8),i)]],X:[[new ts(b(.5,.5),i)]],Y:[[new ts(b(.5,.5),i),[0,0,0],[0,0,-Math.PI/2]]],Z:[[new ts(b(.5,.5),i),[0,0,0],[0,Math.PI/2,0]]]},T={X:[[new ts(A,o),[.5,0,0],[0,0,-Math.PI/2]],[new ts(v,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new ts(A,l),[0,.5,0]],[new ts(v,s)]],Z:[[new ts(A,c),[0,0,.5],[Math.PI/2,0,0]],[new ts(v,a),[0,0,0],[Math.PI/2,0,0]]],XY:[[new ts(new ns(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new ts(new ns(.15,.15,.01),h),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ts(new ns(.15,.15,.01),d),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ts(new ns(.1,.1,.1),p.clone())]]},I={X:[[new ts(new Th(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new ts(new Th(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ts(new Th(.2,0,.6,4),i),[0,.3,0]],[new ts(new Th(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ts(new Th(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new ts(new Th(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new ts(new ns(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new ts(new ns(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ts(new ns(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ts(new ns(.2,.2,.2),i),[0,0,0]]]},P={X:[[new Nc(y,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new Nc(y,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new Nc(y,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function D(e){const t=new Zn;for(const i in e)for(let n=e[i].length;n--;){const r=e[i][n][0].clone(),s=e[i][n][1],a=e[i][n][2],o=e[i][n][3],l=e[i][n][4];r.name=i,r.tag=l,s&&r.position.set(s[0],s[1],s[2]),a&&r.rotation.set(a[0],a[1],a[2]),o&&r.scale.set(o[0],o[1],o[2]),r.updateMatrix();const c=r.geometry.clone();c.applyMatrix4(r.matrix),r.geometry=c,r.renderOrder=1/0,r.position.set(0,0,0),r.rotation.set(0,0,0),r.scale.set(1,1,1),t.add(r)}return t}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=D(x)),this.add(this.gizmo.rotate=D(S)),this.add(this.gizmo.scale=D(T)),this.add(this.picker.translate=D(w)),this.add(this.picker.rotate=D(E)),this.add(this.picker.scale=D(I)),this.add(this.helper.translate=D(C)),this.add(this.helper.rotate=D(M)),this.add(this.helper.scale=D(P)),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,i="local"===("scale"!==this.mode||t?t?"world":this.space:"local")?this.worldQuaternion:fA;this.gizmo.translate.visible="translate"===this.mode,this.gizmo.rotate.visible="rotate"===this.mode,this.gizmo.scale.visible="scale"===this.mode,this.helper.translate.visible="translate"===this.mode,this.helper.rotate.visible="rotate"===this.mode,this.helper.scale.visible="scale"===this.mode;let n=[];n=n.concat(this.picker[this.mode].children),n=n.concat(this.gizmo[this.mode].children),n=n.concat(this.helper[this.mode].children);for(let e=0;e<n.length;e++){const t=n[e];let r;t.visible=!0,t.rotation.set(0,0,0),t.position.copy(this.worldPosition),(r=this.camera.isOrthographicCamera?(this.camera.top-this.camera.bottom)/this.camera.zoom:this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),t.scale.set(1,1,1).multiplyScalar(r*this.size/4),"helper"!==t.tag)?(t.quaternion.copy(i),"translate"===this.mode||"scale"===this.mode?("X"===t.name&&Math.abs(uA.copy(vA).applyQuaternion(i).dot(this.eye))>.99&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1),"Y"===t.name&&Math.abs(uA.copy(_A).applyQuaternion(i).dot(this.eye))>.99&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1),"Z"===t.name&&Math.abs(uA.copy(bA).applyQuaternion(i).dot(this.eye))>.99&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1),"XY"===t.name&&Math.abs(uA.copy(bA).applyQuaternion(i).dot(this.eye))<.2&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1),"YZ"===t.name&&Math.abs(uA.copy(vA).applyQuaternion(i).dot(this.eye))<.2&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1),"XZ"===t.name&&Math.abs(uA.copy(_A).applyQuaternion(i).dot(this.eye))<.2&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1)):"rotate"===this.mode&&(gA.copy(i),uA.copy(this.eye).applyQuaternion(Zf.copy(i).invert()),-1!==t.name.search("E")&&t.quaternion.setFromRotationMatrix(mA.lookAt(this.eye,pA,_A)),"X"===t.name&&(Zf.setFromAxisAngle(vA,Math.atan2(-uA.y,uA.z)),Zf.multiplyQuaternions(gA,Zf),t.quaternion.copy(Zf)),"Y"===t.name&&(Zf.setFromAxisAngle(_A,Math.atan2(uA.x,uA.z)),Zf.multiplyQuaternions(gA,Zf),t.quaternion.copy(Zf)),"Z"===t.name&&(Zf.setFromAxisAngle(bA,Math.atan2(uA.y,uA.x)),Zf.multiplyQuaternions(gA,Zf),t.quaternion.copy(Zf))),t.visible=t.visible&&(-1===t.name.indexOf("X")||this.showX),t.visible=t.visible&&(-1===t.name.indexOf("Y")||this.showY),t.visible=t.visible&&(-1===t.name.indexOf("Z")||this.showZ),t.visible=t.visible&&(-1===t.name.indexOf("E")||this.showX&&this.showY&&this.showZ),t.material._color=t.material._color||t.material.color.clone(),t.material._opacity=t.material._opacity||t.material.opacity,t.material.color.copy(t.material._color),t.material.opacity=t.material._opacity,this.enabled&&this.axis&&(t.name===this.axis||this.axis.split("").some(function(e){return t.name===e}))&&(t.material.__color&&t.material.color.setHex(t.material.__color),t.material.opacity=1)):(t.visible=!1,"AXIS"===t.name?(t.visible=!!this.axis,"X"===this.axis&&(Zf.setFromEuler(dA.set(0,0,0)),t.quaternion.copy(i).multiply(Zf),Math.abs(uA.copy(vA).applyQuaternion(i).dot(this.eye))>.9&&(t.visible=!1)),"Y"===this.axis&&(Zf.setFromEuler(dA.set(0,0,Math.PI/2)),t.quaternion.copy(i).multiply(Zf),Math.abs(uA.copy(_A).applyQuaternion(i).dot(this.eye))>.9&&(t.visible=!1)),"Z"===this.axis&&(Zf.setFromEuler(dA.set(0,Math.PI/2,0)),t.quaternion.copy(i).multiply(Zf),Math.abs(uA.copy(bA).applyQuaternion(i).dot(this.eye))>.9&&(t.visible=!1)),"XYZE"===this.axis&&(Zf.setFromEuler(dA.set(0,Math.PI/2,0)),uA.copy(this.rotationAxis),t.quaternion.setFromRotationMatrix(mA.lookAt(pA,uA,_A)),t.quaternion.multiply(Zf),t.visible=this.dragging),"E"===this.axis&&(t.visible=!1)):"START"===t.name?(t.position.copy(this.worldPositionStart),t.visible=this.dragging):"END"===t.name?(t.position.copy(this.worldPosition),t.visible=this.dragging):"DELTA"===t.name?(t.position.copy(this.worldPositionStart),t.quaternion.copy(this.worldQuaternionStart),Kf.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),Kf.applyQuaternion(this.worldQuaternionStart.clone().invert()),t.scale.copy(Kf),t.visible=this.dragging):(t.quaternion.copy(i),this.dragging?t.position.copy(this.worldPositionStart):t.position.copy(this.worldPosition),this.axis&&(t.visible=-1!==this.axis.search(t.name))))}super.updateMatrixWorld(e)}}class MA extends ts{constructor(){super(new Es(1e5,1e5,2,2),new rA.ObjectConstructors.MeshBasicMaterial({visible:!1,wireframe:!0,side:x,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),"scale"===this.mode&&!t&&(i="local"),xA.copy(vA).applyQuaternion("local"===i?this.worldQuaternion:fA),wA.copy(_A).applyQuaternion("local"===i?this.worldQuaternion:fA),CA.copy(bA).applyQuaternion("local"===i?this.worldQuaternion:fA),uA.copy(wA),this.mode){case"translate":case"scale":switch(this.axis){case"X":uA.copy(this.eye).cross(xA),AA.copy(xA).cross(uA);break;case"Y":uA.copy(this.eye).cross(wA),AA.copy(wA).cross(uA);break;case"Z":uA.copy(this.eye).cross(CA),AA.copy(CA).cross(uA);break;case"XY":AA.copy(CA);break;case"YZ":AA.copy(xA);break;case"XZ":uA.copy(CA),AA.copy(wA);break;case"XYZ":case"E":AA.set(0,0,0)}break;default:AA.set(0,0,0)}0===AA.length()?this.quaternion.copy(this.cameraQuaternion):(yA.lookAt(Kf.set(0,0,0),AA,uA),this.quaternion.setFromRotationMatrix(yA)),super.updateMatrixWorld(e)}}function EA(e,t){if(e.metaKey||e.ctrlKey||"TEXTAREA"===e.target?.tagName||"INPUT"===e.target?.tagName)return!1;switch(e.code){case"KeyQ":return t.toggleSpace(),!0;case"Equal":case"NumpadAdd":return t.adjustSize(.1),!0;case"Minus":case"NumpadSubtract":return t.adjustSize(-.1),!0;case"KeyX":return t.toggleAxis(0),!0;case"KeyY":return t.toggleAxis(1),!0;case"KeyZ":return t.toggleAxis(2),!0;case"Space":return t.toggleEnabled(),!0;default:return!1}}const TA=new Xi,IA=new Xi;function PA(e,t,i,n){const r=t.dot(t),s=t.dot(e)-t.dot(i),a=t.dot(n);return 0===a?-s/r:(TA.copy(n).multiplyScalar(r/a).sub(t),IA.copy(n).multiplyScalar(s/a).add(i).sub(e),-TA.dot(IA)/TA.dot(TA))}const DA=new Sn,RA=new Sn,BA=new Sn,LA=new Sn,OA=new Sn,UA=new Sn,FA=new Sn,kA=new Sn,NA=new Sn,jA=new Sn,zA=new Sn,GA=new fi,QA=new Xi,VA=new Xi,HA=new Xi,WA=new Cn,qA=new Xi,XA=new Xi(0,1,0),YA=new Xi(1,0,0),KA=new Xi(0,1,0),JA=new Xi(0,0,1),ZA=class e extends ll{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 xp,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 ll,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){this.enabled&&this.object&&EA(e,{toggleSpace:()=>{this.space="local"===this.space?"world":"local"},adjustSize:e=>{this.gizmoScale=Math.max(this.gizmoScale+e,.1)},toggleAxis:e=>{this.activeAxes[e]=!this.activeAxes[e],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),r=this.domElement.getBoundingClientRect(),s=(.5*n.x+.5)*r.width,a=(.5*-n.y+.5)*r.height;i.style.left=r.left+s+12+"px",i.style.top=r.top+a-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("arrow"===e.type)i=`${t[e.axis]}: ${this._translation[e.axis].toFixed(2)}`;else if("slider"===e.type){const n=(e.axis+1)%3,r=(e.axis+2)%3;i=`${t[n]}: ${this._translation[n].toFixed(2)}, ${t[r]}: ${this._translation[r].toFixed(2)}`}else if("rotator"===e.type){const n=(180*e.extraState.angle/Math.PI).toFixed(0);i=`${t[e.axis]}: ${n}°`}else"scaler"===e.type&&(i=`${this._uniformScaling?"Uniform":t[e.axis]}: ${e.extraState.scaleCur.toFixed(2)}`);this._showAnnotation(i,this.position)}_buildHandles(){this._handles=[],this._gizmoGroup.clear();const t=e.ObjectConstructors,i=this.depthTest,n=(e,n=this.handleOpacity)=>new t.MeshBasicMaterial({allowOverride:!1,depthTest:i,depthWrite:i,fog:!1,toneMapped:!1,transparent:!0,color:e,opacity:n}),r=()=>new t.MeshBasicMaterial({allowOverride:!1,depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0,opacity:.15,visible:!1}),s=[YA,KA,JA];for(let e=0;e<3;e++){const t=n(this.axisColors[e]),i=r(),a=new Th(.0075,.0075,.5,3);a.translate(0,.25,0);const o=new ts(a,t);o.renderOrder=500,o.raycast=()=>{};const l=new Th(0,.04,.1,12);l.translate(0,.05,0);const c=new ts(l,t);c.position.set(0,.5,0),c.renderOrder=500,c.raycast=()=>{};const h=new Th(.2,0,.6,4);h.translate(0,.3,0);const d=new ts(h,i);d.visible=!1;const u=(new qi).setFromUnitVectors(XA,s[e]),p=new ll;p.quaternion.copy(u),p.add(o,c,d),this._gizmoGroup.add(p);const m={type:"arrow",axis:e,gizmoMeshes:[o,c],pickerMeshes:[d],materials:[t],clickInfo:null,extraState:null};d.userData._pivotHandle=m,this._handles.push(m)}const a=[[2,YA,KA],[1,JA,YA],[0,KA,JA]];for(const[e,t,i]of a){const s=n(this.axisColors[e],.75),a=r(),o=.2,l=new ns(o,o,.01),c=new ts(l,s);c.renderOrder=500,c.raycast=()=>{};const h=new ns(1.25*o,1.25*o,.01),d=new ts(h,a);d.visible=!1;const u=t.clone().normalize(),p=i.clone().normalize(),m=u.clone().cross(p),g=u.clone().multiplyScalar(o).add(p.clone().multiplyScalar(o)),f=new ll,A=(new Sn).makeBasis(u,p,m);f.applyMatrix4(A),f.position.copy(g),f.add(c,d),this._gizmoGroup.add(f);const y={type:"slider",axis:e,gizmoMeshes:[c],pickerMeshes:[d],materials:[s],clickInfo:null,extraState:null};d.userData._pivotHandle=y,this._handles.push(y)}const o=[[2,YA,KA],[1,JA,YA],[0,KA,JA]];for(const[e,t,i]of o){const s=n(this.axisColors[e]),a=r(),o=.5,l=new _d(o,.0075,3,16,Math.PI/2),c=new ts(l,s);c.renderOrder=500,c.raycast=()=>{};const h=new _d(o,.1,4,12,Math.PI/2),d=new ts(h,a);d.visible=!1;const u=t.clone().normalize(),p=i.clone().normalize(),m=u.clone().cross(p),g=new ll,f=(new Sn).makeBasis(u,p,m);g.applyMatrix4(f),g.add(c,d),this._gizmoGroup.add(g);const A={type:"rotator",axis:e,gizmoMeshes:[c],pickerMeshes:[d],materials:[s],clickInfo:null,extraState:{angle0:0,angle:0}};d.userData._pivotHandle=A,this._handles.push(A)}for(let e=0;e<3;e++){const t=n(this.axisColors[e]),i=.04,r=new yd(i,12,12),a=new ts(r,t);a.renderOrder=500;const o=(new qi).setFromUnitVectors(XA,s[e]),l=new ll;l.quaternion.copy(o),a.position.set(0,.6+i,0),l.add(a),this._gizmoGroup.add(l);const c={type:"scaler",axis:e,gizmoMeshes:[a],pickerMeshes:[a],materials:[t],clickInfo:null,extraState:{scale0:1,scaleCur:1}};a.userData._pivotHandle=c,this._handles.push(c)}this.updateHandleVisibility(),this._gizmoGroup.traverse(e=>{e.castShadow=!1,e.receiveShadow=!1,e.userData.__keepShadowDef=!0})}updateHandleVisibility(){if(this._handles)for(const e of this._handles){let t=!0;if("arrow"===e.type)t=!this.disableAxes&&this.activeAxes[e.axis];else if("scaler"===e.type)t=!this.disableScaling&&this.activeAxes[e.axis];else if("slider"===e.type){const i=[[1,2],[0,2],[0,1]],[n,r]=i[e.axis];t=!this.disableSliders&&this.activeAxes[n]&&this.activeAxes[r]}else if("rotator"===e.type){const i=[[1,2],[0,2],[0,1]],[n,r]=i[e.axis];t=!this.disableRotations&&this.activeAxes[n]&&this.activeAxes[r]}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 Xi).setFromMatrixPosition(this.object.matrixWorld);if(this.position.copy(e),"local"!==this.space||this.object.userData?.isMultiSelectDummy?this.quaternion.identity():this.object.matrixWorld.decompose(QA,this.quaternion,VA),this.fixed){let t;if(QA.copy(e),VA.setFromMatrixPosition(this.camera.matrixWorld),this.camera.isOrthographicCamera){const e=this.camera;t=(e.top-e.bottom)/e.zoom}else{const e=this.camera;t=QA.distanceTo(VA)*Math.min(1.9*Math.tan(Math.PI*e.fov/360)/e.zoom,7)}this._gizmoGroup.scale.setScalar(t*this.gizmoScale/4)}else this._gizmoGroup.scale.setScalar(this.gizmoScale);for(const e of this._handles)if("scaler"===e.type){const t=this._uniformScaling?1.8:1;for(const i of e.gizmoMeshes)i.scale.setScalar(t)}}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 GA.x=(e.clientX-t.left)/t.width*2-1,GA.y=-(e.clientY-t.top)/t.height*2+1,GA}_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(0===t.length)return;const i=this._findHandle(t[0].object);i&&(e.stopPropagation(),this._activeHandle=i,this._dragging=!0,DA.copy(this.object.matrix),RA.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 e=this._raycaster.intersectObjects(this._getAllPickers(),!0),t=e.length>0?this._findHandle(e[0].object):null;if(t!==this._hoveredHandle){if(this._hoveredHandle)for(const e of this._hoveredHandle.materials)e.color.set(this.axisColors[this._hoveredHandle.axis]);if(t)for(const e of t.materials)e.color.set(this.hoveredColor);this._hoveredHandle=t,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),"arrow"===e.type){const i=(new Sn).extractRotation(n.matrixWorld),r=XA.clone().applyMatrix4(i).normalize();e.clickInfo={clickPoint:t.clone(),dir:r},e.extraState=this._translation[e.axis]}else if("slider"===e.type){const i=(new Xi).setFromMatrixColumn(n.matrixWorld,0).normalize(),r=(new Xi).setFromMatrixColumn(n.matrixWorld,1).normalize(),s=(new Xi).setFromMatrixColumn(n.matrixWorld,2).normalize(),a=(new Xi).setFromMatrixPosition(n.matrixWorld),o=(new bs).setFromNormalAndCoplanarPoint(s,a);e.clickInfo={clickPoint:t.clone(),e1:i,e2:r,plane:o},e.extraState={x0:this._translation[(e.axis+1)%3],y0:this._translation[(e.axis+2)%3]}}else if("rotator"===e.type){const i=(new Xi).setFromMatrixPosition(n.matrixWorld),r=(new Xi).setFromMatrixColumn(n.matrixWorld,2).normalize(),s=(new Xi).setFromMatrixPosition(this.camera.matrixWorld).sub(i).normalize(),a=r.clone().cross(s);0===a.length()&&a.copy(s).cross(XA),a.normalize();const o=20/i.distanceTo((new Xi).setFromMatrixPosition(this.camera.matrixWorld));e.clickInfo={clickPoint:t.clone(),origin:i,normal:r,tangent:a,rotSpeed:o},e.extraState={angle:0}}else if("scaler"===e.type){const i=(new Sn).extractRotation(n.matrixWorld),r=XA.clone().applyMatrix4(i).normalize(),s=n.matrixWorld.clone(),a=s.clone().invert();e.clickInfo={clickPoint:t.clone(),dir:r,mPLG:s,mPLGInv:a}}}_onDragMove(e,t,i){if(!e.clickInfo)return null;if("arrow"===e.type){const{clickPoint:n,dir:r}=e.clickInfo,s=e.extraState,a=this.translationLimits?.[e.axis];let o=PA(n,r,t.origin,t.direction);if(i.shiftKey&&null!==this.translationSnap){const e=this.translationSnap;o=Math.round(o/e)*e}return a&&(void 0!==a[0]&&(o=Math.max(o,a[0]-s)),void 0!==a[1]&&(o=Math.min(o,a[1]-s))),this._translation[e.axis]=s+o,NA.makeTranslation(r.x*o,r.y*o,r.z*o),NA}if("slider"===e.type){const{clickPoint:n,e1:r,e2:s,plane:a}=e.clickInfo,{x0:o,y0:l}=e.extraState;WA.copy(t),WA.intersectPlane(a,qA),WA.direction.negate(),WA.intersectPlane(a,qA),qA.sub(n);let[c,h]=function(e,t,i){const n=Math.abs(e.x)>=Math.abs(e.y)&&Math.abs(e.x)>=Math.abs(e.z)?0:Math.abs(e.y)>=Math.abs(e.x)&&Math.abs(e.y)>=Math.abs(e.z)?1:2,r=[0,1,2].sort((e,i)=>Math.abs(t.getComponent(i))-Math.abs(t.getComponent(e))),s=n===r[0]?r[1]:r[0],a=e.getComponent(n),o=e.getComponent(s),l=t.getComponent(n),c=t.getComponent(s),h=i.getComponent(n),d=(i.getComponent(s)-h*(o/a))/(c-l*(o/a));return[(h-d*l)/a,d]}(r,s,qA);if(i.shiftKey&&null!==this.translationSnap){const e=this.translationSnap;c=Math.round(c/e)*e,h=Math.round(h/e)*e}const d=this.translationLimits?.[(e.axis+1)%3],u=this.translationLimits?.[(e.axis+2)%3];return d&&(void 0!==d[0]&&(c=Math.max(c,d[0]-o)),void 0!==d[1]&&(c=Math.min(c,d[1]-o))),u&&(void 0!==u[0]&&(h=Math.max(h,u[0]-l)),void 0!==u[1]&&(h=Math.min(h,u[1]-l))),this._translation[(e.axis+1)%3]=o+c,this._translation[(e.axis+2)%3]=l+h,NA.makeTranslation(c*r.x+h*s.x,c*r.y+h*s.y,c*r.z+h*s.z),NA}if("rotator"===e.type){const{clickPoint:n,origin:r,normal:s,tangent:a,rotSpeed:o}=e.clickInfo,l=this.rotationLimits?.[e.axis],c=(new bs).setFromNormalAndCoplanarPoint(s,r);WA.copy(t),WA.intersectPlane(c,qA)||(WA.direction.negate(),WA.intersectPlane(c,qA)),qA.sub(n);let h=qA.dot(a)*o;if(i.shiftKey&&null!==this.rotationSnap){const e=this.rotationSnap*Math.PI/180;h=Math.round(h/e)*e}return l&&(h=gi.clamp(h,l[0],l[1])),e.extraState.angle=h,jA.makeRotationAxis(s,h),HA.copy(r).applyMatrix4(jA).sub(r).negate(),jA.setPosition(HA),jA}if("scaler"===e.type){const{clickPoint:n,dir:r,mPLG:s,mPLGInv:a}=e.clickInfo,o=this.scaleLimits?.[e.axis],l=PA(n,r,t.origin,t.direction);let c=Math.pow(2,.2*l);i.shiftKey&&null!==this.scaleSnap&&(c=Math.round(c/this.scaleSnap)*this.scaleSnap,0===c&&(c=this.scaleSnap));const h=this.uniformScaleEnabled&&i.altKey;this._uniformScaling=h;const d=o?o[0]:1e-5;return c=Math.max(c,d/e.extraState.scale0),o&&void 0!==o[1]&&(c=Math.min(c,o[1]/e.extraState.scale0)),e.extraState.scaleCur=e.extraState.scale0*c,h?zA.makeScale(c,c,c):zA.makeScale(1,c,1).premultiply(s).multiply(a),zA}return null}_onDragEnd(e){"rotator"===e.type&&(e.extraState.angle0=e.extraState.angle),"scaler"===e.type&&(e.extraState.scale0=e.extraState.scaleCur),this._uniformScaling=!1,e.clickInfo=null}_applyTransform(e){this.object&&(this.object.parent?BA.copy(this.object.parent.matrixWorld):BA.identity(),LA.copy(BA).invert(),OA.copy(RA).premultiply(e),UA.copy(OA).premultiply(LA),FA.copy(DA).invert(),kA.copy(UA).multiply(FA),this.autoTransform&&(this.object.matrix.copy(UA),this.object.matrix.decompose(this.object.position,this.object.quaternion,this.object.scale)),this.dispatchEvent({type:"objectChange"}),this.dispatchEvent({type:"change"}))}_getMode(e){return"arrow"===e.type||"slider"===e.type?"translate":"rotator"===e.type?"rotate":"scaler"===e.type?"scale":"unknown"}};ZA.ObjectConstructors={MeshBasicMaterial:vr,LineBasicMaterial:Dc};let $A=ZA;var ey=Object.defineProperty,ty=Object.getOwnPropertyDescriptor,iy=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?ty(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&ey(t,i,s),s};const ny=new Xi,ry=new Sp,sy=new Xi,ay={type:"change"};e.FirstPersonControls2=class extends ri{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 Xi,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;ny.set(0,0,-1).applyQuaternion(e),ry.setFromVector3(ny),this.lat=90-gi.radToDeg(ry.phi),this.lon=gi.radToDeg(ry.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}this.mouseDragOn=!0}onPointerUp(e){if(this.activeLook)switch(e.button){case 0:this.moveForward=!1;break;case 2:this.moveBackward=!1}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}}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}}lookAt(e,t,i){return e.isVector3?sy.copy(e):void 0===t||void 0===i?console.error("FirstPersonControls2.lookAt: y and z parameters are required"):sy.set(e,t,i),this.object.lookAt(sy),this.setOrientation(),this}update(){const e=$p(),t=(this._lastTime<0?16:Math.min(e-this._lastTime,1e3))/1e3;if(this._lastTime=e,!this.enabled)return;if(this.heightSpeed){const e=gi.clamp(this.object.position.y,this.heightMin,this.heightMax)-this.heightMin;this.autoSpeedFactor=t*(e*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 r=1;this.constrainVertical&&(r=Math.PI/(this.verticalMax-this.verticalMin)),this.lon-=this.pointerX*n,this.lookVertical&&(this.lat-=this.pointerY*n*r),this.lat=Math.max(-85,Math.min(85,this.lat));let s=gi.degToRad(90-this.lat);const a=gi.degToRad(this.lon);this.constrainVertical&&(s=gi.mapLinear(s,0,Math.PI,this.verticalMin,this.verticalMax));const o=this.object.position;this.targetPosition.setFromSphericalCoords(1,s,a).add(o),this.object.lookAt(this.targetPosition),this.dispatchEvent(ay)}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()}},iy([qm(),Hg()],e.FirstPersonControls2.prototype,"enabled",2),iy([qm(),Hg()],e.FirstPersonControls2.prototype,"enableKeys",2),iy([qm(),zg()],e.FirstPersonControls2.prototype,"movementSpeed",2),iy([qm(),zg()],e.FirstPersonControls2.prototype,"lookSpeed",2),iy([qm(),Hg()],e.FirstPersonControls2.prototype,"lookVertical",2),iy([qm(),Hg()],e.FirstPersonControls2.prototype,"autoForward",2),iy([qm(),Hg()],e.FirstPersonControls2.prototype,"activeLook",2),iy([qm(),Hg()],e.FirstPersonControls2.prototype,"heightSpeed",2),iy([qm(),zg()],e.FirstPersonControls2.prototype,"heightCoef",2),iy([qm(),zg()],e.FirstPersonControls2.prototype,"heightMin",2),iy([qm(),zg()],e.FirstPersonControls2.prototype,"heightMax",2),iy([qm(),Hg()],e.FirstPersonControls2.prototype,"constrainVertical",2),iy([qm(),zg()],e.FirstPersonControls2.prototype,"verticalMin",2),iy([qm(),zg()],e.FirstPersonControls2.prototype,"verticalMax",2),iy([qm(),Hg()],e.FirstPersonControls2.prototype,"mouseDragOn",2),e.FirstPersonControls2=iy([Wg("First Person Controls")],e.FirstPersonControls2);var oy=Object.defineProperty,ly=Object.getOwnPropertyDescriptor,cy=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?ly(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&oy(t,i,s),s};const hy=new On(0,0,0,"YXZ"),dy=new Xi,uy={type:"change"},py={type:"lock"},my={type:"unlock"},gy=Math.PI/2;e.PointerLockControls2=class extends ri{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 Xi(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(py),this.isLocked=!0):(this.dispatchEvent(my),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){dy.setFromMatrixColumn(this.object.matrix,0),dy.crossVectors(this.object.up,dy),this.object.position.addScaledVector(dy,e)}moveRight(e){dy.setFromMatrixColumn(this.object.matrix,0),this.object.position.addScaledVector(dy,e)}lock(){this.domElement.requestPointerLock()}unlock(){this.domElement.ownerDocument.exitPointerLock()}update(){Math.abs(this._movementX)<1e-4&&Math.abs(this._movementY)<1e-4||(hy.setFromQuaternion(this.object.quaternion),hy.y-=.002*this._movementX*this.pointerSpeed,hy.x-=.002*this._movementY*this.pointerSpeed,this._movementX=0,this._movementY=0,hy.x=Math.max(gy-this.maxPolarAngle,Math.min(gy-this.minPolarAngle,hy.x)),this.object.quaternion.setFromEuler(hy),this.dispatchEvent(uy))}},cy([Hg(),qm()],e.PointerLockControls2.prototype,"enabled",2),cy([zg(),qm()],e.PointerLockControls2.prototype,"minPolarAngle",2),cy([zg(),qm()],e.PointerLockControls2.prototype,"maxPolarAngle",2),cy([zg(),qm()],e.PointerLockControls2.prototype,"pointerSpeed",2),cy([Hg(),qm()],e.PointerLockControls2.prototype,"autoLockOnClick",2),e.PointerLockControls2=cy([Wg("Pointer Lock Controls")],e.PointerLockControls2);var fy=Object.defineProperty,Ay=Object.getOwnPropertyDescriptor,yy=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?Ay(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&fy(t,i,s),s};const vy=new Xi(0,0,1),_y=new On,by=new qi,xy=new qi(-Math.sqrt(.5),0,0,Math.sqrt(.5)),wy=new qi,Cy={type:"change"};e.DeviceOrientationControls2=class extends ri{constructor(e){super(),this.enabled=!1,this.lastOrder="XYZ",this.dampingFactor=.05,this.lastQuaternion=new qi,this.onDeviceOrientationChangeEvent=e=>{this.deviceOrientation=e},this.onScreenOrientationChangeEvent=()=>{this.screenOrientation=screen.orientation},this._initQuaternion=new qi,this._initQuaternionInvert=new qi,this._initQuaternionDest=new qi,this._lastTime=-1,!1===window.isSecureContext&&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(),void 0!==window.DeviceOrientationEvent&&"function"==typeof window.DeviceOrientationEvent.requestPermission?window.DeviceOrientationEvent.requestPermission().then(e=>{"granted"==e&&(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 qi,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=null!==e.alpha?gi.degToRad(e.alpha):0,i=null!==e.beta?gi.degToRad(e.beta):0,n=null!==e.gamma?gi.degToRad(e.gamma):0,r=this.screenOrientation?gi.degToRad(this.screenOrientation.angle):0;this.setObjectQuaternion(t,i,n,r),8*(1-this.lastQuaternion.dot(this.object.quaternion))>1e-6&&(this.lastQuaternion.copy(this.object.quaternion),this.dispatchEvent(Cy))}}dispose(){this.disconnect()}setObjectQuaternion(e,t,i,n){const r=$p()/1e3;_y.set(t,e,-i,"YXZ"),wy.setFromEuler(_y),wy.multiply(xy),wy.multiply(by.setFromAxisAngle(vy,-n)),this._initQuaternionDest.__init||(this._initQuaternionDest.copy(wy).invert(),this._initQuaternionDest.__init=!0),wy.premultiply(this._initQuaternionDest);this.object.quaternion.multiply(this._initQuaternionInvert),this.object.quaternion.slerp(wy,this.dampingFactor/(Math.min(1,r-this._lastTime)/(1/60))),this.object.quaternion.multiply(this._initQuaternion),this._lastTime=r}},yy([qm(),Fg("Damping",[0,1],.01)],e.DeviceOrientationControls2.prototype,"dampingFactor",2),yy([jg("Reset View")],e.DeviceOrientationControls2.prototype,"resetView",1),yy([jg()],e.DeviceOrientationControls2.prototype,"connect",1),yy([jg()],e.DeviceOrientationControls2.prototype,"disconnect",1),e.DeviceOrientationControls2=yy([Wg("Device Orientation Controls")],e.DeviceOrientationControls2);const Sy=new Xi,My=new Xi,Ey=new Xi,Ty=new Xi,Iy=new Xi,Py=new Xi;let Dy=1;const Ry=new Xi(0,1,0);const By=class e extends Ji{constructor(){super(...arguments),this._vector=new Xi}expandByObject(t,i=!1,n=!1,r){if(!1===t.userData?.bboxVisible)return this;if(!t.visible&&n)return this;if(r&&r(t))return this;t.updateWorldMatrix(!1,!1);const s=t.geometry;if(void 0!==s){const n=s.getAttribute("position");if(!0===i&&void 0!==n&&Object.getPrototypeOf(s).computeBoundingBox===Fr.prototype.computeBoundingBox)for(let e=0,i=n.count;e<i;e++)!0===t.isMesh?t.getVertexPosition(e,this._vector):this._vector.fromBufferAttribute(n,e),this._vector.applyMatrix4(t.matrixWorld),this.expandByPoint(this._vector);else void 0!==t.boundingBox?((i||null===t.boundingBox)&&"function"==typeof t.computeBoundingBox&&t.computeBoundingBox(),null!==t.boundingBox?(e._box.copy(t.boundingBox),e._box.applyMatrix4(t.matrixWorld),this.union(e._box)):console.warn("Box3B - Unable to compute bounds for",t)):(null===s.boundingBox&&s.computeBoundingBox(),s.boundingBox?(e._box.copy(s.boundingBox),e._box.applyMatrix4(t.matrixWorld),this.union(e._box)):console.warn("Box3B - Unable to compute bounds for",t,s))}else void 0!==t.boundingBox&&((i||null===t.boundingBox)&&"function"==typeof t.computeBoundingBox&&t.computeBoundingBox(),null!==t.boundingBox?(e._box.copy(t.boundingBox),e._box.applyMatrix4(t.matrixWorld),this.union(e._box)):console.warn("Box3B - Unable to compute bounds for",t));const a=t.children;for(let e=0,t=a.length;e<t;e++)this.expandByObject(a[e],i,n);return this}expandByObjects(e,t=!1,i=!1){for(let n=0,r=e.length;n<r;n++)this.expandByObject(e[n],t,i);return this}getPoints(){return[new Xi(this.min.x,this.min.y,this.min.z),new Xi(this.min.x,this.min.y,this.max.z),new Xi(this.min.x,this.max.y,this.min.z),new Xi(this.min.x,this.max.y,this.max.z),new Xi(this.max.x,this.min.y,this.min.z),new Xi(this.max.x,this.min.y,this.max.z),new Xi(this.max.x,this.max.y,this.min.z),new Xi(this.max.x,this.max.y,this.max.z)]}getScreenSpaceBounds(e){const t=this.getPoints(),i=new Tp;for(const n of t){const t=n.project(e);i.min.min(t),i.max.max(t)}return i}};By._box=new By;let Ly=By;function Oy(e){return null==e||(e instanceof ArrayBuffer||ArrayBuffer.isView(e)?0===e.byteLength:typeof Blob<"u"&&e instanceof Blob?0===e.size:"string"==typeof e&&0===e.length)}function Uy(e){if(iu._orig){if(iu._storage===e)return;Object.assign(iu,iu._orig),delete iu._orig,delete iu._storage}if(!e)return;const t=e,i={...iu};iu._orig=i,iu._storage=e,iu.get=(e,n,r)=>n?e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("chrome-extension")?Promise.resolve(void 0):t.match(e).then(async i=>{if(!i)return;let s;try{s=await async function(e,t,i){switch(t){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":{const t=await e.text();return t?(new DOMParser).parseFromString(t,i??"text/html"):void 0}case"json":{const t=await e.text();return t?JSON.parse(t):void 0}default:if(void 0===i)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(i),n=t&&t[1]?t[1].toLowerCase():void 0;return new TextDecoder(n).decode(await e.arrayBuffer())}}}(i,n,r)}catch{s=void 0}return Oy(s)?(console.warn("[threepipe cache] removing invalid cache entry for",e),void await t.delete(e).catch(()=>{})):s}).catch(t=>{console.warn("[threepipe cache] lookup failed for",e,t)}):i.get(e),iu.add=async(e,n,r)=>{if(!r)return i.add(e,n);if(!(e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("chrome-extension")||e.startsWith("asset://"))){if(Oy(n))return void console.warn("[threepipe cache] skipping empty payload for",e);try{const i="json"===r?JSON.stringify(n):"document"===r?(new XMLSerializer).serializeToString(n):n;await t.match(e)&&await t.delete(e),await t.put(e,new Response(i,{status:200}))}catch(t){console.warn("[threepipe cache] add failed for",e,t)}}},iu.remove=(e,n)=>{if(!n)return i.remove(e);t.delete(e).catch(t=>{console.warn("[threepipe cache] remove failed for",e,t)})}}function Fy(e,t=3,i){let n,r,s,a,o;const l=e.byteLength/(2*t)|0;i=i||new Uint8ClampedArray(4*l);for(let c=0;c<l;c++){n=65504*wr.fromHalfFloat(e[c*t]),r=65504*wr.fromHalfFloat(e[c*t+1]),s=65504*wr.fromHalfFloat(e[c*t+2]),a=Math.max(Math.max(n,r),s);const l=Math.ceil(Math.log2(a));o=Math.pow(2,l-8),i[4*c]=n/o|0,i[4*c+1]=r/o|0,i[4*c+2]=s/o|0,i[4*c+3]=l+128}return i}function ky({uniforms:e,propKey:t,thisTarget:i=!1,onChange:n}={}){const r=!!e,s=!!t,a=i;return(i,o,l)=>{const c=i=>{const n=a?i:r?e:i.uniforms||i._uniforms||i.extraUniforms;let l=s?t:o;a&&(l="_"+l);let c=n[l];return c||(c={value:null},n[l]=c),c},h={get(){return c(this).value},set(e){const t=c(this);t.value!==e&&(t.value=e,Tm(this,"uniformsNeedUpdate",!0,!0),n&&Gm.callFunction(n,this,[o,e]))}};if(l)return Om(l,"value")&&delete l.value,Om(l,"writable")&&delete l.writable,Om(l,"initializer")&&delete l.initializer,Object.assign(l,h);Object.defineProperty(i,o,h)}}function Ny(e,t,i=!1,n,r,s){const a=!!t,o=!!e;return(l,c,h)=>{const d=i=>({t:a?t:i.defines||i._defines||i.extraDefines,p:o?e:c}),u={get(){const{t:e,p:t}=d(i?this:this.material);let n=e[t];return s&&(n=s(n)),n},set(e){const{t:t,p:s}=d(i?this:this.material);r&&(e=r(e)),Tm(t,s,e,!0),void 0===e&&delete t[s],n&&"function"==typeof n?Gm.callFunction(n,this,[s,e]):Tm(i?this:this.material,"needsUpdate",!0,!0)}};if(h)return Om(h,"value")&&delete h.value,Om(h,"writable")&&delete h.writable,Om(h,"initializer")&&delete h.initializer,Object.assign(h,u);Object.defineProperty(l,c,u)}}function jy(e,t,i=!1,n,r=!1){return Ny(e,t,i,n,e=>e?"1":r?void 0:"0",e=>!(!e||"0"===e))}function zy({obj:e,key:t,processVal:i,invProcessVal:n,onChange:r,onChangeParams:s=!0,allowUndefined:a=!1}){const o=!!t;return(l,c,h)=>{const d=i=>{let n=Im(e)||i;"string"==typeof n&&(n=i[n]);let r,s=o&&Im(t)||c;if(Array.isArray(s)){for(;s.length>1&&n&&"object"==typeof n;)n=n[s[0]],s=s.slice(1);r=s.length?s[0]:c}else r=s;return{t:n,p:r}},u={get(){const{t:e,p:t}=d(this);if(!e||"object"!=typeof e)return;let i=e[t];return n&&(i=n(i)),i},set(e){const{t:t,p:n}=d(this);if(!t||"object"!=typeof t)return;i&&(e=i(e)),Tm(t,n,e,!0)&&void 0===e&&!a&&delete t[n];let o=r;o&&("string"==typeof o||"symbol"==typeof o)&&(o=this[o]),o&&"function"==typeof o&&Gm.callFunction(o,this,s?[n,e]:[])}};if(h)return Om(h,"value")&&delete h.value,Om(h,"writable")&&delete h.writable,Om(h,"initializer")&&delete h.initializer,Object.assign(h,u);Object.defineProperty(l,c,u)}}function Gy(e,t){let i;switch(t){case Lt:case Ut:case Ot:i="";break;case Nt:i="RGBM16ToLinear";break;default:console.warn("THREE.WebGLProgram: Unsupported color space:",t),i=""}return`#define ${e}( value ) ${i} ( value )`}function Qy(e,t){return Gy(e+"TexelToLinear",t??Ut)+"\n"}function Vy(e,t=!1){const i=null!==e[0].index,n=new Set(Object.keys(e[0].attributes)),r=new Set(Object.keys(e[0].morphAttributes)),s={},a={},o=e[0].morphTargetsRelative,l=new Fr;let c=0;for(let h=0;h<e.length;++h){const d=e[h];let u=0;if(i!==(null!==d.index))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 e in d.attributes){if(!n.has(e))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+'. All geometries must have compatible attributes; make sure "'+e+'" attribute exists among all geometries, or in none of them.'),null;void 0===s[e]&&(s[e]=[]),s[e].push(d.attributes[e]),u++}if(u!==n.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!==d.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const e in d.morphAttributes){if(!r.has(e))return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+".  .morphAttributes must be consistent throughout all geometries."),null;void 0===a[e]&&(a[e]=[]),a[e].push(d.morphAttributes[e])}if(t){let e;if(i)e=d.index.count;else{if(void 0===d.attributes.position)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index "+h+". The geometry must have either an index or a position attribute"),null;e=d.attributes.position.count}l.addGroup(c,e,h),c+=e}}if(i){let t=0;const i=[];for(let n=0;n<e.length;++n){const r=e[n].index;for(let e=0;e<r.count;++e)i.push(r.getX(e)+t);t+=e[n].attributes.position.count}l.setIndex(i)}for(const e in s){const t=Hy(s[e]);if(!t)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+e+" attribute."),null;l.setAttribute(e,t)}for(const e in a){const t=a[e][0].length;if(0===t)break;l.morphAttributes=l.morphAttributes||{},l.morphAttributes[e]=[];for(let i=0;i<t;++i){const t=[];for(let n=0;n<a[e].length;++n)t.push(a[e][n][i]);const n=Hy(t);if(!n)return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the "+e+" morphAttribute."),null;l.morphAttributes[e].push(n)}}return l}function Hy(e){let t,i,n,r=-1,s=0;for(let a=0;a<e.length;++a){const o=e[a];if(void 0===t&&(t=o.array.constructor),t!==o.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(void 0===i&&(i=o.itemSize),i!==o.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(void 0===n&&(n=o.normalized),n!==o.normalized)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;if(-1===r&&(r=o.gpuType),r!==o.gpuType)return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."),null;s+=o.count*i}const a=new t(s),o=new Mr(a,i,n);let l=0;for(let t=0;t<e.length;++t){const n=e[t];if(n.isInterleavedBufferAttribute){const e=l/i;for(let t=0,r=n.count;t<r;t++)for(let r=0;r<i;r++){const i=n.getComponent(t,r);o.setComponent(t+e,r,i)}}else a.set(n.array,l);l+=n.count*i}return void 0!==r&&(o.gpuType=r),o}function Wy(e){const t=e.data.array.constructor,i=e.count,n=e.itemSize,r=e.normalized,s=new t(i*n);let a;a=e.isInstancedInterleavedBufferAttribute?new rc(s,n,r,e.meshPerAttribute):new Mr(s,n,r);for(let t=0;t<i;t++)a.setX(t,e.getX(t)),n>=2&&a.setY(t,e.getY(t)),n>=3&&a.setZ(t,e.getZ(t)),n>=4&&a.setW(t,e.getW(t));return a}function qy(e,t=1e-4){const i=t>0;t=Math.max(t,Number.EPSILON);const n={},r=e.getIndex(),s=e.getAttribute("position"),a=r?r.count:s.count;let o=0;const l=Object.keys(e.attributes),c={},h={},d=[],u=["getX","getY","getZ","getW"],p=["setX","setY","setZ","setW"];for(let t=0,i=l.length;t<i;t++){const i=l[t],n=e.attributes[i];c[i]=new n.constructor(new n.array.constructor(n.count*n.itemSize),n.itemSize,n.normalized);const r=e.morphAttributes[i];r&&(h[i]||(h[i]=[]),r.forEach((e,t)=>{const n=new e.array.constructor(e.count*e.itemSize);h[i][t]=new e.constructor(n,e.itemSize,e.normalized)}))}const m=.5*t,g=Math.log10(1/t),f=Math.pow(10,g),A=m*f;for(let t=0;t<a;t++){const s=r?r.getX(t):t;let a="";for(let t=0,n=l.length;t<n&&i;t++){const i=l[t],n=e.getAttribute(i),r=n.itemSize;for(let e=0;e<r;e++)a+=~~(n[u[e]](s)*f+A)+","}if(i&&a in n)d.push(n[a]);else{for(let t=0,i=l.length;t<i;t++){const i=l[t],n=e.getAttribute(i),r=e.morphAttributes[i],a=n.itemSize,d=c[i],m=h[i];for(let e=0;e<a;e++){const t=u[e],i=p[e];if(d[i](o,n[t](s)),r)for(let e=0,n=r.length;e<n;e++)m[e][i](o,r[e][t](s))}}i&&(n[a]=o),d.push(o),o++}}const y=e.clone();for(const t in e.attributes){const e=c[t];if(y.setAttribute(t,new e.constructor(e.array.slice(0,o*e.itemSize),e.itemSize,e.normalized)),t in h)for(let e=0;e<h[t].length;e++){const i=h[t][e];y.morphAttributes[t][e]=new i.constructor(i.array.slice(0,o*i.itemSize),i.itemSize,i.normalized)}}return y.setIndex(d),y}function Xy(e,t){if(0===t)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(2===t||1===t){let i=e.getIndex();if(null===i){const t=[],n=e.getAttribute("position");if(void 0===n)return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),e;for(let e=0;e<n.count;e++)t.push(e);e.setIndex(t),i=e.getIndex()}const n=i.count-2,r=[];if(2===t)for(let e=1;e<=n;e++)r.push(i.getX(0)),r.push(i.getX(e)),r.push(i.getX(e+1));else for(let e=0;e<n;e++)e%2==0?(r.push(i.getX(e)),r.push(i.getX(e+1)),r.push(i.getX(e+2))):(r.push(i.getX(e+2)),r.push(i.getX(e+1)),r.push(i.getX(e)));r.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const s=e.clone();return s.setIndex(r),s.clearGroups(),s}return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),e}function Yy(e,t=-1){return qy(e,t)}function Ky(){return gi.generateUUID()}function Jy(e,t,i=new qi){return t.premultiply(e.getWorldQuaternion(i).invert())}function Zy(e,t,i,n=!1){const r=n?Lm(e,t,!1):e in t?t[e]:void 0;r&&r.isTexture&&i.set(e,r)}function $y(e){if(!e)return Ce;const t=e.extensions.has("EXT_color_buffer_half_float")||e.capabilities.isWebGL2&&e.extensions.has("EXT_color_buffer_float"),i=e.capabilities.isWebGL2||e.extensions.has("OES_texture_float")||e.extensions.has("WEBGL_color_buffer_float");return t?De:i?Pe:Ce}function ev(e,t,i){const n=i?.data??new Uint8ClampedArray(e.height*e.width*4),r=e.data instanceof Float32Array,s=e.data instanceof Uint16Array;for(let i=0;i<n.length;i++)n[i]=r?255*e.data[i]:s?255*wr.fromHalfFloat(e.data[i]):e.data[i],t===Ut&&(n[i]=255*Sm(n[i]/255));return i??new ImageData(n,e.width,e.height)}function tv(e,t,i=!1){let n;return n=e.isDataTexture?ev(e.image,e.colorSpace):e.image,iv(n,t,i)}function iv(e,t,i=!1){let n,r;window.VideoFrame||(window.VideoFrame=HTMLVideoElement),e instanceof window.VideoFrame?(n=e.displayWidth,r=e.displayHeight):(n=e.width||e.videoWidth||e.naturalWidth||1,r=e.height||e.videoHeight||e.naturalHeight||1),window.VideoFrame===HTMLVideoElement&&delete window.VideoFrame;const s=document.createElement("canvas");s.width=Math.min(t,n),s.height=Math.floor(1+s.width*r/n);const a=s.getContext("2d");if(!a)return console.error("textureToDataUrl: could not get canvas context"),s;!0===i&&(a.translate(0,s.height),a.scale(1,-1));let o=!1;if(void 0!==e.data){const t=e;if(n!==s.width||r!==s.height){const e=document.createElement("canvas");e.width=n,e.height=r;const i=e.getContext("2d");i?(i.putImageData(t,0,0),a.drawImage(e,0,0,s.width,s.height)):(console.error("textureToDataUrl: could not get temp canvas context"),a.putImageData(t,0,0))}else a.putImageData(t,0,0),i&&(o=!0)}else a.drawImage(e,0,0,s.width,s.height);return o?tg(s):s}const nv={UV:ce,Cube:he,CubeUV:me,Equirectangular:ue},rv={None:"",SRGB:Ot,LinearSRGB:Ut,RGBM16:Nt,DisplayP3:Ft},sv={UnsignedByte:Ce,Byte:Se,Short:Me,UnsignedShort:Ee,Int:Te,UnsignedInt:Ie,Float:Pe,HalfFloat:De,UnsignedShort4444:Re,UnsignedShort5551:Be,UnsignedInt248:Le},av={Basic:Pt,RGBA:Dt,RGB:3202,RG:3203};function ov(e){return{map:e,inv:Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),uiConfig:Object.entries(e).map(([e,t])=>({label:e,value:t}))}}const lv={Blending:ov({None:w,Normal:C,Additive:S,Subtractive:M,Multiply:E,Custom:T}),AnyMapping:ov(nv),ColorSpace:ov(rv),TextureDataType:ov(sv),DepthPackingStrategies:ov(av)},cv=new ImageData(new Uint8ClampedArray([255,255,255,255]),1,1),hv=new Ni(cv);var dv=Object.defineProperty,uv=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&dv(t,i,s),s};const pv=(t=class extends ri{constructor(e,i,n,r){super(),this.hoverEnabled=!1,this.multiSelectEnabled=!0,this.selectionMode="object",this.pickingMode="auto",this.extraObjects=[],this._mouseDownPos=new fi,this._onSelectedRemoved=e=>{const t=e.target;if(this._selected.includes(t)){const e=this._selected.filter(e=>e!==t);this.setSelected(e.length?1===e.length?e[0]:e:null,!1)}},this._onPointerMove=e=>{if(!1!==e.isPrimary&&(this.updateMouseFromEvent(e),this.hoverEnabled)){const{obj:e,intersects:t}=this._hitObject();this.setHoverObject(e,!0,t||void 0)}},this._onPointerLeave=e=>{!1!==e.isPrimary&&(this.domElement.style.cursor=this.cursorStyles.default,(this.hoverEnabled||this.hoverObject)&&this.setHoverObject(null))},this._onPointerEnter=e=>{},this._onPointerCancel=e=>{},this._onPointerDown=e=>{!1!==e.isPrimary&&(this.domElement.style.cursor=this.cursorStyles.down,this._mouseDownTime=this.time,this._mouseDownPos.copy(this.mouse))},this._onPointerUp=e=>{if(!1===e.isPrimary)return;this.domElement.style.cursor=this.cursorStyles.default,this._mouseUpTime=this.time;const i=this.mouseDownDeltaTime,n=this._mouseDownPos.distanceTo(this.mouse);i<t.PointerClickMaxTime&&n<t.PointerClickMaxDistance&&this._onPointerClick(e)},this._onPointerClick=e=>{if(!1===e.isPrimary)return;this.updateMouseFromEvent(e);const{obj:t,intersects:i}=this._hitObject();if(!i?.consumed)if(this.multiSelectEnabled&&(e.shiftKey||e.ctrlKey||e.metaKey)&&t&&"object"===this.selectionMode){const e=[...this._selected],i=e.indexOf(t);i>=0?e.splice(i,1):e.unshift(t),this.setSelected(e.length?1===e.length?e[0]:e:null,!0)}else this.setSelected(t,!0,i||void 0)},this._root=e,this._camera=n,this.domElement=i,this._time=this.time,this._mouseDownTime=0,this._mouseUpTime=1,this.selectionCondition=r??(e=>!1!==e.userData.userSelectable&&!1!==e.userData.bboxVisible&&null!=e.material&&"ShadowMaterial"!==e.material.type),this.raycaster=new xp,this.raycaster.params.Line2={threshold:.01},this.mouse=new fi,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&&"object"!==this.selectionMode?this.selectionMode="object":e?.isMaterial&&"material"!==this.selectionMode?this.selectionMode="material":e?.isTexture&&"texture"!==this.selectionMode?this.selectionMode="texture":e?.isBufferGeometry&&"geometry"!==this.selectionMode&&(this.selectionMode="geometry"));const n=this._selectedIntersects;if(Array.isArray(e)){if(this._selected.length===e.length&&this._selected.every((t,i)=>t===e[i]))return}else if(!this._selected.length&&!e||1===this._selected.length&&this._selected[0]===e&&n?.selectedObject===i?.selectedObject&&n?.selectedWidget===i?.selectedWidget&&n?.selectedHandle===i?.selectedHandle)return;const r=[...this._selected];this._selected=e?Array.isArray(e)?[...e]:[e]:[],this._selectedIntersects=i||void 0;for(const e of r)e&&e.removeEventListener&&e.removeEventListener("__unregister",this._onSelectedRemoved);for(const e of this._selected)e&&e.addEventListener&&e.addEventListener("__unregister",this._onSelectedRemoved);const s=this.selectedObject;this.dispatchEvent({type:"selectedObjectChanged",object:s?.isObject3D?s:null,objects:[...this._selected],material:s?.isMaterial?s:null,value:s,lastValue:r.length?r[0]:null,lastValues:[...r],intersects:i}),t&&this.undoManager?.record({undo:()=>this.setSelected(r.length?1===r.length?r[0]:r: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||1===this._hovering.length&&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=$p(),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("auto"===this.pickingMode?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 e=Array.isArray(t.material)?t.material[0]:t.material;t=e.map||e.normalMap||e.roughnessMap||e.metalnessMap||e.aoMap||null}else t=null;break;case"geometry":t=t.geometry||null}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(e=>!i.includes(e.object.id)&&(i.push(e.object.id),!0));let n,r=null;const s=[];for(const e of t){for(r=e.object,n=e;!(null==r||r.visible&&this.selectionCondition(r));)r=r.parent;null!=r&&(e.object=r,s.push(e))}if(t=s,t.length>0){if(r=t[0].object,n=t[0],this._firstHit&&r.id!==this._firstHit.id)r=n.object;else for(let e=0;e<t.length;e++)if(this.selectedObject&&this.selectedObject.id===t[e].object.id){const i=e+1;if(!(i<t.length))return null;n=t[i],r=n.object}this._firstHit=t[0].object}return r&&n&&r?{selectedObject:r,intersect:n,intersects:t,mouse:this.mouse.clone()}:null}isHovering(){return null!=this.hoverObject}isSelected(){return null!=this.selectedObject}},t.PointerClickMaxTime=200,t.PointerClickMaxDistance=.1,t);uv([Wm("multiSelectChanged")],pv.prototype,"multiSelectEnabled"),uv([Wm("selectionModeChanged")],pv.prototype,"selectionMode"),uv([Wm("pickingModeChanged")],pv.prototype,"pickingMode");let mv=pv;function gv(e){if(!e.isMaterial&&!e.isBufferGeometry)return;const t=Array.from(e.appliedMeshes).filter(e=>!e.isInstancedMesh&&!!e.parent&&0===e.children.length&&!Array.isArray(e.material));if(t.length<2)return;const i=e=>e.parent.uuid+"_"+e.geometry?.uuid+"_"+e.material?.uuid,n=new Map;for(const e of t){const t=i(e);n.has(t)||n.set(t,[]),n.get(t).push(e),e.updateMatrix()}const r=n.keys();for(const e of r){const t=n.get(e),i=t[0];if(!i||t.length<2)continue;const r=new uc(i.geometry,i.material,t.length),s=i.userData;i.userData={},r.copy(i),__(r.userData,s);const a=i.parent;r.position.set(0,0,0),r.rotation.set(0,0,0),r.scale.set(1,1,1),r.updateMatrix();const o=new Float32Array(3*r.count),l=new Float32Array(4*r.count),c=new Float32Array(3*r.count);for(let e=0;e<t.length;e++){const i=t[e],n=i.matrix;n.determinant()<0&&(n.elements[0]*=-1,n.elements[1]*=-1,n.elements[2]*=-1),r.setMatrixAt(e,n),i.position.toArray(o,3*e),i.quaternion.toArray(l,4*e),i.scale.toArray(c,3*e),i.removeFromParent(),i.material=void 0,i.geometry=void 0}r.sourceTrs={TRANSLATION:new Mr(o,3),ROTATION:new Mr(l,4),SCALE:new Mr(c,3)},r.instanceMatrix.needsUpdate=!0,a.add(r),a.setDirty()}}const fv={name:"HorizontalBlurShader",uniforms:{tDiffuse:{value:null},h:{value:1/512}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n\t\tuniform sampler2D tDiffuse;\n\t\tuniform float h;\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvec4 sum = vec4( 0.0 );\n\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ) * 0.1531;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ) * 0.1531;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051;\n\n\t\t\tgl_FragColor = sum;\n\n\t\t}"},Av={name:"VerticalBlurShader",uniforms:{tDiffuse:{value:null},v:{value:1/512}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n\t\tuniform sampler2D tDiffuse;\n\t\tuniform float v;\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvec4 sum = vec4( 0.0 );\n\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ) * 0.1531;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ) * 0.1531;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918;\n\t\t\tsum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051;\n\n\t\t\tgl_FragColor = sum;\n\n\t\t}"};class yv{constructor(e){this._viewer=e,this.horizontalBlurMaterial=new ls(fv),this.verticalBlurMaterial=new ls(Av),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 vv(e,t,i,n=7,r=new Xi(0,0,1.5),s=new ps(45,1,.1,1e3)){const a=t.visible;t.visible=!0;const o=(new Ly).expandByObject(t,!0,!0),l=o.getCenter(new Xi),c=o.getSize(new Xi);s.position.copy(l).add(r.clone().multiplyScalar(Math.max(c.x,c.y,c.z))),s.lookAt(l),t&&t.traverseVisible(e=>{e.layers.enable(n)}),n>0?s.layers.set(n):s.layers.enableAll(),e.setRenderTarget(null);const h=e.getClearColor(new mr),d=e.getClearAlpha();let u;e.setClearColor(0,0);try{e.clear(),"function"==typeof e.renderWithModes?e.renderWithModes({backgroundRender:!1},()=>{e.render(i??t,s)}):e.render(i??t,s),u=e.domElement.toDataURL("image/png"),e.clear()}finally{e.setClearColor(h,d)}return t.visible=a,t.traverseVisible(e=>{e.layers.disable(n)}),s.layers.enableAll(),u}class _v{constructor(){this._lights=[],this.shapes={sphere:new ts(new yd(1)),cube:new ts(new ns(1,1,1)),cylinder:new ts(new Th(.5,.5,1))};const e=new _l;this._channel=7;const t=new mu(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 r=this.shapes[n]||new ts(new yd(1));r.material=e,r.geometry.attributes.tangent||r.geometry.computeTangents(),this._scene.add(r),this._scene.environment=i??null;const s=e.envMapIntensity;"number"==typeof s&&(e.envMapIntensity=Math.max(s,2));const a=vv(t,r,this._scene,this._channel,new Xi(0,0,1.5));return"number"==typeof s&&(e.envMapIntensity=s),this._scene.remove(r),r.material=void 0,a}}const bv=new Ji,xv=new Xi;class wv extends Lu{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type="LineSegmentsGeometry";this.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),this.setAttribute("position",new Ir([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3)),this.setAttribute("uv",new Ir([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){const t=this.attributes.instanceStart,i=this.attributes.instanceEnd;return void 0!==t&&(t.applyMatrix4(e),i.applyMatrix4(e),t.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}setPositions(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));const i=new _p(t,6,1);return this.setAttribute("instanceStart",new wl(i,3,0)),this.setAttribute("instanceEnd",new wl(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 _p(t,6,1);return this.setAttribute("instanceColorStart",new wl(i,3,0)),this.setAttribute("instanceColorEnd",new wl(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 wd(e.geometry)),this}fromLineSegments(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Ji);const e=this.attributes.instanceStart,t=this.attributes.instanceEnd;void 0!==e&&void 0!==t&&(this.boundingBox.setFromBufferAttribute(e),bv.setFromBufferAttribute(t),this.boundingBox.union(bv))}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new fn),null===this.boundingBox&&this.computeBoundingBox();const e=this.attributes.instanceStart,t=this.attributes.instanceEnd;if(void 0!==e&&void 0!==t){const i=this.boundingSphere.center;this.boundingBox.getCenter(i);let n=0;for(let r=0,s=e.count;r<s;r++)xv.fromBufferAttribute(e,r),n=Math.max(n,i.distanceToSquared(xv)),xv.fromBufferAttribute(t,r),n=Math.max(n,i.distanceToSquared(xv));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)}}Is.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new fi(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},Ps.line={uniforms:os.merge([Is.common,Is.fog,Is.line]),vertexShader:"\n\t\t#include <common>\n\t\t#include <color_pars_vertex>\n\t\t#include <fog_pars_vertex>\n\t\t#include <logdepthbuf_pars_vertex>\n\t\t#include <clipping_planes_pars_vertex>\n\n\t\tuniform float linewidth;\n\t\tuniform vec2 resolution;\n\n\t\tattribute vec3 instanceStart;\n\t\tattribute vec3 instanceEnd;\n\n\t\tattribute vec3 instanceColorStart;\n\t\tattribute vec3 instanceColorEnd;\n\n\t\t#ifdef WORLD_UNITS\n\n\t\t\tvarying vec4 worldPos;\n\t\t\tvarying vec3 worldStart;\n\t\t\tvarying vec3 worldEnd;\n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tvarying vec2 vUv;\n\n\t\t\t#endif\n\n\t\t#else\n\n\t\t\tvarying vec2 vUv;\n\n\t\t#endif\n\n\t\t#ifdef USE_DASH\n\n\t\t\tuniform float dashScale;\n\t\t\tattribute float instanceDistanceStart;\n\t\t\tattribute float instanceDistanceEnd;\n\t\t\tvarying float vLineDistance;\n\n\t\t#endif\n\n\t\tvoid trimSegment( const in vec4 start, inout vec4 end ) {\n\n\t\t\t// trim end segment so it terminates between the camera plane and the near plane\n\n\t\t\t// conservative estimate of the near plane\n\t\t\tfloat a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column\n\t\t\tfloat b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column\n\t\t\tfloat nearEstimate = - 0.5 * b / a;\n\n\t\t\tfloat alpha = ( nearEstimate - start.z ) / ( end.z - start.z );\n\n\t\t\tend.xyz = mix( start.xyz, end.xyz, alpha );\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\t#ifdef USE_COLOR\n\n\t\t\t\tvColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;\n\n\t\t\t#endif\n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tvLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;\n\t\t\t\tvUv = uv;\n\n\t\t\t#endif\n\n\t\t\tfloat aspect = resolution.x / resolution.y;\n\n\t\t\t// camera space\n\t\t\tvec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );\n\t\t\tvec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );\n\n\t\t\t#ifdef WORLD_UNITS\n\n\t\t\t\tworldStart = start.xyz;\n\t\t\t\tworldEnd = end.xyz;\n\n\t\t\t#else\n\n\t\t\t\tvUv = uv;\n\n\t\t\t#endif\n\n\t\t\t// special case for perspective projection, and segments that terminate either in, or behind, the camera plane\n\t\t\t// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space\n\t\t\t// but we need to perform ndc-space calculations in the shader, so we must address this issue directly\n\t\t\t// perhaps there is a more elegant solution -- WestLangley\n\n\t\t\tbool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column\n\n\t\t\tif ( perspective ) {\n\n\t\t\t\tif ( start.z < 0.0 && end.z >= 0.0 ) {\n\n\t\t\t\t\ttrimSegment( start, end );\n\n\t\t\t\t} else if ( end.z < 0.0 && start.z >= 0.0 ) {\n\n\t\t\t\t\ttrimSegment( end, start );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// clip space\n\t\t\tvec4 clipStart = projectionMatrix * start;\n\t\t\tvec4 clipEnd = projectionMatrix * end;\n\n\t\t\t// ndc space\n\t\t\tvec3 ndcStart = clipStart.xyz / clipStart.w;\n\t\t\tvec3 ndcEnd = clipEnd.xyz / clipEnd.w;\n\n\t\t\t// direction\n\t\t\tvec2 dir = ndcEnd.xy - ndcStart.xy;\n\n\t\t\t// account for clip-space aspect ratio\n\t\t\tdir.x *= aspect;\n\t\t\tdir = normalize( dir );\n\n\t\t\t#ifdef WORLD_UNITS\n\n\t\t\t\tvec3 worldDir = normalize( end.xyz - start.xyz );\n\t\t\t\tvec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) );\n\t\t\t\tvec3 worldUp = normalize( cross( worldDir, tmpFwd ) );\n\t\t\t\tvec3 worldFwd = cross( worldDir, worldUp );\n\t\t\t\tworldPos = position.y < 0.5 ? start: end;\n\n\t\t\t\t// height offset\n\t\t\t\tfloat hw = linewidth * 0.5;\n\t\t\t\tworldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp;\n\n\t\t\t\t// don't extend the line if we're rendering dashes because we\n\t\t\t\t// won't be rendering the endcaps\n\t\t\t\t#ifndef USE_DASH\n\n\t\t\t\t\t// cap extension\n\t\t\t\t\tworldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir;\n\n\t\t\t\t\t// add width to the box\n\t\t\t\t\tworldPos.xyz += worldFwd * hw;\n\n\t\t\t\t\t// endcaps\n\t\t\t\t\tif ( position.y > 1.0 || position.y < 0.0 ) {\n\n\t\t\t\t\t\tworldPos.xyz -= worldFwd * 2.0 * hw;\n\n\t\t\t\t\t}\n\n\t\t\t\t#endif\n\n\t\t\t\t// project the worldpos\n\t\t\t\tvec4 clip = projectionMatrix * worldPos;\n\n\t\t\t\t// shift the depth of the projected points so the line\n\t\t\t\t// segments overlap neatly\n\t\t\t\tvec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;\n\t\t\t\tclip.z = clipPose.z * clip.w;\n\n\t\t\t#else\n\n\t\t\t\tvec2 offset = vec2( dir.y, - dir.x );\n\t\t\t\t// undo aspect ratio adjustment\n\t\t\t\tdir.x /= aspect;\n\t\t\t\toffset.x /= aspect;\n\n\t\t\t\t// sign flip\n\t\t\t\tif ( position.x < 0.0 ) offset *= - 1.0;\n\n\t\t\t\t// endcaps\n\t\t\t\tif ( position.y < 0.0 ) {\n\n\t\t\t\t\toffset += - dir;\n\n\t\t\t\t} else if ( position.y > 1.0 ) {\n\n\t\t\t\t\toffset += dir;\n\n\t\t\t\t}\n\n\t\t\t\t// adjust for linewidth\n\t\t\t\toffset *= linewidth;\n\n\t\t\t\t// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...\n\t\t\t\toffset /= resolution.y;\n\n\t\t\t\t// select end\n\t\t\t\tvec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;\n\n\t\t\t\t// back to clip space\n\t\t\t\toffset *= clip.w;\n\n\t\t\t\tclip.xy += offset;\n\n\t\t\t#endif\n\n\t\t\tgl_Position = clip;\n\n\t\t\tvec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation\n\n\t\t\t#include <logdepthbuf_vertex>\n\t\t\t#include <clipping_planes_vertex>\n\t\t\t#include <fog_vertex>\n\n\t\t}\n\t\t",fragmentShader:"\n\t\tuniform vec3 diffuse;\n\t\tuniform float opacity;\n\t\tuniform float linewidth;\n\n\t\t#ifdef USE_DASH\n\n\t\t\tuniform float dashOffset;\n\t\t\tuniform float dashSize;\n\t\t\tuniform float gapSize;\n\n\t\t#endif\n\n\t\tvarying float vLineDistance;\n\n\t\t#ifdef WORLD_UNITS\n\n\t\t\tvarying vec4 worldPos;\n\t\t\tvarying vec3 worldStart;\n\t\t\tvarying vec3 worldEnd;\n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tvarying vec2 vUv;\n\n\t\t\t#endif\n\n\t\t#else\n\n\t\t\tvarying vec2 vUv;\n\n\t\t#endif\n\n\t\t#include <common>\n\t\t#include <color_pars_fragment>\n\t\t#include <fog_pars_fragment>\n\t\t#include <logdepthbuf_pars_fragment>\n\t\t#include <clipping_planes_pars_fragment>\n\n\t\tvec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {\n\n\t\t\tfloat mua;\n\t\t\tfloat mub;\n\n\t\t\tvec3 p13 = p1 - p3;\n\t\t\tvec3 p43 = p4 - p3;\n\n\t\t\tvec3 p21 = p2 - p1;\n\n\t\t\tfloat d1343 = dot( p13, p43 );\n\t\t\tfloat d4321 = dot( p43, p21 );\n\t\t\tfloat d1321 = dot( p13, p21 );\n\t\t\tfloat d4343 = dot( p43, p43 );\n\t\t\tfloat d2121 = dot( p21, p21 );\n\n\t\t\tfloat denom = d2121 * d4343 - d4321 * d4321;\n\n\t\t\tfloat numer = d1343 * d4321 - d1321 * d4343;\n\n\t\t\tmua = numer / denom;\n\t\t\tmua = clamp( mua, 0.0, 1.0 );\n\t\t\tmub = ( d1343 + d4321 * ( mua ) ) / d4343;\n\t\t\tmub = clamp( mub, 0.0, 1.0 );\n\n\t\t\treturn vec2( mua, mub );\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\t#include <clipping_planes_fragment>\n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tif ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps\n\n\t\t\t\tif ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX\n\n\t\t\t#endif\n\n\t\t\tfloat alpha = opacity;\n\n\t\t\t#ifdef WORLD_UNITS\n\n\t\t\t\t// Find the closest points on the view ray and the line segment\n\t\t\t\tvec3 rayEnd = normalize( worldPos.xyz ) * 1e5;\n\t\t\t\tvec3 lineDir = worldEnd - worldStart;\n\t\t\t\tvec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );\n\n\t\t\t\tvec3 p1 = worldStart + lineDir * params.x;\n\t\t\t\tvec3 p2 = rayEnd * params.y;\n\t\t\t\tvec3 delta = p1 - p2;\n\t\t\t\tfloat len = length( delta );\n\t\t\t\tfloat norm = len / linewidth;\n\n\t\t\t\t#ifndef USE_DASH\n\n\t\t\t\t\t#ifdef USE_ALPHA_TO_COVERAGE\n\n\t\t\t\t\t\tfloat dnorm = fwidth( norm );\n\t\t\t\t\t\talpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );\n\n\t\t\t\t\t#else\n\n\t\t\t\t\t\tif ( norm > 0.5 ) {\n\n\t\t\t\t\t\t\tdiscard;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t#endif\n\n\t\t\t\t#endif\n\n\t\t\t#else\n\n\t\t\t\t#ifdef USE_ALPHA_TO_COVERAGE\n\n\t\t\t\t\t// artifacts appear on some hardware if a derivative is taken within a conditional\n\t\t\t\t\tfloat a = vUv.x;\n\t\t\t\t\tfloat b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;\n\t\t\t\t\tfloat len2 = a * a + b * b;\n\t\t\t\t\tfloat dlen = fwidth( len2 );\n\n\t\t\t\t\tif ( abs( vUv.y ) > 1.0 ) {\n\n\t\t\t\t\t\talpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );\n\n\t\t\t\t\t}\n\n\t\t\t\t#else\n\n\t\t\t\t\tif ( abs( vUv.y ) > 1.0 ) {\n\n\t\t\t\t\t\tfloat a = vUv.x;\n\t\t\t\t\t\tfloat b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;\n\t\t\t\t\t\tfloat len2 = a * a + b * b;\n\n\t\t\t\t\t\tif ( len2 > 1.0 ) discard;\n\n\t\t\t\t\t}\n\n\t\t\t\t#endif\n\n\t\t\t#endif\n\n\t\t\tvec4 diffuseColor = vec4( diffuse, alpha );\n\n\t\t\t#include <logdepthbuf_fragment>\n\t\t\t#include <color_fragment>\n\n\t\t\tgl_FragColor = vec4( diffuseColor.rgb, alpha );\n\n\t\t\t#include <tonemapping_fragment>\n\t\t\t#include <colorspace_fragment>\n\t\t\t#include <fog_fragment>\n\t\t\t#include <premultiplied_alpha_fragment>\n\n\t\t}\n\t\t"};class Cv extends ls{constructor(e){super({type:"LineMaterial",uniforms:os.clone(Ps.line.uniforms),vertexShader:Ps.line.vertexShader,fragmentShader:Ps.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){!0===e?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){!0===e!==this.dashed&&(this.needsUpdate=!0),!0===e?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&&(!0===e!==this.alphaToCoverage&&(this.needsUpdate=!0),!0===e?this.defines.USE_ALPHA_TO_COVERAGE="":delete this.defines.USE_ALPHA_TO_COVERAGE)}}const Sv=new Gi,Mv=new Xi,Ev=new Xi,Tv=new Gi,Iv=new Gi,Pv=new Gi,Dv=new Xi,Rv=new Sn,Bv=new Dp,Lv=new Xi,Ov=new Ji,Uv=new fn,Fv=new Gi;let kv,Nv;function jv(e,t,i){return Fv.set(0,0,-t,1).applyMatrix4(e.projectionMatrix),Fv.multiplyScalar(1/Fv.w),Fv.x=Nv/i.width,Fv.y=Nv/i.height,Fv.applyMatrix4(e.projectionMatrixInverse),Fv.multiplyScalar(1/Fv.w),Math.abs(Math.max(Fv.x,Fv.y))}class zv extends ts{constructor(e=new wv,t=new Cv({color:16777215*Math.random()})){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 e=0,r=0,s=t.count;e<s;e++,r+=2)Mv.fromBufferAttribute(t,e),Ev.fromBufferAttribute(i,e),n[r]=0===r?0:n[r-1],n[r+1]=n[r]+Mv.distanceTo(Ev);const r=new _p(n,2,1);return e.setAttribute("instanceDistanceStart",new wl(r,1,0)),e.setAttribute("instanceDistanceEnd",new wl(r,1,1)),this}raycast(e,t){const i=this.material.worldUnits,n=e.camera;null===n&&!i&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');const r=void 0!==e.params.Line2&&e.params.Line2.threshold||0;kv=e.ray;const s=this.matrixWorld,a=this.geometry,o=this.material;let l,c;if(Nv=o.linewidth+r,null===a.boundingSphere&&a.computeBoundingSphere(),Uv.copy(a.boundingSphere).applyMatrix4(s),i)l=.5*Nv;else{l=jv(n,Math.max(n.near,Uv.distanceToPoint(kv.origin)),o.resolution)}if(Uv.radius+=l,!1!==kv.intersectsSphere(Uv)){if(null===a.boundingBox&&a.computeBoundingBox(),Ov.copy(a.boundingBox).applyMatrix4(s),i)c=.5*Nv;else{c=jv(n,Math.max(n.near,Ov.distanceToPoint(kv.origin)),o.resolution)}Ov.expandByScalar(c),!1!==kv.intersectsBox(Ov)&&(i?function(e,t){const i=e.matrixWorld,n=e.geometry,r=n.attributes.instanceStart,s=n.attributes.instanceEnd;for(let a=0,o=Math.min(n.instanceCount,r.count);a<o;a++){Bv.start.fromBufferAttribute(r,a),Bv.end.fromBufferAttribute(s,a),Bv.applyMatrix4(i);const n=new Xi,o=new Xi;kv.distanceSqToSegment(Bv.start,Bv.end,o,n),o.distanceTo(n)<.5*Nv&&t.push({point:o,pointOnLine:n,distance:kv.origin.distanceTo(o),object:e,face:null,faceIndex:a,uv:null,uv1:null})}}(this,t):function(e,t,i){const n=t.projectionMatrix,r=e.material.resolution,s=e.matrixWorld,a=e.geometry,o=a.attributes.instanceStart,l=a.attributes.instanceEnd,c=Math.min(a.instanceCount,o.count),h=-t.near;kv.at(1,Pv),Pv.w=1,Pv.applyMatrix4(t.matrixWorldInverse),Pv.applyMatrix4(n),Pv.multiplyScalar(1/Pv.w),Pv.x*=r.x/2,Pv.y*=r.y/2,Pv.z=0,Dv.copy(Pv),Rv.multiplyMatrices(t.matrixWorldInverse,s);for(let t=0,a=c;t<a;t++){if(Tv.fromBufferAttribute(o,t),Iv.fromBufferAttribute(l,t),Tv.w=1,Iv.w=1,Tv.applyMatrix4(Rv),Iv.applyMatrix4(Rv),Tv.z>h&&Iv.z>h)continue;if(Tv.z>h){const e=Tv.z-Iv.z,t=(Tv.z-h)/e;Tv.lerp(Iv,t)}else if(Iv.z>h){const e=Iv.z-Tv.z,t=(Iv.z-h)/e;Iv.lerp(Tv,t)}Tv.applyMatrix4(n),Iv.applyMatrix4(n),Tv.multiplyScalar(1/Tv.w),Iv.multiplyScalar(1/Iv.w),Tv.x*=r.x/2,Tv.y*=r.y/2,Iv.x*=r.x/2,Iv.y*=r.y/2,Bv.start.copy(Tv),Bv.start.z=0,Bv.end.copy(Iv),Bv.end.z=0;const a=Bv.closestPointToPointParameter(Dv,!0);Bv.at(a,Lv);const c=gi.lerp(Tv.z,Iv.z,a),d=c>=-1&&c<=1,u=Dv.distanceTo(Lv)<.5*Nv;if(d&&u){Bv.start.fromBufferAttribute(o,t),Bv.end.fromBufferAttribute(l,t),Bv.start.applyMatrix4(s),Bv.end.applyMatrix4(s);const n=new Xi,r=new Xi;kv.distanceSqToSegment(Bv.start,Bv.end,r,n),i.push({point:r,pointOnLine:n,distance:kv.origin.distanceTo(r),object:e,face:null,faceIndex:t,uv:null,uv1:null})}}}(this,n,t))}}onBeforeRender(e){const t=this.material.uniforms;t&&t.resolution&&(e.getViewport(Sv),this.material.uniforms.resolution.value.set(Sv.z,Sv.w))}}var Gv=Object.defineProperty;const[Qv,Vv,Hv,Wv,qv,Xv]=Array(6).fill(0).map((e,t)=>t),Yv=[new mr(16725587),new mr(9100032),new mr(2920447)],Kv=new Wu,Jv=new Xi,Zv=new qi,$v=new qi,e_=new qi,t_=new Xi,i_=2*Math.PI,n_=new xp,r_=new fi,s_=new Zn;let a_=0;class o_ extends Zn{constructor(e,t,i="bottom-right",n=128,r=2){super(),this.orthoCamera=new zs(-1.8,1.8,1.8,-1.8,0,4),this.isViewHelper=!0,this.animating=!1,this.target=new Xi,this.viewport=new Gi,this.offsetHeight=0,this.renderer=new Al({canvas:document.createElement("canvas"),alpha:!0,antialias:!0,preserveDrawingBuffer:!1}),this.renderer.setPixelRatio(r),this.camera=e,this.domElement=t,this.orthoCamera.position.set(0,0,2),this.backgroundSphere=function(){const e=new yd(1.6);return new ts(e,new vr({color:16777215,side:b,transparent:!0,opacity:.2,depthTest:!1}))}(),this.axesLines=function(){const e=Array(3).fill(0).map((e,t)=>[t?0:.9,1===t?.9:0,2===t?.9:0,0,0,0]).flat(),t=Array(6).fill(0).map((e,t)=>t<2?Yv[0].toArray():t<4?Yv[1].toArray():Yv[2].toArray()).flat(),i=new wv;return i.setPositions(e),i.setColors(t),new zv(i,new Cv({linewidth:.02,vertexColors:!0}))}(),this.spritePoints=function(){const e=["x","y","z"];return Array(6).fill(0).map((t,i)=>{const n=i<3,r=n?"+":"-",s=e[i%3],a=Yv[i%3],o=new kl(function(e,t=null){const i=document.createElement("canvas"),n=0,r=1,s=0;i.width=128*r+4*n+2*s,i.height=64*r+2*n+2*s;const a=i.getContext("2d",{alpha:!0});a.beginPath(),a.arc(32*r+n,32*r+n,32*r-n,0,2*Math.PI),a.closePath(),a.fillStyle=e.getStyle(),a.fill(),a.beginPath(),a.arc(32*r+n,32*r+n,35*r-n,0,2*Math.PI),a.closePath(),a.fillStyle="#"+e.getHexString()+"01",a.fill(),a.beginPath(),a.arc(96*r+3*n+s,32*r+n+s,32*r-n-s,0,2*Math.PI),a.closePath(),a.fillStyle="#FFF",a.fill(),a.beginPath(),a.arc(96*r+3*n+s,32*r+n+s,35+r-n-s,0,2*Math.PI),a.closePath(),a.fillStyle="#FFFFFF01",a.fill(),null!==t&&(a.font="bold calc(44px * "+r+") Arial",a.textAlign="center",a.fillStyle="#111",a.fillText(t.toUpperCase(),32*r+n,48*r+n),a.fillText(t.toUpperCase(),96*r+3*n+s,48*r+n+s));const o=new ih(i);return o.wrapS=o.wrapT=ge,o.repeat.x=.5,o.colorSpace=Ot,o.minFilter=be,o.magFilter=be,o.generateMipmaps=!1,o.needsUpdate=!0,new Cl({map:o,toneMapped:!1,transparent:!0})}(a,n?s:null));return o.userData.type=`${r}${s}`,o.scale.setScalar(n?.6:.4),o.position[s]=n?1.2:-1.2,o.renderOrder=1,o})}(),this.add(this.backgroundSphere,this.axesLines,...this.spritePoints),this.domContainer=function(e,t){const i=document.createElement("div"),n=i.style;n.height=`${t}px`,n.width=`${t}px`,n.borderRadius="100%",n.position="absolute";const[r,s]=e.split("-");return n.transform="",n.left="left"===s?"0":"center"===s?"50%":"",n.right="right"===s?"0":"",n.transform+="center"===s?"translateX(-50%)":"",n.top="top"===r?"0":"bottom"===r?"":"50%",n.bottom="bottom"===r?"0":"",n.transform+="center"===r?"translateY(-50%)":"",i}(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,h_(this.spritePoints),this.domContainer.style.cursor="",this.dispatchEvent({type:"update",event:e,change:"pointer"})}handleClick(e){const t=c_(e,this.domRect,this.orthoCamera,this.spritePoints);t&&this.setOrientation(t.userData.type)}handleHover(e){const t=c_(e,this.domRect,this.orthoCamera,this.spritePoints);h_(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=Kv.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()),function(e,t){t_.set(0,0,1),t_.applyQuaternion(t.quaternion),t_.x>=0?(e[Qv].material.opacity=1,e[Wv].material.opacity=.5):(e[Qv].material.opacity=.5,e[Wv].material.opacity=1),t_.y>=0?(e[Vv].material.opacity=1,e[qv].material.opacity=.5):(e[Vv].material.opacity=.5,e[qv].material.opacity=1),t_.z>=0?(e[Hv].material.opacity=1,e[Xv].material.opacity=.5):(e[Hv].material.opacity=.5,e[Xv].material.opacity=1)}(this.spritePoints,this.camera)}update(){this.domRect=this.domContainer.getBoundingClientRect(),this.offsetHeight=this.domElement.offsetHeight,l_(this.camera,this.target),this.renderer.getViewport(this.viewport),this.updateOrientation()}animate(e){const t=e*i_;$v.rotateTowards(e_,t),this.camera.position.set(0,0,1).applyQuaternion($v).multiplyScalar(a_).add(this.target),this.camera.quaternion.rotateTowards(Zv,t),this.updateOrientation(),0===$v.angleTo(e_)&&(this.animating=!1)}setOrientation(e){(function(e,t,i){switch(i){case"+x":Jv.set(1,0,0),Zv.setFromEuler(new On(0,.5*Math.PI,0));break;case"+y":Jv.set(0,1,0),Zv.setFromEuler(new On(.5*-Math.PI,0,0));break;case"+z":Jv.set(0,0,1),Zv.setFromEuler(new On);break;case"-x":Jv.set(-1,0,0),Zv.setFromEuler(new On(0,.5*-Math.PI,0));break;case"-y":Jv.set(0,-1,0),Zv.setFromEuler(new On(.5*Math.PI,0,0));break;case"-z":Jv.set(0,0,-1),Zv.setFromEuler(new On(0,Math.PI,0));break;default:console.error("ViewHelper: Invalid axis.")}l_(e,t),function(e,t){Jv.multiplyScalar(a_).add(t),s_.position.copy(t),s_.lookAt(e.position),$v.copy(s_.quaternion),s_.lookAt(Jv),e_.copy(s_.quaternion)}(e,t)})(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()}}function l_(e,t){a_=e.position.distanceTo(t)}function c_(e,t,i,n){!function(e,t,i){r_.x=(e.clientX-t.left)/t.width*2-1,r_.y=-(e.clientY-t.top)/t.height*2+1,n_.setFromCamera(r_,i)}(e,t,i);const r=n_.intersectObjects(n);return r.length?r[0].object:null}function h_(e){let t=e.length;for(;t--;){const i=t<3?.6:.4;e[t].scale.set(i,i,i),e[t].material.map.offset.x=1}}((e,t,i)=>{for(var n,r=void 0,s=e.length-1;s>=0;s--)(n=e[s])&&(r=n(t,i,r)||r);r&&Gv(t,i,r)})([Wm()],o_.prototype,"animating");const d_=class extends wh{constructor(){super(),this.type="CurvePath3"}};jm.SerializableClasses.set("CurvePath3",d_);let u_=d_;function p_(e,t){const i=t.getSize(new Xi);let n=1;if(e.isPerspectiveCamera&&i.length()>1e-4){const t=isFinite(e.aspect)?e.aspect:1,r=Math.max(1,e.fov)*(Math.PI/180),s=2*Math.atan(Math.tan(r/2)*t),a=i.z/2+Math.abs(i.x/2/Math.tan(s/2)),o=i.z/2+Math.abs(i.y/2/Math.tan(r/2));n=Math.max(a,o)}return n}const m_=e=>(t,i)=>i?.copy?.(t)??(new e).copy(t),g_=class e{static PrimitiveSerializer(e,t,i,n=1){return{priority:n,isType:e=>e?.[t],serialize:e=>{const n={[t]:!0};for(const t of i)n[t]=e[t];return n},deserialize:m_(e),type:t.startsWith("is")?t.slice(2):e.name}}static Init(){this._init||(this._init=!0,Sp.prototype.isSpherical=!0,jm.RegisterSerializer(...e.Primitives.map(t=>e.PrimitiveSerializer(t[0],t[1],t[2],t[3]))),jm.RegisterSerializer(e.Texture),jm.RegisterSerializer(e.Material),jm.RegisterSerializer(e.RenderTarget),jm.SerializableClasses.set("Shape",Fh),jm.SerializableClasses.set("Curve",nh),jm.SerializableClasses.set("CurvePath",wh),jm.SerializableClasses.set("Path",Ch),jm.SerializableClasses.set("ArcCurve",sh),jm.SerializableClasses.set("CatmullRomCurve3",dh),jm.SerializableClasses.set("CubicBezierCurve",gh),jm.SerializableClasses.set("CubicBezierCurve3",fh),jm.SerializableClasses.set("EllipseCurve",rh),jm.SerializableClasses.set("LineCurve",Ah),jm.SerializableClasses.set("LineCurve3",yh),jm.SerializableClasses.set("QuadraticBezierCurve",vh),jm.SerializableClasses.set("QuadraticBezierCurve3",_h),jm.SerializableClasses.set("SplineCurve",bh),jm.SerializableClasses.set("AnimationClip",eu))}static MakeSerializable(e,t,i){e.prototype.serializableClassId=t,jm.SerializableClasses.set(t,e),i&&jm.TypeMap.set(e,i.map(e=>"string"==typeof e?[e,e]:e))}static Serialize(e,t,i=!1){return this._init||this.Init(),jm.Serialize(e,t,i)}static Deserialize(e,t,i,n=!1){return this._init||this.Init(),jm.Deserialize(e,t,i,n)}};g_.Primitives=[[fi,"isVector2",["x","y"],1],[Xi,"isVector3",["x","y","z"],1],[Gi,"isVector4",["x","y","z","w"],1],[qi,"isQuaternion",["x","y","z","w"],1],[On,"isEuler",["x","y","z","order"],1],[mr,"isColor",["r","g","b"],1],[Mp,"isMatrix2",["elements"],1],[Ai,"isMatrix3",["elements"],1],[Sn,"isMatrix4",["elements"],1],[Sp,"isSpherical",["radius","phi","theta"],1]],g_.Texture={priority:2,isType:e=>e.isTexture||"Texture"===e.metadata?.type,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&&"string"==typeof e.userData.rootPath&&Eg(e.userData.rootPath);let r={};const s=e.userData;try{n&&e.source.data&&(e.userData.embedUrlImagePreviews?e.source.data=tv(e,16,e.flipY):e.source.data=null),e.userData={};const i={images:{}};r=e.toJSON(t||i),!t&&r.image&&(r.image=n&&!e.userData.embedUrlImagePreviews?void 0:i.images[r.image]),r.userData=jm.Serialize(y_({},s),t,!1)}catch(e){console.error("ThreeSerialization: Unable to serialize texture"),console.error(e)}return e.userData=s,n&&(t&&!e.userData.embedUrlImagePreviews&&delete t.images[e.source.uuid],e.source.data=i),t?.textures&&r&&!r.resource&&(t.textures[r.uuid]||(t.textures[r.uuid]=r),r={uuid:r.uuid,resource:"textures"}),r},deserialize:(e,t,i)=>{if(e.isTexture)return e;if("textures"===e.resource&&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 Uu(i?._context.assetImporter?.loadingManager),r={...e};if("string"==typeof r.image&&(i?.images?r.image=i.images[r.image]:console.error("ThreeSerialization: Cannot deserialize texture with image url without meta.images",r)),!r.image||"string"==typeof r.image||!r.image.isSource&&!r.image.url)return console.error("ThreeSerialization: Cannot deserialize texture",r),t;let s;i&&!r.image.isSource&&(i._context.imagePromises||(i._context.imagePromises=[]),i._context.imagePromises.push(new Promise(e=>{s=e})));const a=r.image.isSource?{[r.image.uuid]:r.image}:n.parseImages([r.image],s);r.image=Object.keys(a)[0],i?.images&&(i.images[r.image]=a[r.image]),r.userData&&(r.userData=g_.Deserialize(r.userData,{},i));const o=n.parseTextures([r],a),l=Object.keys(o)[0];return l&&o[l]?(i?.textures&&(i.textures[l]=o[l]),o[l]):(console.error("ThreeSerialization: Cannot deserialize texture",r),t)}},g_.SerializableMaterials=new Set,g_.Material={priority:2,isType:e=>e.isMaterial||"Material"===e.metadata?.type,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={},r={},s=Object.keys(e.constructor.MaterialProperties||e);for(const t of s){if(t.startsWith("__"))continue;const s=e[t];if(s?.isTexture){const a=jm.Serialize(s,i);n[t]=a,r[t]=s,e[t]=a?{isTexture:!0,toJSON:()=>a}:null}}const a=e.userData;e.userData={};let o={};try{o=e.toJSON(t||i,!0),function(e,t,i){e.userData={},v_(e.userData,t);const n=i||{textures:Object.fromEntries(e.textures?.map(e=>[e.uuid,e])||[]),images:Object.fromEntries(e.images?.map(e=>[e.uuid,e])||[])};e.userData=jm.Serialize(e.userData,n),i||(Object.keys(n.textures).length>0&&(e.textures=Object.values(n.textures)),Object.keys(n.images).length>0&&(e.images=Object.values(n.images)))}(o,a,t),o.userData.uuid=a.uuid,e.constructor.TYPE&&(o.type=e.constructor.TYPE);for(const e of Object.keys(o))void 0===o[e]&&delete o[e]}catch(e){console.error("ThreeSerialization: Unable to serialize material"),console.error(e)}e.userData=a;for(const[t,i]of Object.entries(r))e[t]=i,delete r[t];if(o)if(t){for(const[e,t]of Object.entries(n))t&&(o[e]=t);t.materials&&(t.materials[o.uuid]||(t.materials[o.uuid]=o),o={uuid:o.uuid,resource:"materials"})}else{for(const[e,t]of Object.entries(n))t&&(o[e]=t.uuid);o.textures=Object.values(i.textures),o.images=Object.values(i.images)}return o},deserialize:(e,t,i)=>{function n(e){if(e.isMaterial)return t?.isMaterial&&t.uuid===e.uuid?(t!==e&&"function"==typeof t.setValues&&(console.warn("ThreeSerialization: Material uuid already exists, copying values to old material"),t.setValues(e)),t):e}let r=n(e);if(void 0!==r)return r;if("materials"===e.resource&&i?.materials?.[e.uuid]){if(r=n(i.materials[e.uuid]),void 0!==r)return r;console.error("ThreeSerialization: cannot find material in meta",e,r)}const s=e.type;if(!s)return console.error("ThreeSerialization: Cannot deserialize material without type",e),t;const a={...e};a.userData&&(a.userData=jm.Deserialize(a.userData,void 0,i,!1));const o={};for(const[e,t]of Object.entries(a)){if("string"==typeof t&&i?.textures?.[t]&&(a[e]=i.textures[t],o[e]=i.textures[t]),!t||!t.resource||"string"!=typeof t.resource)continue;const n=i?.[t.resource]?.[t.uuid];a[e]=n||null,"textures"===t.resource&&n?.isTexture&&(o[e]=n)}if((!t||!t.isMaterial||t.type!==s&&t.constructor?.TYPE!==s)&&(t&&Object.keys(t).length&&console.warn("ThreeSerialization: Material type mismatch during deserialize, creating a new material",t,a,s,t.constructor?.type),t=null),t&&(!a.uuid||t.uuid===a.uuid))return t.fromJSON?t.fromJSON(a,i,!0):t.setValues?t.setValues(a):console.error("ThreeSerialization: Cannot deserialize material, no fromJSON or setValues method",t,a),t;const l=e.isMaterial?void 0:e.uuid;let c=null;for(const e of g_.SerializableMaterials)if(e.TYPE===s){c=e;break}if(!c)for(const e of g_.SerializableMaterials)if(e.TypeAlias?.includes(s)){c=e;break}if(c){const e=new c;if(e)return l&&Tm(e,"uuid",l,!0,!0),e.fromJSON?e.fromJSON(a,i,!0):e.setValues?e.setValues(a):console.error("ThreeSerialization: Cannot deserialize material, no fromJSON or setValues method",e,a),e}console.warn("Legacy three.js material deserialization");const h=new Ru;for(const[e,t]of Object.entries(o))a[e]=t.uuid;const d={...h.textures};h.setTextures(o);const u=h.parse(a);if(a.uuid&&Tm(u,"uuid",a.uuid,!0,!0),h.setTextures(d),r=n(u),void 0!==r)return r;console.error("ThreeSerialization: cannot deserialize material",e,r,u)}},g_.RenderTarget={priority:2,isType:e=>e.isWebGLRenderTarget||"RenderTarget"===e.metadata?.type,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(e=>e.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 r=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(r.texture))for(let t=0;t<e.textureName.length;t++)r.texture[t].name=e.textureName[t];else Array.isArray(r.texture)||(r.texture.name=Array.isArray(e.textureName)?e.textureName[0]:e.textureName);return r&&(r.uuid=e.uuid,i?.extras&&(i.extras[e.uuid]=r),r)}},g_._init=!1;let f_=g_;function A_(e,t,i=[]){if(!t)return e;for(const n of Object.keys(t)){if(i.includes(n)||n.startsWith("__"))continue;const r=t[n];if("function"==typeof e[n]||"function"==typeof r)continue;const s=!r||r.isTexture||r.isObject3D||r.isMaterial||r.isBufferGeometry||r.userDataSkipClone;s||"function"!=typeof r.clone?s||r.constructor!==Object&&!Array.isArray(r)?e[n]=r:e[n]=A_(Array.isArray(r)?[]:{},r,[]):e[n]=r.clone()}return e}function y_(e,t,i=["uuid"]){return A_(e,t,i)}function v_(e,t,i=["uuid"]){return A_(e,t,i)}function __(e,t,i=["uuid"]){return A_(e,t,i)}function b_(e){Object.values(e).forEach(e=>{e&&Object.values(e).forEach(e=>{e.url&&(!(e.url.data instanceof ArrayBuffer)&&!Array.isArray(e.url.data)||("Uint16Array"===e.url.type?(e.url.data instanceof Uint16Array||(e.url.data=new Uint16Array(e.url.data)),e.url.data="data:application/octet-stream;base64,"+cm(e.url.data.buffer)):"Uint8Array"===e.url.type?(e.url.data instanceof Uint8Array||(e.url.data=new Uint8Array(e.url.data)),e.url.data="data:application/octet-stream;base64,"+cm(e.url.data.buffer)):e.url.data instanceof ArrayBuffer?e.url.data="data:application/octet-stream;base64,"+cm(e.url.data.buffer):console.warn("Unsupported buffer type",e.url.type)))})})}function x_(e){Object.values(e).forEach(e=>{e&&Object.values(e).forEach(e=>{if(!e||!e.url||"string"!=typeof e.url.data)return;const t=e.url.data.match(/^data:.*;base64,(.*)$/);t?.[1]?e.url.data=hm(t?.[1]):("Uint8Array"!==e.url.type&&console.error("ThreeSerialization: Unsupported buffer type string for ",e.url.type,"use base64"),e.url.data=(new TextEncoder).encode(e.url.data).buffer)})})}function w_(e){return{geometries:{...e?.geometries},materials:{...e?.materials},textures:{...e?.textures},images:{...e?.images},shapes:{...e?.shapes},skeletons:{...e?.skeletons},animations:{...e?.animations},extras:{...e?.extras},typed:{...e?.typed},nodes:{...e?.nodes},_context:{}}}class C_{static async ImportMeta(e,t){if(e.__isLoadedResources)return e;const i=M_();i.__isLoadedResources=!0,i._context=e._context,x_(e);const n=e._context.assetImporter;if(!n)throw new Error("assetImporter not found in meta context, which is required for import meta.");const r=e._context.objectLoader||new Uu(n.loadingManager);i.animations=e.animations?r.parseAnimations(Object.values(e.animations)):{},t&&t.animations&&(i.animations={...i.animations,...t.animations}),i.shapes=e.shapes?r.parseShapes(Object.values(e.shapes)):{},t&&t.shapes&&(i.shapes={...i.shapes,...t.shapes}),i.geometries=e.geometries?r.parseGeometries(Object.values(e.geometries),i.shapes):{},t&&t.geometries&&(i.geometries={...i.geometries,...t.geometries}),i.images=e.images?await r.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((e,t)=>(t&&(e[t.uuid]=t),e))),await C_.LoadRootPathTextures({textures:e.textures,images:i.images},n);const s=[];for(const t of Object.values(e.textures)){const e={...t};e.userData&&(e.userData=f_.Deserialize(e.userData,{},i)),s.push(e)}i.textures=e.textures?r.parseTextures(s,i.images):{};for(const e of Object.keys(i.textures)){let t=i.textures[e];if(t){if(t.source.__texCtor){const n=new t.source.__texCtor(t.source.data);if(!n||"function"!=typeof n.copy)continue;n.copy(t),delete t.source.__texCtor,i.textures[e]=n,t=n}if(t.source.data instanceof HTMLCanvasElement&&!t.isCanvasTexture){const n=new ih(t.source.data).copy(t);i.textures[e]=n,t=n}}}const a={...i.textures};for(const t of Object.values(e.textures))t.rootPathPromise?.then(e=>{if(!e)return;const i=a[t.uuid];i.dispose(),i.source=e,i.source.needsUpdate=!0,i.needsUpdate=!0});for(const e of Object.entries(i.textures))e[1]=await n.processRawSingle(e[1],{}),e[1]?i.textures[e[0]]=e[1]:delete i.textures[e[0]];t&&t.textures&&(i.textures={...i.textures,...t.textures});const o=e.materials?Object.values(e.materials):[];i.materials={};for(const e of o)e?.uuid&&(i.materials[e.uuid]=f_.Deserialize(e,void 0,i));if(t&&t.materials&&(i.materials={...i.materials,...t.materials}),e.object&&(i.object=r.parseObject(e.object,i.geometries,i.materials,i.textures,i.animations),e.skeletons&&(i.skeletons=r.parseSkeletons(Object.values(e.skeletons),i.object),r.bindSkeletons(i.object,i.skeletons))),e.extras){i.extras=e.extras;for(const t of Object.values(e.extras))if(t.uuid){if(!t.url){i.extras[t.uuid]=f_.Deserialize(t,void 0,i);continue}if("string"==typeof t.url){const e=await n.importSingle(t.url,t.userData?.rootPathOptions||{});e&&(i.extras[t.uuid]=e)}else if(t.url.data){const e=new File([um(t.url.type,t.url.data)],t.url.path),r=await n.importSingle({path:e.name,file:e},t.userData?.rootPathOptions||{},void 0,!1);r&&(i.extras[t.uuid]=r)}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[t,r]of Object.entries(e.typed))if("string"==typeof r.rootPath&&r.external){const e=await n.importSingle(r.rootPath,r.rootPathOptions||{});e&&(i.typed[t]=e)}else i.typed[t]=f_.Deserialize(r,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 r=[];for(const s of Array.isArray(e)?e:Object.values(e??{})){const e=s?.userData?.rootPath,a=n&&s.image&&t[s.image];if(!e)continue;const o=i.importSingle(e,s.userData.rootPathOptions||{}).then(i=>{const n=i?.source;if(!i||!i.isTexture||!n)return void console.error("AssetImporter: Imported rootPath is not a Texture",e,i);const r=new Ui(n.data);return s.image&&(r.uuid=s.image),s.image=r.uuid,i.constructor!==Ni&&i.constructor!==ec&&i.constructor!==fs&&(r.__texCtor=i.constructor),a||(t[r.uuid]=r),i.dispose(),r}).catch(e=>(console.error("ThreeSerialization: Error loading texture from rootPath",s.userData.rootPath),console.error(e),delete s.userData.rootPath,null));a?s.rootPathPromise=o:r.push(o)}await Promise.allSettled(r)}}function S_(e){if(!e)return{};const t={...e};return t._context&&delete t._context,t}function M_(e,t){return{...e,...w_(e),_context:{assetManager:t?.assetManager,assetImporter:t?.assetManager.importer,renderManager:t?.renderManager,viewer:t}}}function E_(e){const t=new Blob([JSON.stringify(e)],{type:"application/json"});return t.ext="json",t}function T_(e,t,i,n){if(t?.extras[e.uuid])return{uuid:e.uuid,resource:"extras"};let r="";if(e.source?._sourceImgBuffer||e.__sourceBuffer){const t=new Uint8Array(e.source?._sourceImgBuffer||e.__sourceBuffer),i=n||e.userData.mimeType||"";r={data:Array.from(t),type:t.constructor.name,path:e.userData.__sourceBlob?.name||e.userData.rootPath||"file."+i.split("/")[1]},i&&(r.mimeType=i)}else e.userData.rootPath?r=e.userData.rootPath:console.error("ThreeSerialization: Unable to serialize LUT texture, not loaded through asset manager.");const s={uuid:e.uuid,url:r,userData:y_({},e.userData),type:e.type,name:i||e.name};return t?.extras?(t.extras[e.uuid]=s,{uuid:e.uuid,resource:"extras"}):s}function I_(e,t){const i={},n=Array.isArray(t)?t:[];for(const t of n){let n;n=t.startsWith("userData.")?Lm(t.slice(9),e.userData,!1):e[t],void 0!==n&&(i[t]=n)}return i}function P_(e,t){for(const i of Object.keys(e)){const n=e[i];if(i.startsWith("userData.")){const e=t.userData,r=i.split("."),s=r.slice(1,-1),a=r.length&&s.length?Lm(s,e,!1):void 0;if(void 0!==a){a[r[r.length-1]]=n}else console.warn("ThreeSerialization: setSProps: invalid sProperty",i,"in",t)}else t[i]=n}}const D_="shaderReplaceString: str must be passed if str is a RegExp and append/prepend is true";function R_(e,t,i,{replaceAll:n=!1,prepend:r=!1,append:s=!1,str:a,warn:o=!0}={}){const l="string"==typeof t;if(o&&(l?!e.includes(t):!t.test(e)))return console.error(`${t} not found in shader`),e;let c=i;if(a=a??(l?t:void 0),r){if("string"!=typeof a)throw new Error(D_);c=i+a}else if(s){if("string"!=typeof a)throw new Error(D_);c=a+i}return n?e.replaceAll(t,c):e.replace(t,c)}function B_(e,t=0){const i=function(e){return 4*Math.ceil(e/4)}(e.byteLength);if(i!==e.byteLength){const n=new Uint8Array(i);if(n.set(new Uint8Array(e)),0!==t)for(let r=e.byteLength;r<i;r++)n[r]=t;return n.buffer}return e.buffer}function L_(e,t){const i=B_(e),n=new DataView(new ArrayBuffer(8));n.setUint32(0,i.byteLength,!0),n.setUint32(4,5130562,!0);const r=B_((new TextEncoder).encode(JSON.stringify(t||{})),32),s=new DataView(new ArrayBuffer(8));s.setUint32(0,r.byteLength,!0),s.setUint32(4,1313821514,!0);const a=new ArrayBuffer(12),o=new DataView(a);o.setUint32(0,1179937895,!0),o.setUint32(4,2,!0);const l=12+s.byteLength+r.byteLength+n.byteLength+i.byteLength;o.setUint32(8,l,!0);const c=new Blob([a,s,r,n,i],{type:"model/gltf+binary"});return c.ext="glb",c}function O_(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}const U_=(e,t,i)=>Math.min(Math.max(i,e),t),F_=.001;function k_({duration:e=800,bounce:t=.25,velocity:i=0,mass:n=1}){let r,s,a=1-t;a=U_(.05,1,a),e=U_(.01,10,e/1e3),a<1?(r=t=>{const n=t*a,r=n*e,s=n-i,o=j_(t,a),l=Math.exp(-r);return F_-s/o*l},s=t=>{const n=t*a*e,s=n*i+i,o=Math.pow(a,2)*Math.pow(t,2)*e,l=Math.exp(-n),c=j_(Math.pow(t,2),a);return(-r(t)+F_>0?-1:1)*((s-o)*l)/c}):(r=t=>Math.exp(-t*e)*((t-i)*e+1)-F_,s=t=>Math.exp(-t*e)*(e*e*(i-t)));const o=function(e,t,i){let n=i;for(let i=1;i<N_;i++)n-=e(n)/t(n);return n}(r,s,5/e);if(e*=1e3,isNaN(o))return{stiffness:100,damping:10,duration:e};{const t=Math.pow(o,2)*n;return{stiffness:t,damping:2*a*Math.sqrt(n*t),duration:e}}}const N_=12;function j_(e,t){return e*Math.sqrt(1-t*t)}const z_=["duration","bounce"],G_=["stiffness","damping","mass"];function Q_(e,t){return t.some(t=>void 0!==e[t])}function V_(e){var{from:t=0,to:i=1,restSpeed:n=2,restDelta:r}=e,s=O_(e,["from","to","restSpeed","restDelta"]);const a={done:!1,value:t};let{stiffness:o,damping:l,mass:c,velocity:h,duration:d,isResolvedFromDuration:u}=function(e){let t=Object.assign({velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1},e);if(!Q_(e,G_)&&Q_(e,z_)){const i=k_(e);t=Object.assign(Object.assign(Object.assign({},t),i),{velocity:0,mass:1}),t.isResolvedFromDuration=!0}return t}(s),p=H_,m=H_;function g(){const e=h?-h/1e3:0,n=i-t,s=l/(2*Math.sqrt(o*c)),a=Math.sqrt(o/c)/1e3;if(void 0===r&&(r=Math.min(Math.abs(i-t)/100,.4)),s<1){const t=j_(a,s);p=r=>{const o=Math.exp(-s*a*r);return i-o*((e+s*a*n)/t*Math.sin(t*r)+n*Math.cos(t*r))},m=i=>{const r=Math.exp(-s*a*i);return s*a*r*(Math.sin(t*i)*(e+s*a*n)/t+n*Math.cos(t*i))-r*(Math.cos(t*i)*(e+s*a*n)-t*n*Math.sin(t*i))}}else if(1===s)p=t=>i-Math.exp(-a*t)*(n+(e+a*n)*t);else{const t=a*Math.sqrt(s*s-1);p=r=>{const o=Math.exp(-s*a*r),l=Math.min(t*r,300);return i-o*((e+s*a*n)*Math.sinh(l)+t*n*Math.cosh(l))/t}}}return g(),{next:e=>{const t=p(e);if(u)a.done=e>=d;else{const s=1e3*m(e),o=Math.abs(s)<=n,l=Math.abs(i-t)<=r;a.done=o&&l}return a.value=a.done?i:t,a},flipTarget:()=>{h=-h,[t,i]=[i,t],g()}}}V_.needsInterpolation=(e,t)=>"string"==typeof e||"string"==typeof t;const H_=e=>0,W_=(e,t,i)=>{const n=t-e;return 0===n?1:(i-e)/n},q_=(e,t,i)=>-i*e+i*t+e,X_=(e,t)=>i=>Math.max(Math.min(i,t),e),Y_=e=>e%1?Number(e.toFixed(5)):e,K_=/(-)?([\d]*\.?[\d])+/g,J_=/(#[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,Z_=/^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;function $_(e){return"string"==typeof e}const eb={test:e=>"number"==typeof e,parse:parseFloat,transform:e=>e},tb=Object.assign(Object.assign({},eb),{transform:X_(0,1)});Object.assign(Object.assign({},eb),{default:1});const ib={test:e=>$_(e)&&e.endsWith("%")&&1===e.split(" ").length,parse:parseFloat,transform:e=>`${e}%`};Object.assign(Object.assign({},ib),{parse:e=>ib.parse(e)/100,transform:e=>ib.transform(100*e)});const nb=(e,t)=>i=>!!($_(i)&&Z_.test(i)&&i.startsWith(e)||t&&Object.prototype.hasOwnProperty.call(i,t)),rb=(e,t,i)=>n=>{if(!$_(n))return n;const[r,s,a,o]=n.match(K_);return{[e]:parseFloat(r),[t]:parseFloat(s),[i]:parseFloat(a),alpha:void 0!==o?parseFloat(o):1}},sb={test:nb("hsl","hue"),parse:rb("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:i,alpha:n=1})=>"hsla("+Math.round(e)+", "+ib.transform(Y_(t))+", "+ib.transform(Y_(i))+", "+Y_(tb.transform(n))+")"},ab=X_(0,255),ob=Object.assign(Object.assign({},eb),{transform:e=>Math.round(ab(e))}),lb={test:nb("rgb","red"),parse:rb("red","green","blue"),transform:({red:e,green:t,blue:i,alpha:n=1})=>"rgba("+ob.transform(e)+", "+ob.transform(t)+", "+ob.transform(i)+", "+Y_(tb.transform(n))+")"};const cb={test:nb("#"),parse:function(e){let t="",i="",n="",r="";return e.length>5?(t=e.substr(1,2),i=e.substr(3,2),n=e.substr(5,2),r=e.substr(7,2)):(t=e.substr(1,1),i=e.substr(2,1),n=e.substr(3,1),r=e.substr(4,1),t+=t,i+=i,n+=n,r+=r),{red:parseInt(t,16),green:parseInt(i,16),blue:parseInt(n,16),alpha:r?parseInt(r,16)/255:1}},transform:lb.transform},hb=e=>lb.test(e)||cb.test(e)||sb.test(e),db=e=>lb.test(e)?lb.parse(e):sb.test(e)?sb.parse(e):cb.parse(e),ub=e=>$_(e)?e:e.hasOwnProperty("red")?lb.transform(e):sb.transform(e),pb="${c}",mb="${n}";function gb(e){"number"==typeof e&&(e=`${e}`);const t=[];let i=0;const n=e.match(J_);n&&(i=n.length,e=e.replace(J_,pb),t.push(...n.map(db)));const r=e.match(K_);return r&&(e=e.replace(K_,mb),t.push(...r.map(eb.parse))),{values:t,numColors:i,tokenised:e}}function fb(e){return gb(e).values}function Ab(e){const{values:t,numColors:i,tokenised:n}=gb(e),r=t.length;return e=>{let t=n;for(let n=0;n<r;n++)t=t.replace(n<i?pb:mb,n<i?ub(e[n]):Y_(e[n]));return t}}const yb=e=>"number"==typeof e?0:e;const vb={test:function(e){var t,i,n,r;return isNaN(e)&&$_(e)&&(null!==(i=null===(t=e.match(K_))||void 0===t?void 0:t.length)&&void 0!==i?i:0)+(null!==(r=null===(n=e.match(J_))||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0},parse:fb,createTransformer:Ab,getAnimatableNone:function(e){const t=fb(e);return Ab(e)(t.map(yb))}};function _b(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}function bb({hue:e,saturation:t,lightness:i,alpha:n}){e/=360,i/=100;let r=0,s=0,a=0;if(t/=100){const n=i<.5?i*(1+t):i+t-i*t,o=2*i-n;r=_b(o,n,e+1/3),s=_b(o,n,e),a=_b(o,n,e-1/3)}else r=s=a=i;return{red:Math.round(255*r),green:Math.round(255*s),blue:Math.round(255*a),alpha:n}}const xb=(e,t,i)=>{const n=e*e,r=t*t;return Math.sqrt(Math.max(0,i*(r-n)+n))},wb=[cb,lb,sb],Cb=e=>wb.find(t=>t.test(e)),Sb=(e,t)=>{let i=Cb(e),n=Cb(t),r=i.parse(e),s=n.parse(t);i===sb&&(r=bb(r),i=lb),n===sb&&(s=bb(s),n=lb);const a=Object.assign({},r);return e=>{for(const t in a)"alpha"!==t&&(a[t]=xb(r[t],s[t],e));return a.alpha=q_(r.alpha,s.alpha,e),i.transform(a)}},Mb=(e,t)=>i=>t(e(i)),Eb=(...e)=>e.reduce(Mb);function Tb(e,t){return(e=>"number"==typeof e)(e)?i=>q_(e,t,i):hb(e)?Sb(e,t):Rb(e,t)}const Ib=(e,t)=>{const i=[...e],n=i.length,r=e.map((e,i)=>Tb(e,t[i]));return e=>{for(let t=0;t<n;t++)i[t]=r[t](e);return i}},Pb=(e,t)=>{const i=Object.assign(Object.assign({},e),t),n={};for(const r in i)void 0!==e[r]&&void 0!==t[r]&&(n[r]=Tb(e[r],t[r]));return e=>{for(const t in n)i[t]=n[t](e);return i}};function Db(e){const t=vb.parse(e),i=t.length;let n=0,r=0,s=0;for(let e=0;e<i;e++)n||"number"==typeof t[e]?n++:void 0!==t[e].hue?s++:r++;return{parsed:t,numNumbers:n,numRGB:r,numHSL:s}}const Rb=(e,t)=>{const i=vb.createTransformer(t),n=Db(e),r=Db(t);return n.numHSL===r.numHSL&&n.numRGB===r.numRGB&&n.numNumbers>=r.numNumbers?Eb(Ib(n.parsed,r.parsed),i):i=>`${i>0?t:e}`},Bb=(e,t)=>i=>q_(e,t,i);function Lb(e,t,i){const n=[],r=i||function(e){return"number"==typeof e?Bb:"string"==typeof e?hb(e)?Sb:Rb:Array.isArray(e)?Ib:"object"==typeof e?Pb:void 0}(e[0]),s=e.length-1;for(let i=0;i<s;i++){let s=r(e[i],e[i+1]);if(t){const e=Array.isArray(t)?t[i]:t;s=Eb(e,s)}n.push(s)}return n}function Ob(e,t,{clamp:i=!0,ease:n,mixer:r}={}){const s=e.length;t.length,!n||!Array.isArray(n)||n.length,e[0]>e[s-1]&&(e=[].concat(e),t=[].concat(t),e.reverse(),t.reverse());const a=Lb(t,n,r),o=2===s?function([e,t],[i]){return n=>i(W_(e,t,n))}(e,a):function(e,t){const i=e.length,n=i-1;return r=>{let s=0,a=!1;if(r<=e[0]?a=!0:r>=e[n]&&(s=n-1,a=!0),!a){let t=1;for(;t<i&&!(e[t]>r||t===n);t++);s=t-1}const o=W_(e[s],e[s+1],r);return t[s](o)}}(e,a);return i?t=>o(U_(e[0],e[s-1],t)):o}const Ub=e=>t=>1-e(1-t),Fb=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,kb=e=>t=>t*t*((e+1)*t-e),Nb=4/11,jb=8/11,zb=(e=>t=>Math.pow(t,e))(2),Gb=Ub(zb),Qb=Fb(zb),Vb=e=>1-Math.sin(Math.acos(e)),Hb=Ub(Vb),Wb=Fb(Hb),qb=kb(1.525),Xb=Ub(qb),Yb=Fb(qb),Kb=(e=>{const t=kb(e);return e=>(e*=2)<1?.5*t(e):.5*(2-Math.pow(2,-10*(e-1)))})(1.525),Jb=4356/361,Zb=35442/1805,$b=16061/1805,ex=e=>{if(1===e||0===e)return e;const t=e*e;return e<Nb?7.5625*t:e<jb?9.075*t-9.9*e+3.4:e<.9?Jb*t-Zb*e+$b:10.8*e*e-20.52*e+10.72},tx=Ub(ex);function ix(e,t){return e.map(()=>t||Qb).splice(0,e.length-1)}function nx({from:e=0,to:t=1,ease:i,offset:n,duration:r=300}){const s={done:!1,value:e},a=Array.isArray(t)?t:[e,t],o=function(e,t){return e.map(e=>e*t)}(n&&n.length===a.length?n:function(e){const t=e.length;return e.map((e,i)=>0!==i?i/(t-1):0)}(a),r);function l(){return Ob(o,a,{ease:Array.isArray(i)?i:ix(a,i)})}let c=l();return{next:e=>(s.value=c(e),s.done=e>=r,s),flipTarget:()=>{a.reverse(),c=l()}}}const rx={keyframes:nx,spring:V_,decay:function({velocity:e=0,from:t=0,power:i=.8,timeConstant:n=350,restDelta:r=.5,modifyTarget:s}){const a={done:!1,value:t};let o=i*e;const l=t+o,c=void 0===s?l:s(l);return c!==l&&(o=c-t),{next:e=>{const t=-o*Math.exp(-e/n);return a.done=!(t>r||t<-r),a.value=a.done?c:c+t,a},flipTarget:()=>{}}}};const sx=1/60*1e3,ax=typeof performance<"u"?()=>performance.now():()=>Date.now(),ox=typeof window<"u"?e=>window.requestAnimationFrame(e):e=>setTimeout(()=>e(ax()),sx);let lx=!0,cx=!1,hx=!1;const dx={delta:0,timestamp:0},ux=["read","update","preRender","render","postRender"],px=ux.reduce((e,t)=>(e[t]=function(e){let t=[],i=[],n=0,r=!1,s=!1;const a=new WeakSet,o={schedule:(e,s=!1,o=!1)=>{const l=o&&r,c=l?t:i;return s&&a.add(e),-1===c.indexOf(e)&&(c.push(e),l&&r&&(n=t.length)),e},cancel:e=>{const t=i.indexOf(e);-1!==t&&i.splice(t,1),a.delete(e)},process:l=>{if(r)s=!0;else{if(r=!0,[t,i]=[i,t],i.length=0,n=t.length,n)for(let i=0;i<n;i++){const n=t[i];n(l),a.has(n)&&(o.schedule(n),e())}r=!1,s&&(s=!1,o.process(l))}}};return o}(()=>cx=!0),e),{}),mx=ux.reduce((e,t)=>{const i=px[t];return e[t]=(e,t=!1,n=!1)=>(cx||yx(),i.schedule(e,t,n)),e},{}),gx=ux.reduce((e,t)=>(e[t]=px[t].cancel,e),{});ux.reduce((e,t)=>(e[t]=()=>px[t].process(dx),e),{});const fx=e=>px[e].process(dx),Ax=e=>{cx=!1,dx.delta=lx?sx:Math.max(Math.min(e-dx.timestamp,40),1),dx.timestamp=e,hx=!0,ux.forEach(fx),hx=!1,cx&&(lx=!1,ox(Ax))},yx=()=>{cx=!0,lx=!0,hx||ox(Ax)};function vx(e,t,i=0){return e-t-i}const _x=e=>{const t=({delta:t})=>e(t);return{start:()=>mx.update(t,!0),stop:()=>gx.update(t)}};function bx(e){var t,i,{from:n,autoplay:r=!0,driver:s=_x,elapsed:a=0,repeat:o=0,repeatType:l="loop",repeatDelay:c=0,onPlay:h,onStop:d,onComplete:u,onRepeat:p,onUpdate:m}=e,g=O_(e,["from","autoplay","driver","elapsed","repeat","repeatType","repeatDelay","onPlay","onStop","onComplete","onRepeat","onUpdate"]);let f,A,y,{to:v}=g,_=0,b=g.duration,x=!1,w=!0;const C=function(e){if(Array.isArray(e.to))return nx;if(rx[e.type])return rx[e.type];const t=new Set(Object.keys(e));return t.has("ease")||t.has("duration")&&!t.has("dampingRatio")?nx:t.has("dampingRatio")||t.has("stiffness")||t.has("mass")||t.has("damping")||t.has("restSpeed")||t.has("restDelta")?V_:nx}(g);null!==(i=(t=C).needsInterpolation)&&void 0!==i&&i.call(t,n,v)&&(y=Ob([0,100],[n,v],{clamp:!1}),n=0,v=100);const S=C(Object.assign(Object.assign({},g),{from:n,to:v}));function M(){_++,"reverse"===l?(w=_%2==0,a=function(e,t,i=0,n=!0){return n?vx(t+-e,t,i):t-(e-t)+i}(a,b,c,w)):(a=vx(a,b,c),"mirror"===l&&S.flipTarget()),x=!1,p&&p()}function E(e){w||(e=-e),a+=e;const t=Math.max(0,a);if(!x||t<=(b||0)){const e=S.next(t);A=e.value,y&&(A=y(A)),x=w?e.done:a<=0}m?.(A),x&&(0===_&&(b??(b=a)),_<o?function(e,t,i,n){return n?e>=t+i:e<=-i}(a,b,c,w)&&M():(f.stop(),u&&u()))}return r&&(h?.(),f=s(E),f.start()),{stop:()=>{d?.(),f.stop()}}}const xx={linear:e=>e,easeIn:zb,easeOut:Gb,easeInOut:Qb,circIn:Vb,circOut:Hb,circInOut:Wb,backIn:qb,backOut:Xb,backInOut:Yb,anticipate:Kb,bounceOut:ex,bounceIn:tx,bounceInOut:e=>e<.5?.5*(1-ex(1-2*e)):.5*ex(2*e-1)+.5,easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2};function wx(e,t,i){const n=e[t],r=()=>{i?.()},s="boolean"==typeof n;return n&&n.isColor?e=>{n.set(e),r()}:n&&"function"==typeof n.copy?e=>{n.copy(e),r()}:i=>{e[t]=s?!!i:i,r()}}async function Cx(e,t){const i=e.onComplete,n=e.onStop,r=e.onEnd;return e={...e},new Promise((s,a)=>{const o=()=>{try{r?.()}catch(e){return a(e),!1}return!0};e.onComplete=()=>{try{i?.()}catch(e){if(!o())return;return void a(e)}o()&&s()},e.onStop=()=>{try{n?.()}catch(e){if(!o())return;return void a(e)}o()&&s()};const l=bx(e);t&&t.push(l)})}function Sx(e,t,i){const n=t-e;return n>=Math.PI?e+(n-2*Math.PI)*i:n<=-Math.PI?e+(n+2*Math.PI)*i:e+n*i}const Mx=gi.lerp;function Ex({from:e,autoplay:t=!0,driver:i,elapsed:n=0,onPlay:r,onStop:s,onComplete:a,onUpdate:o,delay:l=0,canComplete:c=!0,...h}){const{to:d}=h;let u;const p=h.duration||0;let m,g=!1;const f=nx({...h,from:e,to:d});function A(e){const t=n>=l;if((n+=e)<l&&!t)return;const i=Math.max(0,n-l);if(!g||i<=(p||0)){const e=f.next(i);m=e.value,g=e.done}o?.(m),g&&c&&(u.stop(),a&&a())}return t&&(r?.(),u=i(A),u.start()),{stop:()=>{s?.(),u.stop()}}}function Tx(e){const t=e.position.clone();t.sub(e.target);const i=(new Sp).setFromVector3(t);return i.makeSafe(),i}function Ix(e,t){const i=e.parent,n=e.target.clone(),r=e.getWorldPosition(new Xi),s={target:n,zoom:e.zoom,spherical:Tx({position:r,target:n})},a={position:new Xi,target:new Xi,zoom:1,spherical:new Sp},o={position:t.position,target:t.target,zoom:t.zoom,spherical:Tx(t)};function l(){e.position.copy(i?i.worldToLocal(a.position):a.position),e.target.copy(a.target),e.zoom=a.zoom,e.setDirty()}return{from:0,to:1,onUpdate:e=>{a.spherical.phi=Sx(s.spherical.phi,o.spherical.phi,e),a.spherical.theta=Sx(s.spherical.theta,o.spherical.theta,e),a.spherical.radius=Mx(s.spherical.radius,o.spherical.radius,e),a.target.copy(s.target).lerp(o.target,e),a.position.setFromSpherical(a.spherical),a.position.add(a.target),a.zoom=Mx(s.zoom,o.zoom,e),l()},onComplete:()=>{a.position.copy(o.position),a.target.copy(o.target),a.zoom=o.zoom,l()},onStop:()=>{throw new Error("Animation Stopped")}}}function Px(e,t){const i=e.parent,n=e.target.clone(),r={position:e.getWorldPosition(new Xi),target:n,quaternion:e.getWorldQuaternion(new qi),zoom:e.zoom},s={position:new Xi,target:new Xi,quaternion:new qi,zoom:1},a=t;function o(){e.position.copy(i?i.worldToLocal(s.position):s.position),e.target.copy(s.target),e.quaternion.copy(i?Jy(i,s.quaternion,e.quaternion):s.quaternion),e.zoom=s.zoom,e.setDirty()}return{from:0,to:1,onUpdate:e=>{s.position.lerpVectors(r.position,a.position,e),s.target.lerpVectors(r.target,a.target,e),s.quaternion.slerpQuaternions(r.quaternion,a.quaternion,e),s.zoom=Mx(r.zoom,a.zoom,e),o()},onComplete:()=>{s.position.copy(a.position),s.target.copy(a.target),s.quaternion.copy(a.quaternion),s.zoom=a.zoom,o()},onStop:()=>{throw new Error("Animation Stopped")}}}function Dx(e,t,i){return"number"==typeof t&&"number"==typeof i?Rx(e,t,i):"number"==typeof t?.r&&"number"==typeof i?.r?(new mr).set(Rx(e.from?{...e,from:e.from.r}:e,t.r,i.r),Rx(e.from?{...e,from:e.from.g}:e,t.g,i.g),Rx(e.from?{...e,from:e.from.b}:e,t.b,i.b)):t?.toArray&&i?.toArray&&t.clone&&t.fromArray?Bx(e,t,i):e.t>=1?i:t}function Rx(e,t,i){const{t:n,dt:r}=e;let s;if(n<=0)s=void 0!==e.from?e.from:t;else if(n>=1)s=i;else if(void 0!==e.from)s=e.from*(1-n)+i*n;else{const e=1-n;s=t+(i-t)*Math.max(0,Math.min(r,e)/e)}return s}function Bx(e,t,i){const n=t.toArray(),r=i.toArray(),s=e.from?e.from.toArray():void 0,a=n.map((t,i)=>Dx(s?{...e,from:s[i]}:e,t,r[i]));return t.clone().fromArray(a)}function Lx(e,t,i){if(!e.rm)return console.warn("MaterialManager: RenderManager is required for interpolating textures"),i;const{t:n,dt:r}=e;let s;const a=void 0!==e.from?e.from:t;if(n<=0||n>.99||a===i){let r;s=n<=0?a:i,t&&t.userData?._lerpTexture&&t.isRenderTargetTexture&&(r=t._target),r&&e.rm.releaseTempTarget(r)}else{const o=a||hv;let l,c=!1;if(t&&t.userData?._lerpTexture&&t.isRenderTargetTexture)l=t._target;else{const t=a||i||hv,n={width:t.image?.width||t.image?.naturalWidth||t.image?.videoWidth||1,height:t.image?.height||t.image?.naturalHeight||t.image?.videoHeight||1};l=e.rm.getTempTarget({size:n,colorSpace:t.colorSpace,type:t.type,format:t.format,generateMipmaps:t.generateMipmaps,minFilter:t.minFilter,magFilter:t.magFilter,wrapS:t.wrapS,wrapT:t.wrapT}),l.texture.userData._lerpTexture=!0,c=!0}if(l){(void 0!==e.from||c)&&e.rm.blit(l,{source:o,respectColorSpace:!1,transparent:!0,clear:!0});const t=1-n,a=Math.max(0,Math.min(r,t)/t);e.rm.blit(l,{source:i||hv,respectColorSpace:!1,transparent:!0,clear:!1,blendAlpha:void 0!==e.from?n:a}),s=l.texture}else s=t}return s}function Ox(e,t,i,n){for(const r of Object.keys(e)){if(!i.has(r))continue;const s=t[r];if(void 0===s)continue;const a=n.from?{...n,from:n.from[r]}:n,o=e[r];if("number"==typeof s&&"number"==typeof o){const t=Rx(a,s,o);t===s?delete e[r]:e[r]=t}if(s?.isColor&&o?.isColor){const t=Dx(a,s,o);t.getHex()===s.getHex()?delete e[r]:e[r]=t}if((null==s||s.isTexture)&&(null==o||o.isTexture)&&(s||o)){const t=Lx(a,s||null,o||null);t===s?delete e[r]:e[r]=t}if(s?.toArray&&o?.toArray&&s.clone&&s.fromArray&&s.equals){const t=Bx(a,s,o);t.equals(s)?delete e[r]:e[r]=t}if(Array.isArray(s)&&Array.isArray(o)&&s.length===o.length){const t=s.map((e,t)=>Dx(a,e,o[t]));t.every((e,t)=>e===s[t])?delete e[r]:e[r]=t}}}function Ux(e,t){return e.multiplyScalar(e.w*t),e.w=1,e}function Fx(e,t){const i=Math.max(e.x,Math.max(e.y,e.z));let n=Math.max(Math.min(i/t,1),0);return n=Math.ceil(255*n)/255,e.divideScalar(n*t),e.w=n,e}function kx(){return navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}const Nx=class{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 r=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))),r.width=Math.floor(t.width*n*i),r.height=Math.floor(t.height*n*i);const s=r.getContext("2d");if(!s)return console.error("snapshot: cannot create context"),r;const a=e.style.background||e.parentElement?.style.background||"";if(a.includes("url")){const n=/url\("(.*)"\)/gi.exec(a)?.[1];if(n){const a=new Image;a.src=n,await new Promise((e,t)=>{a.onload=()=>e(),a.onerror=()=>t(),a.complete&&e()}),s.drawImage(a,Math.floor(a.width*t.x*i/e.width),Math.floor(a.height*t.y*i/e.height),Math.floor(a.width*t.width*i/e.width),Math.floor(a.height*t.height*i/e.height),0,0,r.width,r.height)}}else s.fillStyle=e.style.background||e.parentElement?.style.backgroundColor||"#00000000",s.fillRect(0,0,r.width,r.height);return s?.drawImage(e,Math.floor(t.x*i),Math.floor(t.y*i),Math.floor(t.width*i),Math.floor(t.height*i),0,0,r.width,r.height),this.Debug&&(document.body.appendChild(r),r.style.position="absolute",r.style.top="0",r.style.left="0",r.style.borderWidth="2px",r.style.borderColor="#ff00ff",setTimeout(()=>r.remove(),5e3)),r}static async GetDataUrl(e,{mimeType:t="image/png",quality:i,...n}){const r=kx()||n.cloneCanvas||n.rect||n.scale||n.displayPixelRatio;!r&&(n.rect||n.scale||n.displayPixelRatio)&&console.warn("CanvasSnapshot: rect, scale and displayPixelRatio are ignored when cloneCanvas is false");const s=r?await this.GetClonedCanvas(e,n):e,a=s.toDataURL(t,i);return!this.Debug&&s!==e&&s.remove(),a}static async GetImage(e,t={}){const i=await this.GetDataUrl(e,t);return new Promise((e,t)=>{const n=new Image;n.onload=()=>e(n),n.onerror=()=>t(),n.src=i})}static async GetBlob(e,t={}){const i=kx()||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,r=await new Promise((e,i)=>{n.toBlob(t=>{t?e(t):i(new Error("CanvasSnapshot Failed to export blob from canvas"))},t.mimeType??"image/png",t.quality)});return!this.Debug&&n!==e&&n.remove(),r}static async GetFile(e,t="image",i={}){const n="."+(i.mimeType?.split("/")[1]?.toLowerCase()||"png"),r=t.toLowerCase().endsWith(n)?t:t+n;return i.getDataUrl?await this.GetDataUrl(e,i):new File([await this.GetBlob(e,i)],r,{type:i.mimeType??"image/png",lastModified:$p()})}static async GetTiledFiles(e,t="image",i=2,n=2,r={}){const s=r.rect??{x:0,y:0,width:1,height:1,assumeClientRect:!1,normalized:!0},a=[];for(let o=0;o<n;o++)for(let l=0;l<i;l++){const c=r.mimeType?.split("/")[1]??"png",h=await this.GetFile(e,`${t}_${o}_${l}.${c}`,{rect:{x:s.x+o*s.width/n,y:s.y+l*s.height/i,width:s.width/n,height:s.height/i,assumeClientRect:s.assumeClientRect,normalized:s.normalized}}).catch(e=>(console.error(`CanvasSnapshot - Error exporting tiled file ${o}, ${l}`,e),null));h&&a.push(h)}return a}};Nx.Debug=!1;let jx=Nx;var zx=Object.defineProperty,Gx=Object.getOwnPropertyDescriptor,Qx=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?Gx(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&zx(t,i,s),s};const Vx={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 Hx(e,t){let i,n=Array.from((e.access??"").split(new RegExp("(?<!\\\\)\\."))),r=e.targetObject;const s=n.pop()?.replace(/\\\./g,".");if(!s||0===s.length)return{key:void 0,tar:r};t=t??r?._animGetters;const a=n.length>=1?n[0]:void 0,o=n.length>=2?n[1]?.replace(/\\\./g,"."):void 0;if(t&&a&&a in t&&o){n=n.slice(2);const e=t[a](o,n);e?(r=e.tar,n=e.acc,i=e.onChange??i):r=e}return r=Lm(n,r),{key:s,tar:r,onChange:i}}function Wx(e){return{processObject:t=>{const i=Im(e);if(i&&!1!==t.userData.autoRegisterInManager&&(i.object3dManager.registerObject(t),t.material)){if(!i.assetManager)return void console.error("AssetManager is not initialized yet, cannot register material",t.material);const e=Array.isArray(t.material)?t.material:[t.material];for(const t of e)!1!==t.userData.autoRegisterInManager&&i.assetManager.materials.registerMaterial(t)}}}}function qx(e,{autoCenter:t=!1,centerGeometries:i=!1,centerGeometriesKeepPosition:n=!0,autoScale:r=!1,autoScaleRadius:s=2,license:a}){a&&(e.userData.license=[e.userData.license,a].filter(e=>e).join(", "));const o=()=>{!t||e.userData.isCentered||e.userData.pseudoCentered||e.isLight?e.userData.isCentered=!0:e.autoCenter&&e.autoCenter(),!r||e.userData.autoScaled||e.isLight?e.userData.autoScaled=!0:e.autoScale&&e.autoScale(e.userData.autoScaleRadius||s),i&&!e.userData.geometriesCentered&&Xx(e,n),e.userData.geometriesCentered=!0};e._loadingPromise?e._loadingPromise.finally(o):o()}function Xx(e,t){const i=new Set;e.traverseModels&&e.traverseModels(e=>{e.geometry&&i.add(e.geometry)},{visible:!1,widgets:!1});const n=[];return i.forEach(e=>n.push(e.center2(void 0,t))),()=>n.forEach(e=>e())}e.AnimationObject=class extends ri{constructor(e,t,i=""){super(),this.uuid=Ky(),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 e=this.targetObject;e&&"function"==typeof e.setDirty&&e.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(Vx).map(([e,t])=>({label:e,value:t}))},()=>this.values.flatMap((e,t)=>[{...Dg(this.values,t+"",void 0,e),label:0===t?"From":t===this.values.length-1?"To":"Key "+t,onChange:()=>this.setDirty()},t>0&&t<this.values.length-1?{type:"number",label:"Offset "+t,property:[this.offsets,t+""],bounds:[0,1],onChange:()=>this.setDirty()}:null]),Rg(this)],uuid:Ky()},this.target=e,this.viewer=t,this.name=i,this.dispatchEvent=this.dispatchEvent.bind(this)}get targetObject(){return Im(this.target)??this.parent?.targetObject}getViewer(){return this.viewer?Im(this.viewer):this.parent?.getViewer()}fromJSON(e,t){let i={...e};return void 0!==i.access&&(this.access=i.access,delete i.access),void 0!==i.from&&(i={...i},i.values=[i.from,i.to],i.offsets=[0,1],delete i.from,delete i.to),f_.Deserialize(i,this,t,!0),this.animSet.map(e=>{e.parent=this}),this}_onAccessChanged(){const e=this.targetObject;if(!e||e!==this.getViewer()||Object.values(Vx).includes(this.access)){if(e&&e===this.getViewer()&&"scene.environment.rotation"===this.access)this.access="scene.environmentRotation.y";else if(e&&e===this.getViewer()&&"scene.envMapIntensity"===this.access)this.access="scene.environmentIntensity";else if(this.access!==this._lastAccess||!this.values.length||this._lastTarget!==e&&e&&this._lastTarget){this._lastAccess=this.access;const e=this.values;this.values=[],this.offsets=[];const t=this._thisValueCloner();if(!t)return void this.refreshUi();this.values=[t(),t()],e.length>=2&&typeof e[0]==typeof this.values[0]&&("object"!=typeof e[0]||e[0].type&&e[0].type===this.values[0]?.type)&&(this.values=e),this.offsets=this.offsets.length===this.values.length?this.offsets:[0,1],this.refreshUi()}}else this.access=""}_thisValueCloner(){const{key:e,tar:t}=Hx(this),i=t&&void 0!==e?t[e]:null;return null==i?null:()=>i&&(i.isColor?"#"+i.getHexString():"function"==typeof i.clone?i.clone():"object"==typeof i?{...i}:i)}addKeyframe(e){if(this.values.length<2)return void console.warn("AnimationObject: Values not initialized, cannot add keyframe",this);const t=this._thisValueCloner();if(!t)return void console.warn("AnimationObject: No value to add keyframe for",this);const i=e-this.delay,n=this.duration,r=this.delay,s=[...this.offsets],a=[...this.values];let o,l=i/this.duration,c=n,h=r;const d=[...this.values],u=[...this.offsets];if(l<0){const e=-l;l=0;for(let t=0;t<s.length;t++)u[t]=(s[t]+e)/(1+e);c=n-i,h=r+i,o=0}else if(l>1){const e=l-1;l=1;for(let t=0;t<s.length;t++)u[t]=s[t]/(1+e);c=i,o=s.length}else if(o=s.findIndex(e=>e>=l),o<0)o=this.offsets.length;else if(this.offsets[o]===l)return void console.warn("AnimationObject: Keyframe already exists at offset",l,this);const p=t();d.splice(o,0,p),u.splice(o,0,l);const m=()=>{this.duration=c,this.delay=h,this.values=d,this.offsets=u,this.setDirty()};return m(),{undo:()=>{this.duration=n,this.delay=r,this.values=a,this.offsets=s,this.setDirty()},redo:m}}updateKeyframe(e){if(e<0||e>=this.values.length)return void console.warn("AnimationObject: Invalid keyframe index",e,this);const t=this._thisValueCloner();if(!t)return void console.warn("AnimationObject: No value to update keyframe for",this);const i=this.values[e],n=t(),r=()=>{this.values[e]=n,this.setDirty()};return r(),{undo:()=>{this.values[e]=i,this.setDirty()},redo:r}}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("object"==typeof i&&"object"==typeof n){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){("number"!=typeof e||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 e=Ky();return{id:e,options:this.options,stop:()=>{},promise:Promise.resolve(e),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 t=new e.AnimationObject(this.target);return this.add(t),t}},Qx([qm(),Qm("setDirty")],e.AnimationObject.prototype,"name",2),Qx([qm(),Qm(e.AnimationObject.prototype._onAccessChanged)],e.AnimationObject.prototype,"access",2),Qx([qm()],e.AnimationObject.prototype,"values",2),Qx([qm()],e.AnimationObject.prototype,"offsets",2),Qx([qm()],e.AnimationObject.prototype,"options",2),Qx([qm(),Fg(void 0,[0,1e4],1,e=>({hidden:()=>!e.access})),Qm("setDirty")],e.AnimationObject.prototype,"duration",2),Qx([qm(),Fg(void 0,[0,1e4],1,e=>({hidden:()=>!e.access})),Qm("setDirty")],e.AnimationObject.prototype,"delay",2),Qx([qm(),Qm("setDirty")],e.AnimationObject.prototype,"repeat",2),Qx([qm(),Qm("setDirty")],e.AnimationObject.prototype,"repeatDelay",2),Qx([qm(),Qm("setDirty")],e.AnimationObject.prototype,"repeatType",2),Qx([qm(),Ng("ease",Object.keys(xx).map(e=>({label:e})),e=>({hidden:()=>!e.access})),Qm("setDirty")],e.AnimationObject.prototype,"ease",2),Qx([qm(),Hg(void 0,e=>({hidden:()=>!e.access})),Qm("setDirty")],e.AnimationObject.prototype,"updateScene",2),Qx([qm(),Hg(void 0,e=>({hidden:()=>!e.access})),Qm("setDirty")],e.AnimationObject.prototype,"updateCamera",2),Qx([qm(),Hg(void 0,e=>({hidden:()=>!e.access})),Qm("setDirty")],e.AnimationObject.prototype,"updateViewer",2),Qx([qm(),Qm("setDirty")],e.AnimationObject.prototype,"updateTarget",2),Qx([Qm(e.AnimationObject.prototype._onAccessChanged)],e.AnimationObject.prototype,"target",2),Qx([Qm(e.AnimationObject.prototype._onAccessChanged)],e.AnimationObject.prototype,"viewer",2),Qx([jg("Animate")],e.AnimationObject.prototype,"animate",1),Qx([jg("Stop")],e.AnimationObject.prototype,"stop",1),Qx([jg("Delete")],e.AnimationObject.prototype,"removeFromParent2",1),Qx([qm()],e.AnimationObject.prototype,"animSetParallel",2),Qx([qm()],e.AnimationObject.prototype,"animSet",2),e.AnimationObject=Qx([Xm("AnimationObject")],e.AnimationObject);class Yx extends lu{constructor(e){super(e),this.responseType="blob"}load(e,t,i,n){return super.load(e,e=>{try{t?.(xm(e))}catch(e){n?.(e)}},i,n)}}var Kx=Object.defineProperty,Jx=Object.getOwnPropertyDescriptor,Zx=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?Jx(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&Kx(t,i,s),s};const $x=e=>({onChange:t=>{t.last&&e.onChange()}});e.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 t=this.onChange;Object.assign(this,new e.TextSVGOptions),this.onChange=t}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}}},Zx([zg("Text",$x)],e.TextSVGOptions.prototype,"text",2),Zx([Fg("Font Size",[2,1024],1,$x)],e.TextSVGOptions.prototype,"fontSize",2),Zx([Fg("Width",[2,4096],1,$x)],e.TextSVGOptions.prototype,"width",2),Zx([Fg("Height",[2,4096],1,$x)],e.TextSVGOptions.prototype,"height",2),Zx([Fg("X Offset",[-1024,1024],1,$x)],e.TextSVGOptions.prototype,"xOffset",2),Zx([Fg("Y Offset",[-1024,1024],1,$x)],e.TextSVGOptions.prototype,"yOffset",2),Zx([Fg("V-Width",[2,4096],1,$x)],e.TextSVGOptions.prototype,"boxWidth",2),Zx([Fg("V-Height",[2,4096],1,$x)],e.TextSVGOptions.prototype,"boxHeight",2),Zx([Ng("Text Anchor",["start","middle","end"].map(e=>({label:e})),$x)],e.TextSVGOptions.prototype,"textAnchor",2),Zx([zg("Font",$x)],e.TextSVGOptions.prototype,"fontFamily",2),Zx([zg("Font Url",$x)],e.TextSVGOptions.prototype,"fontPath",2),Zx([zg("Font Weight",$x)],e.TextSVGOptions.prototype,"fontWeight",2),Zx([Ng("Font Style",["normal","italic","oblique"].map(e=>({label:e})),$x)],e.TextSVGOptions.prototype,"fontStyle",2),Zx([zg("Line Height",$x)],e.TextSVGOptions.prototype,"lineHeight",2),Zx([zg("Letter Spacing",$x)],e.TextSVGOptions.prototype,"letterSpacing",2),Zx([Ng("White Space",["normal","pre","nowrap","pre-wrap","pre-line"].map(e=>({label:e})),$x)],e.TextSVGOptions.prototype,"whiteSpace",2),Zx([Ng("Direction",["auto","ltr","rtl"].map(e=>({label:e})),$x)],e.TextSVGOptions.prototype,"direction",2),Zx([Hg("Mask Text",$x)],e.TextSVGOptions.prototype,"maskText",2),Zx([Hg("Inner Shadow",$x)],e.TextSVGOptions.prototype,"innerShadow",2),Zx([zg("Text Color",$x)],e.TextSVGOptions.prototype,"textColor",2),Zx([zg("BG Fill",$x)],e.TextSVGOptions.prototype,"bgFillColor",2),Zx([zg("SVG BG",$x)],e.TextSVGOptions.prototype,"svgBackground",2),e.TextSVGOptions=Zx([qg("Text SVG Options")],e.TextSVGOptions);const ew={woff:"woff",woff2:"woff2",ttf:"truetype",otf:"opentype",eot:"embedded-opentype"};function tw({text:e="Custom Text",svgBackground:t="#ffffff",xOffset:i=0,yOffset:n=0,width:r=1024,height:s=1024,boxWidth:a=1024,boxHeight:o=1024,fontFamily:l="",fontSize:c=32,fontWeight:h="normal",fontStyle:d="normal",lineHeight:u="normal",letterSpacing:p="normal",whiteSpace:m="normal",direction:g="auto",maskText:f=!1,innerShadow:A=!1,bgFillColor:y="#000000",textColor:v="#ffffff",textAnchor:_="middle",style:b=""}){return`\n<svg style="background-color:${t}" width="${r}" height="${s}" viewBox="0 0 ${a} ${o}"\n xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n     <defs>\n        <style>\n        ${b}\n        .text-g{\n            overflow:hidden; text-anchor: ${_}; \n            font-size: ${c}px;\n            font-family: ${JSON.stringify(l||"Arial")};\n            font-weight: ${h};\n            font-style: ${d};\n            line-height: ${u};\n            letter-spacing: ${p};\n            white-space: ${m};\n            direction: ${g};\n        }\n        </style>\n    </defs>\n\n    <g class="text-g">\n        <defs>\n\n`+(f?`\n<mask id="textMask">\n<text style="fill:white; font-size: ${c}px; font-weight: ${h}; font-style: ${d}; line-height: ${u}; letter-spacing: ${p}; white-space: ${m}; direction: ${g};" x="${i+a/2}" y="${o/2+n+c/4}" > ${e} </text>\n</mask>\n`:"")+"\n\n"+(A?'\n<filter id="innerShadow" x="-20%" y="-20%" width="140%" height="140%">\n<feGaussianBlur in="SourceGraphic" stdDeviation="0.5" result="blur"/>\n<feOffset in="blur" dx="1.5" dy="1.5"/>\n</filter>\n':"")+"\n\n        </defs>\n\n"+(f?'\n        <g mask="url(#textMask)">\n':"")+`\n\n        <rect x="0" y="0" width="${a}" height="${o}" style="fill:${y}"/>\n        <text style="${A?"filter: url(#innerShadow);":""} fill:${v}; font-weight: ${h}; font-style: ${d}; line-height: ${u}; letter-spacing: ${p}; white-space: ${m}; direction: ${g};" x="${i+a/2}" y="${o/2+n+c/4}"> ${e} </text>\n\n`+(f?"\n        </g>\n":"")+"\n\n    </g>\n</svg>\n"}const iw={roboto:"https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2"};const nw=class extends ri{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=f_.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:(f_.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}};nw.PluginType="AViewerPlugin";let rw=nw;class sw extends rw{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}}function aw(){return[{type:"checkbox",label:"Auto LookAt Target",getValue:()=>this.userData.autoLookAtTarget??!1,setValue:e=>{this.userData.autoLookAtTarget=e,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??nC.defaultMinNear,setValue:e=>{e===nC.defaultMinNear?delete this.userData.minNearPlane:this.userData.minNearPlane=e}},{type:"number",label:"Max Far",hidden:()=>!this.autoNearFar,getValue:()=>this.userData.maxFarPlane??nC.defaultMaxFar,setValue:e=>{e===nC.defaultMaxFar?delete this.userData.maxFarPlane:this.userData.maxFarPlane=e}},{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(e=>({label:""===e?"none":e,value:e})),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 ow(t){if(!this)return{};if(this.uiConfig)return this.uiConfig;const i={type:"folder",label:()=>this.name||"unnamed",expanded:!0,onChange:e=>{if(!e.config||e.config.onChange)return;let t=Array.isArray(e.config.property)?e.config.property[1]:e.config.property;t="string"==typeof t?t:void 0,this.setDirty&&this.setDirty({uiChangeEvent:e,refreshScene:!1,refreshUi:!!e.last,change:t})},children:[{type:"checkbox",label:"Visible",property:[this,"visible"],onChange:e=>{this.setDirty?.({uiChangeEvent:e,refreshScene:!0,refreshUi:!0,change:"visible"})}},{type:"input",property:[this,"uuid"],disabled:!0,tags:["advanced"]},{type:"input",label:"Name",property:[this,"name"],onChange:e=>{e.last&&this.setDirty?.({uiChangeEvent:e,refreshScene:!0,frameFade:!1,refreshUi:!0,change:"name"})}},{type:"checkbox",label:"Casts Shadow",hidden:()=>!this.isMesh,property:[this,"castShadow"],onChange:e=>{this.setDirty?.({uiChangeEvent:e,refreshScene:!0,refreshUi:!0,change:"castShadow"})}},{type:"checkbox",label:"Receive Shadow",hidden:()=>!this.isMesh,property:[this,"receiveShadow"],onChange:e=>{this.setDirty?.({uiChangeEvent:e,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 e.ThreeViewer.Dialog.prompt("Auto Scale Radius: Object will be scaled to the given radius",t);if(null===i)return;const n=parseFloat(i||t);return Math.abs(n)>0?{action:()=>this.autoScale?.(n),undo:()=>this.autoScale?.(n,void 0,void 0,!0)}:void 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 e.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)}},...hw.call(this),{type:"folder",label:"Rotate model",children:["X +","X -","Y +","Y -","Z +","Z -"].map(e=>({type:"button",label:"Rotate "+e+"90",value:()=>{const t=new Xi(e.includes("X")?1:0,e.includes("Y")?1:0,e.includes("Z")?1:0),i=Math.PI/2*(e.includes("-")?-1:1);return{action:()=>{this.rotateOnAxis(t,i),this.setDirty?.({refreshScene:!0,refreshUi:!1})},undo:()=>{this.rotateOnAxis(t,-i),this.setDirty?.({refreshScene:!0,refreshUi:!1})}}}}))},void 0!==this.userData.license?{type:"input",label:"License/Credits",property:[this.userData,"license"]}:{}]};if((this.isLine||this.isMesh)&&!1!==t){const e=[()=>{const e=Object.entries(this.morphTargetDictionary||{});return e.length?{label:"Morph Targets",type:"folder",children:e.map(([e,t])=>({type:"slider",label:e,bounds:[0,1],stepSize:1e-4,property:[this.morphTargetInfluences,t],onChange:e=>{this.setDirty?.({refreshScene:e.last,frameFade:!1,refreshUi:!1})}}))}:void 0},{type:"divider"}];i.children.push(...e)}if(this.isCamera){const e=aw.call(this);i.children.push(...e)}return i.children.push(lw.call(this)),this.uiConfig=i,i}function lw(){return e=>this.objectExtensions?.flatMap(t=>(t.uuid=t.uuid||Ky(),this.__objExtUiConfigs=this.__objExtUiConfigs||{},this.__objExtUiConfigs[t.uuid]||(this.__objExtUiConfigs[t.uuid]=t.getUiConfig?t.getUiConfig(this,this.uiConfig?.uiRefresh):void 0),this.__objExtUiConfigs[t.uuid]?.flatMap(t=>Im(t,e)))).filter(e=>e)}function cw(e,t,i){const n=(i=i??e.name).match(/\(copy( (\d+))?\)$/);if(n){let r=n[2]?parseInt(n[2])+1:2,s=i.replace(/\(copy( \d+)?\)$/,`(copy ${r})`);const a=e.parent;if(a&&a!==t.parent){const t=new Set(a.children.filter(t=>t!==e).map(e=>e.name));for(let e=0;e<1e3&&t.has(s);e++)r++,s=i.replace(/\(copy( \d+)?\)$/,`(copy ${r})`)}t.name=s}else t.name=i+" (copy)"}function hw(){return[{type:"button",label:"Duplicate Object",tags:["context-menu"],value:async e=>qw.duplicateObject(this,e)},{type:"button",label:"Delete Object",tags:["context-menu"],value:async e=>qw.deleteObject(this,e)}]}const dw={setDirty:function(e){this.dispatchEvent({bubbleToObject:!0,...e,type:"geometryUpdate",geometry:this}),this.refreshUi()},refreshUi:function(){this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},dispose:e=>function(t=!0){!t&&!1===this.userData.disposeOnIdle||e.call(this)},clone:e=>function(){return dw.upgradeGeometry.call(e.call(this))},upgradeGeometry:function(){return"geometry"===this.assetType?this:this.isBufferGeometry?(this.assetType="geometry",this.dispose=dw.dispose(this.dispose),this.center=dw.center(this.center),this.clone=dw.clone(this.clone),this.center2||(this.center2=dw.center2),this.setDirty||(this.setDirty=dw.setDirty),this.refreshUi||(this.refreshUi=dw.refreshUi),this.appliedMeshes||(this.appliedMeshes=new Set),this.userData||(this.userData={}),this.uiConfig=dw.makeUiConfig.call(this),this):(console.error("Geometry is not a BufferGeometry",this),this)},center:e=>function(t,i=!1,n=!0){if(i){t=t?t.clone():new Xi,e.call(this,t),t.negate();const i=this.appliedMeshes;for(const e of i)e.updateMatrix(),e.position.copy(t).applyMatrix4(e.matrix),n&&e.setDirty&&e.setDirty()}else e.call(this,t);return n&&this.setDirty(),this},center2:function(e,t=!1,i=!0){const n=e||new Xi;if(t){this.center(n,!1,!1);const e=this.appliedMeshes,t=new WeakMap;for(const r of e)r.updateMatrix(),t.set(r,r.position.clone()),r.position.set(-n.x,-n.y,-n.z).applyMatrix4(r.matrix),i&&r.setDirty&&r.setDirty();return i&&this.setDirty&&this.setDirty(),()=>{for(const n of e){const e=t.get(n);e?(n.position.copy(e),i&&n.setDirty&&n.setDirty()):console.warn("GeometryCommons: No position found for mesh",n)}i&&this.setDirty&&this.setDirty()}}return this.center(n,!1,!1),i&&this.setDirty&&this.setDirty(),()=>{this.translate(-n.x,-n.y,-n.z),i&&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((e,t)=>({type:"folder",label:`Group ${t}`,uuid:"group-"+t,tags:["advanced"],children:[{type:"input",label:"Start",uuid:"start",getValue:()=>e.start,setValue:t=>{e.start=t,this.setDirty&&this.setDirty()}},{type:"input",label:"Count",uuid:"count",getValue:()=>e.count,setValue:t=>{e.count=t,this.setDirty&&this.setDirty()}},{type:"input",label:"Material Index",uuid:"mi",getValue:()=>e.materialIndex,setValue:t=>{e.materialIndex=t,this.setDirty&&this.setDirty()}}]}))}:null,{type:"divider"},{type:"button",label:"Center Geometry",tags:["context-menu"],value:async()=>{if(await e.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 e.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 e.ThreeViewer.Dialog.confirm("Normals already exist, replace with computed normals?\nThis 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 e.ThreeViewer.Dialog.confirm("Tangents already exist, replace with computed tangents?\nThis 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;Yy(this,parseFloat(await e.ThreeViewer.Dialog.prompt("Convert to Indexed: Tolerance?","-1")??"-1")),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 e.ThreeViewer.Dialog.confirm("uv1 already exists, replace with uv data?\nThis 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()=>{this.hasAttribute("color")?await e.ThreeViewer.Dialog.confirm("Remove color attribute?")&&(this.deleteAttribute("color"),this.setDirty&&this.setDirty()):await e.ThreeViewer.Dialog.alert("No color attribute found")}},{type:"button",label:"Auto GPU Instances",hidden:()=>!this.appliedMeshes||this.appliedMeshes.size<2,tags:["context-menu"],value:async()=>{await e.ThreeViewer.Dialog.confirm("This will automatically create Instanced Mesh from geometry instances. This action is irreversible, do you want to continue?")&&gv(this)}},{type:"input",label:"Mesh count",getValue:()=>this.appliedMeshes?.size??0,disabled:!0}]}}};const uw=class{static ApplyMaterialExtensions(e,t,i,n){for(const r of i)this.ApplyMaterialExtension(e,t,r,n)}static ApplyMaterialExtension(e,t,i,n){let r=Im(i.parsFragmentSnippet,n,e)??"";r.length&&(t.fragmentShader=R_(t.fragmentShader,this.VoidMain,"\n"+r+"\n",{prepend:!0})),r=Im(i.parsVertexSnippet,n,e)??"",r.length&&(t.vertexShader=R_(t.vertexShader,this.VoidMain,"\n"+r+"\n",{prepend:!0})),i.extraUniforms&&(t.uniforms=Object.assign(t.uniforms,Um(i.extraUniforms,e=>Im(e,t)||{value:null}))),i.extraDefines&&mw(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+=Im(t.computeCacheKey,e):i+=t.uuid,t.extraDefines&&(i+=Object.values(t.extraDefines).map(e=>Im(e)??"").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)||void 0!==n.isCompatible&&(!n.isCompatible||!n.isCompatible(e))||(i.push(n),n.uuid||(n.uuid=Ky()),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((e,t)=>(t.priority||0)-(e.priority||0)),e.__extListen||(e.__extListen=!0,e.addEventListener("beforeRender",gw),e.addEventListener("afterRender",fw),e.addEventListener("addToMesh",Aw),e.addEventListener("removeFromMesh",yw),e.addEventListener("materialUpdate",vw));for(const t of i)t.onRegister&&t.onRegister(e);return e.needsUpdate=!0,i}static UnregisterExtensions(e,t){if(t){e.materialExtensions=e.materialExtensions?.filter(e=>!t.includes(e))||[];for(const i of t)i.onUnregister&&i.onUnregister(e)}!e.materialExtensions?.length&&e.__extListen&&(e.removeEventListener("beforeRender",gw),e.removeEventListener("afterRender",fw),e.removeEventListener("addToMesh",Aw),e.removeEventListener("removeFromMesh",yw),e.removeEventListener("materialUpdate",vw),delete e.__extListen)}};Object.assign(Ts,Tg),uw.VoidMain="void main()";let pw=uw;function mw(e,t){if(!e||!t)return;(void 0===t.defines||null===t.defines)&&(t.defines={});let i=!1;const n=Object.entries(e);for(const[e,r]of n){const n=Im(r);void 0===n?void 0!==t.defines[e]&&(delete t.defines[e],i=!0):t.defines[e]!==n&&(t.defines[e]="boolean"==typeof n?+n:n,i=!0)}i&&(t.needsUpdate=!0)}function gw({target:e,object:t,renderer:i}){const n=e,r=i;if(!n||!t||!r)throw new Error("Invalid material, object or renderer");if(n.materialExtensions)for(const e of n.materialExtensions){if(e.onObjectRender&&e.onObjectRender(t,n,r),n.lastShader){const t=Im(e.updaters)||[];for(const e of t)e&&e.updateShaderProperties(n.lastShader)}const i="_"+e.uuid+"_version";e.updateVersion!==n.userData[i]&&(n.userData[i]=e.updateVersion,n.needsUpdate=!0)}}function fw({target:e,object:t,renderer:i}){const n=e,r=i;if(!n||!t||!r)throw new Error("Invalid material, object or renderer");if(n.materialExtensions)for(const e of n.materialExtensions)e.onAfterRender&&e.onAfterRender(t,n,r)}function Aw({target:e,object:t}){const i=e;if(!i||!t)throw new Error("Invalid material or object");if(i.materialExtensions)for(const e of i.materialExtensions)e.onAddToMesh&&e.onAddToMesh(t,i)}function yw({target:e,object:t}){const i=e;if(!i||!t)throw new Error("Invalid material or object");if(i.materialExtensions)for(const e of i.materialExtensions)e.onRemoveFromMesh&&e.onRemoveFromMesh(t,i)}function vw({target:e}){const t=e;if(!t)throw new Error("Invalid material");if(t.materialExtensions)for(const e of t.materialExtensions)e.onMaterialUpdate&&e.onMaterialUpdate(t)}function _w(e,t){const i=t||Ky();return{uuid:i,getUiConfig:t=>{if(t.__uiConfigs||(t.__uiConfigs={}),t.__uiConfigs[i])return t.__uiConfigs[i];const n=e(t);return t.__uiConfigs[i]=n,n},isCompatible:()=>!0}}function bw(e,t,i,n,r=()=>e.setDirty&&e.setDirty()){return{type:"folder",label:i??t+" Sampler",hidden:()=>!e[t]||n&&n(),onChange:r,children:[()=>({type:"vec2",label:"Repeat",stepSize:.001,property:[e[t],"repeat"]}),()=>({type:"vec2",label:"Offset",stepSize:.001,property:[e[t],"offset"]}),()=>({type:"vec2",label:"Center",stepSize:.001,property:[e[t],"center"]}),()=>({type:"input",label:"Rotation",stepSize:.001,bounds:[-Math.PI,Math.PI],property:[e[t],"rotation"]}),()=>({type:"dropdown",label:"Color space",property:[e[t],"colorSpace"],children:[["Linear",Ut],["sRGB",Ot]].map(e=>({label:e[0],value:e[1]})),onChange:[()=>{const i=e[t];i&&(i.needsUpdate=!0)}]}),()=>({type:"dropdown",label:"UV Channel",property:[e[t],"channel"],children:[0,1,2,3].map(e=>({label:e.toString(),value:e})),onChange:()=>{const i=e[t];i&&(i.needsUpdate=!0)}}),()=>({type:"checkbox",label:"Flip Y",getValue:()=>e[t]?.flipY??!1,setValue:i=>{const n=e[t];if(n&&n.flipY!==i)if(n.image&&ImageBitmap&&n.image instanceof ImageBitmap){const e=n,t=n.source.data;createImageBitmap(t,{imageOrientation:"flipY"}).then(n=>{t.close&&t.close(),e.flipY=i,e.source.data=n,e.source.needsUpdate=!0,e.needsUpdate=!0,r()})}else n.flipY=i,n.needsUpdate=!0,r()}}),()=>({type:"dropdown",label:"Wrap S",property:[e[t],"wrapS"],children:[["ClampToEdge",fe],["MirroredRepeat",Ae],["Repeat",ge]].map(e=>({label:e[0],value:e[1]})),onChange:[()=>{e[t]&&(e[t].needsUpdate=!0)}]}),()=>({type:"dropdown",label:"Wrap T",property:[e[t],"wrapT"],children:[["ClampToEdge",fe],["MirroredRepeat",Ae],["Repeat",ge]].map(e=>({label:e[0],value:e[1]})),onChange:[()=>{e[t]&&(e[t].needsUpdate=!0)}]}),()=>({type:"input",label:"Anisotropy",bounds:[1,6],stepSize:1,property:[e[t],"anisotropy"],onChange:[()=>{e[t]&&(e[t].needsUpdate=!0),e.needsUpdate=!0}]}),()=>({type:"dropdown",label:"Min Filter",property:[e[t],"minFilter"],children:[["Linear",be],["Nearest",ye],["NearestMipmapNearest",ve],["NearestMipmapLinear",_e],["LinearMipmapNearest",xe],["LinearMipmapLinear",we]].map(e=>({label:e[0],value:e[1]})),onChange:[()=>{e[t]&&(e[t].needsUpdate=!0)}]}),()=>({type:"dropdown",label:"Mag Filter",property:[e[t],"magFilter"],children:[["Linear",be],["Nearest",ye]].map(e=>({label:e[0],value:e[1]})),onChange:[()=>{e[t]&&(e[t].needsUpdate=!0)}]})]}}const xw=e=>[{type:"input",property:[e,"name"]},{type:"checkbox",property:[e,"wireframe"]},{type:"checkbox",property:[e,"vertexColors"]},{type:"color",property:[e,"color"]},void 0!==e.flatShading?{type:"checkbox",property:[e,"flatShading"]}:{},{type:"image",property:[e,"map"]},bw(e,"map")],ww=e=>({type:"folder",label:"Blending",children:[{type:"slider",bounds:[0,1],property:[e,"opacity"]},{type:"checkbox",property:[e,"transparent"],onChange:t=>e.setDirty({uiChangeEvent:t,change:"transparent"})},{type:"dropdown",property:[e,"depthFunc"],children:[["Never",Y],["Always",K],["Less",J],["LessEqual",Z],["Equal",$],["GreaterEqual",ee],["Greater",te],["NotEqual",ie]].map(e=>({label:e[0],value:e[1]}))},{type:"checkbox",property:[e,"depthTest"],onChange:t=>e.setDirty({uiChangeEvent:t,change:"depthTest"})},{type:"checkbox",property:[e,"depthWrite"],onChange:t=>e.setDirty({uiChangeEvent:t,change:"depthWrite"})},{type:"checkbox",property:[e,"colorWrite"],onChange:t=>e.setDirty({uiChangeEvent:t,change:"colorWrite"})},{type:"slider",bounds:[0,1],stepSize:.001,property:[e,"alphaTest"]},{type:"checkbox",property:[e,"alphaHash"]},{type:"checkbox",property:[e,"dithering"]},{type:"dropdown",label:"Blending",property:[e,"blending"],children:[["None",w],["Normal",C],["Additive",S],["Subtractive",M],["Multiply",E],["Custom",T]].map(e=>({label:e[0],value:e[1]}))},{type:"dropdown",hidden:()=>e.blending!==T,property:[e,"blendingEquation"],children:[["Add",I],["Subtract",P],["Reverse Subtract",D],["Min",R],["Max",B]].map(e=>({label:e[0],value:e[1]}))},{type:"dropdown",property:[e,"blendSrc"],hidden:()=>e.blending!==T,children:[["Zero",L],["One",O],["Src Color",U],["One Minus Src Color",F],["Src Alpha",k],["One Minus Src Alpha",N],["Dst Alpha",j],["One Minus Dst Alpha",z],["Dst Color",G],["One Minus Dst Color",Q],["Src Alpha Saturate",V],["Constant Color",H],["One Minus Constant Color",W],["Constant Alpha",q],["One Minus Constant Alpha",X]].map(e=>({label:e[0],value:e[1]}))},{type:"dropdown",property:[e,"blendDst"],hidden:()=>e.blending!==T,children:[["Zero",L],["One",O],["Src Color",U],["One Minus Src Color",F],["Src Alpha",k],["One Minus Src Alpha",N],["Dst Alpha",j],["One Minus Dst Alpha",z],["Dst Color",G],["One Minus Dst Color",Q],["Constant Color",H],["One Minus Constant Color",W],["Constant Alpha",q],["One Minus Constant Alpha",X]].map(e=>({label:e[0],value:e[1]}))},{type:"slider",bounds:[0,1],hidden:()=>e.blending!==T,property:[e,"blendSrcAlpha"]},{type:"slider",bounds:[0,1],hidden:()=>e.blending!==T,property:[e,"blendDstAlpha"]},{type:"color",hidden:()=>e.blending!==T||e.blendSrc!==H&&e.blendSrc!==W&&e.blendDst!==H&&e.blendDst!==W,property:[e,"blendColor"]},{type:"slider",hidden:()=>e.blending!==T||e.blendSrc!==q&&e.blendSrc!==X&&e.blendDst!==q&&e.blendDst!==X,bounds:[0,1],property:[e,"blendAlpha"]},void 0!==e.alphaMap?{type:"image",property:[e,"alphaMap"]}:{},void 0!==e.alphaMap?bw(e,"alphaMap"):{},{type:"checkbox",label:"Render to Gbuffer",getValue:()=>!0===e.userData.renderToGBuffer,setValue:t=>{!t&&!1===e.userData.renderToGBuffer||(e.userData.renderToGBuffer=t,e.setDirty({change:"userData",key:"renderToGBuffer"}))}},{type:"checkbox",label:"Render to Depth",hidden:()=>void 0===e.userData.renderToDepth,getValue:()=>!0===e.userData.renderToDepth,setValue:t=>{!t&&!1===e.userData.renderToDepth||(e.userData.renderToDepth=t,e.setDirty({change:"userData",key:"renderToDepth"}))}},{type:"input",label:"Forced Linear Depth",getValue:()=>e.userData.forcedLinearDepth??-1,setValue:t=>{t<0&&void 0===e.userData.forcedLinearDepth||(t>=0?e.userData.forcedLinearDepth=t:delete e.userData.forcedLinearDepth,e.setDirty({change:"userData",key:"forcedLinearDepth"}))}},e.isPhysicalMaterial?{type:"checkbox",label:"Inverse AlphaMap",hidden:()=>!e.transparent,getValue:()=>!0===e.userData.inverseAlphaMap,setValue:t=>{e.userData.inverseAlphaMap=t||void 0,e.setDirty({change:"userData",key:"inverseAlphaMap"})}}:{}]}),Cw=e=>({type:"folder",label:"Polygon Offset",children:[{type:"checkbox",label:"Polygon Offset",property:[e,"polygonOffset"]},{type:"slider",label:"Polygon Offset Factor",bounds:[-10,10],property:[e,"polygonOffsetFactor"]},{type:"slider",label:"Polygon Offset Units",bounds:[-10,10],property:[e,"polygonOffsetUnits"]}]}),Sw=e=>({type:"folder",label:"AO/Lightmap",children:[{type:"slider",bounds:[0,2],property:[e,"aoMapIntensity"]},{type:"image",property:[e,"aoMap"]},bw(e,"aoMap"),{type:"slider",bounds:[0,2],property:[e,"lightMapIntensity"]},{type:"image",property:[e,"lightMap"]},bw(e,"lightMap")]}),Mw=e=>({type:"folder",label:"Environment",children:[{type:"checkbox",label:"Override Environment",getValue:()=>!0===e.userData.separateEnvMapIntensity,setValue:t=>{e.userData.separateEnvMapIntensity=t,t||delete e.userData.separateEnvMapIntensity}},{type:"slider",bounds:[0,20],hidden:()=>!e.userData.separateEnvMapIntensity,label:"Environment Intensity",property:[e,"envMapIntensity"]},{type:"dropdown",hidden:()=>!e.userData.separateEnvMapIntensity&&!e.userData.envMapSlotKey,label:"Environment Map",children:["","environment1","environment2"].map(e=>({label:e||"default",value:e})),getValue:()=>e.userData.envMapSlotKey||"",setValue:t=>{e.userData.envMapSlotKey=t,t||delete e.userData.envMapSlotKey,e.setDirty({change:"userData",key:"envMapSlotKey"})}}]}),Ew=e=>[()=>e.materialExtensions?.map(t=>(t.uuid=t.uuid||Ky(),e.__matExtUiConfigs=e.__matExtUiConfigs||{},e.__matExtUiConfigs[t.uuid]||(e.__matExtUiConfigs[t.uuid]=t.getUiConfig?.(e,e.uiConfig?.uiRefresh)),e.__matExtUiConfigs[t.uuid])).filter(e=>e),{type:"dropdown",label:"Side",property:[e,"side"],children:[["Front",_],["Back",b],["Double",x]].map(e=>({label:e[0],value:e[1]}))},{type:"input",label:"Mesh count",getValue:()=>e.appliedMeshes.size||0,disabled:!0},{type:"button",label:`Download ${e.constructor.TypeSlug}`,value:()=>{bm(new Blob([JSON.stringify(e.toJSON(),null,2)],{type:"application/json"}),`material.${e.constructor.TypeSlug}`)}},{type:"button",label:`Select ${e.constructor.TypeSlug}`,value:async()=>Cm(!1,!1,e.constructor.TypeSlug).then(async e=>e?.[0]?.text()).then(t=>{if(!t)return;const i=JSON.parse(t);i.uuid&&delete i.uuid;const n=e.toJSON();return e.fromJSON(i,w_()),{undo:()=>e.fromJSON(n,w_()),redo:()=>e.fromJSON(i,w_())}})}],Tw=e=>({type:"folder",label:"Rough/Metal",children:[{type:"slider",bounds:[0,1],property:[e,"roughness"]},{type:"slider",bounds:[0,1],property:[e,"metalness"]},{type:"image",property:[e,"roughnessMap"]},bw(e,"roughnessMap"),{type:"image",property:[e,"metalnessMap"]},bw(e,"metalnessMap")]}),Iw=e=>({type:"folder",label:"Bump/Normal",children:[{type:"slider",bounds:[-500,500],stepSize:.001,property:[e,"bumpScale"],hidden:()=>!e.bumpMap},{type:"image",property:[e,"bumpMap"]},bw(e,"bumpMap"),{type:"image",property:[e,"normalMap"]},{type:"vec2",property:[e,"normalScale"],hidden:()=>!e.normalMap},{type:"dropdown",hidden:()=>!e.normalMap,property:[e,"normalMapType"],children:[["TangentSpace",Rt],["ObjectSpace",Bt]].map(e=>({label:e[0],value:e[1]}))},bw(e,"normalMap"),{type:"input",property:[e,"displacementScale"],hidden:()=>!e.displacementMap},{type:"image",property:[e,"displacementMap"]},bw(e,"displacementMap")]}),Pw=e=>({type:"folder",label:"Emission",children:[{type:"color",property:[e,"emissive"]},{type:"slider",bounds:[0,100],property:[e,"emissiveIntensity"]},{type:"image",property:[e,"emissiveMap"]},bw(e,"emissiveMap")]}),Dw=e=>({type:"folder",label:"Refraction",children:[{type:"slider",bounds:[0,4],property:[e,"ior"]},{type:"slider",bounds:[0,1],property:[e,"transmission"]},{type:"slider",bounds:[0,1],stepSize:.001,property:[e,"thickness"]},{type:"image",property:[e,"transmissionMap"]},bw(e,"transmissionMap"),{type:"image",property:[e,"thicknessMap"]},bw(e,"thicknessMap"),{type:"number",property:[e,"attenuationDistance"]},{type:"color",property:[e,"attenuationColor"]}]}),Rw=e=>({type:"folder",label:"Clearcoat",children:[{type:"slider",bounds:[0,1],property:[e,"clearcoat"]},{type:"slider",bounds:[0,1],hidden:()=>e.clearcoat<.001,property:[e,"clearcoatRoughness"]},{type:"image",property:[e,"clearcoatMap"]},bw(e,"clearcoatMap"),{type:"slider",bounds:[0,1],property:[e,"clearcoatRoughness"]},{type:"image",property:[e,"clearcoatRoughnessMap"]},bw(e,"clearcoatRoughnessMap"),{type:"image",property:[e,"clearcoatNormalMap"]},{type:"vec2",property:[e,"clearcoatNormalScale"],hidden:()=>!e.clearcoatNormalMap},bw(e,"clearcoatNormalMap")]}),Bw=e=>({type:"folder",label:"Iridescence",children:[{type:"slider",bounds:[0,3],label:"Intensity",property:[e,"iridescence"]},{type:"slider",bounds:[0,3],label:"IOR",property:[e,"iridescenceIOR"]},{type:"slider",bounds:[0,500],label:"Thickness0",property:[e.iridescenceThicknessRange,"0"],onChange:t=>e.setDirty({uiChangeEvent:t,change:"iridescenceThicknessRange",key:"0"})},{type:"slider",bounds:[0,500],label:"Thickness1",property:[e.iridescenceThicknessRange,"1"],onChange:t=>e.setDirty({uiChangeEvent:t,change:"iridescenceThicknessRange",key:"1"})},{type:"image",property:[e,"iridescenceMap"]},bw(e,"iridescenceMap"),{type:"image",property:[e,"iridescenceThicknessMap"]},bw(e,"iridescenceThicknessMap")]}),Lw=e=>({type:"folder",label:"Sheen",children:[{type:"slider",bounds:[0,1],property:[e,"sheen"]},{type:"color",hidden:()=>e.sheen<.001,property:[e,"sheenColor"]},{type:"image",property:[e,"sheenColorMap"]},bw(e,"sheenColorMap"),{type:"slider",bounds:[0,1],property:[e,"sheenRoughness"]},{type:"image",property:[e,"sheenRoughnessMap"]},bw(e,"sheenRoughnessMap")]}),Ow={name:"",blending:C,side:_,vertexColors:!1,opacity:1,transparent:!1,blendSrc:k,blendDst:N,blendEquation:I,blendSrcAlpha:null,blendDstAlpha:null,blendEquationAlpha:null,blendColor:"#000000",blendAlpha:0,depthFunc:Z,depthTest:!0,depthWrite:!0,stencilWriteMask:255,stencilFunc:519,stencilRef:0,stencilFuncMask:255,stencilFail:Vt,stencilZFail:Vt,stencilZPass:Vt,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},Uw=["opacity","blendColor","blendAlpha","alphaTest"],Fw=class extends vr{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isUnlitMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Nw.setDirty,this.envMap=null,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Nw.registerMaterialExtensions,this.unregisterMaterialExtensions=Nw.unregisterMaterialExtensions,this.onBeforeRender=Nw.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=Nw.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Unlit Material",uuid:"MBM2_"+this.uuid,expanded:!0,onChange:e=>{if(!e.config||e.config.onChange)return;let t=Array.isArray(e.config.property)?e.config.property[1]:e.config.property;t="string"==typeof t?t:void 0,this.setDirty({uiChangeEvent:e,needsUpdate:!!e.last,refreshUi:!!e.last,change:t})},children:[...xw(this),...Rg(this),ww(this),Sw(this),Cw(this),...Ew(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Nw.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Nw.dispose(super.dispose).call(this)}clone(e=!1){return Nw.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Nw.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 t of n)e.vertexShader=R_(e.vertexShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);for(const t of i)e.fragmentShader=R_(e.fragmentShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);Nw.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)?(Nw.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):(console.error("Material type is not supported:",e.type),this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...f_.Serialize(this,e,!0)}:f_.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(f_.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};Fw.TypeSlug="bmat",Fw.TYPE="UnlitMaterial",Fw.TypeAlias=["unlit","basic",Fw.TYPE,Fw.TypeSlug,"MeshBasicMaterial","MeshBasicMaterial2"],f_.SerializableMaterials.add(Fw),Fw.MaterialProperties={...Ow,color:new mr(16777215),map:null,lightMap:null,lightMapIntensity:1,aoMap:null,aoMapIntensity:1,specularMap:null,alphaMap:null,envMap:null,combine:0,envMapIntensity:1,reflectivity:1,refractionRatio:.98,wireframe:!1,wireframeLinewidth:1,wireframeLinecap:"round",wireframeLinejoin:"round",skinning:!1,fog:!0,flatShading:!1},Fw.MapProperties=["map","aoMap","lightMap","specularMap","alphaMap","envMap"],Fw.InterpolateProperties=[...Uw,"color","color","specular","emissive","reflectivity","refractionRatio","envMapIntensity","lightMapIntensity","aoMapIntensity","wireframeLinewidth"];let kw=Fw;const Nw={threeMaterialPropList:Ow,threeMaterialInterpolateProps:Uw,setDirty:function(e){!1!==e?.needsUpdate&&(this.needsUpdate=!0),Nw.refreshTextureRefs.call(this),this.dispatchEvent({bubbleToObject:!0,bubbleToParent:!0,...e,type:"materialUpdate"}),!1!==e?.last&&!1!==e?.refreshUi&&this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},setValues:e=>function(t,i,n,r){void 0===n&&(n=t.isMaterial),n&&(this.userData={});const s=t?.metadata&&t?.metadata.version<=4.5,a=Pi.enabled;s&&(Pi.enabled=!1);const o=this.constructor.MaterialProperties,l=o?Pm(t,{},Array.from(Object.keys(o))):{...t};for(const e of Object.keys(l))void 0===l[e]&&delete l[e];const c=l.userData;delete l.userData;const h=new Set([...this.constructor.InterpolateProperties||kw.InterpolateProperties,...this.constructor.MapProperties||kw.MapProperties]);return r&&Ox(l,this,h,r),e.call(this,l),c&&v_(this.userData,c),this.userData.uuid=this.uuid,(t?.metadata&&t?.metadata.version<=4.6||this.userData.legacyBumpScale)&&void 0!==this?.bumpScale&&this?.bumpMap&&this.defines&&(console.warn("MaterialManager: Old format material loaded, bump map might be incorrect.",t,t.bumpScale),this.defines.BUMP_MAP_SCALE_LEGACY="1",this.userData.legacyBumpScale=!0,this.needsUpdate=!0),s&&(Pi.enabled=a),this.setDirty&&this.setDirty(),this},dispose:e=>function(t=!0){!t&&!1===this.userData.disposeOnIdle||e.call(this)},clone:e=>function(t=!1){let i;return t&&(this.userData.cloneId||(this.userData.cloneId="0"),this.userData.cloneCount||(this.userData.cloneCount=0),this.userData.cloneCount+=1),this.constructor.prototype?.setValues?(i=new this.constructor,i.setValues(this,!1)):i=e.call(this),t&&(i.userData.cloneId=i.userData.cloneId+"_"+this.userData.cloneCount,i.userData.cloneCount=0,i.name=(i.name||"mat")+"_"+i.userData.cloneId),i},dispatchEvent:e=>function(t){e.call(this,t);const i=t.type;t.bubbleToObject&&("beforeDeserialize"===i||"materialUpdate"===i||"textureUpdate"===i||"select"===i)&&this.appliedMeshes.forEach(e=>e.dispatchEvent({...t,material:this,type:i}))},customProgramCacheKey:function(){return pw.CacheKeyForExtensions(this,this.materialExtensions)+this.userData.inverseAlphaMap},registerMaterialExtensions:function(e){pw.RegisterExtensions(this,e)},unregisterMaterialExtensions:function(e){pw.UnregisterExtensions(this,e)},onBeforeCompile:function(e,t){this.materialExtensions&&pw.ApplyMaterialExtensions(this,e,this.materialExtensions,t),this.dispatchEvent({type:"beforeCompile",shader:e,renderer:t}),e.fragmentShader=e.fragmentShader.replaceAll("#glMarker","// "),e.vertexShader=e.vertexShader.replaceAll("#glMarker","// ")},onBeforeRender:function(e,t,i,n,r){this.defines&&void 0!==this.envMap&&void 0!==t.fixedEnvMapDirection&&(t.fixedEnvMapDirection?this.defines.FIX_ENV_DIRECTION||(this.defines.FIX_ENV_DIRECTION="1",this.needsUpdate=!0):void 0!==this.defines.FIX_ENV_DIRECTION&&(delete this.defines.FIX_ENV_DIRECTION,this.needsUpdate=!0)),this.dispatchEvent({type:"beforeRender",renderer:e,scene:t,camera:i,geometry:n,object:r})},onAfterRender:function(e,t,i,n,r){this.dispatchEvent({type:"afterRender",renderer:e,scene:t,camera:i,geometry:n,object:r})},onBeforeCompileOverride:e=>function(t,i){Nw.onBeforeCompile.call(this,t,i),e.call(this,t,i)},onBeforeRenderOverride:e=>function(...t){e.call(this,...t),Nw.onBeforeRender.call(this,...t)},onAfterRenderOverride:e=>function(...t){e.call(this,...t),Nw.onAfterRender.call(this,...t)},customProgramCacheKeyOverride:e=>function(){return e.call(this)+Nw.customProgramCacheKey.call(this)},upgradeMaterial:Qw,getMapsForMaterial:function(){const e=new Map;for(const t of this.constructor?.MapProperties||zw)Zy(t,this,e);if(this.userData)for(const t of Gw)Zy(t,this.userData,e,!0);return e},refreshTextureRefs:function(){this.__textureUpdate||(this.__textureUpdate=jw.bind(this));const e=Nw.getMapsForMaterial.call(this),t=new Set([...e.values()]),i=this._mapRefs||new Set;let n=!1;const r=new Set,s=new Set;for(const e of t)!e||!e.isTexture||(e.addEventListener("update",this.__textureUpdate),!i.has(e)&&(n=!0,r.add(e)));for(const e of i)t.has(e)||(e.removeEventListener("update",this.__textureUpdate),n=!0,s.add(e));this._mapRefs=t,n&&this.dispatchEvent({type:"texturesChanged",textures:t,oldTextures:i,addedTextures:r,removedTextures:s,material:this,bubbleToObject:!0,bubbleToParent:!0})}},jw=function(e){!this||"material"!==this.assetType||this.dispatchEvent({texture:e.target,bubbleToParent:!0,bubbleToObject:!0,...e,type:"textureUpdate"})},zw=new Set([]),Gw=new Set([]);function Qw(){if(!this.isMaterial)return console.error("Material is not a material",this),this;if(this.setDirty||(this.setDirty=Nw.setDirty),this.appliedMeshes||(this.appliedMeshes=new Set),this.userData||(this.userData={}),this.userData.uuid=this.uuid,this.__upgradeSetup||(this.dispatchEvent=Nw.dispatchEvent(this.dispatchEvent),this.__upgradeSetup=!0),"material"===this.assetType)return this;this.assetType="material",this.setValues=Nw.setValues(this.setValues),this.dispose=Nw.dispose(this.dispose),this.clone=Nw.clone(this.clone),this.extraUniformsToUpload||(this.extraUniformsToUpload={}),this.materialExtensions||(this.materialExtensions=[]),this.registerMaterialExtensions||(this.registerMaterialExtensions=Nw.registerMaterialExtensions),this.unregisterMaterialExtensions||(this.unregisterMaterialExtensions=Nw.unregisterMaterialExtensions);const e=!this.isDerivedMaterial;return this.onBeforeCompile=e?Nw.onBeforeCompileOverride(this.onBeforeCompile):Nw.onBeforeCompile,this.onBeforeRender=Nw.onBeforeRenderOverride(this.onBeforeRender),this.onAfterRender=Nw.onAfterRenderOverride(this.onAfterRender),this.customProgramCacheKey=Nw.customProgramCacheKeyOverride(this.customProgramCacheKey),this.setDirty({change:"upgradeMaterial"}),this}const Vw=class extends ls{constructor({customMaterialExtensions:e,...t}={},i=!1){super(),this.assetType="material",this.isAShaderMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Nw.setDirty,this.type="ShaderMaterial",this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Nw.registerMaterialExtensions,this.unregisterMaterialExtensions=Nw.unregisterMaterialExtensions,this.isRawShaderMaterial=i,i&&(this.type="RawShaderMaterial"),e&&this.registerMaterialExtensions(e),Nw.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Nw.dispose(super.dispose).call(this)}clone(e=!1){return Nw.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Nw.customProgramCacheKey.call(this)}onBeforeCompile(e,t){Nw.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}onBeforeRender(e,t,i,n,r,s){super.onBeforeRender(e,t,i,n,r,s),Nw.onBeforeRender.call(this,e,t,i,n,r,s)}onAfterRender(e,t,i,n,r,s){super.onAfterRender(e,t,i,n,r,s),Nw.onAfterRender.call(this,e,t,i,n,r,s)}setValues(e){return Nw.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}};Vw.TypeSlug="shaderMat",Vw.TYPE="ShaderMaterial2",Vw.MaterialProperties={...Ow,fragmentShader:"",vertexShader:"",uniforms:{},defines:{},extensions:{},isRawShaderMaterial:!1,uniformsGroups:{},wireframe:!1,wireframeLinewidth:1,clipping:!1,lights:!1,fog:!1,glslVersion:null,defaultAttributeValues:{}},Vw.InterpolateProperties=[...Uw,"wireframeLinewidth"];let Hw=Vw;class Ww extends Hw{constructor(e=!0,t){super({vertexShader:"\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#glMarker importsEnd\n#define DEPTH_NORMAL\n#define IS_DEPTH_MATERIAL\nvarying vec3 vViewPosition;\n#ifdef USE_ALPHAMAP\n#define USE_UV\n#endif\nvoid main(){\n#include <uv_vertex>\n#include <batching_vertex>\n#include <beginnormal_vertex>\n#include <morphnormal_vertex>\n#include <skinbase_vertex>\n#include <skinnormal_vertex>\n#include <defaultnormal_vertex>\n#include <normal_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <displacementmap_vertex>\n#include <project_vertex>\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n#glMarker beforeOutput\nvViewPosition=-mvPosition.xyz;}",fragmentShader:"\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\n#glMarker importsEnd\n#define DEPTH_NORMAL\n#define IS_DEPTH_MATERIAL\nvarying vec3 vViewPosition;\n#ifdef USE_ALPHAMAP\n#define USE_UV\n#include <packing>\n#endif\n#if IS_GLSL3 > 0\n#ifndef gl_FragColor\nlayout(location=0)out vec4 gDepthNormal;layout(location=1)out vec4 gFlags;\n#endif\n#endif\nuniform 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(){\n#glMarker mainStart\n#include <clipping_planes_fragment>\nvec4 diffuseColor=vec4(1.0);\n#include <map_fragment>\n#ifdef USE_ALPHAMAP\nfloat alphaMapValue=\n#ifdef ALPHA_I_RGBA_PACKING\n1.-unpackRGBAToDepth(texture2D(alphaMap,vAlphaMapUv));\n#else\ntexture2D(alphaMap,vAlphaMapUv).g;\n#endif\n#if defined(INVERSE_ALPHAMAP) && INVERSE_ALPHAMAP >= 1\ndiffuseColor.a*=1.0-alphaMapValue;\n#else\ndiffuseColor.a*=alphaMapValue;\n#endif\n#endif\n#include <alphatest_fragment>\n#include <logdepthbuf_fragment>\n#include <normal_fragment_begin>\n#include <normal_fragment_maps>\n#glMarker beforeOutput\n#ifdef FORCED_LINEAR_DEPTH\nfloat linearZ=float(FORCED_LINEAR_DEPTH);\n#else\nfloat linearZ=linstep(-cameraNearFar.x,-cameraNearFar.y,-vViewPosition.z);\n#endif\nvec2 packedZ=pack16(pow(max(0.,linearZ),0.5));vec2 packedNormal=packNormal(normal);\n#if IS_GLSL3 > 0\n#ifndef gl_FragColor\ngDepthNormal=vec4(packedZ.x,packedZ.y,packedNormal.x,packedNormal.y);gFlags=flags;\n#else\ngl_FragColor=vec4(packedZ.x,packedZ.y,packedNormal.x,packedNormal.y);\n#endif\n#else\ngl_FragColor=vec4(packedZ.x,packedZ.y,packedNormal.x,packedNormal.y);\n#endif\n}",uniforms:os.merge([Is.common,Is.bumpmap,Is.normalmap,Is.displacementmap,{cameraNearFar:{value:new fi(.1,1e3)},flags:{value:new Gi(255,255,255,255)}}]),defines:{IS_GLSL3:e?"1":"0"},glslVersion:e?ei:"100",...t}),this.flagUpdaters=new Map,this.normalMapType=Rt,this.flatShading=!1,this.reset()}onBeforeRender(e,t,i,n,r,s){super.onBeforeRender(e,t,i,n,r,s);let a=!1,o=r.material;if(Array.isArray(o)&&(o=o[0]),o===this&&(o=r.currentMaterial,a=!0),Array.isArray(o)&&(o=o[0]),!o)return;if(a)mw({FORCED_LINEAR_DEPTH:o.userData.forcedLinearDepth??void 0},this);else{const t=t=>{const i=o[t];i&&(this.uniforms[t].value=i,this.uniforms[t+"Transform"]?i.isTexture&&e.materials.refreshTransformUniform(i,this.uniforms[t+"Transform"]):console.error("GBufferMaterial: "+t+"Transform is not defined in uniform"))};t("map"),void 0!==o.side&&(this.side=o.side??x),t("alphaMap"),void 0!==o.alphaTest&&(this.alphaTest=o.alphaTest<1e-4?1e-4:o.alphaTest),void 0!==o.alphaHash&&(this.alphaHash=o.alphaHash),t("bumpMap"),void 0!==o.bumpScale&&(this.uniforms.bumpScale.value=o.bumpScale),t("normalMap"),void 0!==o.normalScale&&this.uniforms.normalScale.value.copy(o.normalScale),void 0!==o.normalMapType&&(this.normalMapType=o.normalMapType),void 0!==o.flatShading&&(this.flatShading=o.flatShading),t("displacementMap"),void 0!==o.displacementScale&&(this.uniforms.displacementScale.value=o.displacementScale),void 0!==o.displacementBias&&(this.uniforms.displacementBias.value=o.displacementBias),void 0!==o.wireframe&&(this.wireframe=o.wireframe),void 0!==o.wireframeLinewidth&&(this.wireframeLinewidth=o.wireframeLinewidth),mw({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:o.userData.ALPHA_I_RGBA_PACKING?1:void 0,FORCED_LINEAR_DEPTH:o.userData.forcedLinearDepth??void 0},this)}const l=this.uniforms.flags.value;this._updateFlagsUniform(l,o,e,t,i,n,r),i.updateShaderProperties(this),this.uniformsNeedUpdate=!0,o.materialExtensions?.length&&this.registerMaterialExtensions(o.materialExtensions),this.needsUpdate=!0,e.resetCurrentMaterial&&e.resetCurrentMaterial()}_updateFlagsUniform(e,t,i,n,r,s,a){e.set(255,255,255,255);const o=t.userData.gBufferData?.materialId??t.userData.matId;e.z=o||0,this.flagUpdaters.forEach(o=>o(e,{material:t,renderer:i,scene:n,camera:r,geometry:s,object:a})),e.x/=255,e.y/=255,e.z/=255,e.w/=255}onAfterRender(e,t,i,n,r,s){super.onAfterRender(e,t,i,n,r,s);let a=r.material;Array.isArray(a)&&(a=a[0]),a&&a!==this&&(a.materialExtensions?.length&&this.unregisterMaterialExtensions(a.materialExtensions),this.reset())}reset(){this.uniforms.map.value=null,this.side=x,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=Rt,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}}const qw={setDirty:function(e,...t){"string"==typeof e&&(e={change:e}),this.dispatchEvent({bubbleToParent:this.userData?.autoUpdateParent??!0,object:this,...e,type:"objectUpdate",args:t}),!1!==e?.refreshUi&&!1!==e?.last&&this.refreshUi&&this.refreshUi()},upgradeObject3D:function e(t){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",t&&(this.parentRoot=t.parentRoot||t),this.dispatchEvent=qw.dispatchEvent(this.dispatchEvent),this.dispose=qw.dispose(this.dispose),this.clone=qw.clone(this.clone),this.copy=qw.copy(this.copy),this.add=qw.add(this.add),this.setDirty||(this.setDirty=qw.setDirty),this.refreshUi||(this.refreshUi=qw.refreshUi),this.autoScale||(this.autoScale=qw.autoScale.bind(this)),this.autoCenter||(this.autoCenter=qw.autoCenter.bind(this)),this.pivotToBoundsCenter||(this.pivotToBoundsCenter=qw.pivotToBoundsCenter.bind(this)),this.pivotToPoint||(this.pivotToPoint=qw.pivotToPoint.bind(this)),this.traverseModels||(this.traverseModels=qw.traverseModels.bind(this)),this.addEventListener("added",qw.eventCallbacks.onAddedToParent),this.addEventListener("removed",qw.eventCallbacks.onRemovedFromParent),(this.isLineSegments2||this.isLine2)&&(this.isMesh=!0),(this.isMesh||this.isLine)&&!this.__meshSetup){if(this.__meshSetup=!0,this._onGeometryUpdate=e=>qw.eventCallbacks.onGeometryUpdate.call(this,e),qw.initMaterial.call(this),qw.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&&("model"===this.assetType||"camera"===this.assetType)&&qw.makeUiConfig.call(this),!1!==this.autoUpgradeChildren){const t=[...this.children];for(const i of t)e.call(i,this)}return!this.modelObject&&Object.defineProperty(this,"modelObject",{get:()=>(console.error("IObject3D: modelObject is deprecated, use object directly"),this)}),this},makeUiConfig:ow,autoCenter:function(e=!0,t=!1){if(t){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 e=(new Ly).expandByObject(this,!0,!0).getCenter(new Xi);if(!isFinite(e.lengthSq()))return this;this.userData._lastCenter=e,this.position.sub(e),this.userData.autoCentered=!0,this.userData.isCentered=!0}return this.updateMatrix(),e&&this.setDirty&&this.setDirty({change:"autoCenter",undo:t}),this},autoScale:function(e,t,i=!0,n=!1){let r=1;if(n){if(!this.userData.autoScaled||!this.userData._lastScaleRadius)return this;const t=this.userData.autoScaleRadius||e||1;if(r=this.userData._lastScaleRadius/t,!isFinite(r))return this;this.userData.autoScaled=!0,this.userData.autoScaleRadius=e,delete this.userData._lastScaleRadius}else{const t=.5*(new Ly).expandByObject(this,!0,!0).getSize(new Xi).length();if(void 0===e&&(e=this.userData.autoScaleRadius||1),r=e/t,!isFinite(r))return this;this.userData.autoScaled=!0,this.userData.autoScaleRadius=e,this.userData._lastScaleRadius=t}return this.userData.pseudoCentered?this.children.forEach(e=>{e.scale.multiplyScalar(r)}):this.scale.multiplyScalar(r),(t||this.userData.isCentered)&&this.position.multiplyScalar(r),this.traverse(e=>{const t=e;t.isLight&&t.shadow?.camera?.right&&(t.shadow.camera.right*=r,t.shadow.camera.left*=r,t.shadow.camera.top*=r,t.shadow.camera.bottom*=r,e.setDirty&&e.setDirty()),t.isCamera&&t.right&&(t.right*=r,t.left*=r,t.top*=r,t.bottom*=r,e.setDirty&&e.setDirty())}),i&&this.setDirty&&this.setDirty({change:"autoScale",undo:n}),this},pivotToBoundsCenter:function(e=!0){const t=(new Ly).expandByObject(this,!0,!0).getCenter(new Xi);return qw.pivotToPoint.call(this,t,e)},pivotToPoint:function(e,t=!0,i=!0){const n=(new Xi).copy(e),r=(new Xi).copy(n),s=(new Sn).copy(this.matrixWorld).invert(),a=this.parent?.matrixWorld,o=new Sn;void 0!==a&&o.copy(a).invert(),n.applyMatrix4(o);const l=this.position.clone();this.position.copy(n),r.applyMatrix4(s).negate();const c=new Map;if(this.geometry){const e=i?this.geometry.appliedMeshes:void 0;if(e)for(const i of e){if(i===this)continue;c.set(i,i.position.clone()),i.updateMatrix();const e=new Xi(-r.x,-r.y,-r.z).applyMatrix4(i.matrix);i.position.copy(e),t&&i.setDirty&&i.setDirty({change:"pivotToPoint"})}this.geometry.translate(r.x,r.y,r.z)}return this.children.forEach(e=>{e.position.add(r)}),t&&this.setDirty&&this.setDirty({change:"pivotToPoint",undo:!1}),()=>{if(this.position.copy(l),this.geometry){this.geometry.translate(-r.x,-r.y,-r.z);for(const[e,i]of c)e.position.copy(i),t&&e.setDirty&&e.setDirty({change:"pivotToPoint"})}this.children.forEach(e=>{e.position.sub(r)}),t&&this.setDirty&&this.setDirty({change:"pivotToPoint",undo:!0})}},traverseModels:function(e,{visible:t=!1,widgets:i=!1,...n}){if(!this.assetType||!i&&"widget"===this.assetType||t&&!this.visible||!1===e(this))return;const r=this.children;for(let s=0,a=r.length;s<a;s++){const a=r[s];!a.assetType||!a.traverseModels||a.traverseModels(e,{visible:t,widgets:i,...n})}},eventCallbacks:{onAddedToParent:function(e){const t=this.parent?.parentRoot??this.parent;t!==this.parentRoot&&this.traverse(i=>{const n=i.parentRoot;n!==t&&(i.parentRoot=t,i.dispatchEvent({...e,type:"parentRootChanged",object:i,oldParentRoot:n||void 0,bubbleToParent:!1}))}),!this.objectProcessor&&t?.objectProcessor&&this.traverse(e=>{e.objectProcessor=t.objectProcessor,e.objectProcessor?.processObject(e)}),this.setDirty?.({...e,change:"addedToParent"})},onRemovedFromParent:function(e){this.setDirty?.({...e,change:"removedFromParent"}),this.parentRoot&&this.traverse(t=>{const i=t.parentRoot;i&&(t.parentRoot=void 0,t.dispatchEvent({...e,type:"parentRootChanged",object:t,oldParentRoot:i||void 0,bubbleToParent:!1}))})},onGeometryUpdate:function(e){e.bubbleToObject&&this.dispatchEvent({bubbleToParent:!0,...e,object:this,geometry:e.geometry})}},initMaterial:function(){if(Om(this,"_currentMaterial"))return;this._currentMaterial=null;const{protoDesc:e}=Mg(this,"material"),t=this.material;delete this.material,Object.defineProperty(this,"currentMaterial",{configurable:!0,enumerable:!0,get(){return e?.get?e.get.call(this):qw.getMaterial.call(this)},set(t){qw.setMaterial.call(this,t),e?.set?.call(this,t)}}),Object.defineProperty(this,"material",{configurable:!0,enumerable:!0,get(){return this.forcedOverrideMaterial??this.currentMaterial},set(e){this.forcedOverrideMaterial&&console.warn("IObject3D: Material is being set on an object with forcedOverrideMaterial set"),this.currentMaterial=e}}),Object.defineProperty(this,"materials",{configurable:!0,enumerable:!0,get:qw.getMaterials,set:qw.setMaterials}),this.material=t,(this.isLineSegments2||this.isLine2||this.isWireframe)&&(Object.defineProperty(this,"customDepthMaterial",{configurable:!0,enumerable:!0,get:()=>(this._customDepthMaterial||(this._customDepthMaterial=function(e,t=new el({depthPacking:Dt,blending:w,transparent:!1})){return t.onBeforeCompile=i=>{if(i.__modified)return;i.__modified=!0;let n=e.material;if(n===t&&(n=e.currentMaterial),!n.isLineMaterial)return;i.uniforms={...n.uniforms,...i.uniforms},i.defines={...n.defines,...i.defines};const r=i.fragmentShader.split("#include <logdepthbuf_fragment>")[1];i.fragmentShader=R_(n.fragmentShader,"void main()","\nvarying vec2 vHighPrecisionZW;\n#include <packing>\n",{prepend:!0}),i.fragmentShader=R_(i.fragmentShader,"#include <logdepthbuf_fragment>",r+"\n//end-frag-patch\n",{append:!0}),i.fragmentShader=i.fragmentShader.split("//end-frag-patch")[0],i.vertexShader=R_(n.vertexShader,"void main()","\nvarying vec2 vHighPrecisionZW;\n",{prepend:!0}),i.vertexShader=R_(i.vertexShader,"#include <clipping_planes_vertex>","\nvHighPrecisionZW = gl_Position.zw;\n",{append:!0})},t}(this)),this._customDepthMaterial),set:e=>{this._customDepthMaterial=e,e&&(e.needsUpdate=!0),this.setDirty&&this.setDirty({change:"customDepthMaterial"})}}),Object.defineProperty(this,"customGBufferMaterial",{configurable:!0,enumerable:!0,get:()=>(this._customGBufferMaterial||(this._customGBufferMaterial=function(e,t=new Ww(!0,{blending:w,transparent:!1})){return t.onBeforeCompile=i=>{if(i.__modified)return;i.__modified=!0;let n=e.material;if(n===t&&(n=e.currentMaterial),!n.isLineMaterial)return;i.uniforms={...n.uniforms,...i.uniforms};const r=i.fragmentShader.split("void main()")[0].split("#glMarker importsEnd")[1]||"",s="\nvec3 normal = vec3(0.,0.,1.);\n"+i.fragmentShader.split("#glMarker beforeOutput")[1];i.fragmentShader=R_(n.fragmentShader,"void main()",r+"\n",{prepend:!0}),i.fragmentShader=R_(i.fragmentShader,"#include <logdepthbuf_fragment>",s+"\n//end-frag-patch\n",{append:!0}),i.fragmentShader=i.fragmentShader.split("//end-frag-patch")[0];const a=i.vertexShader.split("void main()")[0].split("#glMarker importsEnd")[1]||"",o=i.vertexShader.split("#glMarker beforeOutput")[1].replace(/}\s*$/,"")+"\n";i.vertexShader=R_(n.vertexShader,"void main()",a,{prepend:!0}),i.vertexShader=R_(i.vertexShader,"#include <clipping_planes_vertex>",o,{append:!0})},t}(this)),this._customGBufferMaterial),set:e=>{this._customGBufferMaterial=e,e&&(e.needsUpdate=!0),this.setDirty&&this.setDirty({change:"customDepthMaterial"})}})),this.setMaterial||(this.setMaterial=e=>{const t=this.material;return console.error("IObject3D: setMaterial is deprecated, use material property directly"),this.material=e,t})},getMaterial:function(){return this._currentMaterial||void 0},getMaterials:function(){const e=this.currentMaterial;return e?Array.isArray(e)?[...e]:[e]:[]},setMaterial:function(e){const t=(Array.isArray(e)?e:[e]).filter(e=>e);if(this.material==t||1===t.length&&this.material===t[0])return[];const i=this.material,n=Array.isArray(i)?[...i]:[i];let r=[];const s=[];for(const e of n)e&&r.push(e);const a=[];for(const e of t)e&&(e.assetType||Nw.upgradeMaterial.call(e),r.includes(e)?r=r.filter(t=>t!==e):s.push(e),a.push(e));for(const e of r)e.dispatchEvent({type:"removeFromMesh",object:this});for(const e of s)e.dispatchEvent({type:"addToMesh",object:this});this._currentMaterial=a.length?1!==a.length?a:a[0]||null:null,this.dispatchEvent({type:"materialChanged",material:this._currentMaterial??null,oldMaterial:i??null,object:this,bubbleToParent:!0}),this.refreshUi&&this.refreshUi()},setMaterials:function(e){this.currentMaterial=e||void 0},initGeometry:function(){this._currentGeometry=null;const{protoDesc:e}=Mg(this,"geometry"),t=this.geometry;delete this.geometry,Object.defineProperty(this,"geometry",{configurable:!0,enumerable:!0,get(){return this.forcedOverrideGeometry??(e?.get?e.get.call(this):qw.getGeometry.call(this))},set(t){this.forcedOverrideGeometry&&console.warn("IObject3D: Geometry is being set on an object with forcedOverrideGeometry set"),qw.setGeometry.call(this,t),e?.set?.call(this,t)}}),this.geometry=t,this.setGeometry||(this.setGeometry=e=>{const t=this.geometry;return console.error("IObject3D: setGeometry is deprecated, use geometry property directly"),this.geometry=e,t})},getGeometry:function(){return this._currentGeometry||void 0},setGeometry:function(e){const t=this.geometry||void 0;t!==e&&(t&&this._onGeometryUpdate&&t.removeEventListener("geometryUpdate",this._onGeometryUpdate),e&&(e.assetType||dw.upgradeGeometry.call(e)),this._currentGeometry=e||null,e&&this._onGeometryUpdate&&e.addEventListener("geometryUpdate",this._onGeometryUpdate),this.dispatchEvent({type:"geometryChanged",geometry:e??null,oldGeometry:t,bubbleToParent:!0,object:this}),this.refreshUi&&this.refreshUi())},refreshUi:function(){this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},dispatchEvent:e=>function(t){if(!t.target||t.target===this||!1!==this.acceptChildEvents){if(t.bubbleToParent||this.userData?.__autoBubbleToParentEvents?.includes(t.type)){const e=this.parentRoot||this.parent;this.parentRoot!==this&&e?.dispatchEvent(t)}e.call(this,t)}},clone:e=>function(t,...i){const n=this.userData;this.userData={};const r=e.call(this,t,...i);if(this.userData=n,__(r.userData,n),qw.upgradeObject3D.call(r),r.userData.cloneParent=this.uuid,this._sChildren)if(t){r._sChildren=[];for(const e of this._sChildren){if(!e)continue;let t;if(this.children.includes(e)){const i=this.children.indexOf(e);t=r.children[i]}else t=e.clone(!0);r._sChildren.push(t)}}else r._sChildren=[...this._sChildren];return r},copy:e=>function(t,...i){const n=this.isLight?this.target:null,r=t.userData;t.userData={};const s=this.userData;return e.call(this,t,...i),this.userData=s,t.userData=r,__(this.userData,t.userData),n&&this.target&&(n.position.copy(this.target.position),n.updateMatrixWorld(),this.target=n),this},add:e=>function(...t){if(!1!==this.autoUpgradeChildren)for(const e of t)qw.upgradeObject3D.call(e);return e.call(this,...t)},dispose:e=>function(t=!0){t&&this.parent&&(this.removeFromParent(),delete this.parentRoot),this.dispatchEvent({type:"dispose",bubbleToParent:!1});for(const e of[...this.children])e?.dispose&&e.dispose(!1);return e&&e.call(this),this},getMapsForObject3D:function(){const e=new Map;for(const t of this.constructor?.MapProperties||Zw)Zy(t,this,e);if(this.isScene)for(const t of Jw)Zy(t,this,e);return e},deleteObject:async(t,i)=>{if(!i?.shiftKey&&!await e.ThreeViewer.Dialog.confirm("Delete Object: Are you sure you want to delete this object?"))return;const n=t.parent;return t.dispose&&t.dispose(!0),()=>{n&&n.add(t)}},duplicateObject:async(e,t)=>{const i=e.parent,n=e.clone(!0);cw(e,n);const r=!!t&&!t.shiftKey;return{action:()=>{i&&!n.parent&&i.add(n),r&&n.dispatchEvent({type:"select",value:n,object:n,ui:!!t,bubbleToParent:!0,trackUndo:!1})},undo:()=>{n.parent===i&&n.removeFromParent()}}}};function Xw(e){const t=new Set(e);return e.filter(e=>{let i=e.parent;for(;i;){if(t.has(i))return!1;i=i.parent}return!0})}async function Yw(t){const i=Xw(t);if(!i.length)return;const n=i.map(e=>e.name||e.uuid.slice(0,8)).join(", ");if(!await e.ThreeViewer.Dialog.confirm(`Delete ${i.length} object${i.length>1?"s":""}: ${n}?`))return;const r=new Map;for(const e of i)r.set(e,e.parent);for(const e of i)e.dispose&&e.dispose(!0);return{undo:()=>{for(const e of i){const t=r.get(e);t&&t.add(e)}},redo:()=>{for(const e of i)e.dispose&&e.dispose(!0)}}}function Kw(e){const t=Xw(e),i=[],n=new Map;for(const e of t){const t=e.clone(!0);cw(e,t),n.set(t,e.parent),i.push(t)}for(const e of i){const t=n.get(e);t&&!e.parent&&t.add(e)}return{clones:i,undo:()=>{for(const e of i)e.removeFromParent()},redo:()=>{for(const e of i){const t=n.get(e);t&&!e.parent&&t.add(e)}}}}const Jw=new Set(["environmentMap","background"]),Zw=new Set([]);var $w=Object.defineProperty,eC=Object.getOwnPropertyDescriptor,tC=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?eC(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&$w(t,i,s),s};function iC(e){const t="chordal",i=e.map(e=>e.position.clone()),n=new dh(i,!0,t,.75),r=e.map(e=>e.target.clone()),s=new dh(r,!0,t,.75);return{getPosition:(e,t,r)=>{r=r||new Xi;const s=1/i.length,a=((0===t?i.length:t)-1)*s;return n.getPointAt(a+e*s,r),r},getTarget:(e,t,i)=>{i=i||new Xi;const n=1/r.length,a=((0===t?r.length:t)-1)*n;return s.getPointAt(a+e*n,i),i}}}e.CameraView=class extends ri{constructor(e,t,i,n,r,s=1,a){super(),this.uuid=Ky(),this.name="Camera View",this.position=new Xi,this.target=new Xi,this.quaternion=new qi,this.zoom=1,this.duration=1,this.isWorldSpace=!0,this.set=e=>this.dispatchEvent({type:"setView",camera:e,view:this}),this.update=e=>this.dispatchEvent({type:"updateView",camera:e,view:this}),this.delete=e=>this.dispatchEvent({type:"deleteView",camera:e,view:this}),this.animate=(e,t)=>this.dispatchEvent({type:"animateView",camera:e,duration:t,view:this}),this.setDirty=e=>{this.dispatchEvent({...e,type:"update"}),this.uiConfig&&("name"===e?.key?(this.uiConfig.label=this.name,this.uiConfig.uiRefresh?.()):this.uiConfig.uiRefresh?.(!0,"postFrame"))},void 0!==e&&(this.name=e),t&&this.position.copy(t),i&&this.target.copy(i),n&&this.quaternion.copy(n),void 0!==r&&(this.zoom=r),void 0!==s&&0!==s&&(this.duration=s),void 0!==a&&(this.isWorldSpace=a)}clone(){return new e.CameraView(this.name,this.position,this.target,this.quaternion,this.zoom,this.duration,this.isWorldSpace)}},tC([Hm("setDirty"),qm(),zg()],e.CameraView.prototype,"name",2),tC([Hm("setDirty"),qm(),kg()],e.CameraView.prototype,"position",2),tC([Hm("setDirty"),qm(),kg()],e.CameraView.prototype,"target",2),tC([Hm("setDirty"),qm(),kg()],e.CameraView.prototype,"quaternion",2),tC([Hm("setDirty"),qm(),Gg()],e.CameraView.prototype,"zoom",2),tC([Hm("setDirty"),qm(),Gg()],e.CameraView.prototype,"duration",2),tC([Hm("setDirty"),qm()],e.CameraView.prototype,"isWorldSpace",2),tC([jg()],e.CameraView.prototype,"set",2),tC([jg()],e.CameraView.prototype,"update",2),tC([jg()],e.CameraView.prototype,"delete",2),tC([jg()],e.CameraView.prototype,"animate",2),e.CameraView=tC([Xm("CameraView"),Wg("Camera View")],e.CameraView);const nC={setDirty:function(e){if(!this._positionWorld)return;const t="string"==typeof e,i=t?e:e?.change??e?.key;let n=!1;!1!==e?.projectionUpdated&&(!i||["zoom","fov","left","right","top","bottom","aspect","frustumSize","view","coordinateSystem","projection","activateMain","deactivateMain","near","far","nearFar","deserialize"].includes(i))&&(this.updateProjectionMatrix(),n=!0),n=n||e?.projectionUpdated||!1,t&&(e=void 0),this.getWorldPosition(this._positionWorld),this.controls&&this.controls.target&&!1!==this.controls.enabled&&this.target!==this.controls.target?this.controls.target.copy(this.target):this.userData.autoLookAtTarget&&this.lookAt(this.target),this.dispatchEvent({...e,type:"update",bubbleToParent:!1,camera:this}),this.dispatchEvent({...e,type:"cameraUpdate",projectionUpdated:n,bubbleToParent:!0,camera:this}),qw.setDirty.call(this,{refreshScene:!1,...e,projectionUpdated:n})},activateMain:function(e={},t=!1,i=!0,n){if(!t)return null===e.camera?this.deactivateMain(e,t,i):this.dispatchEvent({type:"activateMain",...e,camera:this,bubbleToParent:!0});this.userData.__isMainCamera||(this.userData.__isMainCamera=!0,this.userData.__lastScale=this.scale.clone(),this.scale.divide(this.getWorldScale(new Xi)),n&&this.setCanvas?this.setCanvas(n,i):i&&(this.refreshCameraControls(!1),this.refreshAspect(!1)),this.setDirty({change:"activateMain",...e}))},deactivateMain:function(e={},t=!1,i=!0,n=!1){if(!t)return this.dispatchEvent({type:"activateMain",...e,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),n?this.setCanvas(void 0,i):i&&this.refreshCameraControls(!1),i&&this.refreshCameraControls(!1),this.setDirty({change:"deactivateMain",...e}))},refreshUi:function(){this.uiConfig?.uiRefresh?.(!0,"postFrame",1)},refreshTarget:function(e=4,t=!0){this.controls?.enabled&&this.controls.target?this.controls.target!==this.target&&this.target.copy(this.controls.target):this.getWorldDirection(this.target).multiplyScalar(e).add(this.getWorldPosition(new Xi)),t&&this.setDirty({change:"target"})},refreshAspect:function(e=!0){if(this.autoAspect)if(this._canvas){let e=this._canvas.clientWidth/this._canvas.clientHeight;isFinite(e)||(e=1),this.aspect=e,this.refreshFrustum&&this.refreshFrustum(!1)}else console.warn("ICamera: cannot calculate aspect ratio without canvas/container");e&&this.setDirty({change:"aspect"})},updateShaderProperties:function(e){return e.uniforms.cameraPositionWorld?.value?.copy(this._positionWorld),e.uniforms.cameraNearFar?.value?.set(this.near,this.far),e.uniforms.projection&&(e.uniforms.projection.value=this.projectionMatrix),e.defines.PERSPECTIVE_CAMERA="PerspectiveCamera"===this.type?"1":"0",e.defines.ORTHOGRAPHIC_CAMERA="OrthographicCamera"===this.type?"1":"0",this},upgradeCamera:function(){if(!this.isCamera)return void console.error("Object is not a camera",this);this.userData.__cameraSetup||(this.userData.__cameraSetup=!0,qw.upgradeObject3D.call(this),this.copy=nC.copy(this.copy),this.target||(this.target=new Xi),this._positionWorld||(this._positionWorld=new Xi),this.refreshTarget||(this.refreshTarget=nC.refreshTarget),this.refreshAspect||(this.refreshAspect=nC.refreshAspect),this.updateShaderProperties||(this.updateShaderProperties=nC.updateShaderProperties),this.activateMain||(this.activateMain=nC.activateMain),this.deactivateMain||(this.deactivateMain=nC.deactivateMain),this.refreshUi||(this.refreshUi=nC.refreshUi),this.setDirty||(this.setDirty=nC.setDirty),this.getView||(this.getView=nC.getView),this.setView||(this.setView=nC.setView),this.fitObject||(this.fitObject=nC.fitObject),this.setViewFromCamera||(this.setViewFromCamera=nC.setViewFromCamera),this.setViewToMain||(this.setViewToMain=nC.setViewToMain),this.setCanvas||(this.setCanvas=()=>rC("setCanvas")),this.setControlsCtor||(this.setControlsCtor=()=>rC("setControlsCtor")),this.removeControlsCtor||(this.removeControlsCtor=()=>rC("removeControlsCtor")),this.refreshCameraControls||(this.refreshCameraControls=()=>rC("refreshCameraControls")),this.setInteractions||(this.setInteractions=()=>rC("setInteractions")),this.dispose||(this.dispose=()=>rC("dispose")),this.assetType="camera")},copy:e=>function(t,i,n,r,...s){if(!t.isCamera)return console.error("ICamera.copy: camera is not a Camera",t),this;if(e.call(this,t,i,...s),t.target?.isVector3)this.target.copy(t.target);else{const e=this.controls?.minDistance??n??4;t.getWorldDirection(this.target).multiplyScalar(e).add(this.getWorldPosition(new Xi))}if(r){const e=t.getWorldPosition(this.position);this.parent&&this.position.copy(this.parent.worldToLocal(e))}return this.updateMatrixWorld(!0),this.updateProjectionMatrix(),this.refreshAspect(!1),this.setDirty(),this},getView:function(t=!0,i){const n=new Xi;this.updateWorldMatrix(!0,!1);const r=this.matrixWorld;n.x=r.elements[4],n.y=r.elements[5],n.z=r.elements[6],n.normalize();const s=i||new e.CameraView;s.name=this.name,s.position.copy(this.position),s.target.copy(this.target),s.quaternion.copy(this.quaternion),s.zoom=this.zoom;const a=this.parent;return a&&(t?(s.position.applyMatrix4(a.matrixWorld),this.getWorldQuaternion(s.quaternion)):n.transformDirection(a.matrixWorld.clone().invert())),s.isWorldSpace=t,s},setView:function(e){this.position.copy(e.position),this.target.copy(e.target),this.quaternion.copy(e.quaternion),this.zoom=e.zoom,this.setDirty()},fitObject:function(e,t=1.5,i){const n=Array.isArray(e)?e:[e];if(!n.length)return;const r=(new Ly).expandByObject(n[0],!1,!0);for(let e=1;e<n.length;e++)r.expandByObject(n[e],!1,!0);const s=p_(this,r),a=r.getCenter(new Xi);r.getSize(new Xi).lengthSq()<=0&&n[0].getWorldPosition(a);const o=i?.min??.5,l=i?.max??50,c=Math.min(l,Math.max(o,s*t)),h=this.getView(!0);h.target.copy(a);const d=(new Xi).subVectors(h.target,h.position).normalize();h.position.copy(d.multiplyScalar(-c).add(h.target)),this.setView(h)},setViewFromCamera:function(e,t,i=!0){this.copy(e,void 0,t,i)},setViewToMain:function(e){this.dispatchEvent({type:"setView",...e,camera:this,bubbleToParent:!0})},setNearFar(e,t,i,n,r){const s=Math.abs(e.near-t)+Math.abs(e.far-i)>.001;return e.near=t,e.far=i,n&&s&&e.setDirty?(e.setDirty({change:"nearFar",source:r}),!0):(e.updateProjectionMatrix(),!1)},defaultMinNear:.1,defaultMaxFar:1e3};function rC(e){console.warn(`ICamera.${e} is not supported on this object. Please use objects of PerspectiveCamera2 or OrthographicCamera2 classes.`)}var sC=Object.defineProperty,aC=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&sC(t,i,s),s};const oC=class extends ps{constructor(t,i,n,r,s){super(r,s),this.assetType="camera",this._currentControlsMode="",this.userData={},this.target=new Xi(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=nC.refreshAspect,this.refreshUi=nC.refreshUi,this.refreshTarget=nC.refreshTarget,this.activateMain=nC.activateMain,this.deactivateMain=nC.deactivateMain,this.updateShaderProperties=nC.updateShaderProperties,this.controlsCtors=new Map([["orbit",(t,i)=>{const n=i?i.ownerDocument?i:i.documentElement:document.body,r=new e.OrbitControls3(t,n);return-1===n.tabIndex&&(n.tabIndex=1e3,n.style.outline="none"),r.listenToKeyEvents(n),r.screenSpacePanning=!0,r}]]),this._controlsChanged=()=>{this._controls&&this._controls.target&&this.refreshTarget(void 0,!1),this.setDirty({change:"controls"})},this.getView=nC.getView,this.setView=nC.setView,this.fitObject=nC.fitObject,this.setViewFromCamera=nC.setViewFromCamera,this.setViewToMain=nC.setViewToMain,this._positionWorld=new Xi,this._camUi=[...Rg(this)||[],{type:"input",label:"Dolly FoV",property:[this,"dollyFov"]},...aw.call(this),lw.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=i,this.autoAspect=n??!!i,nC.upgradeCamera.call(this),this.controlsMode=t||"",this.refreshTarget(void 0,!1),this.setDirty()}get controls(){return this._controls}get isMainCamera(){return this.userData&&this.userData.__isMainCamera||!1}get interactionsEnabled(){return 0===this._interactionsDisabledBy.size}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 0===this._interactionsDisabledBy.size&&this.isMainCamera&&""!==this.controlsMode}setDirty(e){nC.setDirty.call(this,e),!1!==e?.last&&this._camUi?.forEach(e=>e?.uiRefresh?.(!1,"postFrame",1))}setControlsCtor(e,t,i=!1){i||!this.controlsCtors.has(e)?this.controlsCtors.set(e,t):console.error("PerspectiveCamera2: "+e+" already exists.")}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 Xi),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 e=this.canUserInteract;this._controls.enabled=e,e&&this.up.copy(Zn.DEFAULT_UP)}e&&this.setDirty(),this.refreshUi()}}toJSON(e,t=!1){return t?{...super.toJSON(e),...f_.Serialize(this,e,!0)}:f_.Serialize(this,e,!1)}fromJSON(e,t){if((e.camOptions||"auto"===e.aspect)&&(e={...e}),e.camOptions){const t=e.camOptions;t.fov&&(e.fov=t.fov),t.focus&&(e.focus=t.focus),t.zoom&&(e.zoom=t.zoom),t.aspect&&(e.aspect=t.aspect),t.controlsMode&&(e.controlsMode=t.controlsMode),delete e.camOptions}return"auto"===e.aspect&&(e.aspect=this.aspect,this.autoAspect=!0),f_.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()}};aC([zg("Name")],oC.prototype,"name"),aC([qm("camControls")],oC.prototype,"_controls"),aC([Ng("Controls Mode",void 0,e=>({children:["none",...e.controlsCtors.keys()].map(e=>({label:e,value:"none"===e?"":e}))})),qm(),Vm(oC.prototype.refreshCameraControls)],oC.prototype,"controlsMode"),aC([qm()],oC.prototype,"userData"),aC([Hm(oC.prototype.setDirty),Fg("Field Of View",[1,180],.001),qm()],oC.prototype,"fov"),aC([Hm(oC.prototype.setDirty),qm()],oC.prototype,"focus"),aC([Hm(oC.prototype.setDirty),Gg("FoV Zoom"),qm()],oC.prototype,"zoom"),aC([kg("Position",void 0,void 0,e=>({onChange:()=>e.setDirty({change:"position"})})),qm()],oC.prototype,"position"),aC([kg("Up",void 0,void 0,e=>({onChange:()=>e.setDirty({change:"up"})})),qm()],oC.prototype,"up"),aC([kg("Rotation",void 0,void 0,e=>({onChange:()=>e.setDirty({change:"rotation"}),disabled:()=>e.autoLookAtTarget}))],oC.prototype,"rotation"),aC([kg("Target",void 0,void 0,e=>({onChange:()=>e.setDirty({change:"target"}),disabled:()=>!e.autoLookAtTarget})),qm()],oC.prototype,"target"),aC([qm(),Vm("refreshAspect"),Hg("Auto Aspect")],oC.prototype,"autoAspect"),aC([qm(),Vm("refreshAspect"),Gg("Aspect Ratio",e=>({hidden:()=>e.autoAspect}))],oC.prototype,"aspect"),aC([zy({obj:"userData",onChange:"setDirty"})],oC.prototype,"autoLookAtTarget"),aC([zy({obj:"userData",onChange:"setDirty"})],oC.prototype,"autoNearFar"),aC([zy({obj:"userData",onChange:"setDirty"})],oC.prototype,"minNearPlane"),aC([zy({obj:"userData",onChange:"setDirty"})],oC.prototype,"maxFarPlane"),aC([zy({obj:"userData"})],oC.prototype,"dollyFov"),aC([Qm((e,t)=>{t||console.warn("Setting camera invisible is not supported",e,t)})],oC.prototype,"visible");let lC=oC;class cC extends lC{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 hC=Object.defineProperty,dC=Object.getOwnPropertyDescriptor,uC=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?dC(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&hC(t,i,s),s};const pC=class extends zs{constructor(t,i,n,r,s,a,o,l,c,h,d){super(s,a,o,l,c,h),this.assetType="camera",this._currentControlsMode="",this.userData={},this._frustumSize=void 0,this.target=new Xi(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=nC.refreshAspect,this.refreshUi=nC.refreshUi,this.refreshTarget=nC.refreshTarget,this.activateMain=nC.activateMain,this.deactivateMain=nC.deactivateMain,this.updateShaderProperties=nC.updateShaderProperties,this.controlsCtors=new Map([["orbit",(t,i)=>{const n=i?i.ownerDocument?i:i.documentElement:document.body,r=new e.OrbitControls3(t,n);return-1===n.tabIndex&&(n.tabIndex=1e3,n.style.outline="none"),r.listenToKeyEvents(n),r.screenSpacePanning=!0,r}]]),this._controlsChanged=()=>{this._controls&&this._controls.target&&this.refreshTarget(void 0,!1),this.setDirty({change:"controls"})},this.getView=nC.getView,this.setView=nC.setView,this.fitObject=nC.fitObject,this.setViewFromCamera=nC.setViewFromCamera,this.setViewToMain=nC.setViewToMain,this._positionWorld=new Xi,this._camUi=[...Rg(this)||[],...aw.call(this),lw.call(this)],this.uiConfig={type:"folder",label:()=>this.name||"Camera",children:[...this._camUi,()=>this._controls?.uiConfig]},this._canvas=i,this.aspect=d||1,this._frustumSize=r??4,this.autoAspect=n??!!i,nC.upgradeCamera.call(this),this.controlsMode=t||"",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 0===this._interactionsDisabledBy.size}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 0===this._interactionsDisabledBy.size&&this.isMainCamera&&""!==this.controlsMode}setDirty(e){nC.setDirty.call(this,e),!1!==e?.last&&this._camUi?.forEach(e=>e?.uiRefresh?.(!1,"postFrame",1))}refreshFrustum(e=!0){void 0!==this._frustumSize&&(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){i||!this.controlsCtors.has(e)?this.controlsCtors.set(e,t):console.error("OrthographicCamera2: "+e+" already exists.")}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 Xi),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 e=this.canUserInteract;this._controls.enabled=e,e&&this.up.copy(Zn.DEFAULT_UP)}e&&this.setDirty(),this.refreshUi()}}toJSON(e,t=!1){return t?{...super.toJSON(e),...f_.Serialize(this,e,!0)}:f_.Serialize(this,e,!1)}fromJSON(e,t){return f_.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()}};uC([zg("Name")],pC.prototype,"name",2),uC([qm("camControls")],pC.prototype,"_controls",2),uC([Ng("Controls Mode",void 0,e=>({children:["none",...e.controlsCtors.keys()].map(e=>({label:e,value:"none"===e?"":e}))})),qm(),Vm(pC.prototype.refreshCameraControls)],pC.prototype,"controlsMode",2),uC([qm()],pC.prototype,"userData",2),uC([Hm(pC.prototype.setDirty),Gg("Zoom"),qm()],pC.prototype,"zoom",2),uC([Hm(pC.prototype.setDirty),Gg("Left",e=>({hidden:()=>void 0!==e._frustumSize})),qm()],pC.prototype,"left",2),uC([Hm(pC.prototype.setDirty),Gg("Right",e=>({hidden:()=>void 0!==e._frustumSize})),qm()],pC.prototype,"right",2),uC([Hm(pC.prototype.setDirty),Gg("Top",e=>({hidden:()=>void 0!==e._frustumSize})),qm()],pC.prototype,"top",2),uC([Hm(pC.prototype.setDirty),Gg("Bottom",e=>({hidden:()=>void 0!==e._frustumSize})),qm()],pC.prototype,"bottom",2),uC([zg("Frustum Size")],pC.prototype,"frustumSize",1),uC([kg("Position",void 0,void 0,e=>({onChange:()=>e.setDirty({change:"position"})})),qm()],pC.prototype,"position",2),uC([kg("Up",void 0,void 0,e=>({onChange:()=>e.setDirty({change:"up"})})),qm()],pC.prototype,"up",2),uC([kg("Rotation",void 0,void 0,e=>({onChange:()=>e.setDirty({change:"rotation"}),disabled:()=>e.autoLookAtTarget}))],pC.prototype,"rotation",2),uC([kg("Target",void 0,void 0,e=>({onChange:()=>e.setDirty({change:"target"}),disabled:()=>!e.autoLookAtTarget})),qm()],pC.prototype,"target",2),uC([qm(),Vm("refreshAspect"),Hg("Auto Aspect")],pC.prototype,"autoAspect",2),uC([qm(),Vm("refreshAspect"),Gg("Aspect Ratio",e=>({hidden:()=>e.autoAspect}))],pC.prototype,"aspect",2),uC([zy({obj:"userData",onChange:"setDirty"})],pC.prototype,"autoLookAtTarget",2),uC([zy({obj:"userData",onChange:"setDirty"})],pC.prototype,"autoNearFar",2),uC([zy({obj:"userData",onChange:"setDirty"})],pC.prototype,"minNearPlane",2),uC([zy({obj:"userData",onChange:"setDirty"})],pC.prototype,"maxFarPlane",2),uC([Qm((e,t)=>{t||console.warn("Setting camera invisible is not supported",e,t)})],pC.prototype,"visible",2);let mC=pC;class gC extends mC{constructor(e,t,i,n,r,s){super(void 0,void 0,void 0,void 0,e,t,i,n,r,s,1),(void 0!==r||s)&&(this.autoNearFar=!1,r&&(this.near=r,this.minNearPlane=r),s&&(this.far=s,this.maxFarPlane=s))}}class fC extends Hw{constructor(e,t,i=!1){super(e,i),this.textures=[],this.setTextureIds(t)}setTextureIds(e){this.textures.map(e=>e.id).join(";")!==e.join(";")&&(this.textures=e.map(e=>({id:e,colorSpace:Ut})),this.setDirty())}_setUniformTexSize(e,t){if(!t||!e)return;const i=t?.width??512,n=t?.height??512,r=e.value;r.isVector2||console.warn("uniform is not a Vector2"),r&&Math.abs(r.x-i)+Math.abs(r.y-n)>.1&&(r.x=i,r.y=n,this.uniformsNeedUpdate=!0)}onBeforeRender(e,t,i,n,r,s){this.uniforms.screenSize&&this._setUniformTexSize(this.uniforms.screenSize,e.getRenderTarget()??e.getSize(new fi));for(const e of this.textures){const t=e.id,i=this.uniforms[t]?.value;i&&(this._setUniformTexSize(this.uniforms[t+"Size"],i.image),i.colorSpace!==e.colorSpace&&(e.colorSpace=i.colorSpace,this.needsUpdate=!0))}super.onBeforeRender(e,t,i,n,r,s)}onBeforeCompile(e,t){const i="\n"+this.textures.map(e=>`uniform sampler2D ${e.id}; \n`+Qy(e.id??"input",e.colorSpace)).join("\n");e.fragmentShader.includes("#include <encodings_pars_fragment>")?e.fragmentShader=R_(e.fragmentShader,"#include <encodings_pars_fragment>",i,{append:!0}):e.fragmentShader.includes("precision highp float;")?e.fragmentShader=R_(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 AC=class extends Id{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isPhysicalMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Nw.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=Nw.registerMaterialExtensions,this.unregisterMaterialExtensions=Nw.unregisterMaterialExtensions,this.onAfterRender=Nw.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Physical Material",uuid:"MPM2_"+this.uuid,expanded:!0,onChange:e=>{if(!e.config||e.config.onChange)return;let t=Array.isArray(e.config.property)?e.config.property[1]:e.config.property;t="string"==typeof t?t:void 0,this.setDirty({uiChangeEvent:e,needsUpdate:!!e.last,refreshUi:!!e.last,change:t})},children:[...xw(this),...Rg(this),ww(this),Tw(this),Iw(this),Pw(this),Dw(this),Mw(this),Sw(this),Rw(this),Bw(this),Lw(this),Cw(this),...Ew(this)]},this.fog=!1,this.attenuationDistance=0,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Nw.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Nw.dispose(super.dispose).call(this)}clone(e=!1){return Nw.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Nw.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 t of n)e.vertexShader=R_(e.vertexShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);for(const t of i)e.fragmentShader=R_(e.fragmentShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);e.fragmentShader=R_(e.fragmentShader,"#include <opaque_fragment>","gl_FragColor = clamp(gl_FragColor, 0.0, 1000.0);\n",{append:!0}),Nw.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,r,s){super.onBeforeRender(e,t,i,n,r,s),Nw.onBeforeRender.call(this,e,t,i,n,r,s);const a=this.userData.inverseAlphaMap?1:0;a!==this.defines.INVERSE_ALPHAMAP&&(this.defines.INVERSE_ALPHAMAP=a,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))return void console.error("Material type is not supported:",e.type);"number"==typeof e.normalScale&&(e.normalScale=[e.normalScale,e.normalScale]),void 0!==e.ior&&(this.ior=e.ior),Nw.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),...f_.Serialize(this,e,!0)}:f_.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(f_.Deserialize(e,this,t,!0),this.setValues(e),this):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};AC.TypeSlug="pmat",AC.TYPE="PhysicalMaterial",AC.TypeAlias=["physical","standard",AC.TYPE,AC.TypeSlug,"MeshStandardMaterial","MeshStandardMaterial2","MeshPhysicalMaterial"],f_.SerializableMaterials.add(AC),AC.MaterialProperties={...Ow,color:new mr(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:Rt,normalScale:new fi(1,1),displacementMap:null,displacementScale:1,displacementBias:0,roughnessMap:null,metalnessMap:null,alphaMap:null,envMap:null,envMapRotation:new On,envMapIntensity:1,wireframe:!1,wireframeLinewidth:1,wireframeLinecap:"round",wireframeLinejoin:"round",flatShading:!1,fog:!0,clearcoat:0,clearcoatMap:null,clearcoatRoughness:0,clearcoatRoughnessMap:null,clearcoatNormalScale:new fi(1,1),clearcoatNormalMap:null,dispersion:0,reflectivity:.5,iridescence:0,iridescenceMap:null,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],iridescenceThicknessMap:null,sheen:0,sheenColor:new mr(0),sheenColorMap:null,sheenRoughness:1,sheenRoughnessMap:null,transmission:0,transmissionMap:null,thickness:0,thicknessMap:null,attenuationDistance:1/0,attenuationColor:new mr(1,1,1),specularIntensity:1,specularIntensityMap:null,specularColor:new mr(1,1,1),specularColorMap:null,anisotropy:0,anisotropyRotation:0,anisotropyMap:null},AC.MapProperties=["map","lightMap","aoMap","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap","envMap","clearcoatMap","clearcoatRoughnessMap","clearcoatNormalMap","iridescenceMap","iridescenceThicknessMap","sheenColorMap","sheenRoughnessMap","transmissionMap","thicknessMap","specularIntensityMap","specularColorMap","anisotropyMap"],AC.InterpolateProperties=[...Uw,"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 yC=AC;const vC=class extends ls{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isObjectShaderMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Nw.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Nw.registerMaterialExtensions,this.unregisterMaterialExtensions=Nw.unregisterMaterialExtensions,this.onBeforeRender=Nw.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=Nw.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Shader Material",uuid:"OSM2_"+this.uuid,expanded:!0,onChange:e=>{if(!e.config||e.config.onChange)return;let t=Array.isArray(e.config.property)?e.config.property[1]:e.config.property;t="string"==typeof t?t:void 0,this.setDirty({uiChangeEvent:e,needsUpdate:!!e.last,refreshUi:!!e.last,change:t})},children:[...Rg(this),...xw(this),ww(this),Cw(this),...Ew(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Nw.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Nw.dispose(super.dispose).call(this)}clone(e=!1){return Nw.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Nw.customProgramCacheKey.call(this)}onBeforeCompile(e,t){Nw.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)?(Nw.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):(console.error("Material type is not supported:",e.type),this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...f_.Serialize(this,e,!0)}:f_.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(f_.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};vC.TypeSlug="shmat",vC.TYPE="ObjectShaderMaterial",vC.TypeAlias=["shader",vC.TYPE,vC.TypeSlug,"ShaderMaterial"],f_.SerializableMaterials.add(vC),vC.MaterialProperties={...Ow,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},vC.InterpolateProperties=[...Uw,"linewidth","wireframeLinewidth"];let _C=vC;const bC=class extends Dc{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isUnlitLineMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Nw.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Nw.registerMaterialExtensions,this.unregisterMaterialExtensions=Nw.unregisterMaterialExtensions,this.onBeforeRender=Nw.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=Nw.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Unlit Line Material",uuid:"MBLM2_"+this.uuid,expanded:!0,onChange:e=>{if(!e.config||e.config.onChange)return;let t=Array.isArray(e.config.property)?e.config.property[1]:e.config.property;t="string"==typeof t?t:void 0,this.setDirty({uiChangeEvent:e,needsUpdate:!!e.last,refreshUi:!!e.last,change:t})},children:[{type:"input",property:[this,"name"]},{type:"checkbox",property:[this,"vertexColors"]},{type:"color",property:[this,"color"]},bw(this,"map"),{type:"number",property:[this,"linewidth"]},{type:"dropdown",property:[this,"linecap"],children:["butt","round","square"].map(e=>({label:e}))},{type:"dropdown",property:[this,"linejoin"],children:["bevel","round","miter"].map(e=>({label:e}))},ww(this),Cw(this),...Ew(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Nw.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Nw.dispose(super.dispose).call(this)}clone(e=!1){return Nw.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Nw.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 t of n)e.vertexShader=R_(e.vertexShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);for(const t of i)e.fragmentShader=R_(e.fragmentShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);Nw.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)?(Nw.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):(console.error("Material type is not supported:",e.type),this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...f_.Serialize(this,e,!0)}:f_.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(f_.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};bC.TypeSlug="blmat",bC.TYPE="UnlitLineMaterial",bC.TypeAlias=["unlitline","basicline",bC.TYPE,bC.TypeSlug,"LineBasicMaterial"],f_.SerializableMaterials.add(bC),bC.MaterialProperties={...Ow,color:new mr(16777215),map:null,linewidth:1,linecap:"round",linejoin:"round",fog:!0},bC.MapProperties=["map"],bC.InterpolateProperties=[...Uw,"color","linewidth"];let xC=bC;var wC=Object.defineProperty,CC=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&wC(t,i,s),s};const SC=(i=class extends Cv{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isLineMaterial2=!0,this.appliedMeshes=new Set,this.setDirty=Nw.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Nw.registerMaterialExtensions,this.unregisterMaterialExtensions=Nw.unregisterMaterialExtensions,this.autoUpdateResolution=!0,this.uiConfig={type:"folder",label:"Line Material",uuid:"MPM2_"+this.uuid,expanded:!0,onChange:e=>{if(!e.config||e.config.onChange)return;let t=Array.isArray(e.config.property)?e.config.property[1]:e.config.property;t="string"==typeof t?t:void 0,this.setDirty({uiChangeEvent:e,needsUpdate:!!e.last,refreshUi:!!e.last,change:t})},children:[...Rg(this)||[],ww(this),Cw(this),...Ew(this)]},this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Nw.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Nw.dispose(super.dispose).call(this)}clone(e=!1){return Nw.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Nw.customProgramCacheKey.call(this)}onBeforeCompile(e,t){const i=[["vec4 diffuseColor = ","beforeAccumulation"],["#include <clipping_planes_fragment>","mainStart"]],n=[["#ifdef USE_COLOR","mainStart"]];for(const t of n)e.vertexShader=R_(e.vertexShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);for(const t of i)e.fragmentShader=R_(e.fragmentShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);Nw.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}onBeforeRender(e,t,i,n,r,s){this.autoUpdateResolution&&e.getSize(this.resolution),super.onBeforeRender(e,t,i,n,r,s),Nw.onBeforeRender.call(this,e,t,i,n,r,s)}onAfterRender(e,t,i,n,r,s){super.onAfterRender(e,t,i,n,r,s),Nw.onAfterRender.call(this,e,t,i,n,r,s)}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?(Nw.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):(console.error("Material type is not supported:",e.type),this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...f_.Serialize(this,e,!0)}:f_.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(f_.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}},i.TypeSlug="lmat",i.TYPE="LineMaterial2",i.TypeAlias=["line",i.TYPE,i.TypeSlug,"LineMaterial"],f_.SerializableMaterials.add(i),i.MaterialProperties={...Ow,color:new mr(16777215),dashed:!1,dashScale:1,dashSize:1,dashOffset:0,gapSize:1,linewidth:1,resolution:new fi(1,1),alphaToCoverage:!1,worldUnits:!1,uniforms:{},defines:{},extensions:{},clipping:!1,fog:!0,fragmentShader:"",vertexShader:""},i.InterpolateProperties=[...Uw,"color","dashScale","dashSize","dashOffset","gapSize","linewidth","resolution"],i);CC([zg()],SC.prototype,"name"),CC([Qg()],SC.prototype,"color"),CC([Hg()],SC.prototype,"dashed"),CC([Gg()],SC.prototype,"dashScale"),CC([Gg()],SC.prototype,"dashSize"),CC([Gg()],SC.prototype,"dashOffset"),CC([Gg()],SC.prototype,"gapSize"),CC([Gg()],SC.prototype,"linewidth"),CC([kg()],SC.prototype,"resolution"),CC([Hg()],SC.prototype,"alphaToCoverage"),CC([Hg()],SC.prototype,"worldUnits");let MC=SC;const EC=class extends Pd{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isLegacyPhongMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Nw.setDirty,this.envMap=null,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Nw.registerMaterialExtensions,this.unregisterMaterialExtensions=Nw.unregisterMaterialExtensions,this.onBeforeRender=Nw.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=Nw.onAfterRenderOverride(super.onAfterRender),this.uiConfig={type:"folder",label:"Phong Material",uuid:"MBM2_"+this.uuid,expanded:!0,onChange:e=>{if(!e.config||e.config.onChange)return;let t=Array.isArray(e.config.property)?e.config.property[1]:e.config.property;t="string"==typeof t?t:void 0,this.setDirty({uiChangeEvent:e,needsUpdate:!!e.last,refreshUi:!!e.last,change:t})},children:[...xw(this),ww(this),Cw(this),Sw(this),{type:"folder",label:"Specular",children:[{type:"color",property:[this,"specular"]},{type:"image",property:[this,"specularMap"]},bw(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}]},Iw(this),Pw(this),{type:"folder",label:"Env Map",children:[{type:"image",property:[this,"envMap"]},bw(this,"envMap"),{type:"slider",label:"Env Map Intensity",property:[this,"envMapIntensity"],bounds:[0,5],stepSize:.01}]},...Ew(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Nw.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Nw.dispose(super.dispose).call(this)}clone(e=!1){return Nw.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Nw.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 t of n)e.vertexShader=R_(e.vertexShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);for(const t of i)e.fragmentShader=R_(e.fragmentShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);Nw.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)?(Nw.setValues(super.setValues).call(this,e,t,i,n),this.userData.uuid=this.uuid,this):(console.error("Material type is not supported:",e.type),this):this}copy(e){return this.setValues(e,!1)}toJSON(e,t=!1){return t?{...super.toJSON(e),...f_.Serialize(this,e,!0)}:f_.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(f_.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};EC.TypeSlug="phongmat",EC.TYPE="LegacyPhongMaterial",EC.TypeAlias=["phong",EC.TYPE,EC.TypeSlug,"MeshPhongMaterial"],f_.SerializableMaterials.add(EC),EC.MaterialProperties={...Ow,color:new mr(16777215),specular:new mr(1118481),shininess:30,map:null,lightMap:null,lightMapIntensity:1,aoMap:null,aoMapIntensity:1,emissive:new mr(0),emissiveIntensity:1,emissiveMap:null,bumpMap:null,bumpScale:1,normalMap:null,normalMapType:"TangentSpaceNormalMap",normalScale:new fi(1,1),displacementMap:null,displacementScale:1,displacementBias:0,specularMap:null,alphaMap:null,envMap:null,combine:0,envMapIntensity:1,reflectivity:1,refractionRatio:.98,wireframe:!1,wireframeLinewidth:1,wireframeLinecap:"round",wireframeLinejoin:"round",skinning:!1,fog:!0,flatShading:!1},EC.MapProperties=["map","lightMap","aoMap","emissiveMap","bumpMap","normalMap","displacementMap","specularMap","alphaMap","envMap"],EC.InterpolateProperties=[...Uw,"color","specular","emissive","shininess","lightMapIntensity","aoMapIntensity","emissiveIntensity","bumpScale","normalScale","displacementScale","displacementBias","envMapIntensity","reflectivity","refractionRatio","wireframeLinewidth"];let TC=EC;class IC extends Zn{constructor(){super(),this.assetType="model",this.setDirty=qw.setDirty,this.refreshUi=qw.refreshUi,qw.upgradeObject3D.call(this)}get modelObject(){return this}dispose(){}}class PC extends ll{constructor(){super(),this.assetType="model",this.setDirty=qw.setDirty,this.refreshUi=qw.refreshUi,qw.upgradeObject3D.call(this)}get modelObject(){return this}dispose(){}}class DC extends ts{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=qw.setDirty,this.refreshUi=qw.refreshUi,qw.upgradeObject3D.call(this)}get modelObject(){return this}}class RC extends wv{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 BC extends zv{constructor(e=new RC,t=new Cv({color:16777215*Math.random()})){super(e,t),this.isLine2=!0,this.type="Line2"}}class LC extends BC{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=qw.setDirty,this.refreshUi=qw.refreshUi,this.isMeshLine=!0,qw.upgradeObject3D.call(this)}get modelObject(){return this}}class OC extends zv{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=qw.setDirty,this.refreshUi=qw.refreshUi,this.isMeshLineSegments=!0,qw.upgradeObject3D.call(this)}get modelObject(){return this}}class UC extends Fr{constructor(){super(),this.center2=dw.center2,this.setDirty=dw.setDirty,this.refreshUi=dw.refreshUi,this.appliedMeshes=new Set,dw.upgradeGeometry.call(this)}}class FC extends RC{constructor(){super(),this.center2=dw.center2,this.setDirty=dw.setDirty,this.refreshUi=dw.refreshUi,this.appliedMeshes=new Set,dw.upgradeGeometry.call(this)}getPositions(){return kC(this.attributes.instanceStart)}getColors(){return kC(this.attributes.instanceColorStart)}}function kC(e){const t=e?.data.array;if(!t)return null;const i=t.length/2+3,n=new Float32Array(i);n[0]=t[0],n[1]=t[1],n[2]=t[2];for(let e=3;e<i;e+=3){const i=2*e-3;n[e]=t[i],n[e+1]=t[i+1],n[e+2]=t[i+2]}return n}class NC extends wv{constructor(){super(),this.center2=dw.center2,this.setDirty=dw.setDirty,this.refreshUi=dw.refreshUi,this.appliedMeshes=new Set,dw.upgradeGeometry.call(this)}getPositions(){return this.attributes.instanceStart?.data.array||null}getColors(){return this.attributes.instanceColorStart?.data.array||null}}class jC extends wv{constructor(e){super(),this.isWireframeGeometry2=!0,this.type="WireframeGeometry2",this.fromWireframeGeometry(new wd(e))}}class zC extends Fr{constructor(e,t,i=32,n=64,r=!1,s=new fi(1,1),a="shape"){super(),this.type="TubeShapeGeometry",this.parameters={path:t,shape:e,shapeSegments:i,tubularSegments:n,closed:r,primary:a,shapeScale:s.clone()};const o=t.computeFrenetFrames(n,r);this.frames=o;const l=new Xi,c=new Xi,h=new Xi,d=new fi;let u=new Xi;const p=[],m=[],g=[],f=e.getSpacedPoints(i);for(const e of f)e.multiply(s);(function(){for(let e=0;e<n;e++)y(e);y(!1===r?n:0),function(){for(let e=0;e<=n;e++)for(let t=0;t<=i;t++)d.x=e/n,d.y=t/i,m.push(d.x,d.y)}(),function(){const e="shape"===a,t=e?i:n,r=e?n:i;for(let n=1;n<=t;n++)for(let t=1;t<=r;t++){const[r,s]=e?[t,n]:[n,t],a=(i+1)*(r-1)+(s-1),o=(i+1)*r+(s-1),l=(i+1)*r+s,c=(i+1)*(r-1)+s;g.push(a,o,c),g.push(o,l,c)}}()})(),this.setIndex(g),this.setAttribute("position",new Ir(p,3)),this.setAttribute("uv",new Ir(m,2)),this.computeVertexNormals();const A=this.attributes.normal;function y(e){u=t.getPointAt(e/n,u);const r=o.normals[e],s=o.binormals[e];for(let e=0;e<=i;e++){const t=f[e%i];c.set(0,0,0).addScaledVector(r,t.x).addScaledVector(s,t.y),l.copy(u).add(c),p.push(l.x,l.y,l.z)}}!function(){for(let e=1;e<i;e++){const t=e+n*(i+1);c.fromBufferAttribute(A,e),h.fromBufferAttribute(A,t),c.add(h).normalize(),A.setXYZ(e,c.x,c.y,c.z),A.setXYZ(t,c.x,c.y,c.z)}for(let e=1;e<n;e++){const t=e*(i+1),n=t+i;c.fromBufferAttribute(A,t),h.fromBufferAttribute(A,n),c.add(h).normalize(),A.setXYZ(t,c.x,c.y,c.z),A.setXYZ(n,c.x,c.y,c.z)}c.fromBufferAttribute(A,0),h.fromBufferAttribute(A,i),c.add(h);const e=n*(i+1);h.fromBufferAttribute(A,e),c.add(h),h.fromBufferAttribute(A,e+i),c.add(h),c.normalize(),A.setXYZ(0,c.x,c.y,c.z),A.setXYZ(i,c.x,c.y,c.z),A.setXYZ(e,c.x,c.y,c.z),A.setXYZ(e+i,c.x,c.y,c.z),A.needsUpdate=!0}()}createSplits(e){this.clearGroups();const t="shape"===this.parameters.primary?this.parameters.shapeSegments:this.parameters.tubularSegments,i=this.index.count,n=[...e,1].sort((e,t)=>e-t);let r=0,s=0;for(const e of n){const n=Math.round(t*e)*i/t;this.addGroup(r,n-r,s++),r=n}return this.groups.length}toJSON(){const e=super.toJSON();return e.path=this.parameters.path.toJSON(),e.shape=this.parameters.shape.toJSON(),e}}const GC=class extends rh{constructor(e,t,i,n,r,s,a,o){super(e,t,i,n,r,s,a,o),this.type="EllipseCurve3D"}getPoint(e,t){return super.getPoint(e,t||new Xi)}};jm.SerializableClasses.set("EllipseCurve3D",GC);let QC=GC;const VC={setDirty:function(e,...t){"string"==typeof e&&(e={change:e}),qw.setDirty.call(this,e,...t)},upgradeLight:function(e){this&&qw.upgradeObject3D.call(this,e)},refreshUi:qw.refreshUi};var HC=Object.defineProperty,WC=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&HC(t,i,s),s};class qC extends Tu{constructor(e,t){super(e,t),this.assetType="light",this.setDirty=VC.setDirty,this.refreshUi=VC.refreshUi,this.uiConfig={type:"folder",label:"Ambient Light",children:[...Rg(this),...hw.call(this)]},this.isAmbientLight2=!0,VC.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}}WC([Hg("Enabled"),Hm("setDirty")],qC.prototype,"visible"),WC([zg("Name"),Hm("setDirty")],qC.prototype,"name"),WC([Qg("Color",e=>({onChange:()=>e.setDirty()}))],qC.prototype,"color"),WC([Gg("Intensity"),Hm("setDirty")],qC.prototype,"intensity");var XC=Object.defineProperty,YC=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&XC(t,i,s),s};const KC=class extends Eu{constructor(e,t){super(e,t),this.assetType="light",this.setDirty=VC.setDirty,this.refreshUi=VC.refreshUi,this.uiConfig={type:"folder",label:"Directional Light",children:[...Rg(this),...hw.call(this)]},this.isDirectionalLight2=!0,this.target.position.set(0,0,-1),this.add(this.target),VC.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}};YC([Hg("Enabled"),Hm("setDirty")],KC.prototype,"visible"),YC([zg("Name"),Hm("setDirty")],KC.prototype,"name"),YC([Qg("Color",e=>({onChange:()=>e.setDirty()}))],KC.prototype,"color"),YC([Fg("Intensity",[0,100],.01),Hm("setDirty")],KC.prototype,"intensity"),YC([kg("Position",void 0,void 0,e=>({onChange:()=>e.setDirty()}))],KC.prototype,"position"),YC([kg("Rotation",void 0,void 0,e=>({onChange:()=>e.setDirty()}))],KC.prototype,"rotation"),YC([Hg("Cast Shadow"),Hm("setDirty")],KC.prototype,"castShadow"),YC([kg("Shadow Map Size",void 0,void 0,e=>({onChange:()=>e._mapSizeChanged()})),zy({obj:"shadow",key:"mapSize",onChange:KC.prototype._mapSizeChanged,onChangeParams:!1})],KC.prototype,"shadowMapSize"),YC([Fg("Shadow Bias",[-.001,.001],1e-5),zy({obj:"shadow",key:"bias",onChange:"setDirty"})],KC.prototype,"shadowBias"),YC([Fg("Shadow Normal Bias",[-.1,.1],.005),zy({obj:"shadow",key:"normalBias",onChange:"setDirty"})],KC.prototype,"shadowNormalBias"),YC([Fg("Shadow Radius",[0,5],.01),zy({obj:"shadow",key:"radius",onChange:"setDirty"})],KC.prototype,"shadowRadius"),YC([Gg("Shadow Frustum"),Vm(KC.prototype._shadowFrustumChanged)],KC.prototype,"shadowFrustum"),YC([Gg("Shadow Near"),zy({obj:"shadow",key:["camera","near"],onChange:KC.prototype._shadowCamUpdate})],KC.prototype,"shadowNear"),YC([Gg("Shadow Far"),zy({obj:"shadow",key:["camera","far"],onChange:KC.prototype._shadowCamUpdate})],KC.prototype,"shadowFar");let JC=KC;var ZC=Object.defineProperty,$C=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&ZC(t,i,s),s};class eS extends mu{constructor(e,t,i){super(e,t,i),this.assetType="light",this.setDirty=VC.setDirty,this.refreshUi=VC.refreshUi,this.uiConfig={type:"folder",label:"Hemisphere Light",children:[...Rg(this),...hw.call(this)]},this.isHemisphereLight2=!0,VC.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}}$C([Hg("Enabled"),Hm("setDirty")],eS.prototype,"visible"),$C([zg("Name"),Hm("setDirty")],eS.prototype,"name"),$C([Qg("Sky Color",e=>({onChange:()=>e.setDirty()}))],eS.prototype,"color"),$C([Qg("Ground Color",e=>({onChange:()=>e.setDirty()}))],eS.prototype,"groundColor"),$C([Gg("Intensity"),Hm("setDirty")],eS.prototype,"intensity"),$C([kg("Position",void 0,void 0,e=>({onChange:()=>e.setDirty()}))],eS.prototype,"position");var tS=Object.defineProperty,iS=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&tS(t,i,s),s};const nS=class extends Su{constructor(e,t,i,n){super(e,t,i,n),this.assetType="light",this.setDirty=VC.setDirty,this.refreshUi=VC.refreshUi,this.uiConfig={type:"folder",label:"Point Light",children:[...Rg(this),...hw.call(this)]},this.isPointLight2=!0,VC.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}};iS([Hg("Enabled"),Hm("setDirty")],nS.prototype,"visible"),iS([zg("Name"),Hm("setDirty")],nS.prototype,"name"),iS([Qg("Color",e=>({onChange:()=>e.setDirty()}))],nS.prototype,"color"),iS([Gg("Intensity"),Hm("setDirty")],nS.prototype,"intensity"),iS([Gg("Distance"),Hm("setDirty")],nS.prototype,"distance"),iS([Gg("Decay"),Hm("setDirty")],nS.prototype,"decay"),iS([Gg("Power"),Hm("setDirty")],nS.prototype,"power"),iS([kg("Position",void 0,void 0,e=>({onChange:()=>e.setDirty()}))],nS.prototype,"position"),iS([Hg("Cast Shadow"),Hm("setDirty")],nS.prototype,"castShadow"),iS([kg("Shadow Map Size",void 0,void 0,e=>({onChange:()=>e._mapSizeChanged()})),zy({obj:"shadow",key:"mapSize",onChange:nS.prototype._mapSizeChanged,onChangeParams:!1})],nS.prototype,"shadowMapSize"),iS([Fg("Shadow Bias",[-.001,.001],1e-5),zy({obj:"shadow",key:"bias",onChange:"setDirty"})],nS.prototype,"shadowBias"),iS([Fg("Shadow Radius",[0,5],.01),zy({obj:"shadow",key:"radius",onChange:"setDirty"})],nS.prototype,"shadowRadius"),iS([Gg("Shadow Near"),zy({obj:"shadow",key:["camera","near"],onChange:nS.prototype._shadowCamUpdate})],nS.prototype,"shadowNear"),iS([Gg("Shadow Far"),zy({obj:"shadow",key:["camera","far"],onChange:nS.prototype._shadowCamUpdate})],nS.prototype,"shadowFar"),iS([Gg("Shadow Aspect"),zy({obj:"shadow",key:"aspect",onChange:nS.prototype._shadowCamUpdate})],nS.prototype,"shadowAspect"),iS([Fg("Shadow FOV",[1,179],1),zy({obj:"shadow",key:"fov",onChange:nS.prototype._shadowCamUpdate})],nS.prototype,"shadowFov");let rS=nS;var sS=Object.defineProperty,aS=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&sS(t,i,s),s};class oS extends Iu{constructor(e,t,i,n){super(e,t,i,n),this.assetType="light",this.setDirty=VC.setDirty,this.refreshUi=VC.refreshUi,this.uiConfig={type:"folder",label:"RectArea Light",children:[...Rg(this),...hw.call(this)]},this.isRectAreaLight2=!0,VC.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}}aS([Hg("Enabled"),Hm("setDirty")],oS.prototype,"visible"),aS([zg("Name"),Hm("setDirty")],oS.prototype,"name"),aS([Qg("Color",e=>({onChange:()=>e.setDirty()}))],oS.prototype,"color"),aS([Gg("Intensity"),Hm("setDirty")],oS.prototype,"intensity"),aS([Gg("Width"),Hm("setDirty")],oS.prototype,"width"),aS([Gg("Height"),Hm("setDirty")],oS.prototype,"height"),aS([Gg("Power"),Hm("setDirty")],oS.prototype,"power");var lS=Object.defineProperty,cS=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&lS(t,i,s),s};const hS=class extends _u{constructor(e,t,i,n,r,s){super(e,t,i,n,r,s),this.assetType="light",this.setDirty=VC.setDirty,this.refreshUi=VC.refreshUi,this.uiConfig={type:"folder",label:"Spot Light",children:[...Rg(this),...hw.call(this)]},this.isSpotLight2=!0,this.target.position.set(0,0,-1),this.add(this.target),VC.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}};cS([Hg("Enabled"),Hm("setDirty")],hS.prototype,"visible"),cS([zg("Name"),Hm("setDirty")],hS.prototype,"name"),cS([Qg("Color",e=>({onChange:()=>e.setDirty()}))],hS.prototype,"color"),cS([Gg("Intensity"),Hm("setDirty")],hS.prototype,"intensity"),cS([Fg("Angle",[0,2],.01),Hm("setDirty")],hS.prototype,"angle"),cS([Fg("Penumbra",[0,.9999],.01),Hm("setDirty")],hS.prototype,"penumbra"),cS([zg("Distance"),Hm("setDirty")],hS.prototype,"distance"),cS([zg("Decay"),Hm("setDirty")],hS.prototype,"decay"),cS([kg("Position",void 0,void 0,e=>({onChange:()=>e.setDirty()}))],hS.prototype,"position"),cS([kg("Rotation",void 0,void 0,e=>({onChange:()=>e.setDirty()}))],hS.prototype,"rotation"),cS([Hg("Cast Shadow"),Hm("setDirty")],hS.prototype,"castShadow"),cS([kg("Shadow Map Size",void 0,void 0,e=>({onChange:()=>e._mapSizeChanged()})),zy({obj:"shadow",key:"mapSize",onChange:hS.prototype._mapSizeChanged,onChangeParams:!1})],hS.prototype,"shadowMapSize"),cS([Fg("Shadow Bias",[-.001,.001],1e-5),zy({obj:"shadow",key:"bias",onChange:"setDirty"})],hS.prototype,"shadowBias"),cS([Fg("Shadow Radius",[0,5],.01),zy({obj:"shadow",key:"radius",onChange:"setDirty"})],hS.prototype,"shadowRadius"),cS([Fg("Shadow Focus",[0,1],.001),zy({obj:"shadow",key:"focus",onChange:"setDirty"})],hS.prototype,"shadowFocus"),cS([Gg("Shadow Near"),zy({obj:"shadow",key:["camera","near"],onChange:hS.prototype._shadowCamUpdate})],hS.prototype,"shadowNear"),cS([Gg("Shadow Far"),zy({obj:"shadow",key:["camera","far"],onChange:hS.prototype._shadowCamUpdate})],hS.prototype,"shadowFar"),cS([Gg("Shadow Aspect"),zy({obj:"shadow",key:"aspect",onChange:hS.prototype._shadowCamUpdate})],hS.prototype,"shadowAspect"),cS([Fg("Shadow FOV",[1,179],1),zy({obj:"shadow",key:"fov",onChange:hS.prototype._shadowCamUpdate})],hS.prototype,"shadowFov");let dS=hS;function uS(){this.assetType="texture",this.userData||(this.userData={}),this.appliedObjects||(this.appliedObjects=new Set),this.setDirty||(this.setDirty=()=>this.needsUpdate=!0)}function pS(e){return this.userData?.__isIWebGLRenderer||(this.userData||(this.userData={__isIWebGLRenderer:!0}),this.userData.__isIWebGLRenderer=!0,this.renderWithModes||(this.renderWithModes=mS),this.renderManager=e,this.baseRenderer||Object.defineProperty(this,"baseRenderer",{get:()=>(console.warn("IWebGLRenderer.baseRenderer is deprecated, use IWebGLRenderer.renderManager instead"),this.renderManager)})),this}function mS(e,t){const i=this.userData,{backgroundRender:n,transparentRender:r,shadowMapRender:s,mainRenderPass:a,opaqueRender:o,transmissionRender:l,sceneRender:c,screenSpaceRendering:h}=i;void 0!==e.backgroundRender&&(i.backgroundRender=e.backgroundRender),void 0!==e.transparentRender&&(i.transparentRender=e.transparentRender),void 0!==e.shadowMapRender&&(i.shadowMapRender=e.shadowMapRender),void 0!==e.mainRenderPass&&(i.mainRenderPass=e.mainRenderPass),void 0!==e.opaqueRender&&(i.opaqueRender=e.opaqueRender),void 0!==e.sceneRender&&(i.sceneRender=e.sceneRender),void 0!==e.transmissionRender&&(i.transmissionRender=e.transmissionRender),void 0!==e.screenSpaceRendering&&(i.screenSpaceRendering=e.screenSpaceRendering),t(),i.backgroundRender=n,i.transparentRender=r,i.shadowMapRender=s,i.mainRenderPass=a,i.opaqueRender=o,i.sceneRender=c,i.transmissionRender=l,i.screenSpaceRendering=h}const gS=mS;var fS=Object.defineProperty,AS=Object.getOwnPropertyDescriptor,yS=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?AS(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&fS(t,i,s),s};e.RootScene=class extends _l{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 lC(""),this._mainCameraUpdate=e=>{this._mainCamera?.parent||this.setDirty({refreshScene:!1}),this.dispatchEvent({...e,type:"mainCameraUpdate"}),this.dispatchEvent({...e,type:"activeCameraUpdate"}),"RootScene"!==e.source&&("fov"===e.key&&this.dollyActiveCameraFov()||this.refreshActiveCameraNearFar(!e.projectionUpdated))},this._sceneBounds=new Ly,this._sceneBoundingRadius=0,this.refreshUi=qw.refreshUi.bind(this),this.traverseModels=qw.traverseModels.bind(this),this._v1=new Xi,this._v2=new Xi,this._autoNearFarDisabled=new Set,this.overrideRenderEnvironment=null,this._isMainRendering=!1,this.setDirty=this.setDirty.bind(this),this.name="RootScene",this.objectProcessor=t,qw.upgradeObject3D.call(this),this.objectProcessor?.processObject(this),this.addEventListener("materialUpdate",e=>this.dispatchEvent({...e,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 Zn,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&&null!==this.overrideRenderEnvironment?this.overrideRenderEnvironment:this._environment,set:e=>{const t=this._environment;this._environment=e,this._onEnvironmentChange({key:"environment",value:e,oldValue:t,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 mr(16777215),this.refreshUi?.(),this.setDirty()}toggleEnvironmentBackground(){"environment"===this.background?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(t=>!t.userData.license&&(t.userData.license=e.userData.gltfAsset?.copyright)),e.animations){this.modelRoot.animations||(this.modelRoot.animations=[]);for(const t of e.animations)this.modelRoot.animations.includes(t)||this.modelRoot.animations.push(t)}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(e=>this.addObject(e,{...t,clearSceneObjects:!1,disposeSceneObjects:!1}))}_addObject3D(e,{addToRoot:t=!1,...i}={}){const n=e;if(!n||!n.isObject3D)return void console.error("RootScene: Invalid object, cannot add to scene.");const r=t?this:this.modelRoot;if(r.add(n),void 0!==i.indexInParent){const e=i.indexInParent,t=r.children.indexOf(n);e>=0&&t>=0&&e!==t&&e<r.children.length&&(r.children.splice(t,1),r.children.splice(e,0,n))}qx(n,i),this.setDirty({refreshScene:!0})}centerAllGeometries(e=!0,t){return Xx(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 e of[...this.modelRoot.children])e.dispose?e.dispose():e.removeFromParent();this.modelRoot.clear(),e&&this.setDirty({refreshScene:!0})}else for(const e of this.modelRoot.children)e.dispose&&e.dispose(!1)}_onEnvironmentChange(e){e?.oldValue&&e.oldValue!==e.value&&this.autoDisposeSceneMaps&&"function"==typeof e.oldValue.dispose&&e.oldValue.dispose(),this.environment?.mapping===ce&&(this.environment.mapping=ue,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&&"function"==typeof e.oldValue.dispose&&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(e=>e.parent!==this);return t.length&&super.add(...t),this}setBackgroundColor(e){const t=e||"number"==typeof e?new mr(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}),qw.setDirty.call(this,{...e,scene:this}),this}refreshScene(e){const t=e&&"objectUpdate"===e.type&&(e.object===this||e.target===this);return!1===e?.sceneUpdate||!1===e?.refreshScene||e?.object?.isCamera?t?this:this.setDirty(e):(this.refreshActiveCameraNearFar(),this._sceneBounds=this.getBounds(!1,!0),this._sceneBoundingRadius=this._sceneBounds.getSize(new Xi).length()/2,this.dispatchEvent({...e,type:"sceneUpdate",hierarchyChanged:["addedToParent","removedFromParent"].includes(e?.change||"")}),t||qw.setDirty.call(this,{...e,scene:this}),this)}dispose(e=!0){this.disposeSceneModels(!1,e),e&&([...this.children].forEach(e=>e.dispose?e.dispose():e.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 Ly).expandByObject(this,e,t,e=>!(!i||!e.isWidget&&"widget"!==e.assetType)||(n?.(e)??!1))}getModelBounds(e=!1,t=!0,i=!0,n){return null==this.modelRoot?new Ly:(new Ly).expandByObject(this.modelRoot,e,t,e=>!(!i||"widget"!==e.assetType)||(n?.(e)??!1))}autoGPUInstanceMeshes(){const e=new Set;this.modelRoot.traverseModels(t=>{t.geometry&&e.add(t.geometry)},{visible:!1,widgets:!1}),e.forEach(e=>gv(e))}disableAutoNearFar(e="default"){const t=0===this._autoNearFarDisabled.size;this._autoNearFarDisabled.add(e);const i=this.mainCamera;if(t&&!1!==i.userData.autoNearFar){let e=i.near,t=i.far;e=i.userData.minNearPlane??nC.defaultMinNear,t=i.userData.maxFarPlane??nC.defaultMaxFar,nC.setNearFar(i,e,t,!0,"RootScene")}}enableAutoNearFar(e="default"){if(!this._autoNearFarDisabled.has(e))return;this._autoNearFarDisabled.delete(e);const t=this.mainCamera;0===this._autoNearFarDisabled.size&&t&&this.setDirty()}refreshActiveCameraNearFar(e=!0){const t=this.mainCamera;if(!t)return!1;let i=t.near,n=t.far;if(void 0!==t.userData.minNearPlane&&(i=t.userData.minNearPlane),void 0!==t.userData.maxFarPlane&&(n=t.userData.maxFarPlane),0!==this._autoNearFarDisabled.size||!1===t.userData.autoNearFar)return nC.setNearFar(t,i,n,e,"RootScene");const r=this.getBounds(!1),s=r.getSize(this._v2).length();if(s<.001)return nC.setNearFar(t,i,n,e,"RootScene");t.getWorldPosition(this._v1).sub(r.getCenter(this._v2));const a=1.5*Math.max(.25,s)/2,o=this._v1.length(),l=Math.max(.1,-this._v1.normalize().dot(t.getWorldDirection(new Xi)));return i=Math.max(Math.max(t.userData.minNearPlane??nC.defaultMinNear,.001),l*(o-a)),n=Math.min(Math.max(i+a,l*(o+a)),t.userData.maxFarPlane??nC.defaultMaxFar),(n<i||n-i<.1)&&(n=i+.1),nC.setNearFar(t,i,n,e,"RootScene")}dollyActiveCameraFov(){const e=this.mainCamera;if(!e||!e.userData.dollyFov)return!1;const t=1.5*p_(e,this.getModelBounds(!1,!0,!0)),i=(new Xi).subVectors(e.target,e.position).normalize();return e.position.copy(i.multiplyScalar(-t).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=f_.Serialize(this,e,!0);return t.envMapIntensity=t.environmentIntensity,t}fromJSON(e,t){const i=e.environment;return void 0!==i&&(this.environment=f_.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)),void 0!==e.environmentIntensity&&void 0!==e.envMapIntensity&&delete(e={...e}).envMapIntensity,f_.Deserialize(e,this,t,!0),e.environment=i,this}addEventListener(e,t){"activeCameraChange"===e&&console.error("activeCameraChange is deprecated. Use mainCameraChange instead."),"activeCameraUpdate"===e&&console.error("activeCameraUpdate is deprecated. Use mainCameraUpdate instead."),"sceneMaterialUpdate"===e&&console.error("sceneMaterialUpdate is deprecated. Use materialUpdate instead."),"update"===e&&console.error("update is deprecated. Use sceneUpdate instead."),super.addEventListener(e,t)}findObjectsByName(e,t,i=!1){const n=[],r=t=>{t.name===e&&n.push(t)},s=t??this;return i&&s.traverseModels?s.traverseModels(r,{visible:!1,widgets:!0}):s.traverse(r),n}resetCamera(e=void 0,t=new Xi(1,1,1),i=new Xi(0,0,0)){if(this._mainCamera){this.matrixWorldNeedsUpdate=!0,this.updateMatrixWorld(!0);const n=e?(new Ly).expandByObject(e,!0,!0):this.getBounds(!0),r=n.getCenter(new Xi),s=.5*n.getSize(new Xi).length();r.add(i.clone().multiplyScalar(s)),this._mainCamera.position=new Xi(r.x+t.x*s,r.y+t.y*s,r.z+t.z*s),this._mainCamera.target=r,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 0===this._autoNearFarDisabled.size}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}},yS([qm(),Vm(e.RootScene.prototype.onBackgroundChange)],e.RootScene.prototype,"backgroundColor",2),yS([Qg("Background Color",e=>({hidden:()=>null===e.backgroundColor||void 0===e.backgroundColor||"environment"===e.background}))],e.RootScene.prototype,"_backgroundColorUi",1),yS([Hm(e.RootScene.prototype.onBackgroundChange),qm(),Vg("Background Image",e=>({hidden:()=>null===e.backgroundColor||void 0===e.backgroundColor||"environment"===e.background}))],e.RootScene.prototype,"background",2),yS([jg(void 0,e=>({label:()=>e.backgroundColor?"Set Transparent BG":"Set Color Background",tags:["context-menu"]}))],e.RootScene.prototype,"toggleTransparentBackground",1),yS([jg(void 0,e=>({label:()=>"environment"===e.background?"Remove Env Background":"Set Env Background",disabled:()=>!e.environment,tags:["context-menu"]}))],e.RootScene.prototype,"toggleEnvironmentBackground",1),yS([qm(),Hm(e.RootScene.prototype.setDirty),Fg("Background Intensity",[0,10],.01)],e.RootScene.prototype,"backgroundIntensity",2),yS([Hg("Background Tonemap"),Hm(e.RootScene.prototype.setDirty),qm()],e.RootScene.prototype,"backgroundTonemap",2),yS([Vg("Environment"),qm()],e.RootScene.prototype,"environment",2),yS([Fg("Environment Intensity",[0,10],.01),qm(),Hm(e.RootScene.prototype.setDirty)],e.RootScene.prototype,"environmentIntensity",2),yS([qm(),kg("Environment Rotation",void 0,void 0,e=>({disabled:()=>e.fixedEnvMapDirection||!e.environment}))],e.RootScene.prototype,"environmentRotation",2),yS([qm(),kg("Background Rotation",void 0,void 0,e=>({hidden:()=>!e.background||"environment"===e.background||!e.background.isTexture||e.background.mapping!==ue}))],e.RootScene.prototype,"backgroundRotation",2),yS([qm()],e.RootScene.prototype,"textureSlots",2),yS([Hg("Fixed Env Direction"),qm(),Hm(e.RootScene.prototype.setDirty)],e.RootScene.prototype,"fixedEnvMapDirection",2),yS([Lg(),qm()],e.RootScene.prototype,"defaultCamera",2),yS([jg("Center All Geometries",{sendArgs:!1,tags:["context-menu"]})],e.RootScene.prototype,"centerAllGeometries",1),yS([jg("Auto GPU Instance Meshes",{tags:["context-menu"]})],e.RootScene.prototype,"autoGPUInstanceMeshes",1),e.RootScene=yS([qg("Root Scene")],e.RootScene);class vS{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 _S=new zs(-1,1,1,-1,0,1);const bS=new class extends Fr{constructor(){super(),this.setAttribute("position",new Ir([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Ir([0,2,0,0,2,0],2))}};class xS{constructor(e){this._mesh=new ts(bS,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,_S)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class wS extends vS{constructor(e,t,i=null,n=null,r=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=i,this.clearColor=n,this.clearAlpha=r,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this._oldClearColor=new mr}render(e,t,i,n,r,s){if(!this.scene||!this.camera)return;const a=e.autoClear;let o,l;if(e.autoClear=!1,null!==this.overrideMaterial&&(l=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),null!==this.clearColor&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),null!==this.clearAlpha&&(o=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),1==this.clearDepth&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:i),s){const t=e.getContext();t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,s)}if(!0===this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),s){const t=e.getContext();t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,null)}null!==this.clearColor&&e.setClearColor(this._oldClearColor),null!==this.clearAlpha&&e.setClearAlpha(o),null!==this.overrideMaterial&&(this.scene.overrideMaterial=l),e.autoClear=a}}const CS={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n\t\tuniform float opacity;\n\n\t\tuniform sampler2D tDiffuse;\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvec4 texel = texture2D( tDiffuse, vUv );\n\t\t\tgl_FragColor = opacity * texel;\n\n\n\t\t}"};class SS extends vS{constructor(e,t){super(),this.textureID=void 0!==t?t:"tDiffuse",e instanceof ls?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=os.clone(e.uniforms),this.material=new ls({name:void 0!==e.name?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this.fsQuad=new xS(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 MS=Object.defineProperty;const ES=(n=class extends SS{constructor(e,...t){super(e.isMaterial?e:new fC(e,t),t.length<1?n.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,r){this.enabled&&e.renderWithModes({backgroundRender:!1},()=>{super.render(e,t||null,this.overrideReadBuffer||i,n,r)})}updateShaderProperties(e){e&&(Array.isArray(e)||(e=[e]),e.forEach(e=>e?.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}},n.DEFAULT_TEX_ID="tDiffuse",n);((e,t,i)=>{for(var n,r=void 0,s=e.length-1;s>=0;s--)(n=e[s])&&(r=n(t,i,r)||r);r&&MS(t,i,r)})([Hg("Enabled"),qm(),Vm(ES.prototype.setDirty)],ES.prototype,"enabled");let TS=ES;class IS extends TS{constructor(e,t="c = a + b;",i="",n,r=120){super({vertexShader:CS.vertexShader,fragmentShader:`\n                varying vec2 vUv;\n                ${i}\n                void main() {\n                    vec4 a = tDiffuseTexelToLinear ( texture2D( tDiffuse, vUv ) );\n                    vec4 b = tDiffuse2TexelToLinear ( texture2D( tDiffuse2, vUv ) );\n                    vec4 c = vec4(0);\n                    ${t}\n                    c = clamp(c, vec4(0), vec4(MAX_INTENSITY));\n                    gl_FragColor = c;\n                    #include <colorspace_fragment>\n                }\n            `,uniforms:{tDiffuse:{value:null},tDiffuse2:{value:n},...e},defines:{MAX_INTENSITY:r}},"tDiffuse","tDiffuse2"),this.clear=!1,this.needsSwap=!0}}var PS=Object.defineProperty;class DS extends wS{constructor(e,t,i=new mr(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:Rg(this)},this.renderManager=e,this._blendPass=new IS({},"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 t=this.renderManager.msaa;this._transparentTarget=this.renderManager.getTempTarget({sizeMultiplier:1,samples:t?"number"!=typeof t?e.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:t:0,stencilBuffer:this.renderManager.composerTarget.stencilBuffer,colorSpace:Lt,type:this.renderManager.renderer.extensions.has("EXT_color_buffer_half_float")?De:Ce,format:Ue,minFilter:be,magFilter:be,depthBuffer:!1})}return this._transparentTarget}_releaseTransparentTarget(){this._transparentTarget&&this.renderManager.releaseTempTarget(this._transparentTarget),this._transparentTarget=void 0}get opaqueTarget(){if(!this._opaqueTarget){const t=this.renderManager.composerTarget,i=this.renderManager.msaa;this._opaqueTarget=this.renderManager.getTempTarget({sizeMultiplier:1,samples:i?"number"!=typeof i?e.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:i:0,stencilBuffer:this.renderManager.composerTarget.stencilBuffer,colorSpace:t.texture.colorSpace,type:this.renderManager.rgbm?Ce:De,format:t.texture.format,minFilter:t.texture.minFilter,magFilter:t.texture.magFilter,depthBuffer:t.depthBuffer,generateMipmaps:t.texture.generateMipmaps})}return this._opaqueTarget}_releaseOpaqueTarget(){this._opaqueTarget&&this.renderManager.releaseTempTarget(this._opaqueTarget),this._opaqueTarget=void 0}render(e,t,i,n,r){if(!this.enabled)return;let s=!1;if(e.userData.mainRenderPass=!0,!this._doTransmissionFix&&!this.renderManager.rgbm)return super.render(e,t||null,i,n,r),this.needsSwap=s,void(e.userData.mainRenderPass=void 0);const a=e.userData;a||console.error("threejs is not patched. Use three-modded (npm install three@npm:three-modded) for this functionality.");const o=(this.renderManager.zPrepass||!this.renderManager.depthBuffer)&&this.renderManager.gbufferTarget;let l;if(o){const t=this.renderManager.gbufferTarget;if(t){const i=e.properties.get(t);l=i.__webglDepthRenderbuffer||i.__webglDepthbuffer}l||console.warn("No depth/gbuffer present for zPrepass.")}const c=i;i=this.renderManager.msaa?this.opaqueTarget:i;let h=()=>{super.render(e,null,i,n,r,l)};if(this.renderManager.rgbm){if(this.renderManager.rgbm){s=!1;const c=this.renderToScreen;if(c&&!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 t=e.autoClearDepth;e.autoClearDepth=!o,e.renderWithModes({shadowMapRender:!0,backgroundRender:this.renderBackground,opaqueRender:!0,transparentRender:!1,transmissionRender:!1},h),e.autoClearDepth=t}if(!o&&i){const t=e.properties.get(i);l=t.__webglDepthRenderbuffer||t.__webglDepthbuffer}h=()=>{super.render(e,null,this.transparentTarget,n,r,l)};{const t=this.clear,i=e.autoClearDepth;e.autoClearDepth=!1,this.clear=!0,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!1,transparentRender:!0,transmissionRender:!1},h),this.clear=t,e.autoClearDepth=i}(!e.info||e.info.render.calls>0)&&(this._blendPass.uniforms.tDiffuse2.value=this.transparentTarget.texture,this._blendPass.render(e,t,i,n,r),s=!0);{const n=this.clear;this.clear=!1,a.transmissionRenderTarget=s?t:i,a.blurTransmissionTarget=this.blurTransmissionTarget&&0===a.transmissionRenderTarget.samples,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!1,transparentRender:!1,transmissionRender:!0},h),a.blurTransmissionTarget=void 0,a.transmissionRenderTarget=void 0,this.clear=n}if((!e.info||e.info.render.calls>0)&&(this._blendPass.uniforms.tDiffuse2.value=this.transparentTarget.texture,this._blendPass.render(e,t,i,n,r),s=!0),c){this.renderToScreen=!0;const e=s?t?.texture:i?.texture,n=Array.isArray(e)?e[0]:e;n&&this.renderManager.blit(void 0,{source:n,respectColorSpace:!0})}}}else{{const t=this.clear,i=e.autoClearDepth;e.autoClearDepth=!o,this.clear=!0,e.renderWithModes({shadowMapRender:!0,backgroundRender:this.renderBackground,opaqueRender:!0,transparentRender:!0,transmissionRender:!1},h),this.clear=t,e.autoClearDepth=i}{const n=i?i.texture:void 0;this.renderManager.blit(t,{clear:!0,source:n});const r=this.clear;this.clear=!1,a.transmissionRenderTarget=t,a.blurTransmissionTarget=this.blurTransmissionTarget&&0===a.transmissionRenderTarget.samples,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!1,transparentRender:!1,transmissionRender:!0},h),a.blurTransmissionTarget=void 0,a.transmissionRenderTarget=void 0,this.clear=r}s=!1}if(!s&&c!==i&&i){const e=Array.isArray(i.texture)?i.texture[0]:i.texture;e&&this.renderManager.blit(c,{source:e,clear:!0}),i=c}this.preserveTransparentTarget||this._releaseTransparentTarget(),this.preserveOpaqueTarget||this._releaseOpaqueTarget(),this.needsSwap=s,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}}((e,t,i)=>{for(var n,r=void 0,s=e.length-1;s>=0;s--)(n=e[s])&&(r=n(t,i,r)||r);r&&PS(t,i,r)})([Hg("Enabled"),qm()],DS.prototype,"enabled");class RS extends TS{constructor(e,t=!0){super({uniforms:os.clone(CS.uniforms),vertexShader:CS.vertexShader,fragmentShader:ym`
                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?Im(e,"diffuseColor"):""}
                    #ifdef OPAQUE
                    diffuseColor.a = 1.0;
                    #endif
                    gl_FragColor = diffuseColor;
                    ${t?"#include <colorspace_fragment>":""}
                }
            `},"tDiffuse")}}var BS=Object.defineProperty,LS=Object.getOwnPropertyDescriptor,OS=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?LS(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&BS(t,i,s),s};e.GBufferRenderPass=class extends wS{constructor(e,t,i,n=new mr(1,1,1),r=1){super(void 0,void 0,i,n,r),this.passId=e,this.target=t,this.isGBufferRenderPass=!0,this.enabled=!0,this._transparentMats=new Set,this._transmissiveMats=new Set,this.preprocessMaterial=(e,t)=>{t=t??e.userData.renderToGBuffer,e.userData.pluginsDisabled&&(t=!1),(e.transparent&&(t||e.opacity>.99&&!e.map&&!e.alphaMap)||!e.transparent&&!e.transmission&&!1===t)&&(this._transparentMats.add(e),e.transparent=!e.transparent),e.transmission&&Math.abs(e.transmission||0)>0&&t&&(this._transmissiveMats.add([e,e.transmission]),e.transmission=0)},this.preprocessObject=e=>{if(e.customDepthMaterial){const t=e.customDepthMaterial;t.allowOverride=!1;const i=e.material;e.forcedOverrideMaterial=t;const n=Array.isArray(i)?i[0]:i;return n&&(t.userData.renderToGBuffer=n.userData.renderToGBuffer,t.userData.renderToDepth=n.userData.renderToDepth,t.userData.pluginsDisabled=n.userData.pluginsDisabled,t.side=n.side),t}return e.material},this.postprocessObject=e=>{e.customDepthMaterial&&delete e.forcedOverrideMaterial}}render(e,t,i,n,r){if(!this.scene||!this.camera)return;const s=e.getRenderTarget(),a=e.getActiveCubeFace(),o=e.getActiveMipmapLevel(),l=new Set;this.scene.traverse(e=>{if(!e.visible)return;l.add(e);const t=this.preprocessObject(e);t&&(Array.isArray(t)?t.forEach(e=>this.preprocessMaterial(e)):this.preprocessMaterial(t))}),e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!0,transparentRender:!1,transmissionRender:!1,mainRenderPass:!1},()=>super.render(e,null,Im(this.target),n,r)),this._transparentMats.forEach(e=>e.transparent=!e.transparent),this._transparentMats.clear(),this._transmissiveMats.forEach(([e,t])=>e.transmission=t),this._transmissiveMats.clear(),e.setRenderTarget(s,a,o),l.forEach(e=>this.postprocessObject(e))}beforeRender(e,t,i){this.scene=e,this.camera=t}},OS([Hg("Enabled")],e.GBufferRenderPass.prototype,"enabled",2),e.GBufferRenderPass=OS([qg(e=>e.passId+" Render Pass")],e.GBufferRenderPass);const US="#include <packing>\nvarying vec2 vUv;\n#include <alphatest_pars_fragment>\nvoid main(){vec4 diffuseColor=tDiffuseTexelToLinear(texture2D(tDiffuse,vUv));\n#ifdef HAS_TRANSPARENT_TARGET\nvec4 transparentColor=tTransparentTexelToLinear(texture2D(tTransparent,vUv));\n#else\nvec4 transparentColor=vec4(0.0);\n#endif\n#ifdef HAS_GBUFFER\nfloat depth=getDepth(vUv);bool isBackground=depth>0.99&&transparentColor.a<0.001;\n#endif\n#glMarker\n#ifdef HAS_GBUFFER\n#if (defined(CLIP_BACKGROUND) && CLIP_BACKGROUND > 0) || defined(CLIP_BACKGROUND_FORCE)\nif(isBackground)diffuseColor.a=0.0;if(depth>0.99&&transparentColor.a>=0.001)diffuseColor.a=transparentColor.a;\n#endif\nif(depth<0.00001)diffuseColor.a=0.0;\n#endif\n#include <alphatest_fragment>\n#ifdef OPAQUE\ndiffuseColor.a=1.0;\n#endif\ngl_FragColor=diffuseColor;\n#include <colorspace_fragment>\n}";var FS=Object.defineProperty,kS=Object.getOwnPropertyDescriptor,NS=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?kS(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&FS(t,i,s),s};function jS(e){const t=[],i={};for(const t of e)t.passId&&(i[t.passId]={after:t.after??[],before:t.before??[],dependencies:new Set(t.required??[])});for(const[e,t]of Object.entries(i)){const n=new Set([...t.after,...t.before]);t.dependencies.forEach(e=>n.has(e)&&n.delete(e)),n.forEach(n=>{const r=i[n];if(r){if(r.dependencies.has(e))throw console.error("cyclic",e,n),"Encountered cyclic dependency when sorting passes";t.dependencies.add(n)}})}for(;;){let n=!1;const r=[...Object.entries(i)];for(const[s,a]of r)if(!t.includes(s)&&Dm(t,a.dependencies.values())){const r=Math.max(-1,...a.after.map(e=>t.indexOf(e))),o=Math.min(t.length,...a.before.map(e=>{const i=t.indexOf(e);return i<0?t.length:i}));if(r>=o)throw console.error(a,e,t,r,o),"Unknown error when sorting passes";t.splice(a.after.length>0?r+1:o,0,s),n=!0,delete i[s]}if(Object.keys(i).length<1)break;if(!n)throw console.error(r,i,t),"Required pass dependency removed unexpectedly"}return t}e.ScreenPass=class extends TS{constructor(e="",...t){super(e?.fragmentShader||e?.isShaderMaterial?e:function(e){const t=R_(US,"void main()",(Array.isArray(e)?e[0]:e?.pars||"")+"\n",{prepend:!0}),i=t.includes("#glMarker")?R_(t,"#glMarker",(Array.isArray(e)?e[1]:"string"==typeof e?e:e?.main||"")+"\n",{prepend:!0}):t;return{...CS,fragmentShader:i,uniforms:{tDiffuse:{value:null},tTransparent:{value:null}},transparent:!0,blending:w,side:_}}(e),...t.length?t:["tDiffuse","tTransparent"]),this.passId="screen",this.after=["render"],this.required=["render"],this.outputColorSpace=Ot,this._needsReRender=!1,this.clipBackgroundForce=!1,this.clipBackground=!1,this.material.addEventListener("materialUpdate",this.setDirty)}render(e,t,i,n,r){const s=e.outputColorSpace;(!t||this.renderToScreen)&&(e.outputColorSpace=this.outputColorSpace),super.render(e,t,i,n,r),this._lastReadBuffer=i,e.outputColorSpace=s,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}},NS([Ng("Output Color Space",lv.ColorSpace.uiConfig,e=>({onChange:e.setDirty}))],e.ScreenPass.prototype,"outputColorSpace",2),NS([jy("CLIP_BACKGROUND_FORCE",void 0,void 0,e.ScreenPass.prototype.setDirty,!0)],e.ScreenPass.prototype,"clipBackgroundForce",2),NS([jy("CLIP_BACKGROUND",void 0,void 0,e.ScreenPass.prototype.setDirty),Hg()],e.ScreenPass.prototype,"clipBackground",2),e.ScreenPass=NS([qg("Screen Pass")],e.ScreenPass);class zS extends vS{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(),r=e.state;let s,a;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0),this.inverse?(s=0,a=1):(s=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(n.REPLACE,n.REPLACE,n.REPLACE),r.buffers.stencil.setFunc(n.ALWAYS,s,4294967295),r.buffers.stencil.setClear(a),r.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),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(n.EQUAL,1,4294967295),r.buffers.stencil.setOp(n.KEEP,n.KEEP,n.KEEP),r.buffers.stencil.setLocked(!0)}}class GS extends vS{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class QS{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),void 0===t){const i=e.getSize(new fi);this._width=i.width,this._height=i.height,(t=new Vi(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:De})).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 SS(CS),this.copyPass.material.blending=w,this.clock=new Wu}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);-1!==t&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){void 0===e&&(e=this.clock.getDelta());const t=this.renderer.getRenderTarget();let i=!1;for(let t=0,n=this.passes.length;t<n;t++){const n=this.passes[t];if(!1!==n.enabled){if(n.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),n.render(this.renderer,this.writeBuffer,this.readBuffer,e,i),n.needsSwap){if(i){const t=this.renderer.getContext(),i=this.renderer.state.buffers.stencil;i.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),i.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}void 0!==zS&&(n instanceof zS?i=!0:n instanceof GS&&(i=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(void 0===e){const t=this.renderer.getSize(new fi);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,(e=this.renderTarget1.clone()).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 e=0;e<this.passes.length;e++)this.passes[e].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 VS extends QS{constructor(e,t){super(e,t),this.copyPass2=new RS}setPixelRatio(e,t=!0){const i=this.setSize;t||(this.setSize=()=>{}),super.setPixelRatio(e),t||(this.setSize=i)}}function HS(e={}){return[e.sizeMultiplier,e.samples,e.colorSpace,e.type,e.format,e.depthBuffer,e.depthTexture,e.textureCount,e.size?.width,e.size?.height].join(";")}class WS extends ri{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,samples:t=0,colorSpace:i="",type:n=Ce,format:r=Ue,stencilBuffer:s=!1,depthBuffer:a=!0,depthTexture:o=!1,depthTextureType:l=Ie,depthTextureFormat:c=Fe,size:h,textureCount:d=1,...u}={},p=!0){this.isWebGL2||(t=0),void 0!==e&&void 0!==h&&console.error("Both sizeMultiplier and size are defined. sizeMultiplier will be ignored."),(h=h||this.renderSize.clone().multiplyScalar(this.renderScale*(e=e||1))).width=Math.floor(h.width),h.height=Math.floor(h.height);const m=o?new ua(h.width,h.height,l):null;m&&(m.format=c);const g=this.createTargetCustom(h,{samples:t,colorSpace:i,type:n,format:r,depthBuffer:a,count:d,depthTexture:m,stencilBuffer:s});return this._processNewTarget(g,e,p),this._setTargetOptions(g,u),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=HS(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 r=[e,t];if(n?.prototype===As.prototype){if(e!==t)throw"Width and height of cube render target must be equal";r=[e]}return this._createTargetClass(n??Vi,r,{format:Ue,minFilter:be,magFilter:be,generateMipmaps:!1,type:Ce,colorSpace:Lt,...i})}dispose(e=!0){this._trackedTargets.forEach(e=>e.dispose()),Object.values(this._trackedTempTargets).forEach(e=>e.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,void 0===this._releasedTempTargets[t]&&(this._releasedTempTargets[t]=[]),this._trackedTempTargets.push(e),e}_setTargetOptions(e,t){const i=e.texture;for(const e of Array.isArray(i)?i:[i])this._setTargetTextureOptions(e,t)}_setTargetTextureOptions(e,t){e.minFilter=t.minFilter??be,e.magFilter=t.magFilter??be,e.wrapS=t.wrapS??fe,e.wrapT=t.wrapT??fe,e.generateMipmaps=t.generateMipmaps??!1,e.generateMipmaps&&e.minFilter===be&&(e.minFilter=1008),!e.generateMipmaps&&1008===e.minFilter&&(e.minFilter=be)}_processNewTarget(e,t,i){return void 0!==t&&(e.sizeMultiplier=t),i&&this.trackTarget(e),e}}class qS{constructor(e,t,i,n,r){this.extensions=[],this.cls=e,this.ext=t,this.mime=i.filter(Boolean).map(e=>e.toLowerCase()),this.root=n,this.onCtor=r}ctor(e){const t=this.cls&&new this.cls(e.loadingManager);return"function"==typeof this.onCtor?this.onCtor(t,e,this):t}}const XS=class extends ri{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 qS(lu,["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 nu(this._onLoad,this._onProgress,this._onError),this._loadingManager.onStart=this._onStart;const n=this._loadingManager.itemStart;this._loadingManager.itemStart=e=>{this.dispatchEvent({type:"importFile",path:e,state:"downloading",progress:0}),n.call(this._loadingManager,e)};let r=[];const s=this._loadingManager.itemEnd;this._loadingManager.itemEnd=e=>{if(r.includes(e))return r=r.filter(t=>t!==e),void s.call(this._loadingManager,e);this.dispatchEvent({type:"importFile",path:e,state:"downloading",progress:1}),s.call(this._loadingManager,e),this.dispatchEvent({type:"importFile",path:e,state:"done"})};const a=this._loadingManager.itemError;this._loadingManager.itemError=e=>{r.push(e),this.dispatchEvent({type:"importFile",path:e,state:"error"}),a.call(this._loadingManager,e)},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))return void console.warn("AssetImporter: Importer already added",t);this.importers.push(t)}}removeImporter(...e){for(const t of e){const e=this.importers.indexOf(t);e>=0&&this.importers.splice(e,1),this._loaderCache=this._loaderCache.filter(e=>e.importer!==t||(this._disposeLoader(e),!1))}}async import(e,t,i,n){return e?Array.isArray(e)?(await Promise.all(e.map(async e=>this.import(e,t,i,n)))).flat(1):e instanceof File?await this.importFile(e,t,i):"object"==typeof e?await this.importAsset(e,t,i,n):"string"==typeof e?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),r=this._cachedAssets.find(t=>t.path===e&&t._options===n);let s;return s=r||{path:e},s._options=n,t.importedFile&&(s.file=t.importedFile),await this.importAsset(s,t,i,!1)}_serializeOptions(e){const{pathOverride:t,forceImport:i,reimportDisposed:n,fileHandler:r,importedFile:s,...a}=e;return JSON.stringify(a)}async importAsset(e,t={},i,n){if(!e)return[];if(!e.path&&!e.file&&!t.pathOverride)return[e];if(!1!==t.cacheAsset&&this.cacheImportedAssets&&!this._cachedAssets.includes(e)){if(1===Object.entries(e).length&&e.path){const t=this._cachedAssets.find(t=>t.path===e.path);t&&Object.assign(e,t)}const t=this._cachedAssets.findIndex(t=>t.path===e.path);t>=0&&this._cachedAssets.splice(t,1),this._cachedAssets.push(e)}let r=e?.preImported;!r&&e?.preImportedRaw&&(r=await e.preImportedRaw);const s=t.pathOverride||e.path;if(!t.forceImport&&r)return await this.processRaw(r,t,s);if(void 0===n&&(n="function"==typeof e.file?.arrayBuffer),e.preImportedRaw=this._loadFile(s,"function"==typeof e.file?.arrayBuffer?e.file:void 0,t,i,n),r=await e.preImportedRaw,this.cacheImportedAssets||(e.preImportedRaw=void 0),r&&(r=await this.processRaw(r,t,s)),r){!1!==t.processRaw&&this.cacheImportedAssets&&(e.preImported=r);const i=[],n=e=>{e.userData?.rootSceneModelRoot?i.push(...e.children):i.push(e)};Array.isArray(r)?r.map(n):n(r),i.forEach(t=>t?.addEventListener&&t.addEventListener("dispose",()=>{e?.preImportedRaw&&(e.preImportedRaw=void 0),e?.preImported&&(e.preImported=void 0)}))}return r}async importFile(e,t={},i){return e?e instanceof File?this.importAsset(this._cachedAssets.find(t=>t.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),0===e.size)return i;this.dispatchEvent({type:"importFiles",files:e,state:"start"});const r=[],s=[];if(e.forEach((e,t)=>{this.registerFile(t,e);const i=e.ext,a=e.mime;(i||a)&&(n?.includes((i||a||"").toLowerCase())??1)&&(this._isRootFile(i)?r.push(t):s.push(t))}),r.length>0)for(const e of r){let n=await this._loadFile(e,void 0,t,void 0,!0);n&&(n=await this.processRaw(n,t,e)),i.set(e,n)}else for(const e of s){let n=await this._loadFile(e,void 0,t,void 0,!0);n&&(n=await this.processRaw(n,t,e)),i.set(e,n)}return this.dispatchEvent({type:"importFiles",files:e,state:"end"}),e.forEach((e,t)=>this.unregisterFile(t)),i}async _loadFile(e,t,i={},n,r=!1){let s;this._cacheStoreInitPromise&&await this._cacheStoreInitPromise,this.dispatchEvent({type:"importFile",path:e,state:"downloading",progress:0});try{const r=this.registerFile(e,t,i.fileExtension,i.fileHandler);if(!r)throw new Error("AssetImporter: Unable to find loader for "+e);this._rootContext={path:e,rootUrl:Bu.extractUrlBase(e)},r.importOptions=i,s=await r.loadAsync(e+(i.queryString?(e.includes("?")?"&":"?")+i.queryString:""),t=>{n&&n(t);const i=t.lengthComputable?t.total:void 0;this.dispatchEvent({type:"importFile",path:e,state:"downloading",loadedBytes:t.loaded||void 0,totalBytes:i&&i<t.loaded?t.loaded:t.total||void 0,progress:i&&i>0&&i>t.loaded?t.loaded/i:1})}),r.transform&&(s=await r.transform(s,i)),delete r.importOptions,this._rootContext=void 0,t?this._logger("AssetImporter: loaded",e):this._logger("AssetImporter: downloaded",e),t&&this.unregisterFile(e)}catch(i){return console.error("AssetImporter: Unable to import file",e,t),console.error(i),console.error(i?.stack),this.dispatchEvent({type:"importFile",path:e,state:"error",error:i}),t&&this.unregisterFile(e),[]}if(s&&"object"==typeof s&&!Array.isArray(s)){if(i.fileHandler&&!i.fileExtension&&console.warn("AssetImporter - Pass fileExtension to options when using fileHandler to be able to use `rootPath`",i.fileHandler,e),!r&&!e.startsWith("blob:")&&!e.startsWith("data:")&&(s.__rootPath=e,i)){const e=this._serializeOptions(i);e&&(s.__rootPathOptions=JSON.parse(e))}const n=t||this._fileDatabase.get(e);n&&(s.__rootBlob=n)}return s}registerFile(e,t,i,n){const r=e.startsWith("data:")||!1;r||(e=e.replace(/\?.*$/,""));const s=i||(r?void 0:t?.ext??mm(t?.name??e.trim())?.toLowerCase()),a=(t?.mime??r)&&e.slice(0,e.indexOf(";")).split(":")[1]||void 0;return t&&(void 0===t.name&&(t.name=e),t.ext||(t.ext=s),t.mime||(t.mime=a),this._fileDatabase.has(e)&&(console.warn("AssetImporter: File already registered, replacing",e),this.unregisterFile(e)),this._fileDatabase.set(e,t)),n||this._getLoader(e,s,a)||this._createLoader(e,s,a)}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(void 0!==t.processImported&&(console.error("AssetImporter: processImported is deprecated, use processRaw instead"),t.processRaw=t.processImported),Array.isArray(e)){const n=[];for(const r of e)n.push(...await this.processRaw(r,t,i));return n}if(!1===t.processRaw)return[e];if(e.assetImporterProcessed&&!t.forceImporterReprocess)return[e];const n=e.__rootPath,r=e.__rootPathOptions,s=e.__rootBlob;if(e.userData){const t=e.userData;!t.rootPath&&n&&!n.startsWith("blob:")&&(t.rootPath=n,r&&(t.rootPathOptions=r)),s&&(t.__sourceBlob=s,t.__needsSourceBuffer&&(t.__sourceBuffer=await s.arrayBuffer(),delete t.__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=(s?.filePath||s?.name||n||"").replace(/^\/|\/$/,"").split("/").pop()),e.assetImporterProcessed=!0,this.dispatchEvent({type:"processRaw",data:e,options:t,path:i}),e instanceof Map&&!1!==t.autoImportZipContents?[...(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((e,t)=>t(e),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(),null!=this.importers.find(i=>i.root&&(e&&Im(i.ext)?.includes(e.toLowerCase())||t&&i.mime.includes(t.toLowerCase())))}_getImporter(e,t,i,n=!1){return i=i?.toLowerCase(),t=t?.toLowerCase(),this.importers.find(r=>!(n&&!r.root)&&!!(i&&r.mime?.find(e=>i===e)||Im(r.ext)?.find(i=>t?i===t:e?.toLowerCase()?.endsWith("."+i)||i?.startsWith("data:")&&e?.startsWith(i))))}_getLoader(e,t,i){return!t&&!i&&e&&(t=mm(e).toLowerCase()),i=i?.toLowerCase().trim(),t=t?.toLowerCase().trim(),(e?this._loadingManager.getHandler(e.trim()):void 0)||this._loaderCache.find(e=>t&&e.ext.includes(t)||i&&e.mime.includes(i))?.loader}_createLoader(e,t,i){const n=this._getImporter(e,t,i);if(!n)return;const r=n.ctor(this);if(!r)return;const s=[];return Im(n.ext)?.forEach(e=>{const t=new RegExp(e.startsWith("data:")?"^"+gm(e)+"[\\/\\+\\:\\,\\;]":"\\."+e+"$","i");this._loadingManager.addHandler(t,r),s.push(t)}),n.mime?.forEach(e=>{const t=new RegExp("^data:"+gm(e)+"[\\/\\+\\:\\,\\;]","i");this._loadingManager.addHandler(t,r),s.push(t)}),this._loaderCache.push({loader:r,ext:Im(n.ext)||[],mime:n.mime,importer:n,handlers:s}),this.dispatchEvent({type:"loaderCreate",loader:r}),r}_initCacheStorage(e,t){if(!0===t&&window?.caches)this._cacheStoreInitPromise=window.caches.open?.("threepipe-assetmanager").then(t=>{this._initCacheStorage(e,t),this._storage=t,this._cacheStoreInitPromise=void 0});else{if(e||t){e&&(iu.enabled=!0);Uy(t&&window.Cache&&"function"==typeof window.Cache&&t instanceof window.Cache?t:void 0)}this._storage="boolean"==typeof t?void 0:t}}addEventListener(e,t){if(super.addEventListener(e,t),"loaderCreate"===e)for(const e of this._loaderCache)this.dispatchEvent({type:"loaderCreate",loader:e.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)}};XS.DummyMaterial=new kw({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),XS.DummyLineBasicMaterial=new xC({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),XS.DummyLineMaterial=new MC({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),XS.DummyGeometry=new Fr,XS.DummyMaterial.uiConfig={},XS.DummyLineBasicMaterial.uiConfig={},XS.DummyLineMaterial.uiConfig={},XS.DummyGeometry.uiConfig={};let YS,KS,JS,ZS,$S=XS;function eM(e,t=1/0,i=null){KS||(KS=new Es(2,2,1,1)),JS||(JS=new ls({uniforms:{blitTexture:new yp(e)},vertexShader:"\n\t\t\tvarying vec2 vUv;\n\t\t\tvoid main(){\n\t\t\t\tvUv = uv;\n\t\t\t\tgl_Position = vec4(position.xy * 1.0,0.,.999999);\n\t\t\t}",fragmentShader:"\n\t\t\tuniform sampler2D blitTexture; \n\t\t\tvarying vec2 vUv;\n\n\t\t\tvoid main(){ \n\t\t\t\tgl_FragColor = vec4(vUv.xy, 0, 1);\n\t\t\t\t\n\t\t\t\t#ifdef IS_SRGB\n\t\t\t\tgl_FragColor = sRGBTransferOETF( texture2D( blitTexture, vUv) );\n\t\t\t\t#else\n\t\t\t\tgl_FragColor = texture2D( blitTexture, vUv);\n\t\t\t\t#endif\n\t\t\t}"})),JS.uniforms.blitTexture.value=e,JS.defines.IS_SRGB=e.colorSpace==Ot,JS.needsUpdate=!0,ZS||(ZS=new ts(KS,JS),ZS.frustumCulled=!1);const n=new ps,r=new _l;r.add(ZS),null===i&&(i=YS=new Al({antialias:!1}));const s=Math.min(e.image.width,t),a=Math.min(e.image.height,t);i.setSize(s,a),i.clear(),i.render(r,n);const o=document.createElement("canvas"),l=o.getContext("2d");o.width=s,o.height=a,l.drawImage(i.domElement,0,0,s,a);const c=new ih(o);return c.minFilter=e.minFilter,c.magFilter=e.magFilter,c.wrapS=e.wrapS,c.wrapT=e.wrapT,c.name=e.name,YS&&(YS.forceContextLoss(),YS.dispose(),YS=null),c}const tM={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 iM{constructor(){this.pluginCallbacks=[],this.register(function(e){return new UM(e)}),this.register(function(e){return new FM(e)}),this.register(function(e){return new zM(e)}),this.register(function(e){return new GM(e)}),this.register(function(e){return new QM(e)}),this.register(function(e){return new VM(e)}),this.register(function(e){return new kM(e)}),this.register(function(e){return new NM(e)}),this.register(function(e){return new jM(e)}),this.register(function(e){return new HM(e)}),this.register(function(e){return new WM(e)}),this.register(function(e){return new qM(e)}),this.register(function(e){return new XM(e)}),this.register(function(e){return new YM(e)})}register(e){return-1===this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.push(e),this}unregister(e){return-1!==this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,n,r){const s=r||new OM,a=[];for(let e=0,t=this.pluginCallbacks.length;e<t;e++)a.push(this.pluginCallbacks[e](s));s.setPlugins(a),s.write(e,t,n).catch(i)}parseAsync(e,t){const i=this;return new Promise(function(n,r){i.parse(e,n,r,t)})}}const nM=0,rM=1,sM=2,aM=3,oM=4,lM=5120,cM=5121,hM=5122,dM=5123,uM=5124,pM=5125,mM=5126,gM=34962,fM=34963,AM=9728,yM=9729,vM=9984,_M=9985,bM=9986,xM=9987,wM=33071,CM=33648,SM=10497,MM="KHR_mesh_quantization",EM={};EM[ye]=AM,EM[ve]=vM,EM[_e]=bM,EM[be]=yM,EM[xe]=_M,EM[we]=xM,EM[fe]=wM,EM[ge]=SM,EM[Ae]=CM;const TM={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},IM=new mr;function PM(e,t){return e.length===t.length&&e.every(function(e,i){return e===t[i]})}function DM(e){return 4*Math.ceil(e/4)}function RM(e,t=0){const i=DM(e.byteLength);if(i!==e.byteLength){const n=new Uint8Array(i);if(n.set(new Uint8Array(e)),0!==t)for(let r=e.byteLength;r<i;r++)n[r]=t;return n.buffer}return e}function BM(){return typeof document>"u"&&typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas")}function LM(e,t){if(void 0!==e.toBlob)return new Promise(i=>e.toBlob(i,t));let i;return"image/jpeg"===t?i=.92:"image/webp"===t&&(i=.8),e.convertToBlob({type:t,quality:i})}class OM{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,r=n.buffers,s=n.json;i=n.options;const a=n.extensionsUsed,o=n.extensionsRequired,l=new Blob(r,{type:"application/octet-stream"}),c=Object.keys(a),h=Object.keys(o);if(c.length>0&&(s.extensionsUsed=c),h.length>0&&(s.extensionsRequired=h),s.buffers&&s.buffers.length>0&&(s.buffers[0].byteLength=l.size),!0===i.binary){const e=new FileReader;e.readAsArrayBuffer(l),e.onloadend=function(){const i=RM(e.result),n=new DataView(new ArrayBuffer(8));n.setUint32(0,i.byteLength,!0),n.setUint32(4,5130562,!0);const r=RM(function(e){return(new TextEncoder).encode(e).buffer}(JSON.stringify(s)),32),a=new DataView(new ArrayBuffer(8));a.setUint32(0,r.byteLength,!0),a.setUint32(4,1313821514,!0);const o=new ArrayBuffer(12),l=new DataView(o);l.setUint32(0,1179937895,!0),l.setUint32(4,2,!0);const c=12+a.byteLength+r.byteLength+n.byteLength+i.byteLength;l.setUint32(8,c,!0);const h=new Blob([o,a,r,n,i],{type:"application/octet-stream"}),d=new FileReader;d.readAsArrayBuffer(h),d.onloadend=function(){t(d.result)}}}else if(s.buffers&&s.buffers.length>0){const e=new FileReader;e.readAsDataURL(l),e.onloadend=function(){const i=e.result;s.buffers[0].uri=i,t(s)}}else t(s)}serializeUserData(e,t){if(0===Object.keys(e.userData).length)return;const i=this.options,n=this.extensionsUsed;try{const r=JSON.parse(JSON.stringify(e.userData));if(i.includeCustomExtensions&&r.gltfExtensions){void 0===t.extensions&&(t.extensions={});for(const e in r.gltfExtensions)t.extensions[e]=r.gltfExtensions[e],n[e]=!0;delete r.gltfExtensions}Object.keys(r).length>0&&(t.extras=r)}catch(t){console.warn("THREE.GLTFExporter: userData of '"+e.name+"' won't be serialized because of JSON.stringify error - "+t.message),console.warn({...e.userData})}}getUID(e,t=!1){if(!1===this.uids.has(e)){const t=new Map;t.set(!0,this.uid++),t.set(!1,this.uid++),this.uids.set(e,t)}return this.uids.get(e).get(t)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;const t=new Xi;for(let i=0,n=e.count;i<n;i++)if(Math.abs(t.fromBufferAttribute(e,i).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 Xi;for(let e=0,t=i.count;e<t;e++)n.fromBufferAttribute(i,e),0===n.x&&0===n.y&&0===n.z?n.setX(1):n.normalize(),i.setXYZ(e,n.x,n.y,n.z);return t.attributesNormalized.set(e,i),i}applyTextureTransform(e,t){let i=!1;const n={};(0!==t.offset.x||0!==t.offset.y)&&(n.offset=t.offset.toArray(),i=!0),0!==t.rotation&&(n.rotation=t.rotation,i=!0),(1!==t.repeat.x||1!==t.repeat.y)&&(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(e){return e.colorSpace===Ot?function(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}:function(e){return e}}console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."),e instanceof $c&&(e=eM(e)),t instanceof $c&&(t=eM(t));const n=e?e.image:null,r=t?t.image:null,s=Math.max(n?n.width:0,r?r.width:0),a=Math.max(n?n.height:0,r?r.height:0),o=BM();o.width=s,o.height=a;const l=o.getContext("2d",{willReadFrequently:!0});l.fillStyle="#00ffff",l.fillRect(0,0,s,a);const c=l.getImageData(0,0,s,a);if(n){l.drawImage(n,0,0,s,a);const t=i(e),r=l.getImageData(0,0,s,a).data;for(let e=2;e<r.length;e+=4)c.data[e]=256*t(r[e]/256)}if(r){l.drawImage(r,0,0,s,a);const e=i(t),n=l.getImageData(0,0,s,a).data;for(let t=1;t<n.length;t+=4)c.data[t]=256*e(n[t]/256)}l.putImageData(c,0,0);const h=(e||t).clone();return h.source=new Ui(o),h.colorSpace=Lt,h.channel=(e||t).channel,e&&t&&e.channel!==t.channel&&console.warn("THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match."),h}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,r){const s=this.json;let a;switch(s.bufferViews||(s.bufferViews=[]),t){case lM:case cM:a=1;break;case hM:case dM:a=2;break;default:a=4}let o=e.itemSize*a;r===gM&&(o=4*Math.ceil(o/4));const l=DM(n*o),c=new DataView(new ArrayBuffer(l));let h=0;for(let r=i;r<i+n;r++){for(let i=0;i<e.itemSize;i++){let n;e.itemSize>4?n=e.array[r*e.itemSize+i]:(0===i?n=e.getX(r):1===i?n=e.getY(r):2===i?n=e.getZ(r):3===i&&(n=e.getW(r)),!0===e.normalized&&(n=gi.normalize(n,e.array))),t===mM?c.setFloat32(h,n,!0):t===uM?c.setInt32(h,n,!0):t===pM?c.setUint32(h,n,!0):t===hM?c.setInt16(h,n,!0):t===dM?c.setUint16(h,n,!0):t===lM?c.setInt8(h,n):t===cM&&c.setUint8(h,n),h+=a}h%o!==0&&(h+=o-h%o)}const d={buffer:this.processBuffer(c.buffer),byteOffset:this.byteOffset,byteLength:l};return void 0!==r&&(d.target=r),r===gM&&(d.byteStride=o),this.byteOffset+=l,s.bufferViews.push(d),{id:s.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const t=this,i=t.json;return i.bufferViews||(i.bufferViews=[]),new Promise(function(n){const r=new FileReader;r.readAsArrayBuffer(e),r.onloadend=function(){const e=RM(r.result),s={buffer:t.processBuffer(e),byteOffset:t.byteOffset,byteLength:e.byteLength};t.byteOffset+=e.byteLength,n(i.bufferViews.push(s)-1)}})}processBufferViewImageBuffer(e){const t=this,i=t.json;i.bufferViews||(i.bufferViews=[]),e=RM(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 r=this.json;let s;if(e.array.constructor===Float32Array)s=mM;else if(e.array.constructor===Int32Array)s=uM;else if(e.array.constructor===Uint32Array)s=pM;else if(e.array.constructor===Int16Array)s=hM;else if(e.array.constructor===Uint16Array)s=dM;else if(e.array.constructor===Int8Array)s=lM;else{if(e.array.constructor!==Uint8Array)throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);s=cM}if(void 0===i&&(i=0),(void 0===n||n===1/0)&&(n=e.count),0===n)return null;const a=function(e,t,i){const n={min:new Array(e.itemSize).fill(Number.POSITIVE_INFINITY),max:new Array(e.itemSize).fill(Number.NEGATIVE_INFINITY)};for(let r=t;r<t+i;r++)for(let t=0;t<e.itemSize;t++){let i;e.itemSize>4?i=e.array[r*e.itemSize+t]:(0===t?i=e.getX(r):1===t?i=e.getY(r):2===t?i=e.getZ(r):3===t&&(i=e.getW(r)),!0===e.normalized&&(i=gi.normalize(i,e.array))),n.min[t]=Math.min(n.min[t],i),n.max[t]=Math.max(n.max[t],i)}return n}(e,i,n);let o;void 0!==t&&(o=e===t.index?fM:gM);const l=this.processBufferView(e,s,i,n,o),c={bufferView:l.id,byteOffset:l.byteOffset,componentType:s,count:n,max:a.max,min:a.min,type:{1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"}[e.itemSize]};return!0===e.normalized&&(c.normalized=!0),r.accessors||(r.accessors=[]),r.accessors.push(c)-1}processImage(e,t,i,n="image/png",r=void 0,s=void 0){if(null!==e){const a=this,o=a.cache,l=a.json,c=a.options,h=a.pending;o.images.has(e)||o.images.set(e,{});const d=o.images.get(e),u=n+":flipY/"+i.toString()+(r||s?";"+r+";"+s:"");if(void 0!==d[u])return d[u];l.images||(l.images=[]);const p={mimeType:n},m=BM();m.width=Math.min(r||e.width,c.maxTextureSize),m.height=Math.min(s||e.height,c.maxTextureSize);const g=m.getContext("2d",{willReadFrequently:!0});if(!0===i&&(g.translate(0,m.height),g.scale(1,-1)),void 0!==e.data){t!==Ue&&console.error("GLTFExporter: Only RGBAFormat is supported.",t),(e.width>c.maxTextureSize||e.height>c.maxTextureSize)&&console.warn("GLTFExporter: Image size is bigger than maxTextureSize",e);const i=new Uint8ClampedArray(e.height*e.width*4);for(let t=0;t<i.length;t+=4)i[t+0]=e.data[t+0],i[t+1]=e.data[t+1],i[t+2]=e.data[t+2],i[t+3]=e.data[t+3];g.putImageData(new ImageData(i,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))throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.");g.drawImage(e,0,0,m.width,m.height)}!0===c.binary?h.push(LM(m,n).then(e=>a.processBufferViewImage(e)).then(e=>{p.bufferView=e})):void 0!==m.toDataURL?p.uri=m.toDataURL(n):h.push(LM(m,n).then(e=>(new FileReader).readAsDataURL(e)).then(e=>{p.uri=e}));const f=l.images.push(p)-1;return d[u]=f,f}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:EM[e.magFilter],minFilter:EM[e.minFilter],wrapS:EM[e.wrapS],wrapT:EM[e.wrapT]};return t.samplers.push(i)-1}processTexture(e){const t=this.options,i=this.cache,n=this.json;if(i.textures.has(e))return i.textures.get(e);n.textures||(n.textures=[]),e instanceof $c&&!e.source._canSerialize&&(e=eM(e,t.maxTextureSize));let r=e.userData.mimeType;"image/webp"===r&&(r="image/png"),"image/jpg"===r&&(r="image/jpeg");const s={sampler:this.processSampler(e),source:!r||["image/jpeg","image/png"].includes(r)?this.processImage(e.image,e.format,e.flipY,r):null};e.name&&(s.name=e.name),this._invokeAll(function(t){t.writeTexture&&t.writeTexture(e,s)}),null===s.source&&console.error("GLTFExporter: Unsupported mime type: "+r+". Cannot export texture.",e);const a=n.textures.push(s)-1;return i.textures.set(e,a),a}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:{}};!0!==e.isMeshStandardMaterial&&!0!==e.isMeshBasicMaterial&&console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");const r=e.color.toArray().concat([e.opacity]);if(PM(r,[1,1,1,1])||(n.pbrMetallicRoughness.baseColorFactor=r),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 t=this.buildMetalRoughTexture(e.metalnessMap,e.roughnessMap),i={index:this.processTexture(t),channel:t.channel};this.applyTextureTransform(i,t),n.pbrMetallicRoughness.metallicRoughnessTexture=i}if(this.checkEmptyMap(e.map)){const t={index:this.processTexture(e.map),texCoord:e.map.channel};this.applyTextureTransform(t,e.map),n.pbrMetallicRoughness.baseColorTexture=t}if(e.emissive){const t=e.emissive;if(Math.max(t.r,t.g,t.b)>0&&(n.emissiveFactor=e.emissive.toArray()),this.checkEmptyMap(e.emissiveMap)){const t={index:this.processTexture(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(t,e.emissiveMap),n.emissiveTexture=t}}if(this.checkEmptyMap(e.normalMap)){const t={index:this.processTexture(e.normalMap),texCoord:e.normalMap.channel};e.normalScale&&1!==e.normalScale.x&&(t.scale=e.normalScale.x),this.applyTextureTransform(t,e.normalMap),n.normalTexture=t}if(this.checkEmptyMap(e.aoMap)){const t={index:this.processTexture(e.aoMap),texCoord:e.aoMap.channel};1!==e.aoMapIntensity&&(t.strength=e.aoMapIntensity),this.applyTextureTransform(t,e.aoMap),n.occlusionTexture=t}e.transparent?n.alphaMode="BLEND":e.alphaTest>0&&(n.alphaMode="MASK",n.alphaCutoff=e.alphaTest),e.side===x&&(n.doubleSided=!0),""!==e.name&&(n.name=e.name),this.serializeUserData(e,n),this._invokeAll(function(t){t.writeMaterial&&t.writeMaterial(e,n)});const s=i.materials.push(n)-1;return t.materials.set(e,s),s}processMesh(e){const t=this.cache,i=this.json,n=[e.geometry.uuid];if(Array.isArray(e.material))for(let t=0,i=e.material.length;t<i;t++)n.push(e.material[t].uuid);else n.push(e.material.uuid);const r=n.join(":");if(t.meshes.has(r))return t.meshes.get(r);const s=e.geometry;let a;a=e.isLineSegments?rM:e.isLineLoop?sM:e.isLine?aM:e.isPoints?nM:e.material.wireframe?rM:oM;const o={},l={},c=[],h=[],d={uv:"TEXCOORD_0",uv1:"TEXCOORD_1",uv2:"TEXCOORD_2",uv3:"TEXCOORD_3",color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},u=s.getAttribute("normal");void 0!==u&&!this.isNormalizedNormalAttribute(u)&&(console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."),s.setAttribute("normal",this.createNormalizedNormalAttribute(u)));let p=null;for(let e in s.attributes){if("morph"===e.slice(0,5))continue;const i=s.attributes[e];if(e=d[e]||e.toUpperCase(),/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.test(e)||(e="_"+e),t.attributes.has(this.getUID(i))){l[e]=t.attributes.get(this.getUID(i));continue}p=null;const n=i.array;"JOINTS_0"===e&&!(n instanceof Uint16Array)&&!(n instanceof Uint8Array)&&(console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'),p=new Mr(new Uint16Array(n),i.itemSize,i.normalized));const r=this.processAccessor(p||i,s);null!==r&&(e.startsWith("_")||this.detectMeshQuantization(e,i),l[e]=r,t.attributes.set(this.getUID(i),r))}if(void 0!==u&&s.setAttribute("normal",u),0===Object.keys(l).length)return null;if(void 0!==e.morphTargetInfluences&&e.morphTargetInfluences.length>0){const i=[],n=[],r={};if(void 0!==e.morphTargetDictionary)for(const t in e.morphTargetDictionary)r[e.morphTargetDictionary[t]]=t;for(let a=0;a<e.morphTargetInfluences.length;++a){const o={};let l=!1;for(const e in s.morphAttributes){if("position"!==e&&"normal"!==e){l||(console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."),l=!0);continue}const i=s.morphAttributes[e][a],n=e.toUpperCase(),r=s.attributes[e];if(t.attributes.has(this.getUID(i,!0))){o[n]=t.attributes.get(this.getUID(i,!0));continue}const c=i.clone();if(!s.morphTargetsRelative)for(let e=0,t=i.count;e<t;e++)for(let t=0;t<i.itemSize;t++)0===t&&c.setX(e,i.getX(e)-r.getX(e)),1===t&&c.setY(e,i.getY(e)-r.getY(e)),2===t&&c.setZ(e,i.getZ(e)-r.getZ(e)),3===t&&c.setW(e,i.getW(e)-r.getW(e));o[n]=this.processAccessor(c,s),t.attributes.set(this.getUID(r,!0),o[n])}h.push(o),i.push(e.morphTargetInfluences[a]),void 0!==e.morphTargetDictionary&&n.push(r[a])}o.weights=i,n.length>0&&(o.extras={},o.extras.targetNames=n)}const m=Array.isArray(e.material);if(m&&0===s.groups.length)return null;let g=!1;if(m&&null===s.index){const e=[];for(let t=0,i=s.attributes.position.count;t<i;t++)e[t]=t;s.setIndex(e),g=!0}const f=m?e.material:[e.material],A=m?s.groups:[{materialIndex:0,start:void 0,count:void 0}];for(let e=0,i=A.length;e<i;e++){const i={mode:a,attributes:l};if(this.serializeUserData(s,i),h.length>0&&(i.targets=h),null!==s.index){let n=this.getUID(s.index);(void 0!==A[e].start||void 0!==A[e].count)&&(n+=":"+A[e].start+":"+A[e].count),t.attributes.has(n)?i.indices=t.attributes.get(n):(i.indices=this.processAccessor(s.index,s,A[e].start,A[e].count),t.attributes.set(n,i.indices)),null===i.indices&&delete i.indices}const n=this.processMaterial(f[A[e].materialIndex]);null!==n&&(i.material=n),c.push(i)}!0===g&&s.setIndex(null),o.primitives=c,i.meshes||(i.meshes=[]),this._invokeAll(function(t){t.writeMesh&&t.writeMesh(e,o)});const y=i.meshes.push(o)-1;return t.meshes.set(r,y),y}detectMeshQuantization(e,t){if(this.extensionsUsed[MM])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];tM[n]&&tM[n].includes(i)&&(this.extensionsUsed[MM]=!0,this.extensionsRequired[MM]=!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:2*e.right,ymag:2*e.top,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:n.perspective={aspectRatio:e.aspect,yfov:gi.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=iM.Utils.mergeMorphTargetTracks(e.clone(),t)}catch(t){if(console.warn('THREE.GLTFExporter: Could not export animation clip "%s".',e.name),!this.options.ignoreInvalidMorphTargetTracks)throw t;return console.error(t),null}const r=e.tracks,s=[],a=[];for(let e=0;e<r.length;++e){const i=r[e],o=mp.parseTrackName(i.name);let l=mp.findNode(t,o.nodeName);const c=TM[o.propertyName];if("bones"===o.objectName&&(l=!0===l.isSkinnedMesh?l.skeleton.getBoneByName(o.objectIndex):void 0),!l||!c){console.warn('THREE.GLTFExporter: Could not export animation track "%s".',i.name);continue}const h=1;let d,u=i.values.length/i.times.length;c===TM.morphTargetInfluences&&(u/=l.morphTargetInfluences.length),!0===i.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline?(d="CUBICSPLINE",u/=3):d=i.getInterpolation()===wt?"STEP":"LINEAR",a.push({input:this.processAccessor(new Mr(i.times,h)),output:this.processAccessor(new Mr(i.values,u)),interpolation:d}),s.push({sampler:a.length-1,target:{node:n.get(l),path:c}})}const o={name:e.name||"clip_"+i.animations.length,samplers:a,channels:s};return this.serializeUserData(e,o),i.animations.push(o),i.animations.length-1}processSkin(e){const t=this.json,i=this.nodeMap,n=t.nodes[i.get(e)],r=e.skeleton;if(void 0===r)return null;const s=e.skeleton.bones[0];if(void 0===s)return null;const a=[],o=new Float32Array(16*r.bones.length),l=new Sn;for(let t=0;t<r.bones.length;++t)a.push(i.get(r.bones[t])),l.copy(r.boneInverses[t]),l.multiply(e.bindMatrix).toArray(o,16*t);return void 0===t.skins&&(t.skins=[]),t.skins.push({inverseBindMatrices:this.processAccessor(new Mr(o,16)),joints:a,skeleton:i.get(s)}),n.skin=t.skins.length-1}processNode(e){const t=this.json,i=this.options,n=this.nodeMap;t.nodes||(t.nodes=[]);const r={};if(i.trs){const t=e.quaternion.toArray(),i=e.position.toArray(),n=e.scale.toArray();PM(t,[0,0,0,1])||(r.rotation=t),PM(i,[0,0,0])||(r.translation=i),PM(n,[1,1,1])||(r.scale=n)}else e.matrixAutoUpdate&&e.updateMatrix(),!1===function(e){return PM(e.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}(e.matrix)&&(r.matrix=e.matrix.elements);if(""!==e.name&&(r.name=String(e.name)),this.serializeUserData(e,r),e.isMesh||e.isLine||e.isPoints){const t=this.processMesh(e);null!==t&&(r.mesh=t)}else e.isCamera&&(r.camera=this.processCamera(e));if(e.isSkinnedMesh&&this.skins.push(e),e.children.length>0){const t=[];for(let n=0,r=e.children.length;n<r;n++){const r=e.children[n];if(r.visible||!1===i.onlyVisible){const e=this.processNode(r);null!==e&&t.push(e)}}t.length>0&&(r.children=t)}this._invokeAll(function(t){t.writeNode&&t.writeNode(e,r)});const s=t.nodes.push(r)-1;return n.set(e,s),s}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 r=[];for(let t=0,n=e.children.length;t<n;t++){const n=e.children[t];if(n.visible||!1===i.onlyVisible){const e=this.processNode(n);null!==e&&r.push(e)}}r.length>0&&(n.nodes=r),this.serializeUserData(e,n)}processObjects(e){const t=new _l;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(t){t.beforeParse&&t.beforeParse(e)});const i=[];for(let t=0;t<e.length;t++)e[t]instanceof _l?this.processScene(e[t]):i.push(e[t]);i.length>0&&this.processObjects(i);for(let e=0;e<this.skins.length;++e)this.processSkin(this.skins[e]);for(let i=0;i<t.animations.length;++i)this.processAnimation(t.animations[i],e[0]);this._invokeAll(function(t){t.afterParse&&t.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 UM{constructor(e){this.writer=e,this.name="KHR_lights_punctual"}writeNode(e,t){if(!e.isLight)return;if(!e.isDirectionalLight&&!e.isPointLight&&!e.isSpotLight)return void console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.",e);const i=this.writer,n=i.json,r=i.extensionsUsed,s={};e.name&&(s.name=e.name),s.color=e.color.toArray(),s.intensity=e.intensity,e.isDirectionalLight?s.type="directional":e.isPointLight?(s.type="point",e.distance>0&&(s.range=e.distance)):e.isSpotLight&&(s.type="spot",e.distance>0&&(s.range=e.distance),s.spot={},s.spot.innerConeAngle=(1-e.penumbra)*e.angle,s.spot.outerConeAngle=e.angle),void 0!==e.decay&&2!==e.decay&&console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2."),e.target&&(e.target.parent!==e||0!==e.target.position.x||0!==e.target.position.y||-1!==e.target.position.z)&&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."),r[this.name]||(n.extensions=n.extensions||{},n.extensions[this.name]={lights:[]},r[this.name]=!0);const a=n.extensions[this.name].lights;a.push(s),t.extensions=t.extensions||{},t.extensions[this.name]={light:a.length-1}}}let FM=class{constructor(e){this.writer=e,this.name="KHR_materials_unlit"}writeMaterial(e,t){if(!e.isMeshBasicMaterial)return;const i=this.writer.extensionsUsed;t.extensions=t.extensions||{},t.extensions[this.name]={},i[this.name]=!0,t.pbrMetallicRoughness.metallicFactor=0,t.pbrMetallicRoughness.roughnessFactor=.9}},kM=class{constructor(e){this.writer=e,this.name="KHR_materials_clearcoat"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0===e.clearcoat)return;const i=this.writer,n=i.extensionsUsed,r={};if(r.clearcoatFactor=e.clearcoat,i.checkEmptyMap(e.clearcoatMap)){const t={index:i.processTexture(e.clearcoatMap),texCoord:e.clearcoatMap.channel};i.applyTextureTransform(t,e.clearcoatMap),r.clearcoatTexture=t}if(r.clearcoatRoughnessFactor=e.clearcoatRoughness,i.checkEmptyMap(e.clearcoatRoughnessMap)){const t={index:i.processTexture(e.clearcoatRoughnessMap),texCoord:e.clearcoatRoughnessMap.channel};i.applyTextureTransform(t,e.clearcoatRoughnessMap),r.clearcoatRoughnessTexture=t}if(i.checkEmptyMap(e.clearcoatNormalMap)){const t={index:i.processTexture(e.clearcoatNormalMap),texCoord:e.clearcoatNormalMap.channel};1!==e.clearcoatNormalScale.x&&(t.scale=e.clearcoatNormalScale.x),i.applyTextureTransform(t,e.clearcoatNormalMap),r.clearcoatNormalTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},NM=class{constructor(e){this.writer=e,this.name="KHR_materials_dispersion"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0===e.dispersion)return;const i=this.writer.extensionsUsed,n={};n.dispersion=e.dispersion,t.extensions=t.extensions||{},t.extensions[this.name]=n,i[this.name]=!0}},jM=class{constructor(e){this.writer=e,this.name="KHR_materials_iridescence"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0===e.iridescence)return;const i=this.writer,n=i.extensionsUsed,r={};if(r.iridescenceFactor=e.iridescence,i.checkEmptyMap(e.iridescenceMap)){const t={index:i.processTexture(e.iridescenceMap),texCoord:e.iridescenceMap.channel};i.applyTextureTransform(t,e.iridescenceMap),r.iridescenceTexture=t}if(r.iridescenceIor=e.iridescenceIOR,r.iridescenceThicknessMinimum=e.iridescenceThicknessRange[0],r.iridescenceThicknessMaximum=e.iridescenceThicknessRange[1],i.checkEmptyMap(e.iridescenceThicknessMap)){const t={index:i.processTexture(e.iridescenceThicknessMap),texCoord:e.iridescenceThicknessMap.channel};i.applyTextureTransform(t,e.iridescenceThicknessMap),r.iridescenceThicknessTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},zM=class{constructor(e){this.writer=e,this.name="KHR_materials_transmission"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;const i=this.writer,n=i.extensionsUsed,r={};if(r.transmissionFactor=e.transmission,i.checkEmptyMap(e.transmissionMap)){const t={index:i.processTexture(e.transmissionMap),texCoord:e.transmissionMap.channel};i.applyTextureTransform(t,e.transmissionMap),r.transmissionTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},GM=class{constructor(e){this.writer=e,this.name="KHR_materials_volume"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0===e.transmission)return;const i=this.writer,n=i.extensionsUsed,r={};if(r.thicknessFactor=e.thickness,i.checkEmptyMap(e.thicknessMap)){const t={index:i.processTexture(e.thicknessMap),texCoord:e.thicknessMap.channel};i.applyTextureTransform(t,e.thicknessMap),r.thicknessTexture=t}e.attenuationDistance!==1/0&&(r.attenuationDistance=e.attenuationDistance),r.attenuationColor=e.attenuationColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},QM=class{constructor(e){this.writer=e,this.name="KHR_materials_ior"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||1.5===e.ior)return;const i=this.writer.extensionsUsed,n={};n.ior=e.ior,t.extensions=t.extensions||{},t.extensions[this.name]=n,i[this.name]=!0}},VM=class{constructor(e){this.writer=e,this.name="KHR_materials_specular"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||1===e.specularIntensity&&e.specularColor.equals(IM)&&!e.specularIntensityMap&&!e.specularColorMap)return;const i=this.writer,n=i.extensionsUsed,r={};if(i.checkEmptyMap(e.specularIntensityMap)){const t={index:i.processTexture(e.specularIntensityMap),texCoord:e.specularIntensityMap.channel};i.applyTextureTransform(t,e.specularIntensityMap),r.specularTexture=t}if(i.checkEmptyMap(e.specularColorMap)){const t={index:i.processTexture(e.specularColorMap),texCoord:e.specularColorMap.channel};i.applyTextureTransform(t,e.specularColorMap),r.specularColorTexture=t}r.specularFactor=e.specularIntensity,r.specularColorFactor=e.specularColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},HM=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,r={};if(i.checkEmptyMap(e.sheenRoughnessMap)){const t={index:i.processTexture(e.sheenRoughnessMap),texCoord:e.sheenRoughnessMap.channel};i.applyTextureTransform(t,e.sheenRoughnessMap),r.sheenRoughnessTexture=t}if(i.checkEmptyMap(e.sheenColorMap)){const t={index:i.processTexture(e.sheenColorMap),texCoord:e.sheenColorMap.channel};i.applyTextureTransform(t,e.sheenColorMap),r.sheenColorTexture=t}r.sheenRoughnessFactor=e.sheenRoughness,r.sheenColorFactor=e.sheenColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=r,t.extras=t.extras||{},t.extras.sheenFactor=e.sheen,n[this.name]=!0}},WM=class{constructor(e){this.writer=e,this.name="KHR_materials_anisotropy"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||0==e.anisotropy)return;const i=this.writer,n=i.extensionsUsed,r={};if(i.checkEmptyMap(e.anisotropyMap)){const t={index:i.processTexture(e.anisotropyMap)};i.applyTextureTransform(t,e.anisotropyMap),r.anisotropyTexture=t}r.anisotropyStrength=e.anisotropy,r.anisotropyRotation=e.anisotropyRotation,t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},qM=class{constructor(e){this.writer=e,this.name="KHR_materials_emissive_strength"}writeMaterial(e,t){if(!e.isMeshStandardMaterial||1===e.emissiveIntensity)return;const i=this.writer.extensionsUsed,n={};n.emissiveStrength=e.emissiveIntensity,t.extensions=t.extensions||{},t.extensions[this.name]=n,i[this.name]=!0}},XM=class{constructor(e){this.writer=e,this.name="EXT_materials_bump"}writeMaterial(e,t){if(!e.isMeshStandardMaterial||1===e.bumpScale&&!e.bumpMap)return;const i=this.writer,n=i.extensionsUsed,r={};if(e.bumpMap){const t={index:i.processTexture(e.bumpMap),texCoord:e.bumpMap.channel};i.applyTextureTransform(t,e.bumpMap),r.bumpTexture=t}r.bumpFactor=e.bumpScale,t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},YM=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,r=new Float32Array(3*n.count),s=new Float32Array(4*n.count),a=new Float32Array(3*n.count),o=new Sn,l=new Xi,c=new qi,h=new Xi;for(let e=0;e<n.count;e++)n.getMatrixAt(e,o),o.decompose(l,c,h),l.toArray(r,3*e),c.toArray(s,4*e),h.toArray(a,3*e);const d={TRANSLATION:i.processAccessor(new Mr(r,3)),ROTATION:i.processAccessor(new Mr(s,4)),SCALE:i.processAccessor(new Mr(a,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}};iM.Utils={GLTFWriter:OM,insertKeyframe:function(e,t){const i=e.getValueSize(),n=new e.TimeBufferType(e.times.length+1),r=new e.ValueBufferType(e.values.length+i),s=e.createInterpolant(new e.ValueBufferType(i));let a;if(0===e.times.length){n[0]=t;for(let e=0;e<i;e++)r[e]=0;a=0}else if(t<e.times[0]){if(Math.abs(e.times[0]-t)<.001)return 0;n[0]=t,n.set(e.times,1),r.set(s.evaluate(t),0),r.set(e.values,i),a=0}else if(t>e.times[e.times.length-1]){if(Math.abs(e.times[e.times.length-1]-t)<.001)return e.times.length-1;n[n.length-1]=t,n.set(e.times,0),r.set(e.values,0),r.set(s.evaluate(t),e.values.length),a=n.length-1}else for(let o=0;o<e.times.length;o++){if(Math.abs(e.times[o]-t)<.001)return o;if(e.times[o]<t&&e.times[o+1]>t){n.set(e.times.slice(0,o+1),0),n[o+1]=t,n.set(e.times.slice(o+1),o+2),r.set(e.values.slice(0,(o+1)*i),0),r.set(s.evaluate(t),(o+1)*i),r.set(e.values.slice((o+1)*i),(o+2)*i),a=o+1;break}}return e.times=n,e.values=r,a},mergeMorphTargetTracks:function(e,t){const i=[],n={},r=e.tracks;for(let e=0;e<r.length;++e){let s=r[e];const a=mp.parseTrackName(s.name),o=mp.findNode(t,a.nodeName);if("morphTargetInfluences"!==a.propertyName||void 0===a.propertyIndex){i.push(s);continue}if(s.createInterpolant!==s.InterpolantFactoryMethodDiscrete&&s.createInterpolant!==s.InterpolantFactoryMethodLinear){if(s.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."),s=s.clone(),s.setInterpolation(Ct)}const l=o.morphTargetInfluences.length,c=o.morphTargetDictionary[a.propertyIndex];if(void 0===c)throw new Error("THREE.GLTFExporter: Morph target name not found: "+a.propertyIndex);let h;if(void 0===n[o.uuid]){h=s.clone();const e=new h.ValueBufferType(l*h.times.length);for(let t=0;t<h.times.length;t++)e[t*l+c]=h.values[t];h.name=(a.nodeName||"")+".morphTargetInfluences",h.values=e,n[o.uuid]=h,i.push(h);continue}const d=s.createInterpolant(new s.ValueBufferType(1));h=n[o.uuid];for(let e=0;e<h.times.length;e++)h.values[e*l+c]=d.evaluate(h.times[e]);for(let e=0;e<s.times.length;e++){const t=this.insertKeyframe(h,s.times[e]);h.values[t*l+c]=s.values[e]}}return e.tracks=i,e}};class KM extends iM.Utils.GLTFWriter{constructor(){super(),this.TPAssetVersion=1,this.serializationMeta=w_(),this._defaultMaterial=new Td,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(([e,t])=>{(!t||"function"==typeof t||t.isObject3D||t.isTexture||t.isMaterial||null!=t.assetType||e.startsWith("_"))&&(n[e]=t,delete i[e])});const r=f_.Serialize(i,this.serializationMeta);Object.entries(n).forEach(([e,t])=>{i[e]=t,delete n[e]}),e.userData=r,super.serializeUserData(e,t),e.userData=i}processObjects(e){1===e.length&&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(null===i)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]),r=JSON.parse(n),s=e.color?.isColor?e.color.toArray().concat([e.opacity]):null;s&&!s.every(e=>1===e)&&r.pbrMetallicRoughness&&(r.pbrMetallicRoughness.baseColorFactor=s),this.serializeUserData(e,r),this._invokeAll(t=>{t.writeMaterial&&t.writeMaterial(e,r)});const a=this.json.materials.push(r)-1;return this.cache.materials.set(e,a),a}processImageBlob(e,t){if(!e)return-1;const i=this.cache,n=this.options,r=this.pending,s=this.json,a=t.image;i.images.has(a)||i.images.set(a,{});const o=i.images.get(a),l=e.type+":flipY/"+t.flipY.toString();if(void 0!==o[l])return o[l];s.images||(s.images=[]);const c={mimeType:e.type};!0===n.binary?r.push(new Promise(t=>{this.processBufferViewImage(e).then(e=>{c.bufferView=e,t()})})):r.push(xm(e).then(e=>{c.uri=e}));const h=s.images.push(c)-1;return o[l]=h,h}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,r=e.userData.mimeType,s=!e.isRenderTargetTexture&&e.userData.rootPath&&"string"==typeof e.userData.rootPath&&Eg(e.userData.rootPath);s&&!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 a=super.processTexture(e),o=i.textures[a];if(!o)return console.error("No texture def",a,e),a;if(s&&!this.options.exporterOptions.embedUrlImages){if(e.source.data?delete e.source.data._savePreview:e.source.data=n,e.userData.mimeType=r,!o)return console.error("textureDef is null",a,e),a;let t=e.userData.rootPath;const i=this.options.exporterOptions._basePath;if(i&&"string"==typeof t&&t.startsWith(i)&&(t=t.slice(i.length)),o.source>=0){const i=this.json.images[o.source];i.uri?console.warn("uri already set",i.uri):(i.uri=t,i.mimeType=r,i.extras||(i.extras={}),i.extras.flipY=e.flipY,i.extras.uri=t)}else o.source=this.processImageUri(e.image,t,e.flipY,r)}if(o.source<0)console.error("textureDef.source cannot be saved",o,e),delete o.source;else{const t=i.images?i.images[o.source]:null;t&&(t.extras||(t.extras={}),e.source&&(t.extras.uuid=e.source.uuid),t.extras.t_uuid=e.uuid)}return a}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 r=this.cache,s=this.json;r.images.has(e)||r.images.set(e,{});const a=r.images.get(e),o=n+":flipY/"+i.toString();if(void 0!==a[o])return a[o];s.images||(s.images=[]);const l={mimeType:n,uri:t,extras:{flipY:i}},c=s.images.push(l)-1;return a[o]=c,c}}const JM=class{};JM.WebGiLightExtrasExtension="WEBGI_light_extras",JM.Import=e=>({name:"__"+JM.WebGiLightExtrasExtension,afterRoot:async e=>{(e.scenes||(e.scene?[e.scene]:[])).forEach(e=>{e.traverse(e=>{if(!e.isLight)return;const t=e.userData?.gltfExtensions?.[JM.WebGiLightExtrasExtension];t&&(!e.shadow&&t.shadow&&console.error("Light has no shadow, cannot import",e,t),t.shadow&&e.shadow&&(void 0!==t.shadow.bias&&(e.shadow.bias=t.shadow.bias),void 0!==t.shadow.normalBias&&(e.shadow.normalBias=t.shadow.normalBias),void 0!==t.shadow.radius&&(e.shadow.radius=t.shadow.radius),void 0!==t.shadow.mapSize&&e.shadow.mapSize.fromArray(t.shadow.mapSize),void 0!==t.shadow.camera&&(e.shadow.camera=(new Uu).parseObject(t.shadow.camera,{},{},{},{}))),delete e.userData.gltfExtensions[JM.WebGiLightExtrasExtension])})})}}),JM.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[JM.WebGiLightExtrasExtension]=n,e.extensionsUsed[JM.WebGiLightExtrasExtension]=!0)}}),JM.Textures=void 0;let ZM=JM;const $M=class{};$M.WebGiMaterialExtrasExtension="WEBGI_material_extras",$M.Import=e=>t=>({name:"__"+$M.WebGiMaterialExtrasExtension,afterRoot:async i=>{const n=i.scenes||(i.scene?[i.scene]:[]);for(const i of n){const n=i.userData?.gltfExtensions?.[$M.WebGiMaterialExtrasExtension],r=n?.resources?await e(n.resources):{};i.traverse(e=>{const i=e?.material;if(!i?.isMaterial)return;const n=i.userData?.gltfExtensions?.[$M.WebGiMaterialExtrasExtension];if(!n)return;void 0!==n.emissiveIntensity&&(i.emissiveIntensity=n.emissiveIntensity),void 0!==n.fog&&(i.fog=n.fog),void 0!==n.flatShading&&(i.flatShading=n.flatShading),void 0!==n.blending&&(i.blending=n.blending),void 0!==n.side&&(i.side=n.side),void 0!==n.shadowSide&&(i.shadowSide=n.shadowSide),void 0!==n.depthFunc&&(i.depthFunc=n.depthFunc),void 0!==n.depthTest&&(i.depthTest=n.depthTest),void 0!==n.depthWrite&&(i.depthWrite=n.depthWrite),void 0!==n.colorWrite&&(i.colorWrite=n.colorWrite),void 0!==n.vertexColors&&(i.vertexColors=n.vertexColors),void 0!==n.alphaTest&&(i.alphaTest=n.alphaTest),void 0!==n.alphaHash&&(i.alphaHash=n.alphaHash),void 0!==n.envMapIntensity&&(i.envMapIntensity=n.envMapIntensity),void 0!==n.envMapRotation&&Array.isArray(n.envMapRotation)&&i.envMapRotation?.fromArray&&i.envMapRotation.fromArray(n.envMapRotation),void 0!==n.blendSrc&&(i.blendSrc=n.blendSrc),void 0!==n.blendDst&&(i.blendDst=n.blendDst),void 0!==n.blendEquation&&(i.blendEquation=n.blendEquation),void 0!==n.blendSrcAlpha&&(i.blendSrcAlpha=n.blendSrcAlpha),void 0!==n.blendDstAlpha&&(i.blendDstAlpha=n.blendDstAlpha),void 0!==n.blendEquationAlpha&&(i.blendEquationAlpha=n.blendEquationAlpha),void 0!==n.blendColor&&void 0!==i.blendColor&&i.blendColor.setHex(n.blendColor),void 0!==n.blendAlpha&&(i.blendAlpha=n.blendAlpha),void 0!==n.stencilWrite&&(i.stencilWrite=n.stencilWrite),void 0!==n.stencilWriteMask&&(i.stencilWriteMask=n.stencilWriteMask),void 0!==n.stencilFunc&&(i.stencilFunc=n.stencilFunc),void 0!==n.stencilRef&&(i.stencilRef=n.stencilRef),void 0!==n.stencilFuncMask&&(i.stencilFuncMask=n.stencilFuncMask),void 0!==n.stencilFail&&(i.stencilFail=n.stencilFail),void 0!==n.stencilZFail&&(i.stencilZFail=n.stencilZFail),void 0!==n.stencilZPass&&(i.stencilZPass=n.stencilZPass),void 0!==n.wireframe&&(i.wireframe=n.wireframe),void 0!==n.wireframeLinewidth&&(i.wireframeLinewidth=n.wireframeLinewidth),void 0!==n.wireframeLinecap&&(i.wireframeLinecap=n.wireframeLinecap),void 0!==n.wireframeLinejoin&&(i.wireframeLinejoin=n.wireframeLinejoin),void 0!==n.rotation&&(i.rotation=n.rotation),void 0!==n.linewidth&&(i.linewidth=n.linewidth),void 0!==n.worldUnits&&(i.worldUnits=n.worldUnits),void 0!==n.dashed&&(i.dashed=n.dashed),void 0!==n.dashSize&&(i.dashSize=n.dashSize),void 0!==n.dashScale&&(i.dashScale=n.dashScale),void 0!==n.dashOffset&&(i.dashOffset=n.dashOffset),void 0!==n.gapSize&&(i.gapSize=n.gapSize),void 0!==n.resolution&&i.resolution&&i.resolution.fromArray&&i.resolution.fromArray(n.resolution),void 0!==n.polygonOffset&&(i.polygonOffset=n.polygonOffset),void 0!==n.polygonOffsetFactor&&(i.polygonOffsetFactor=n.polygonOffsetFactor),void 0!==n.polygonOffsetUnits&&(i.polygonOffsetUnits=n.polygonOffsetUnits),void 0!==n.dithering&&(i.dithering=n.dithering),void 0!==n.alphaToCoverage&&(i.alphaToCoverage=n.alphaToCoverage),void 0!==n.premultipliedAlpha&&(i.premultipliedAlpha=n.premultipliedAlpha),void 0!==n.toneMapped&&(i.toneMapped=n.toneMapped),void 0!==n.normalScale&&void 0!==i.normalScale&&(Array.isArray(n.normalScale)?i.normalScale.fromArray(n.normalScale):"number"==typeof n.normalScale?i.normalScale.set(n.normalScale,n.normalScale):console.warn("normalScale is not an array or number",n.normalScale)),void 0!==n.reflectivity&&(i.reflectivity=n.reflectivity),Object.entries(n).forEach(([e,t])=>{e.startsWith("_")||t&&t.resource&&"string"==typeof t.resource&&(i[e]=f_.Deserialize(t,i[e],r))}),delete i.userData.gltfExtensions[$M.WebGiMaterialExtrasExtension];const s=t.json?.asset?.version?parseFloat(t.json?.asset?.version):null;(i.userData.legacyBumpScale||s&&s<=2)&&void 0!==i?.bumpScale&&i?.bumpMap&&i.defines&&(console.warn("MaterialManager: Old format material loaded, bump map might be incorrect.",i,i.bumpScale),i.defines.BUMP_MAP_SCALE_LEGACY="1",i.userData.legacyBumpScale=!0,i.needsUpdate=!0)}),n&&delete i.userData.gltfExtensions[$M.WebGiMaterialExtrasExtension]}}}),$M.Export=e=>({writeMaterial(t,i){if(!t?.isMaterial)return;i.extensions||(i.extensions={});const n={};void 0!==t.fog&&t.fog!==yC.MaterialProperties.fog&&(n.fog=t.fog),void 0!==t.flatShading&&t.flatShading!==yC.MaterialProperties.flatShading&&(n.flatShading=t.flatShading),void 0!==t.blending&&t.blending!==Ow.blending&&(n.blending=t.blending),void 0!==t.side&&t.side!==x&&(n.side=t.side),void 0!==t.shadowSide&&t.shadowSide!==Ow.shadowSide&&(n.shadowSide=t.shadowSide),void 0!==t.depthFunc&&t.depthFunc!==Ow.depthFunc&&(n.depthFunc=t.depthFunc),void 0!==t.depthTest&&t.depthTest!==Ow.depthTest&&(n.depthTest=t.depthTest),void 0!==t.depthWrite&&t.depthWrite!==Ow.depthWrite&&(n.depthWrite=t.depthWrite),void 0!==t.colorWrite&&t.colorWrite!==Ow.colorWrite&&(n.colorWrite=t.colorWrite),void 0!==t.vertexColors&&t.vertexColors!==Ow.vertexColors&&(n.vertexColors=t.vertexColors),void 0!==t.alphaTest&&t.alphaTest!==Ow.alphaTest&&(n.alphaTest=t.alphaTest),void 0!==t.alphaHash&&t.alphaHash!==Ow.alphaHash&&(n.alphaHash=t.alphaHash),void 0!==t.envMapIntensity&&t.envMapIntensity!==yC.MaterialProperties.envMapIntensity&&(n.envMapIntensity=t.envMapIntensity),void 0!==t.envMapRotation&&!t.envMapRotation.equals(yC.MaterialProperties.envMapRotation)&&(n.envMapRotation=t.envMapRotation.toArray()),void 0!==t.blendSrc&&t.blendSrc!==Ow.blendSrc&&(n.blendSrc=t.blendSrc),void 0!==t.blendDst&&t.blendDst!==Ow.blendDst&&(n.blendDst=t.blendDst),void 0!==t.blendEquation&&t.blendEquation!==Ow.blendEquation&&(n.blendEquation=t.blendEquation),void 0!==t.blendSrcAlpha&&t.blendSrcAlpha!==Ow.blendSrcAlpha&&(n.blendSrcAlpha=t.blendSrcAlpha),void 0!==t.blendDstAlpha&&t.blendDstAlpha!==Ow.blendDstAlpha&&(n.blendDstAlpha=t.blendDstAlpha),void 0!==t.blendEquationAlpha&&t.blendEquationAlpha!==Ow.blendEquationAlpha&&(n.blendEquationAlpha=t.blendEquationAlpha),void 0!==t.blendColor&&t.blendColor!==Ow.blendColor&&(n.blendColor=t.blendColor.getHex()),void 0!==t.blendAlpha&&t.blendAlpha!==Ow.blendAlpha&&(n.blendAlpha=t.blendAlpha),void 0!==t.stencilWrite&&t.stencilWrite!==Ow.stencilWrite&&(n.stencilWrite=t.stencilWrite),void 0!==t.stencilWriteMask&&t.stencilWriteMask!==Ow.stencilWriteMask&&(n.stencilWriteMask=t.stencilWriteMask),void 0!==t.stencilFunc&&t.stencilFunc!==Ow.stencilFunc&&(n.stencilFunc=t.stencilFunc),void 0!==t.stencilRef&&t.stencilRef!==Ow.stencilRef&&(n.stencilRef=t.stencilRef),void 0!==t.stencilFuncMask&&t.stencilFuncMask!==Ow.stencilFuncMask&&(n.stencilFuncMask=t.stencilFuncMask),void 0!==t.stencilFail&&t.stencilFail!==Ow.stencilFail&&(n.stencilFail=t.stencilFail),void 0!==t.stencilZFail&&t.stencilZFail!==Ow.stencilZFail&&(n.stencilZFail=t.stencilZFail),void 0!==t.stencilZPass&&t.stencilZPass!==Ow.stencilZPass&&(n.stencilZPass=t.stencilZPass),void 0!==t.wireframe&&t.wireframe!==yC.MaterialProperties.wireframe&&(n.wireframe=t.wireframe),void 0!==t.wireframeLinewidth&&t.wireframeLinewidth!==yC.MaterialProperties.wireframeLinewidth&&(n.wireframeLinewidth=t.wireframeLinewidth),void 0!==t.wireframeLinecap&&t.wireframeLinecap!==yC.MaterialProperties.wireframeLinecap&&(n.wireframeLinecap=t.wireframeLinecap),void 0!==t.wireframeLinejoin&&t.wireframeLinejoin!==yC.MaterialProperties.wireframeLinejoin&&(n.wireframeLinejoin=t.wireframeLinejoin),void 0!==t.rotation&&(n.rotation=t.rotation),void 0!==t.linewidth&&t.linewidth!==MC.MaterialProperties.linewidth&&(n.linewidth=t.linewidth),void 0!==t.worldUnits&&t.worldUnits!==MC.MaterialProperties.worldUnits&&(n.worldUnits=t.worldUnits),void 0!==t.dashed&&t.dashed!==MC.MaterialProperties.dashed&&(n.dashed=t.dashed),void 0!==t.dashSize&&t.dashSize!==MC.MaterialProperties.dashSize&&(n.dashSize=t.dashSize),void 0!==t.dashScale&&t.dashScale!==MC.MaterialProperties.dashScale&&(n.dashScale=t.dashScale),void 0!==t.dashOffset&&t.dashOffset!==MC.MaterialProperties.dashOffset&&(n.dashOffset=t.dashOffset),void 0!==t.gapSize&&t.gapSize!==MC.MaterialProperties.gapSize&&(n.gapSize=t.gapSize),void 0!==t.polygonOffset&&t.polygonOffset!==Ow.polygonOffset&&(n.polygonOffset=t.polygonOffset),void 0!==t.polygonOffsetFactor&&t.polygonOffsetFactor!==Ow.polygonOffsetFactor&&(n.polygonOffsetFactor=t.polygonOffsetFactor),void 0!==t.polygonOffsetUnits&&t.polygonOffsetUnits!==Ow.polygonOffsetUnits&&(n.polygonOffsetUnits=t.polygonOffsetUnits),void 0!==t.dithering&&t.dithering!==Ow.dithering&&(n.dithering=t.dithering),void 0!==t.alphaToCoverage&&t.alphaToCoverage!==Ow.alphaToCoverage&&(n.alphaToCoverage=t.alphaToCoverage),void 0!==t.premultipliedAlpha&&t.premultipliedAlpha!==Ow.premultipliedAlpha&&(n.premultipliedAlpha=t.premultipliedAlpha),void 0!==t.toneMapped&&t.toneMapped!==Ow.toneMapped&&(n.toneMapped=t.toneMapped),void 0!==t.normalScale&&t.normalScale.isVector2&&(t.normalScale.x!==yC.MaterialProperties.normalScale.x||t.normalScale.y!==yC.MaterialProperties.normalScale.y)&&(n.normalScale=[t.normalScale.x,t.normalScale.y]);const r=this.materialExternalResources[t.uuid];r&&Object.entries(r).forEach(([t,i])=>{if(t.startsWith("_"))return;let r=!1;i?.userData&&void 0===i.userData.embedUrlImagePreviews&&(i.userData.embedUrlImagePreviews=e.options.exporterOptions?.embedUrlImagePreviews,r=!0),n[t]=f_.Serialize(i,this.serializedMeta),i?.userData&&r&&delete i.userData.embedUrlImagePreviews}),Object.keys(n).length>0&&(i.extensions[$M.WebGiMaterialExtrasExtension]=n,e.extensionsUsed[$M.WebGiMaterialExtrasExtension]=!0)},materialExternalResources:{},serializedMeta:{images:{},textures:{}},beforeParse(t){if(this.materialExternalResources={},!e.options.externalImagesInExtras)return;const i=[];(Array.isArray(t)?t:[t]).forEach(e=>{e?.traverse(e=>{e&&e.material?.isMaterial&&i.push(e.material)})}),i.forEach(e=>{e&&(this.materialExternalResources[e.uuid]||(this.materialExternalResources[e.uuid]={}),this.materialExternalResources[e.uuid].__materialRef=e,Object.entries(e).forEach(([t,i])=>{t.startsWith("_")||i&&i.isTexture&&i.userData.rootPath&&Eg(i.userData.rootPath)&&(e[t]=null,this.materialExternalResources[e.uuid][t]=i)}))})},afterParse(t){const i=Object.values(this.materialExternalResources);if(i.length<1)return;i.forEach(e=>{const t=e.__materialRef;t&&(Object.entries(e).forEach(([e,i])=>{e.startsWith("_")||i&&(t[e]=i)}),delete this.materialExternalResources[t.uuid])});const n=e.json.scenes[e.json.scene||0];n.extensions||(n.extensions={}),n.extensions[$M.WebGiMaterialExtrasExtension]={resources:this.serializedMeta},e.extensionsUsed[$M.WebGiMaterialExtrasExtension]=!0}}),$M.Textures=void 0;let eE=$M;const tE=class{};tE.WebGiMaterialsAlphaMapExtension="WEBGI_materials_alphamap",tE.Import=e=>new nE(e),tE.Export=e=>new rE(e),tE.Textures={alphaTexture:"G"};let iE=tE;class nE{constructor(e){this.parser=e,this.name=iE.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 r=[],s=n.extensions[this.name];return void 0!==s.alphaTexture&&r.push(i.assignTexture(t,"alphaMap",s.alphaTexture)),Promise.all(r)}}class rE{constructor(e){this.writer=e,this.name=iE.WebGiMaterialsAlphaMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||!e.alphaMap)return;const i=this.writer,n=i.extensionsUsed,r={};if(e.alphaMap&&i.checkEmptyMap(e.alphaMap)){const t={index:i.processTexture(e.alphaMap)};i.applyTextureTransform(t,e.alphaMap),r.alphaTexture=t}Object.keys(r)&&(t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0)}}const sE=class{};sE.WebGiMaterialsBumpMapExtension="WEBGI_materials_bumpmap",sE.Import=e=>new oE(e),sE.Export=e=>new lE(e),sE.Textures={bumpTexture:"R"};let aE=sE;class oE{constructor(e){this.parser=e,this.name=aE.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 r=[],s=n.extensions[this.name];return void 0!==s.bumpScale&&(t.bumpScale=s.bumpScale),void 0!==s.bumpTexture&&r.push(i.assignTexture(t,"bumpMap",s.bumpTexture)),Promise.all(r)}}class lE{constructor(e){this.writer=e,this.name=aE.WebGiMaterialsBumpMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||0===e.bumpScale)return;const i=this.writer,n=i.extensionsUsed,r={};if(e.bumpScale!==yC.MaterialProperties.bumpScale&&(r.bumpScale=e.bumpScale),e.bumpMap&&i.checkEmptyMap(e.bumpMap)){const t={index:i.processTexture(e.bumpMap)};i.applyTextureTransform(t,e.bumpMap),r.bumpTexture=t}Object.keys(r)&&(t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0)}}const cE=class{};cE.WebGiMaterialsDisplacementMapExtension="WEBGI_materials_displacementmap",cE.Import=e=>new dE(e),cE.Export=e=>new uE(e),cE.Textures={displacementTexture:"R"};let hE=cE;class dE{constructor(e){this.parser=e,this.name=hE.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 r=[],s=n.extensions[this.name];return void 0!==s.displacementScale&&(t.displacementScale=s.displacementScale),void 0!==s.displacementBias&&(t.displacementBias=s.displacementBias),void 0!==s.displacementTexture&&r.push(i.assignTexture(t,"displacementMap",s.displacementTexture)),Promise.all(r)}}class uE{constructor(e){this.writer=e,this.name=hE.WebGiMaterialsDisplacementMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||0===e.displacementScale)return;const i=this.writer,n=i.extensionsUsed,r={};if(e.displacementScale!==yC.MaterialProperties.displacementScale&&(r.displacementScale=e.displacementScale),e.displacementBias!==yC.MaterialProperties.displacementBias&&(r.displacementBias=e.displacementBias),e.displacementMap&&i.checkEmptyMap(e.displacementMap)){const t={index:i.processTexture(e.displacementMap)};i.applyTextureTransform(t,e.displacementMap),r.displacementTexture=t}Object.keys(r)&&(t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0)}}const pE=class{};pE.WebGiMaterialsLightMapExtension="WEBGI_materials_lightmap",pE.Import=e=>new gE(e),pE.Export=e=>new fE(e),pE.Textures={lightMapTexture:"RGB"};let mE=pE;class gE{constructor(e){this.parser=e,this.name=mE.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 r=[],s=n.extensions[this.name];return void 0!==s.lightMapIntensity&&(t.lightMapIntensity=s.lightMapIntensity),void 0!==s.lightMapTexture&&r.push(i.assignTexture(t,"lightMap",s.lightMapTexture)),Promise.all(r)}}class fE{constructor(e){this.writer=e,this.name=mE.WebGiMaterialsLightMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||0===e.lightMapIntensity)return;const i=this.writer,n=i.extensionsUsed,r={};if(e.lightMapIntensity!==yC.MaterialProperties.lightMapIntensity&&(r.lightMapIntensity=e.lightMapIntensity),e.lightMap&&i.checkEmptyMap(e.lightMap)){const t={index:i.processTexture(e.lightMap)};i.applyTextureTransform(t,e.lightMap),r.lightMapTexture=t}Object.keys(r)&&(t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0)}}const AE=class{};AE.WebGiObject3DExtrasExtension="WEBGI_object3d_extras",AE.Import=e=>({name:"__"+AE.WebGiObject3DExtrasExtension,afterRoot:async e=>{(e.scenes||(e.scene?[e.scene]:[])).forEach(e=>{e.traverse(e=>{if(!e||!e.isObject3D)return;const t=e.userData?.gltfExtensions?.[AE.WebGiObject3DExtrasExtension];t?(e.castShadow=t.castShadow??!1,e.receiveShadow=t.receiveShadow??!1,void 0!==t.visible&&(e.visible=t.visible),void 0!==t.frustumCulled&&(e.frustumCulled=t.frustumCulled),void 0!==t.renderOrder&&(e.renderOrder=t.renderOrder),void 0!==t.layers&&(e.layers.mask=t.layers),e.userData.__keepShadowDef=!0,delete e.userData.gltfExtensions[AE.WebGiObject3DExtrasExtension]):e.isLight&&!e.isAmbientLight&&(e.castShadow=!0)})})}}),AE.Export=e=>({writeNode:(t,i)=>{if(!t?.isObject3D)return;i.extensions||(i.extensions={});const n={};void 0!==t.castShadow&&t.castShadow&&(n.castShadow=t.castShadow),void 0!==t.receiveShadow&&t.receiveShadow&&(n.receiveShadow=t.receiveShadow),!1===t.visible&&(n.visible=!1),!1===t.frustumCulled&&(n.frustumCulled=!1),0!==t.renderOrder&&(n.renderOrder=t.renderOrder),1!==t.layers.mask&&(n.layers=t.layers.mask),!1===t.matrixAutoUpdate&&(n.matrixAutoUpdate=!1),Object.keys(n).length>0&&(i.extensions[AE.WebGiObject3DExtrasExtension]=n,e.extensionsUsed[AE.WebGiObject3DExtrasExtension]=!0)}}),AE.Textures=void 0;let yE=AE;class vE extends lu{constructor(e){super(e),this.type=De}async loadAsync(e,t){const i=await this.parseAsync(e,t,!1),n=new ec(i.data,i.width,i.height,Ue,this.type);return n.needsUpdate=!0,n.flipY=!0,n.colorSpace=Ot,n.minFilter=be,n.magFilter=be,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 i=await super.loadAsync(e,t);e=URL.createObjectURL(i),n=!0}const r=await $m(e);n&&URL.revokeObjectURL(e);let s=Uint8Array;return this.type===De?s=Uint16Array:this.type===Pe&&(s=Float32Array),{data:_E(r.data,4,s,i),width:r.width,height:r.height}}setDataType(e){return this.type=e,this}}function _E(e,t=3,i=Uint16Array,n=!1){let r;const s=e.byteLength>>2,a=new i(s*t);for(let i=0;i<s;i++)r=Math.pow(2,e[4*i+3]-136),n?(a[i*t]=Math.min(e[4*i]*r,65504),a[i*t+1]=Math.min(e[4*i+1]*r,65504),a[i*t+2]=Math.min(e[4*i+2]*r,65504)):(a[i*t]=wr.toHalfFloat(Math.min(e[4*i]*r,65504)),a[i*t+1]=wr.toHalfFloat(Math.min(e[4*i+1]*r,65504)),a[i*t+2]=wr.toHalfFloat(Math.min(e[4*i+2]*r,65504))),4===t&&(a[i*t+3]=wr.toHalfFloat(1));return a}const bE=class e{static async ImportViewerConfig(e,t,i,n){if(!n){const r=e.json.scenes||[];if(1!==r.length){for(const n of r){const s=r.indexOf(n);await this.ImportViewerConfig(e,t,s>=0?[i[s]]:i,n)}return{}}n=r[0]}const r=i.length>0?i[0]:void 0,s=n.extensions?.[this.ViewerConfigGLTFExtension];if(!s)return{};const a={type:"ThreeViewer",version:"0",plugins:[],assetType:"config",...s};return a.resources&&(a.resources=await this.ImportResources(a.resources,e,t)),r&&(r.importedViewerConfig=a),a}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[i,r]of[...Object.entries(e.textures)]){if(r.uuid||!i)continue;delete e.textures[i];const s=t.json.textures.findIndex(e=>e.extras?.uuid===i||t.json.samplers?.[e.sampler]?.extras?.uuid===i||t.json.images?.[e.source]?.extras?.t_uuid===i);s>=0&&(n.textures[i]=await t.getDependency("texture",s))}if(e.materials&&t.json.materials)for(const[r,s]of[...Object.entries(e.materials)]){if(s.uuid||!r)continue;delete e.materials[r];const a=t.json.materials.findIndex(e=>e.extras?.uuid===r);if(a>=0){const e=await t.getDependency("material",a);n.materials[r]=i.assetManager.materials.convertToIMaterial(e)}}return n}static async _parseArrayBuffers(e,t){const i=[];Object.values(e).forEach(e=>{Object.values(e).forEach(e=>{e.url&&("Uint16Array"===e.url.type&&e.url.data&&i.push(e.url),"Uint8Array"===e.url.type&&e.url.data&&i.push(e.url))})});for(const e of i){const i=e.data.image,n=t.json.images[i],r=await t.getDependency("bufferView",n.bufferView);if(n.mimeType.startsWith("image/")&&"Uint16Array"===e.type&&"rgbe"===e.encoding){const t=new Blob([r]);let i=URL.createObjectURL(t);const n=e.encodingVersion||1;n<2&&(i="data:image/png;base64,"+btoa(await t.text())),e.data=(await(new vE).parseAsync(i,void 0,n<3)).data,URL.revokeObjectURL(i),delete e.encoding,delete e.encodingVersion}else e.data=r}}static ExportViewerConfig(t,i){const n=Object.entries(i.serializationMeta).reduce((e,t)=>e+(t[0].startsWith("_")?0:Object.keys(t[1]).length),0)?i.serializationMeta:void 0,r=t.toJSON(!0,void 0,n),s=i.json.scenes[i.json.scene||0];s.extensions||(s.extensions={}),i.extensionsUsed[this.ViewerConfigGLTFExtension]=!0,s.extensions[this.ViewerConfigGLTFExtension]=r;const a=r.resources;if(a&&(e.BundleExtraResources(i.json,a),e.BundleArrayBuffers(a,i),n))return delete r.resources,a}static BundleArrayBuffers(e,t){const i=[];Object.entries(e).forEach(([e,t])=>{e.startsWith("_")||t&&Object.values(t).forEach(e=>{e.url&&("Uint16Array"===e.url.type&&e.url.data&&(e.url.data instanceof Uint16Array||(e.url.data=new Uint16Array(e.url.data)),i.push(e.url)),"Uint8Array"===e.url.type&&e.url.data&&(e.url.data instanceof Uint8Array||(e.url.data=new Uint8Array(e.url.data)),i.push(e.url)))})});for(const e of i){let i="application/octet-stream";if(e.mimeType&&(i=e.mimeType),t.options.exporterOptions.encodeUint16Rgbe&&"Uint16Array"===e.type&&e.width>0&&e.height>0){const t=Fy(e.data,4),n=new ImageData(t,e.width,e.height),r=Li.getDataURL(n,!0).split(",")[1];i="image/png",e.data=Uint8Array.from(atob(r),e=>e.charCodeAt(0)),e.encoding="rgbe",e.encodingVersion=3}t.json.images||(t.json.images=[]);const n={mimeType:i},r=t.json.images.push(n)-1,s=e.data;n.bufferView=t.processBufferViewImageBuffer(s),e.data={image:r}}}static BundleExtraResources(e,t){const{textures:i,materials:n}=t;e.textures&&e.samplers&&e.images&&i&&[...Object.entries(i)].forEach(([n,r])=>{e.textures.find(t=>t.extras?.uuid===n||e.samplers[t.sampler]?.extras?.uuid===n||e.images[t.source]?.extras?.t_uuid===n)&&(r.image&&t.images&&t.images[r.image]&&delete t.images[r.image],i[n]={})}),e.materials&&n&&[...Object.entries(n)].forEach(([t,i])=>{e.materials.find(e=>e.extras?.uuid===t)&&(n[t]={})})}};bE.ViewerConfigGLTFExtension="WEBGI_viewer";let xE=bE;class wE extends su{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new IE(e)}),this.register(function(e){return new PE(e)}),this.register(function(e){return new NE(e)}),this.register(function(e){return new jE(e)}),this.register(function(e){return new zE(e)}),this.register(function(e){return new RE(e)}),this.register(function(e){return new BE(e)}),this.register(function(e){return new LE(e)}),this.register(function(e){return new OE(e)}),this.register(function(e){return new TE(e)}),this.register(function(e){return new UE(e)}),this.register(function(e){return new DE(e)}),this.register(function(e){return new kE(e)}),this.register(function(e){return new FE(e)}),this.register(function(e){return new ME(e)}),this.register(function(e){return new GE(e)}),this.register(function(e){return new QE(e)})}load(e,t,i,n){const r=this;let s;if(""!==this.resourcePath)s=this.resourcePath;else if(""!==this.path){const t=Bu.extractUrlBase(e);s=Bu.resolveURL(t,this.path)}else s=Bu.extractUrlBase(e);this.manager.itemStart(e);const a=function(t){n?n(t):console.error(t),r.manager.itemError(e),r.manager.itemEnd(e)},o=new lu(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(i){try{r.parse(i,s,function(i){t(i),r.manager.itemEnd(e)},a,e)}catch(e){a(e)}},i,a)}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-1===this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.push(e),this}unregister(e){return-1!==this.pluginCallbacks.indexOf(e)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,n,r){let s;const a={},o={},l=new TextDecoder;if("string"==typeof e)s=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===VE){try{a[SE.KHR_BINARY_GLTF]=new qE(e)}catch(e){return void(n&&n(e))}s=JSON.parse(a[SE.KHR_BINARY_GLTF].content)}else s=JSON.parse(l.decode(e));else s=e;if(void 0===s.asset||s.asset.version[0]<2)return void(n&&n(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")));const c=new vT(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let e=0;e<this.pluginCallbacks.length;e++){const t=this.pluginCallbacks[e](c);t.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),o[t.name]=t,a[t.name]=!0}if(s.extensionsUsed)for(let e=0;e<s.extensionsUsed.length;++e){const t=s.extensionsUsed[e],i=s.extensionsRequired||[];switch(t){case SE.KHR_MATERIALS_UNLIT:a[t]=new EE;break;case SE.KHR_DRACO_MESH_COMPRESSION:a[t]=new XE(s,this.dracoLoader);break;case SE.KHR_TEXTURE_TRANSFORM:a[t]=new YE;break;case SE.KHR_MESH_QUANTIZATION:a[t]=new KE;break;default:i.indexOf(t)>=0&&void 0===o[t]&&console.warn('THREE.GLTFLoader: Unknown extension "'+t+'".')}}c.setExtensions(a),c.setPlugins(o),c.parse(i,n)}parseAsync(e,t){const i=this;return new Promise(function(n,r){i.parse(e,t,n,r)})}}function CE(){let e={};return{get:function(t){return e[t]},add:function(t,i){e[t]=i},remove:function(t){delete e[t]},removeAll:function(){e={}}}}wE.ObjectConstructors={DirectionalLight:Eu,PointLight:Su,SpotLight:_u,MeshStandardMaterial:Td,MeshBasicMaterial:vr,MeshPhysicalMaterial:Id,LineBasicMaterial:Dc,PointsMaterial:Hc,PerspectiveCamera:ps,OrthographicCamera:zs};const SE={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 ME{constructor(e){this.parser=e,this.name=SE.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 n=t[i];n.extensions&&n.extensions[this.name]&&void 0!==n.extensions[this.name].light&&e._addNodeRef(this.cache,n.extensions[this.name].light)}}_loadLight(e){const t=this.parser,i="light:"+e;let n=t.cache.get(i);if(n)return n;const r=t.json,s=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let a;const o=new mr(16777215);void 0!==s.color&&o.setRGB(s.color[0],s.color[1],s.color[2],Ut);const l=void 0!==s.range?s.range:0;switch(s.type){case"directional":a=new wE.ObjectConstructors.DirectionalLight(o),a.target.position.set(0,0,-1),a.add(a.target);break;case"point":a=new wE.ObjectConstructors.PointLight(o),a.distance=l;break;case"spot":a=new wE.ObjectConstructors.SpotLight(o),a.distance=l,s.spot=s.spot||{},s.spot.innerConeAngle=void 0!==s.spot.innerConeAngle?s.spot.innerConeAngle:0,s.spot.outerConeAngle=void 0!==s.spot.outerConeAngle?s.spot.outerConeAngle:Math.PI/4,a.angle=s.spot.outerConeAngle,a.penumbra=1-s.spot.innerConeAngle/s.spot.outerConeAngle,a.target.position.set(0,0,-1),a.add(a.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+s.type)}return a.position.set(0,0,0),a.decay=2,pT(a,s),void 0!==s.intensity&&(a.intensity=s.intensity),a.name=t.createUniqueName(s.name||"light_"+e),n=Promise.resolve(a),t.cache.add(i,n),n}getDependency(e,t){if("light"===e)return this._loadLight(t)}createNodeAttachment(e){const t=this,i=this.parser,n=i.json.nodes[e],r=(n.extensions&&n.extensions[this.name]||{}).light;return void 0===r?null:this._loadLight(r).then(function(e){return i._getNodeRef(t.cache,r,e)})}}class EE{constructor(){this.name=SE.KHR_MATERIALS_UNLIT}getMaterialType(){return wE.ObjectConstructors.MeshBasicMaterial}extendParams(e,t,i){const n=[];e.color=new mr(1,1,1),e.opacity=1;const r=t.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const t=r.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],Ut),e.opacity=t[3]}void 0!==r.baseColorTexture&&n.push(i.assignTexture(e,"map",r.baseColorTexture,Ot))}return Promise.all(n)}}class TE{constructor(e){this.parser=e,this.name=SE.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const n=i.extensions[this.name].emissiveStrength;return void 0!==n&&(t.emissiveIntensity=n),Promise.resolve()}}class IE{constructor(e){this.parser=e,this.name=SE.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?wE.ObjectConstructors.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[],s=n.extensions[this.name];if(void 0!==s.clearcoatFactor&&(t.clearcoat=s.clearcoatFactor),void 0!==s.clearcoatTexture&&r.push(i.assignTexture(t,"clearcoatMap",s.clearcoatTexture)),void 0!==s.clearcoatRoughnessFactor&&(t.clearcoatRoughness=s.clearcoatRoughnessFactor),void 0!==s.clearcoatRoughnessTexture&&r.push(i.assignTexture(t,"clearcoatRoughnessMap",s.clearcoatRoughnessTexture)),void 0!==s.clearcoatNormalTexture&&(r.push(i.assignTexture(t,"clearcoatNormalMap",s.clearcoatNormalTexture)),void 0!==s.clearcoatNormalTexture.scale)){const e=s.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new fi(e,e)}return Promise.all(r)}}class PE{constructor(e){this.parser=e,this.name=SE.KHR_MATERIALS_DISPERSION}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?Id:null}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const n=i.extensions[this.name];return t.dispersion=void 0!==n.dispersion?n.dispersion:0,Promise.resolve()}}class DE{constructor(e){this.parser=e,this.name=SE.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?wE.ObjectConstructors.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[],s=n.extensions[this.name];return void 0!==s.iridescenceFactor&&(t.iridescence=s.iridescenceFactor),void 0!==s.iridescenceTexture&&r.push(i.assignTexture(t,"iridescenceMap",s.iridescenceTexture)),void 0!==s.iridescenceIor&&(t.iridescenceIOR=s.iridescenceIor),void 0===t.iridescenceThicknessRange&&(t.iridescenceThicknessRange=[100,400]),void 0!==s.iridescenceThicknessMinimum&&(t.iridescenceThicknessRange[0]=s.iridescenceThicknessMinimum),void 0!==s.iridescenceThicknessMaximum&&(t.iridescenceThicknessRange[1]=s.iridescenceThicknessMaximum),void 0!==s.iridescenceThicknessTexture&&r.push(i.assignTexture(t,"iridescenceThicknessMap",s.iridescenceThicknessTexture)),Promise.all(r)}}class RE{constructor(e){this.parser=e,this.name=SE.KHR_MATERIALS_SHEEN}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?wE.ObjectConstructors.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[];t.sheenColor=new mr(0,0,0),t.sheenRoughness=0,t.sheen=1;const s=n.extensions[this.name];if(void 0!==s.sheenColorFactor){const e=s.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],Ut)}return void 0!==s.sheenRoughnessFactor&&(t.sheenRoughness=s.sheenRoughnessFactor),void 0!==s.sheenColorTexture&&r.push(i.assignTexture(t,"sheenColorMap",s.sheenColorTexture,Ot)),void 0!==s.sheenRoughnessTexture&&r.push(i.assignTexture(t,"sheenRoughnessMap",s.sheenRoughnessTexture)),n.extras&&void 0!==n.extras.sheenFactor&&(t.sheen=n.extras.sheenFactor,delete n.extras.sheenFactor),Promise.all(r)}}class BE{constructor(e){this.parser=e,this.name=SE.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?wE.ObjectConstructors.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[],s=n.extensions[this.name];return void 0!==s.transmissionFactor&&(t.transmission=s.transmissionFactor),void 0!==s.transmissionTexture&&r.push(i.assignTexture(t,"transmissionMap",s.transmissionTexture)),Promise.all(r)}}class LE{constructor(e){this.parser=e,this.name=SE.KHR_MATERIALS_VOLUME}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?wE.ObjectConstructors.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[],s=n.extensions[this.name];t.thickness=void 0!==s.thicknessFactor?s.thicknessFactor:0,void 0!==s.thicknessTexture&&r.push(i.assignTexture(t,"thicknessMap",s.thicknessTexture)),t.attenuationDistance=s.attenuationDistance||1/0;const a=s.attenuationColor||[1,1,1];return t.attenuationColor=(new mr).setRGB(a[0],a[1],a[2],Ut),Promise.all(r)}}class OE{constructor(e){this.parser=e,this.name=SE.KHR_MATERIALS_IOR}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?wE.ObjectConstructors.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const n=i.extensions[this.name];return t.ior=void 0!==n.ior?n.ior:1.5,Promise.resolve()}}class UE{constructor(e){this.parser=e,this.name=SE.KHR_MATERIALS_SPECULAR}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?wE.ObjectConstructors.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[],s=n.extensions[this.name];t.specularIntensity=void 0!==s.specularFactor?s.specularFactor:1,void 0!==s.specularTexture&&r.push(i.assignTexture(t,"specularIntensityMap",s.specularTexture));const a=s.specularColorFactor||[1,1,1];return t.specularColor=(new mr).setRGB(a[0],a[1],a[2],Ut),void 0!==s.specularColorTexture&&r.push(i.assignTexture(t,"specularColorMap",s.specularColorTexture,Ot)),Promise.all(r)}}class FE{constructor(e){this.parser=e,this.name=SE.EXT_MATERIALS_BUMP}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?wE.ObjectConstructors.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[],s=n.extensions[this.name];return t.bumpScale=void 0!==s.bumpFactor?s.bumpFactor:1,void 0!==s.bumpTexture&&r.push(i.assignTexture(t,"bumpMap",s.bumpTexture)),Promise.all(r)}}class kE{constructor(e){this.parser=e,this.name=SE.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?wE.ObjectConstructors.MeshPhysicalMaterial:null}extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[],s=n.extensions[this.name];return void 0!==s.anisotropyStrength&&(t.anisotropy=s.anisotropyStrength),void 0!==s.anisotropyRotation&&(t.anisotropyRotation=s.anisotropyRotation),void 0!==s.anisotropyTexture&&r.push(i.assignTexture(t,"anisotropyMap",s.anisotropyTexture)),Promise.all(r)}}class NE{constructor(e){this.parser=e,this.name=SE.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 r=n.extensions[this.name],s=t.options.ktx2Loader;if(!s){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,r.source,s)}}class jE{constructor(e){this.parser=e,this.name=SE.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,i=this.parser,n=i.json,r=n.textures[e];if(!r.extensions||!r.extensions[t])return null;const s=r.extensions[t],a=n.images[s.source];let o=i.textureLoader;if(a.uri){const e=i.options.manager.getHandler(a.uri);null!==e&&(o=e)}return this.detectSupport().then(function(r){if(r)return i.loadTextureImage(e,s.source,o);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(1===t.height)}})),this.isSupported}}class zE{constructor(e){this.parser=e,this.name=SE.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,i=this.parser,n=i.json,r=n.textures[e];if(!r.extensions||!r.extensions[t])return null;const s=r.extensions[t],a=n.images[s.source];let o=i.textureLoader;if(a.uri){const e=i.options.manager.getHandler(a.uri);null!==e&&(o=e)}return this.detectSupport().then(function(r){if(r)return i.loadTextureImage(e,s.source,o);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(1===t.height)}})),this.isSupported}}class GE{constructor(e){this.name=SE.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 e=i.extensions[this.name],n=this.parser.getDependency("buffer",e.buffer),r=this.parser.options.meshoptDecoder;if(!r||!r.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 n.then(function(t){const i=e.byteOffset||0,n=e.byteLength||0,s=e.count,a=e.byteStride,o=new Uint8Array(t,i,n);return r.decodeGltfBufferAsync?r.decodeGltfBufferAsync(s,a,o,e.mode,e.filter).then(function(e){return e.buffer}):r.ready.then(function(){const t=new ArrayBuffer(s*a);return r.decodeGltfBuffer(new Uint8Array(t),s,a,o,e.mode,e.filter),t})})}return null}}class QE{constructor(e){this.name=SE.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]||void 0===i.mesh)return null;const n=t.meshes[i.mesh];for(const e of n.primitives)if(e.mode!==eT.TRIANGLES&&e.mode!==eT.TRIANGLE_STRIP&&e.mode!==eT.TRIANGLE_FAN&&void 0!==e.mode)return null;const r=i.extensions[this.name].attributes,s=[],a={};for(const e in r)s.push(this.parser.getDependency("accessor",r[e]).then(t=>(a[e]=t,a[e])));return s.length<1?null:(s.push(this.parser.createNodeMesh(e)),Promise.all(s).then(e=>{const t=e.pop(),i=t.isGroup?t.children:[t],n=e[0].count,r=[];for(const e of i){const t=new Sn,i=new Xi,s=new qi,o=new Xi(1,1,1),l=new uc(e.geometry,e.material,n);for(let e=0;e<n;e++)a.TRANSLATION&&i.fromBufferAttribute(a.TRANSLATION,e),a.ROTATION&&s.fromBufferAttribute(a.ROTATION,e),a.SCALE&&o.fromBufferAttribute(a.SCALE,e),l.setMatrixAt(e,t.compose(i,s,o));l.sourceTrs=a;for(const t in a)if("_COLOR_0"===t){const e=a[t];l.instanceColor=new rc(e.array,e.itemSize,e.normalized)}else"TRANSLATION"!==t&&"ROTATION"!==t&&"SCALE"!==t&&e.geometry.setAttribute(t,a[t]);Zn.prototype.copy.call(l,e),this.parser.assignFinalMaterial(l),r.push(l)}return t.isGroup?(t.clear(),t.add(...r),t):r[0]}))}}const VE="glTF",HE=1313821514,WE=5130562;class qE{constructor(e){this.name=SE.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,12),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!==VE)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-12,r=new DataView(e,12);let s=0;for(;s<n;){const t=r.getUint32(s,!0);s+=4;const n=r.getUint32(s,!0);if(s+=4,n===HE){const n=new Uint8Array(e,12+s,t);this.content=i.decode(n)}else if(n===WE){const i=12+s;this.body=e.slice(i,i+t)}s+=t}if(null===this.content)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class XE{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=SE.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const i=this.json,n=this.dracoLoader,r=e.extensions[this.name].bufferView,s=e.extensions[this.name].attributes,a={},o={},l={};for(const e in s){const t=sT[e]||e.toLowerCase();a[t]=s[e]}for(const t in e.attributes){const n=sT[t]||t.toLowerCase();if(void 0!==s[t]){const r=i.accessors[e.attributes[t]],s=tT[r.componentType];l[n]=s.name,o[n]=!0===r.normalized}}return t.getDependency("bufferView",r).then(function(e){return new Promise(function(t,i){n.decodeDracoFile(e,function(e){for(const t in e.attributes){const i=e.attributes[t],n=o[t];void 0!==n&&(i.normalized=n)}t(e)},a,l,Ut,i)})})}}class YE{constructor(){this.name=SE.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(void 0===t.texCoord||t.texCoord===e.channel)&&void 0===t.offset&&void 0===t.rotation&&void 0===t.scale||(e.__hasGLTFUuid||(e=e.clone()),void 0!==t.texCoord&&(e.channel=t.texCoord),void 0!==t.offset&&e.offset.fromArray(t.offset),void 0!==t.rotation&&(e.rotation=t.rotation),void 0!==t.scale&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class KE{constructor(){this.name=SE.KHR_MESH_QUANTIZATION}}class JE extends Gd{constructor(e,t,i,n){super(e,t,i,n)}copySampleValue_(e){const t=this.resultBuffer,i=this.sampleValues,n=this.valueSize,r=e*n*3+n;for(let e=0;e!==n;e++)t[e]=i[r+e];return t}interpolate_(e,t,i,n){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=2*a,l=3*a,c=n-t,h=(i-t)/c,d=h*h,u=d*h,p=e*l,m=p-l,g=-2*u+3*d,f=u-d,A=1-g,y=f-d+h;for(let e=0;e!==a;e++){const t=s[m+e+a],i=s[m+e+o]*c,n=s[p+e+a],l=s[p+e]*c;r[e]=A*t+y*i+g*n+f*l}return r}}const ZE=new qi;class $E extends JE{interpolate_(e,t,i,n){const r=super.interpolate_(e,t,i,n);return ZE.fromArray(r).normalize().toArray(r),r}}const eT={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},tT={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},iT={9728:ye,9729:be,9984:ve,9985:xe,9986:_e,9987:we},nT={33071:fe,33648:Ae,10497:ge},rT={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},sT={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"},aT={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},oT={CUBICSPLINE:void 0,LINEAR:Ct,STEP:wt},lT="OPAQUE",cT="MASK",hT="BLEND";function dT(e){return void 0===e.DefaultMaterial&&(e.DefaultMaterial=new wE.ObjectConstructors.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:_})),e.DefaultMaterial}function uT(e,t,i){for(const n in i.extensions)void 0===e[n]&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[n]=i.extensions[n])}function pT(e,t){void 0!==t.extras&&("object"==typeof t.extras?Object.assign(e.userData,t.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+t.extras))}function mT(e,t){if(e.updateMorphTargets(),void 0!==t.weights)for(let i=0,n=t.weights.length;i<n;i++)e.morphTargetInfluences[i]=t.weights[i];if(t.extras&&Array.isArray(t.extras.targetNames)){const i=t.extras.targetNames;if(e.morphTargetInfluences.length===i.length){e.morphTargetDictionary={};for(let t=0,n=i.length;t<n;t++)e.morphTargetDictionary[i[t]]=t}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function gT(e){let t;const i=e.extensions&&e.extensions[SE.KHR_DRACO_MESH_COMPRESSION];if(t=i?"draco:"+i.bufferView+":"+i.indices+":"+fT(i.attributes):e.indices+":"+fT(e.attributes)+":"+e.mode,void 0!==e.targets)for(let i=0,n=e.targets.length;i<n;i++)t+=":"+fT(e.targets[i]);return t}function fT(e){let t="";const i=Object.keys(e).sort();for(let n=0,r=i.length;n<r;n++)t+=i[n]+":"+e[i[n]]+";";return t}function AT(e){switch(e){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.")}}const yT=new Sn;class vT{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new CE,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,r=!1,s=-1;if(typeof navigator<"u"){const e=navigator.userAgent;i=!0===/^((?!chrome|android).)*safari/i.test(e);const t=e.match(/Version\/(\d+)/);n=i&&t?parseInt(t[1],10):-1,r=e.indexOf("Firefox")>-1,s=r?e.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&n<17||r&&s<98?this.textureLoader=new uu(this.options.manager):this.textureLoader=new ju(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new lu(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),"use-credentials"===this.options.crossOrigin&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const i=this,n=this.json,r=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(e){return e._markDefs&&e._markDefs()}),Promise.all(this._invokeAll(function(e){return e.beforeRoot&&e.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(t){const s={scene:t[0][n.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:n.asset,parser:i,userData:{}};return uT(r,s,n),pT(s,n),Promise.all(i._invokeAll(function(e){return e.afterRoot&&e.afterRoot(s)})).then(function(){for(const e of s.scenes)e.updateMatrixWorld();e(s)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let i=0,n=t.length;i<n;i++){const n=t[i].joints;for(let t=0,i=n.length;t<i;t++)e[n[t]].isBone=!0}for(let t=0,n=e.length;t<n;t++){const n=e[t];void 0!==n.mesh&&(this._addNodeRef(this.meshCache,n.mesh),void 0!==n.skin&&(i[n.mesh].isSkinnedMesh=!0)),void 0!==n.camera&&this._addNodeRef(this.cameraCache,n.camera)}}_addNodeRef(e,t){void 0!==t&&(void 0===e.refs[t]&&(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(),r=(e,t)=>{const i=this.associations.get(e);null!=i&&this.associations.set(t,i);for(const[i,n]of e.children.entries())r(n,t.children[i])};return r(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 r=e(t[n]);r&&i.push(r)}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(e){return e.loadNode&&e.loadNode(t)});break;case"mesh":n=this._invokeOne(function(e){return e.loadMesh&&e.loadMesh(t)});break;case"accessor":n=this.loadAccessor(t);break;case"bufferView":n=this._invokeOne(function(e){return e.loadBufferView&&e.loadBufferView(t)});break;case"buffer":n=this.loadBuffer(t);break;case"material":n=this._invokeOne(function(e){return e.loadMaterial&&e.loadMaterial(t)});break;case"texture":n=this._invokeOne(function(e){return e.loadTexture&&e.loadTexture(t)});break;case"skin":n=this.loadSkin(t);break;case"animation":n=this._invokeOne(function(e){return e.loadAnimation&&e.loadAnimation(t)});break;case"camera":n=this.loadCamera(t);break;default:if(n=this._invokeOne(function(i){return i!=this&&i.getDependency&&i.getDependency(e,t)}),!n)throw new Error("Unknown type: "+e)}this.cache.add(i,n)}return n}getDependencies(e){let t=this.cache.get(e);if(!t){const i=this,n=this.json[e+("mesh"===e?"es":"s")]||[];t=Promise.all(n.map(function(t,n){return i.getDependency(e,n)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],i=this.fileLoader;if(t.type&&"arraybuffer"!==t.type)throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(void 0===t.uri&&0===e)return Promise.resolve(this.extensions[SE.KHR_BINARY_GLTF].body);const n=this.options;return new Promise(function(e,r){i.load(Bu.resolveURL(t.uri,n.path),e,void 0,function(){r(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(e){const i=t.byteLength||0,n=t.byteOffset||0;return e.slice(n,n+i)})}loadAccessor(e){const t=this,i=this.json,n=this.json.accessors[e];if(void 0===n.bufferView&&void 0===n.sparse){const e=rT[n.type],t=tT[n.componentType],i=!0===n.normalized,r=new t(n.count*e);return Promise.resolve(new Mr(r,e,i))}const r=[];return void 0!==n.bufferView?r.push(this.getDependency("bufferView",n.bufferView)):r.push(null),void 0!==n.sparse&&(r.push(this.getDependency("bufferView",n.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",n.sparse.values.bufferView))),Promise.all(r).then(function(e){const r=e[0],s=rT[n.type],a=tT[n.componentType],o=a.BYTES_PER_ELEMENT,l=o*s,c=n.byteOffset||0,h=void 0!==n.bufferView?i.bufferViews[n.bufferView].byteStride:void 0,d=!0===n.normalized;let u,p;if(h&&h!==l){const e=Math.floor(c/h),i="InterleavedBuffer:"+n.bufferView+":"+n.componentType+":"+e+":"+n.count;let l=t.cache.get(i);l||(u=new a(r,e*h,n.count*h/o),l=new bl(u,h/o),t.cache.add(i,l)),p=new wl(l,s,c%h/o,d)}else u=null===r?new a(n.count*s):new a(r,c,n.count*s),p=new Mr(u,s,d);if(void 0!==n.sparse){const t=rT.SCALAR,i=tT[n.sparse.indices.componentType],o=n.sparse.indices.byteOffset||0,l=n.sparse.values.byteOffset||0,c=new i(e[1],o,n.sparse.count*t),h=new a(e[2],l,n.sparse.count*s);null!==r&&(p=new Mr(p.array.slice(),p.itemSize,p.normalized));for(let e=0,t=c.length;e<t;e++){const t=c[e];if(p.setX(t,h[e*s]),s>=2&&p.setY(t,h[e*s+1]),s>=3&&p.setZ(t,h[e*s+2]),s>=4&&p.setW(t,h[e*s+3]),s>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}}return p})}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 n=t.textures[e].source;if(n<0||n>=t.images.length)return console.warn("THREE.GLTFLoader: Invalid source index:",n),null;const r=t.images[n];let s=this.textureLoader;if(r.uri){const e=i.manager.getHandler(r.uri);null!==e&&(s=e)}return this.loadTextureImage(e,n,s)}loadTextureImage(e,t,i){const n=this,r=this.json,s=r.textures[e],a=r.images[t],o=(a.uri||a.bufferView)+":"+s.sampler;if(this.textureCache[o])return this.textureCache[o];const l=this.loadImageSource(t,i).then(function(t){t.name=s.name||a.name||"",""===t.name&&"string"==typeof a.uri&&!1===a.uri.startsWith("data:image/")&&(t.name=a.uri);const i=(r.samplers||{})[s.sampler]||{};return t.magFilter=iT[i.magFilter]||be,t.minFilter=iT[i.minFilter]||we,t.wrapS=nT[i.wrapS]||ge,t.wrapT=nT[i.wrapT]||ge,i.extras&&(void 0!==i.extras.uuid&&(t.uuid=i.extras.uuid,t.__hasGLTFUuid=!0),void 0!==i.extras.colorSpace&&(t.colorSpace=i.extras.colorSpace,t.userData._forcedColorSpace=!0,delete i.extras.colorSpace)),n.associations.set(t,{textures:e}),t}).catch(function(){return null});return this.textureCache[o]=l,l}loadImageSource(e,t,i=!1,n=!1){const r=this,s=this.json,a=this.options;if(!n&&void 0!==this.sourceCache[e])return this.sourceCache[e].then(e=>e.clone());const o=s.images[e],l=self.URL||self.webkitURL;void 0===o.uri&&o.extras&&o.extras.uri&&(o.uri=o.extras.uri);let c=o.uri||"",h=!1,d=null;if(void 0===o.bufferView||i&&c){if(void 0===o.uri)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView")}else c=r.getDependency("bufferView",o.bufferView).then(function(e){h=!0;const t=new Blob([e],{type:o.mimeType});return c=l.createObjectURL(t),d=t,c});const u=Promise.resolve(c).then(function(e){return new Promise(function(i,n){let s=i;!0===t.isImageBitmapLoader&&(s=function(e){const t=new Ni(e);t.needsUpdate=!0,i(t)}),t.load(Bu.resolveURL(e,a.path),s,void 0,function(o){!0===t.isImageBitmapLoader?(t=new uu(r.options.manager),s=i,t.setCrossOrigin(r.options.crossOrigin),t.setRequestHeader(r.options.requestHeader),t.load(Bu.resolveURL(e,a.path),s,void 0,n)):n(o)})})}).then(function(n){if(!0===h&&l.revokeObjectURL(c),pT(n,o),n.userData.mimeType=o.mimeType||function(e){return e.search(/\.jpe?g($|\?)/i)>0||0===e.search(/^data\:image\/jpeg/)?"image/jpeg":e.search(/\.webp($|\?)/i)>0||0===e.search(/^data\:image\/webp/)?"image/webp":"image/png"}(o.uri),n.flipY=!1,o.extras){if(void 0!==o.extras.flipY){if(!0===t.isImageBitmapLoader&&void 0!==typeof createImageBitmap){let e=n;const t=o.extras.flipY&&!e.flipY;createImageBitmap(e.source.data,{imageOrientation:t?"flipY":"none"}).then(function(t){e._newTex&&(e=e._newTex),e.source.data.close&&e.source.data.close(),e.source.data=t,e.source.needsUpdate=!0,e.needsUpdate=!0})}n.flipY=o.extras.flipY,n.needsUpdate=!0,delete o.extras.flipY}void 0!==o.extras.uuid&&(n.source.uuid=o.extras.uuid),void 0!==o.extras.t_uuid&&(n.uuid=o.extras.t_uuid,n.__hasGLTFUuid=!0),void 0!==o.extras.t_colorSpace&&(n.colorSpace=o.extras.t_colorSpace,n.userData._forcedColorSpace=!0,delete o.extras.t_colorSpace)}return o.uri&&"string"==typeof o.uri&&!1===h&&(n.userData.rootPath=a.path&&a.path.startsWith("/")?o.uri:Bu.resolveURL(o.uri,a.path)),d&&(n.userData.__sourceBlob=d),!i&&o.uri&&o.uri!==c&&r.loadImageSource(e,t,!0,!0).then(function(e){n.source.data&&n.source.data.close&&n.source.data.close(),n.dispose(),n.source=e.source,n.source.needsUpdate=!0,n.needsUpdate=!0,n.uuid=e.uuid,e.__hasGLTFUuid&&(n.__hasGLTFUuid=!0),n.flipY=e.flipY,n.colorSpace=e.colorSpace,n.userData=e.userData,n.setDirty&&n.setDirty(),e._newTex=n}),n}).catch(function(e){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),e});return this.sourceCache[e]=u,u}assignTexture(e,t,i,n){const r=this;return this.getDependency("texture",i.index).then(function(s){if(!s)return null;if(void 0!==i.texCoord&&i.texCoord>0&&((s=s.clone()).channel=i.texCoord),r.extensions[SE.KHR_TEXTURE_TRANSFORM]){const e=void 0!==i.extensions?i.extensions[SE.KHR_TEXTURE_TRANSFORM]:void 0;if(e){const t=r.associations.get(s);s=r.extensions[SE.KHR_TEXTURE_TRANSFORM].extendTexture(s,e),r.associations.set(s,t)}}return void 0!==n&&!s.userData._forcedColorSpace&&(s.colorSpace=n),e[t]=s,s})}assignFinalMaterial(e){const t=e.geometry;let i=e.material;const n=void 0===t.attributes.tangent,r=void 0!==t.attributes.color,s=void 0===t.attributes.normal;if(e.isPoints){const e="PointsMaterial:"+i.uuid;let t=this.cache.get(e);t||(t=new wE.ObjectConstructors.PointsMaterial,Ar.prototype.copy.call(t,i),t.color.copy(i.color),t.map=i.map,t.sizeAttenuation=!1,this.cache.add(e,t)),i=t}else if(e.isLine){const e="LineBasicMaterial:"+i.uuid;let t=this.cache.get(e);t||(t=new wE.ObjectConstructors.LineBasicMaterial,Ar.prototype.copy.call(t,i),t.color.copy(i.color),t.map=i.map,this.cache.add(e,t)),i=t}const a=!(!i.userData||!i.userData.gltfExtensions)&&!!i.userData.gltfExtensions.WEBGI_material_extras;if((n||r||s)&&!a){let e="ClonedMaterial:"+i.uuid+":";n&&(e+="derivative-tangents:"),r&&(e+="vertex-colors:"),s&&(e+="flat-shading:");let t=this.cache.get(e);t||(t=i.clone(),r&&(t.vertexColors=!0),s&&(t.flatShading=!0),n&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(i))),i=t}e.material=i}getMaterialType(){return wE.ObjectConstructors.MeshStandardMaterial}loadMaterial(e){const t=this,i=this.json,n=this.extensions,r=i.materials[e];let s;const a={},o=[];if((r.extensions||{})[SE.KHR_MATERIALS_UNLIT]){const e=n[SE.KHR_MATERIALS_UNLIT];s=e.getMaterialType(),o.push(e.extendParams(a,r,t))}else{const i=r.pbrMetallicRoughness||{};if(a.color=new mr(1,1,1),a.opacity=1,Array.isArray(i.baseColorFactor)){const e=i.baseColorFactor;a.color.setRGB(e[0],e[1],e[2],Ut),a.opacity=e[3]}void 0!==i.baseColorTexture&&o.push(t.assignTexture(a,"map",i.baseColorTexture,Ot)),a.metalness=void 0!==i.metallicFactor?i.metallicFactor:1,a.roughness=void 0!==i.roughnessFactor?i.roughnessFactor:1,void 0!==i.metallicRoughnessTexture&&(o.push(t.assignTexture(a,"metalnessMap",i.metallicRoughnessTexture)),o.push(t.assignTexture(a,"roughnessMap",i.metallicRoughnessTexture))),s=this._invokeOne(function(t){return t.getMaterialType&&t.getMaterialType(e)}),o.push(Promise.all(this._invokeAll(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,a)})))}!0===r.doubleSided&&(a.side=x);const l=r.alphaMode||lT;if(l===hT?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,l===cT&&(a.alphaTest=void 0!==r.alphaCutoff?r.alphaCutoff:.5)),void 0!==r.normalTexture&&s!==wE.ObjectConstructors.MeshBasicMaterial&&(o.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new fi(1,1),void 0!==r.normalTexture.scale)){const e=r.normalTexture.scale;a.normalScale.set(e,e)}if(void 0!==r.occlusionTexture&&s!==wE.ObjectConstructors.MeshBasicMaterial&&(o.push(t.assignTexture(a,"aoMap",r.occlusionTexture)),void 0!==r.occlusionTexture.strength&&(a.aoMapIntensity=r.occlusionTexture.strength)),void 0!==r.emissiveFactor&&s!==wE.ObjectConstructors.MeshBasicMaterial){const e=r.emissiveFactor;a.emissive=(new mr).setRGB(e[0],e[1],e[2],Ut)}return void 0!==r.emissiveTexture&&s!==wE.ObjectConstructors.MeshBasicMaterial&&o.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,Ot)),Promise.all(o).then(function(){const i=new s(a);return r.extras&&r.extras.uuid&&(i.uuid=r.extras.uuid),r.name&&(i.name=r.name),pT(i,r),t.associations.set(i,{materials:e}),r.extensions&&uT(n,i,r),i})}createUniqueName(e){const t=mp.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 r(e){return i[SE.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(i){return _T(i,e,t)})}const s=[];for(let i=0,a=e.length;i<a;i++){const a=e[i],o=gT(a),l=n[o];if(l)s.push(l.promise);else{let e;e=a.extensions&&a.extensions[SE.KHR_DRACO_MESH_COMPRESSION]?r(a):_T(new Fr,a,t),n[o]={primitive:a,promise:e},s.push(e)}}return Promise.all(s)}loadMesh(e){const t=this,i=this.json,n=this.extensions,r=i.meshes[e],s=r.primitives,a=[];for(let e=0,t=s.length;e<t;e++){const t=void 0===s[e].material?dT(this.cache):this.getDependency("material",s[e].material);a.push(t)}return a.push(t.loadGeometries(s)),Promise.all(a).then(function(i){const a=i.slice(0,i.length-1),o=i[i.length-1],l=[];for(let i=0,c=o.length;i<c;i++){const c=o[i],h=s[i];let d;const u=a[i];if(h.mode===eT.TRIANGLES||h.mode===eT.TRIANGLE_STRIP||h.mode===eT.TRIANGLE_FAN||void 0===h.mode)d=!0===r.isSkinnedMesh?new Zl(c,u):new ts(c,u),!0===d.isSkinnedMesh&&d.normalizeSkinWeights(),h.mode===eT.TRIANGLE_STRIP?d.geometry=Xy(d.geometry,1):h.mode===eT.TRIANGLE_FAN&&(d.geometry=Xy(d.geometry,2));else if(h.mode===eT.LINES)d=new Qc(c,u);else if(h.mode===eT.LINE_STRIP)d=new Nc(c,u);else if(h.mode===eT.LINE_LOOP)d=new Vc(c,u);else{if(h.mode!==eT.POINTS)throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+h.mode);d=new Kc(c,u)}Object.keys(d.geometry.morphAttributes).length>0&&mT(d,r),d.name=t.createUniqueName(r.name||"mesh_"+e),d.geometry&&r.extras&&r.extras.isGeometryUserData?(pT(d.geometry,r),h.extensions&&uT(n,d.geometry,h)):(pT(d,r),h.extensions&&uT(n,d,h)),t.assignFinalMaterial(d),l.push(d)}r.extensions&&l.forEach(e=>uT(n,e,r));for(let i=0,n=l.length;i<n;i++)t.associations.set(l[i],{meshes:e,primitives:i});if(1===l.length)return r.extensions&&uT(n,l[0],r),l[0];const c=new ll;r.extensions&&uT(n,c,r),t.associations.set(c,{meshes:e});for(let e=0,t=l.length;e<t;e++)c.add(l[e]);return c})}loadCamera(e){let t;const i=this.json.cameras[e],n=i[i.type];if(n)return"perspective"===i.type?t=new wE.ObjectConstructors.PerspectiveCamera(gi.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):"orthographic"===i.type&&(t=new wE.ObjectConstructors.OrthographicCamera(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),pT(t,i),Promise.resolve(t);console.warn("THREE.GLTFLoader: Missing camera parameters.")}loadSkin(e){const t=this.json.skins[e],i=[];for(let e=0,n=t.joints.length;e<n;e++)i.push(this._loadNodeShallow(t.joints[e]));return void 0!==t.inverseBindMatrices?i.push(this.getDependency("accessor",t.inverseBindMatrices)):i.push(null),Promise.all(i).then(function(e){const i=e.pop(),n=e,r=[],s=[];for(let e=0,a=n.length;e<a;e++){const a=n[e];if(a){r.push(a);const t=new Sn;null!==i&&t.fromArray(i.array,16*e),s.push(t)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[e])}return new nc(r,s)})}loadAnimation(e){const t=this.json,i=this,n=t.animations[e],r=n.name?n.name:"animation_"+e,s=[],a=[],o=[],l=[],c=[];for(let e=0,t=n.channels.length;e<t;e++){const t=n.channels[e],i=n.samplers[t.sampler],r=t.target,h=r.node,d=void 0!==n.parameters?n.parameters[i.input]:i.input,u=void 0!==n.parameters?n.parameters[i.output]:i.output;void 0!==r.node&&(s.push(this.getDependency("node",h)),a.push(this.getDependency("accessor",d)),o.push(this.getDependency("accessor",u)),l.push(i),c.push(r))}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c)]).then(function(e){const t=e[0],s=e[1],a=e[2],o=e[3],l=e[4],c=[];for(let e=0,n=t.length;e<n;e++){const n=t[e],r=s[e],h=a[e],d=o[e],u=l[e];if(void 0===n)continue;n.updateMatrix&&n.updateMatrix();const p=i._createAnimationTracks(n,r,h,d,u);if(p)for(let e=0;e<p.length;e++)c.push(p[e])}const h=new eu(r,void 0,c);return pT(h,n),h})}createNodeMesh(e){const t=this.json,i=this,n=t.nodes[e];return void 0===n.mesh?null:i.getDependency("mesh",n.mesh).then(function(e){const t=i._getNodeRef(i.meshCache,n.mesh,e);return void 0!==n.weights&&t.traverse(function(e){if(e.isMesh)for(let t=0,i=n.weights.length;t<i;t++)e.morphTargetInfluences[t]=n.weights[t]}),t})}loadNode(e){const t=this,i=this.json.nodes[e],n=t._loadNodeShallow(e),r=[],s=i.children||[];for(let e=0,i=s.length;e<i;e++)r.push(t.getDependency("node",s[e]));const a=void 0===i.skin?Promise.resolve(null):t.getDependency("skin",i.skin);return Promise.all([n,Promise.all(r),a]).then(function(e){const t=e[0],i=e[1],n=e[2];null!==n&&t.traverse(function(e){e.isSkinnedMesh&&e.bind(n,yT)});for(let e=0,n=i.length;e<n;e++)t.add(i[e]);return t})}_loadNodeShallow(e){const t=this.json,i=this.extensions,n=this;if(void 0!==this.nodeCache[e])return this.nodeCache[e];const r=t.nodes[e],s=r.name?n.createUniqueName(r.name):"",a=[],o=n._invokeOne(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return o&&a.push(o),void 0!==r.camera&&a.push(n.getDependency("camera",r.camera).then(function(e){return n._getNodeRef(n.cameraCache,r.camera,e)})),n._invokeAll(function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)}).forEach(function(e){a.push(e)}),this.nodeCache[e]=Promise.all(a).then(function(t){let a;if(a=!0===r.isBone?new $l:t.length>1?new ll:1===t.length?t[0]:new Zn,a!==t[0])for(let e=0,i=t.length;e<i;e++)a.add(t[e]);if(r.name&&(a.userData.name=r.name,a.name=s),pT(a,r),r.extensions&&uT(i,a,r),void 0!==r.matrix){const e=new Sn;e.fromArray(r.matrix),a.applyMatrix4(e)}else void 0!==r.translation&&a.position.fromArray(r.translation),void 0!==r.rotation&&a.quaternion.fromArray(r.rotation),void 0!==r.scale&&a.scale.fromArray(r.scale);return n.associations.has(a)||n.associations.set(a,{}),n.associations.get(a).nodes=e,a}),this.nodeCache[e]}loadScene(e){const t=this.extensions,i=this.json.scenes[e],n=this,r=new ll;i.name&&(r.name=n.createUniqueName(i.name)),pT(r,i),i.extensions&&uT(t,r,i);const s=i.nodes||[],a=[];for(let e=0,t=s.length;e<t;e++)a.push(n.getDependency("node",s[e]));return Promise.all(a).then(function(e){for(let t=0,i=e.length;t<i;t++)r.add(e[t]);return n.associations=(e=>{const t=new Map;for(const[e,i]of n.associations)(e instanceof Ar||e instanceof Ni)&&t.set(e,i);return e.traverse(e=>{const i=n.associations.get(e);null!=i&&t.set(e,i)}),t})(r),r})}_createAnimationTracks(e,t,i,n,r){const s=[],a=e.name?e.name:e.uuid,o=[];let l;switch(aT[r.path]===aT.weights?e.traverse(function(e){e.morphTargetInfluences&&o.push(e.name?e.name:e.uuid)}):o.push(a),aT[r.path]){case aT.weights:l=Yd;break;case aT.rotation:l=Jd;break;case aT.position:case aT.scale:l=$d;break;default:l=1===i.itemSize?Yd:$d}const c=void 0!==n.interpolation?oT[n.interpolation]:Ct,h=this._getArrayFromAccessor(i);for(let e=0,i=o.length;e<i;e++){const i=new l(o[e]+"."+aT[r.path],t.array,h,c);"CUBICSPLINE"===n.interpolation&&this._createCubicSplineTrackInterpolant(i),s.push(i)}return s}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const e=AT(t.constructor),i=new Float32Array(t.length);for(let n=0,r=t.length;n<r;n++)i[n]=t[n]*e;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof Jd?$E:JE)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function _T(e,t,i){const n=t.attributes,r=[];function s(t,n){return i.getDependency("accessor",t).then(function(t){e.setAttribute(n,t)})}for(const t in n){const i=sT[t]||t.toLowerCase();i in e.attributes||r.push(s(n[t],i))}if(void 0!==t.indices&&!e.index){const n=i.getDependency("accessor",t.indices).then(function(t){e.setIndex(t)});r.push(n)}return Pi.workingColorSpace!==Ut&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Pi.workingColorSpace}" not supported.`),pT(e,t),function(e,t,i){const n=t.attributes,r=new Ji;if(void 0===n.POSITION)return;{const e=i.json.accessors[n.POSITION],t=e.min,s=e.max;if(void 0===t||void 0===s)return void console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");if(r.set(new Xi(t[0],t[1],t[2]),new Xi(s[0],s[1],s[2])),e.normalized){const t=AT(tT[e.componentType]);r.min.multiplyScalar(t),r.max.multiplyScalar(t)}}const s=t.targets;if(void 0!==s){const e=new Xi,t=new Xi;for(let n=0,r=s.length;n<r;n++){const r=s[n];if(void 0!==r.POSITION){const n=i.json.accessors[r.POSITION],s=n.min,a=n.max;if(void 0!==s&&void 0!==a){if(t.setX(Math.max(Math.abs(s[0]),Math.abs(a[0]))),t.setY(Math.max(Math.abs(s[1]),Math.abs(a[1]))),t.setZ(Math.max(Math.abs(s[2]),Math.abs(a[2]))),n.normalized){const e=AT(tT[n.componentType]);t.multiplyScalar(e)}e.max(t)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}r.expandByVector(e)}e.boundingBox=r;const a=new fn;r.getCenter(a.center),a.radius=r.min.distanceTo(r.max)/2,e.boundingSphere=a}(e,t,i),Promise.all(r).then(function(){return void 0!==t.targets?function(e,t,i){let n=!1,r=!1,s=!1;for(let e=0,i=t.length;e<i;e++){const i=t[e];if(void 0!==i.POSITION&&(n=!0),void 0!==i.NORMAL&&(r=!0),void 0!==i.COLOR_0&&(s=!0),n&&r&&s)break}if(!n&&!r&&!s)return Promise.resolve(e);const a=[],o=[],l=[];for(let c=0,h=t.length;c<h;c++){const h=t[c];if(n){const t=void 0!==h.POSITION?i.getDependency("accessor",h.POSITION):e.attributes.position;a.push(t)}if(r){const t=void 0!==h.NORMAL?i.getDependency("accessor",h.NORMAL):e.attributes.normal;o.push(t)}if(s){const t=void 0!==h.COLOR_0?i.getDependency("accessor",h.COLOR_0):e.attributes.color;l.push(t)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then(function(t){const i=t[0],a=t[1],o=t[2];return n&&(e.morphAttributes.position=i),r&&(e.morphAttributes.normal=a),s&&(e.morphAttributes.color=o),e.morphTargetsRelative=!0,e})}(e,t.targets,i):e})}const bT=async(e,t)=>{if(!(e&&e instanceof ArrayBuffer&&e.byteLength&&t.encrypt))return e;if(!t.encryptKey&&window&&window.prompt&&(t.encryptKey=window.prompt("GLTFEncryption: Enter encryption key/password")||""),!t.encryptKey)return console.warn("GLTF Export: encryption key not provided, skipping encryption"),e;return L_(await Ym(new Uint8Array(e),t.encryptKey),{asset:{version:"2.0",generator:"ThreePipeGLBWrapper",encryption:{type:"aesgcm",version:1}}})},xT={key:(e,t,i)=>e.key||window&&window.prompt&&window.prompt("GLTFEncryption: Please enter the password/key for the model: "+i)||"",async process(e,t){if("string"==typeof e||e.byteLength<100)return e;if(!(new TextDecoder).decode(new Uint8Array(e,0,100)).includes("GLBWrapper"))return e;const i=new qE(e),n=JSON.parse(i.content||"{}");let r=i.body||e;const s=n.asset?.encryption;if(!s)return r;const a=s.type,o=s.version;if("aesgcm"===a&&1===o){const e=await Im(this.key,s,n,t)||"";try{r=(await Km(new Uint8Array(r),e)).buffer}catch{throw new ErrorEvent("decryption error")}}return r}},wT=class extends lu{async parseAsync(e){return e}load(e,t,i,n){return super.load(e,e=>{try{if("string"!=typeof e)throw new Error("Invalid JSON");this.parseAsync(JSON.parse(e)).then(t)}catch(e){n?.(e)}},i,n)}};wT.SupportedJSONTypes=[],wT.SupportedJSONExtensions=[];let CT=wT;const ST=class e extends CT{async parseAsync(t){if(!this.viewer)throw"Viewer not set in JSONMaterialLoader.";let i;return e.FindExistingMaterial&&t.uuid&&this.viewer&&(i=this.viewer.materialManager.findMaterial(t.uuid)),await e.DeserializeMaterialJSON(t,this.viewer,void 0,i)}static async DeserializeMaterialJSON(e,t,i,n){i=i||w_();const r={...e};e.images&&(Array.isArray(e.images)?i.images=Object.fromEntries(e.images.map(e=>[e.uuid,e])):i.images=e.images,delete r.images),e.textures&&(Array.isArray(e.textures)?i.textures=Object.fromEntries(e.textures.map(e=>[e.uuid,e])):i.textures=e.textures,delete r.textures),e.materials&&(Array.isArray(e.materials)?i.materials=Object.fromEntries(e.materials.map(e=>[e.uuid,e])):i.materials=e.materials,delete r.materials);const s=await t.loadConfigResources(i);return f_.Deserialize(r,n||void 0,s)}};ST.SupportedJSONTypes=()=>["Material",...[...f_.SerializableMaterials.values()].flatMap(e=>[e.TYPE,...e.TypeAlias||[]])],ST.SupportedJSONExtensions=()=>["mat",...[...f_.SerializableMaterials.values()].map(e=>e.TypeSlug)],ST.FindExistingMaterial=!1;let MT=ST;class ET extends su{constructor(e){super(e)}load(e,t,i,n){const r=this,s=""===this.path?Bu.extractUrlBase(e):this.path,a=new lu(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(i){try{t(r.parse(i,s))}catch(t){n?n(t):console.error(t),r.manager.itemError(e)}},i,n)}setMaterialOptions(e){return this.materialOptions=e,this}parse(e,t){const i=e.split("\n");let n={};const r=/\s+/,s={};for(let e=0;e<i.length;e++){let t=i[e];if(t=t.trim(),0===t.length||"#"===t.charAt(0))continue;const a=t.indexOf(" ");let o=a>=0?t.substring(0,a):t;o=o.toLowerCase();let l=a>=0?t.substring(a+1):"";if(l=l.trim(),"newmtl"===o)n={name:l},s[l]=n;else if("ka"===o||"kd"===o||"ks"===o||"ke"===o){const e=l.split(r,3);n[o]=[parseFloat(e[0]),parseFloat(e[1]),parseFloat(e[2])]}else n[o]=l}const a=new TT(this.resourcePath||t,this.materialOptions);return a.setCrossOrigin(this.crossOrigin),a.setManager(this.manager),a.setMaterials(s),a}}class TT{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=void 0!==this.options.side?this.options.side:_,this.wrap=void 0!==this.options.wrap?this.options.wrap:ge}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],r={};t[i]=r;for(const e in n){let t=!0,i=n[e];const s=e.toLowerCase();switch(s){case"kd":case"ka":case"ks":this.options&&this.options.normalizeRGB&&(i=[i[0]/255,i[1]/255,i[2]/255]),this.options&&this.options.ignoreZeroRGBs&&0===i[0]&&0===i[1]&&0===i[2]&&(t=!1)}t&&(r[s]=i)}}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(e=>this.create(e)));return i.forEach((i,r)=>{e[r]=n[r],t[i]=r}),e}async create(e){if(void 0===this.materials[e]){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],r={name:e,side:this.side};const s=new Map;function a(e,i){const n=()=>r[e]?void 0:async function(e,i){const n=t.getTextureParams(i,r),s=function(e,t){return"string"!=typeof t||""===t?"":/^https?:\/\//i.test(t)?t:e+t}(t.baseUrl,n.url),a=await new Promise(e=>{t.loadTexture(s,void 0,e,void 0,t=>{console.warn("MTLLoader2: Unable to load texture",s,t),e(void 0)})});a&&(a.repeat.copy(n.scale),a.offset.copy(n.offset),a.wrapS=t.wrap,a.wrapT=t.wrap,("map"===e||"emissiveMap"===e)&&(a.colorSpace=Ot),r[e]=a)}(e,i);s.set(e,s.has(e)?s.get(e).then(n):n())}const o=Array.from(Object.keys(n||{}));let l=o.includes("d")||o.includes("D");for(const e of o){const t=n[e];let i;if(""!==t)switch(e.toLowerCase()){case"kd":r.color=(new mr).fromArray(t).convertSRGBToLinear();break;case"ks":r.specular=(new mr).fromArray(t).convertSRGBToLinear();break;case"ke":r.emissive=(new mr).fromArray(t).convertSRGBToLinear();break;case"map_kd":a("map",t);break;case"map_ks":a("specularMap",t);break;case"map_ke":a("emissiveMap",t);break;case"norm":a("normalMap",t);break;case"map_bump":case"bump":a("bumpMap",t);break;case"map_d":a("alphaMap",t),r.transparent=!0;break;case"ns":r.shininess=parseFloat(t);break;case"d":i=parseFloat(t),i<1&&(r.opacity=i,r.transparent=!0);break;case"tr":if(l)break;i=parseFloat(t),this.options&&this.options.invertTrProperty&&(i=1-i),i>0&&(r.opacity=1-i,r.transparent=!0)}}return await Promise.all(s.values()),i[e]=new Pd(r),i[e]}getTextureParams(e,t){const i={scale:new fi(1,1),offset:new fi(0,0)},n=e.split(/\s+/);let r;return r=n.indexOf("-bm"),r>=0&&(t.bumpScale=parseFloat(n[r+1]),n.splice(r,2)),r=n.indexOf("-s"),r>=0&&(i.scale.set(parseFloat(n[r+1]),parseFloat(n[r+2])),n.splice(r,4)),r=n.indexOf("-o"),r>=0&&(i.offset.set(parseFloat(n[r+1]),parseFloat(n[r+2])),n.splice(r,4)),i.url=n.join(" ").trim(),i}loadTexture(e,t,i,n,r){const s=void 0!==this.manager?this.manager:ru;let a=s.getHandler(e);null===a&&(a=new uu(s)),a.setCrossOrigin&&a.setCrossOrigin(this.crossOrigin);const o=a.load(e,i,n,r);return void 0!==t&&(o.mapping=t),o}}const IT=/^[og]\s*(.+)?/,PT=/^mtllib /,DT=/^usemtl /,RT=/^usemap /,BT=/\s+/,LT=new Xi,OT=new Xi,UT=new Xi,FT=new Xi,kT=new Xi,NT=new mr;function jT(){const e={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&!1===this.object.fromDeclaration)return this.object.name=e,void(this.object.fromDeclaration=!1!==t);const i=this.object&&"function"==typeof this.object.currentMaterial?this.object.currentMaterial():void 0;if(this.object&&"function"==typeof this.object._finalize&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:!1!==t,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(e,t){const i=this._finalize(!1);i&&(i.inherited||i.groupCount<=0)&&this.materials.splice(i.index,1);const n={index:this.materials.length,name:e||"",mtllib:Array.isArray(t)&&t.length>0?t[t.length-1]:"",smooth:void 0!==i?i.smooth:this.smooth,groupStart:void 0!==i?i.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(e){const t={index:"number"==typeof e?e:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return t.clone=this.clone.bind(t),t}};return this.materials.push(n),n},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(e){const t=this.currentMaterial();if(t&&-1===t.groupEnd&&(t.groupEnd=this.geometry.vertices.length/3,t.groupCount=t.groupEnd-t.groupStart,t.inherited=!1),e&&this.materials.length>1)for(let e=this.materials.length-1;e>=0;e--)this.materials[e].groupCount<=0&&this.materials.splice(e,1);return e&&0===this.materials.length&&this.materials.push({name:"",smooth:this.smooth}),t}},i&&i.name&&"function"==typeof i.clone){const e=i.clone(0);e.inherited=!0,this.object.materials.push(e)}this.objects.push(this.object)},finalize:function(){this.object&&"function"==typeof this.object._finalize&&this.object._finalize(!0)},parseVertexIndex:function(e,t){const i=parseInt(e,10);return 3*(i>=0?i-1:i+t/3)},parseNormalIndex:function(e,t){const i=parseInt(e,10);return 3*(i>=0?i-1:i+t/3)},parseUVIndex:function(e,t){const i=parseInt(e,10);return 2*(i>=0?i-1:i+t/2)},addVertex:function(e,t,i){const n=this.vertices,r=this.object.geometry.vertices;r.push(n[e+0],n[e+1],n[e+2]),r.push(n[t+0],n[t+1],n[t+2]),r.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,r=this.object.geometry.normals;r.push(n[e+0],n[e+1],n[e+2]),r.push(n[t+0],n[t+1],n[t+2]),r.push(n[i+0],n[i+1],n[i+2])},addFaceNormal:function(e,t,i){const n=this.vertices,r=this.object.geometry.normals;LT.fromArray(n,e),OT.fromArray(n,t),UT.fromArray(n,i),kT.subVectors(UT,OT),FT.subVectors(LT,OT),kT.cross(FT),kT.normalize(),r.push(kT.x,kT.y,kT.z),r.push(kT.x,kT.y,kT.z),r.push(kT.x,kT.y,kT.z)},addColor:function(e,t,i){const n=this.colors,r=this.object.geometry.colors;void 0!==n[e]&&r.push(n[e+0],n[e+1],n[e+2]),void 0!==n[t]&&r.push(n[t+0],n[t+1],n[t+2]),void 0!==n[i]&&r.push(n[i+0],n[i+1],n[i+2])},addUV:function(e,t,i){const n=this.uvs,r=this.object.geometry.uvs;r.push(n[e+0],n[e+1]),r.push(n[t+0],n[t+1]),r.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,r,s,a,o,l){const c=this.vertices.length;let h=this.parseVertexIndex(e,c),d=this.parseVertexIndex(t,c),u=this.parseVertexIndex(i,c);if(this.addVertex(h,d,u),this.addColor(h,d,u),void 0!==a&&""!==a){const e=this.normals.length;h=this.parseNormalIndex(a,e),d=this.parseNormalIndex(o,e),u=this.parseNormalIndex(l,e),this.addNormal(h,d,u)}else this.addFaceNormal(h,d,u);if(void 0!==n&&""!==n){const e=this.uvs.length;h=this.parseUVIndex(n,e),d=this.parseUVIndex(r,e),u=this.parseUVIndex(s,e),this.addUV(h,d,u),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 n=this.parseVertexIndex(e[i],t);this.addVertexPoint(n),this.addColor(n)}},addLineGeometry:function(e,t){this.object.geometry.type="Line";const i=this.vertices.length,n=this.uvs.length;for(let t=0,n=e.length;t<n;t++)this.addVertexLine(this.parseVertexIndex(e[t],i));for(let e=0,i=t.length;e<i;e++)this.addUVLine(this.parseUVIndex(t[e],n))}};return e.startObject("",!1),e}class zT extends su{constructor(e){super(e),this.materials=null}load(e,t,i,n){const r=this,s=new lu(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),r.currentUrl=e,s.load(e,async function(i){try{t(await r.parse(i))}catch(t){n?n(t):console.error(t),r.manager.itemError(e)}r.currentUrl=void 0},i,n)}setMaterials(e){return this.materials=e,this}async parse(e){const t=new jT;-1!==e.indexOf("\r\n")&&(e=e.replace(/\r\n/g,"\n")),-1!==e.indexOf("\\\n")&&(e=e.replace(/\\\n/g,""));const i=e.split("\n");let n=[];for(let e=0,r=i.length;e<r;e++){const r=i[e].trimStart();if(0===r.length)continue;const s=r.charAt(0);if("#"!==s)if("v"===s){const e=r.split(BT);switch(e[0]){case"v":t.vertices.push(parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3])),e.length>=7?(NT.setRGB(parseFloat(e[4]),parseFloat(e[5]),parseFloat(e[6])).convertSRGBToLinear(),t.colors.push(NT.r,NT.g,NT.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3]));break;case"vt":t.uvs.push(parseFloat(e[1]),parseFloat(e[2]))}}else if("f"===s){const e=r.slice(1).trim().split(BT),i=[];for(let t=0,n=e.length;t<n;t++){const n=e[t];if(n.length>0){const e=n.split("/");i.push(e)}}const n=i[0];for(let e=1,r=i.length-1;e<r;e++){const r=i[e],s=i[e+1];t.addFace(n[0],r[0],s[0],n[1],r[1],s[1],n[2],r[2],s[2])}}else if("l"===s){const e=r.substring(1).trim().split(" ");let i=[];const n=[];if(-1===r.indexOf("/"))i=e;else for(let t=0,r=e.length;t<r;t++){const r=e[t].split("/");""!==r[0]&&i.push(r[0]),""!==r[1]&&n.push(r[1])}t.addLineGeometry(i,n)}else if("p"===s){const e=r.slice(1).trim().split(" ");t.addPointGeometry(e)}else if(null!==(n=IT.exec(r))){const e=(" "+n[0].slice(1).trim()).slice(1);t.startObject(e)}else if(DT.test(r))t.object.startMaterial(r.substring(7).trim(),t.materialLibraries);else if(PT.test(r)){t.materialLibraries.push(r.substring(7).trim());let e=r.substring(7).trim(),i=this.manager.getHandler(e);if(!i&&e.trim().split("?")[0].endsWith(".mtl")&&(i=new ET(this.manager),i.setPath(this.path),i.setWithCredentials(this.withCredentials),i.setRequestHeader(this.requestHeader),i.setResourcePath(this.resourcePath),i.setCrossOrigin(this.crossOrigin)),this.currentUrl.startsWith("http")&&!e.startsWith("http")&&(e=this.currentUrl.substring(0,this.currentUrl.lastIndexOf("/")+1)+e),i){const t=await i.loadAsync(e).catch(e=>{console.warn(e)});t&&this.setMaterials(t)}else console.warn("OBJLoader2: Register MTLLoader2 or any other material loader to loading manager to load the material file:",e)}else if(RT.test(r))console.warn('OBJLoader2: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.');else if("s"===s){if(n=r.split(" "),n.length>1){const e=n[1].trim().toLowerCase();t.object.smooth="0"!==e&&"off"!==e}else t.object.smooth=!0;const e=t.object.currentMaterial();e&&(e.smooth=t.object.smooth)}else{if("\0"===r)continue;console.warn('THREE.OBJLoader: Unexpected line: "'+r+'"')}}t.finalize();const r=new ll;if(r.materialLibraries=[].concat(t.materialLibraries),!0==!(1===t.objects.length&&0===t.objects[0].geometry.vertices.length)){const e=null===this.materials?[]:await Promise.all(t.objects.map(e=>0===e.geometry.vertices.length?[]:Promise.all(e.materials.map(e=>this.materials.create(e.name)))));for(let i=0,n=t.objects.length;i<n;i++){const n=t.objects[i],s=n.geometry,a=n.materials,o="Line"===s.type,l="Points"===s.type;let c=!1;if(0===s.vertices.length)continue;const h=new Fr;h.setAttribute("position",new Ir(s.vertices,3)),s.normals.length>0&&h.setAttribute("normal",new Ir(s.normals,3)),s.colors.length>0&&(c=!0,h.setAttribute("color",new Ir(s.colors,3))),!0===s.hasUVIndices&&h.setAttribute("uv",new Ir(s.uvs,2));const d=[];for(let n=0,r=a.length;n<r;n++){const r=a[n],s=r.name+"_"+r.smooth+"_"+c;let h=t.materials[s];if(null!==this.materials)if(h=e[i][n],!o||!h||h instanceof Dc){if(l&&h&&!(h instanceof Hc)){const e=new Hc({size:10,sizeAttenuation:!1});Ar.prototype.copy.call(e,h),e.color.copy(h.color),e.map=h.map,h=e}}else{const e=new Dc;Ar.prototype.copy.call(e,h),e.color.copy(h.color),h=e}void 0===h&&(h=o?new Dc:l?new Hc({size:1,sizeAttenuation:!1}):new Td,h.name=r.name,h.flatShading=!r.smooth,h.vertexColors=c,t.materials[s]=h),d.push(h)}let u;if(d.length>1){for(let e=0,t=a.length;e<t;e++){const t=a[e];h.addGroup(t.groupStart,t.groupCount,e)}u=o?new Qc(h,d):l?new Kc(h,d):new ts(h,d)}else u=o?new Qc(h,d[0]):l?new Kc(h,d[0]):new ts(h,d[0]);u.name=n.name,r.add(u)}}else if(t.vertices.length>0){const e=new Hc({size:1,sizeAttenuation:!1}),i=new Fr;i.setAttribute("position",new Ir(t.vertices,3)),t.colors.length>0&&void 0!==t.colors[0]&&(i.setAttribute("color",new Ir(t.colors,3)),e.vertexColors=!0);const n=new Kc(i,e);r.add(n)}return r}}var GT={},QT=Uint8Array,VT=Uint16Array,HT=Int32Array,WT=new QT([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]),qT=new QT([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]),XT=new QT([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),YT=function(e,t){for(var i=new VT(31),n=0;n<31;++n)i[n]=t+=1<<e[n-1];var r=new HT(i[30]);for(n=1;n<30;++n)for(var s=i[n];s<i[n+1];++s)r[s]=s-i[n]<<5|n;return{b:i,r:r}},KT=YT(WT,2),JT=KT.b,ZT=KT.r;JT[28]=258,ZT[258]=28;for(var $T=YT(qT,0),eI=$T.b,tI=$T.r,iI=new VT(32768),nI=0;nI<32768;++nI){var rI=(43690&nI)>>1|(21845&nI)<<1;rI=(61680&(rI=(52428&rI)>>2|(13107&rI)<<2))>>4|(3855&rI)<<4,iI[nI]=((65280&rI)>>8|(255&rI)<<8)>>1}var sI=function(e,t,i){for(var n=e.length,r=0,s=new VT(t);r<n;++r)e[r]&&++s[e[r]-1];var a,o=new VT(t);for(r=1;r<t;++r)o[r]=o[r-1]+s[r-1]<<1;if(i){a=new VT(1<<t);var l=15-t;for(r=0;r<n;++r)if(e[r])for(var c=r<<4|e[r],h=t-e[r],d=o[e[r]-1]++<<h,u=d|(1<<h)-1;d<=u;++d)a[iI[d]>>l]=c}else for(a=new VT(n),r=0;r<n;++r)e[r]&&(a[r]=iI[o[e[r]-1]++]>>15-e[r]);return a},aI=new QT(288);for(nI=0;nI<144;++nI)aI[nI]=8;for(nI=144;nI<256;++nI)aI[nI]=9;for(nI=256;nI<280;++nI)aI[nI]=7;for(nI=280;nI<288;++nI)aI[nI]=8;var oI=new QT(32);for(nI=0;nI<32;++nI)oI[nI]=5;var lI=sI(aI,9,0),cI=sI(aI,9,1),hI=sI(oI,5,0),dI=sI(oI,5,1),uI=function(e){for(var t=e[0],i=1;i<e.length;++i)e[i]>t&&(t=e[i]);return t},pI=function(e,t,i){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&i},mI=function(e,t){var i=t/8|0;return(e[i]|e[i+1]<<8|e[i+2]<<16)>>(7&t)},gI=function(e){return(e+7)/8|0},fI=function(e,t,i){return(null==t||t<0)&&(t=0),(null==i||i>e.length)&&(i=e.length),new QT(e.subarray(t,i))},AI=["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"],yI=function(e,t,i){var n=new Error(t||AI[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,yI),!i)throw n;return n},vI=function(e,t,i,n){var r=e.length,s=n?n.length:0;if(!r||t.f&&!t.l)return i||new QT(0);var a=!i,o=a||2!=t.i,l=t.i;a&&(i=new QT(3*r));var c=function(e){var t=i.length;if(e>t){var n=new QT(Math.max(2*t,e));n.set(i),i=n}},h=t.f||0,d=t.p||0,u=t.b||0,p=t.l,m=t.d,g=t.m,f=t.n,A=8*r;do{if(!p){h=pI(e,d,1);var y=pI(e,d+1,3);if(d+=3,!y){var v=e[(P=gI(d)+4)-4]|e[P-3]<<8,_=P+v;if(_>r){l&&yI(0);break}o&&c(u+v),i.set(e.subarray(P,_),u),t.b=u+=v,t.p=d=8*_,t.f=h;continue}if(1==y)p=cI,m=dI,g=9,f=5;else if(2==y){var b=pI(e,d,31)+257,x=pI(e,d+10,15)+4,w=b+pI(e,d+5,31)+1;d+=14;for(var C=new QT(w),S=new QT(19),M=0;M<x;++M)S[XT[M]]=pI(e,d+3*M,7);d+=3*x;var E=uI(S),T=(1<<E)-1,I=sI(S,E,1);for(M=0;M<w;){var P,D=I[pI(e,d,T)];if(d+=15&D,(P=D>>4)<16)C[M++]=P;else{var R=0,B=0;for(16==P?(B=3+pI(e,d,3),d+=2,R=C[M-1]):17==P?(B=3+pI(e,d,7),d+=3):18==P&&(B=11+pI(e,d,127),d+=7);B--;)C[M++]=R}}var L=C.subarray(0,b),O=C.subarray(b);g=uI(L),f=uI(O),p=sI(L,g,1),m=sI(O,f,1)}else yI(1);if(d>A){l&&yI(0);break}}o&&c(u+131072);for(var U=(1<<g)-1,F=(1<<f)-1,k=d;;k=d){var N=(R=p[mI(e,d)&U])>>4;if((d+=15&R)>A){l&&yI(0);break}if(R||yI(2),N<256)i[u++]=N;else{if(256==N){k=d,p=null;break}var j=N-254;if(N>264){var z=WT[M=N-257];j=pI(e,d,(1<<z)-1)+JT[M],d+=z}var G=m[mI(e,d)&F],Q=G>>4;G||yI(3),d+=15&G;O=eI[Q];if(Q>3){z=qT[Q];O+=mI(e,d)&(1<<z)-1,d+=z}if(d>A){l&&yI(0);break}o&&c(u+131072);var V=u+j;if(u<O){var H=s-O,W=Math.min(O,V);for(H+u<0&&yI(3);u<W;++u)i[u]=n[H+u]}for(;u<V;++u)i[u]=i[u-O]}}t.l=p,t.p=k,t.b=u,t.f=h,p&&(h=1,t.m=g,t.d=m,t.n=f)}while(!h);return u!=i.length&&a?fI(i,0,u):i.subarray(0,u)},_I=function(e,t,i){i<<=7&t;var n=t/8|0;e[n]|=i,e[n+1]|=i>>8},bI=function(e,t,i){i<<=7&t;var n=t/8|0;e[n]|=i,e[n+1]|=i>>8,e[n+2]|=i>>16},xI=function(e,t){for(var i=[],n=0;n<e.length;++n)e[n]&&i.push({s:n,f:e[n]});var r=i.length,s=i.slice();if(!r)return{t:II,l:0};if(1==r){var a=new QT(i[0].s+1);return a[i[0].s]=1,{t:a,l:1}}i.sort(function(e,t){return e.f-t.f}),i.push({s:-1,f:25001});var o=i[0],l=i[1],c=0,h=1,d=2;for(i[0]={s:-1,f:o.f+l.f,l:o,r:l};h!=r-1;)o=i[i[c].f<i[d].f?c++:d++],l=i[c!=h&&i[c].f<i[d].f?c++:d++],i[h++]={s:-1,f:o.f+l.f,l:o,r:l};var u=s[0].s;for(n=1;n<r;++n)s[n].s>u&&(u=s[n].s);var p=new VT(u+1),m=wI(i[h-1],p,0);if(m>t){n=0;var g=0,f=m-t,A=1<<f;for(s.sort(function(e,t){return p[t.s]-p[e.s]||e.f-t.f});n<r;++n){var y=s[n].s;if(!(p[y]>t))break;g+=A-(1<<m-p[y]),p[y]=t}for(g>>=f;g>0;){var v=s[n].s;p[v]<t?g-=1<<t-p[v]++-1:++n}for(;n>=0&&g;--n){var _=s[n].s;p[_]==t&&(--p[_],++g)}m=t}return{t:new QT(p),l:m}},wI=function(e,t,i){return-1==e.s?Math.max(wI(e.l,t,i+1),wI(e.r,t,i+1)):t[e.s]=i},CI=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new VT(++t),n=0,r=e[0],s=1,a=function(e){i[n++]=e},o=1;o<=t;++o)if(e[o]==r&&o!=t)++s;else{if(!r&&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(r),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(r);s=1,r=e[o]}return{c:i.subarray(0,n),n:t}},SI=function(e,t){for(var i=0,n=0;n<t.length;++n)i+=e[n]*t[n];return i},MI=function(e,t,i){var n=i.length,r=gI(t+2);e[r]=255&n,e[r+1]=n>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var s=0;s<n;++s)e[r+s+4]=i[s];return 8*(r+4+n)},EI=function(e,t,i,n,r,s,a,o,l,c,h){_I(t,h++,i),++r[256];for(var d=xI(r,15),u=d.t,p=d.l,m=xI(s,15),g=m.t,f=m.l,A=CI(u),y=A.c,v=A.n,_=CI(g),b=_.c,x=_.n,w=new VT(19),C=0;C<y.length;++C)++w[31&y[C]];for(C=0;C<b.length;++C)++w[31&b[C]];for(var S=xI(w,7),M=S.t,E=S.l,T=19;T>4&&!M[XT[T-1]];--T);var I,P,D,R,B=c+5<<3,L=SI(r,aI)+SI(s,oI)+a,O=SI(r,u)+SI(s,g)+a+14+3*T+SI(w,M)+2*w[16]+3*w[17]+7*w[18];if(l>=0&&B<=L&&B<=O)return MI(t,h,e.subarray(l,l+c));if(_I(t,h,1+(O<L)),h+=2,O<L){I=sI(u,p,0),P=u,D=sI(g,f,0),R=g;var U=sI(M,E,0);_I(t,h,v-257),_I(t,h+5,x-1),_I(t,h+10,T-4),h+=14;for(C=0;C<T;++C)_I(t,h+3*C,M[XT[C]]);h+=3*T;for(var F=[y,b],k=0;k<2;++k){var N=F[k];for(C=0;C<N.length;++C){var j=31&N[C];_I(t,h,U[j]),h+=M[j],j>15&&(_I(t,h,N[C]>>5&127),h+=N[C]>>12)}}}else I=lI,P=aI,D=hI,R=oI;for(C=0;C<o;++C){var z=n[C];if(z>255){bI(t,h,I[(j=z>>18&31)+257]),h+=P[j+257],j>7&&(_I(t,h,z>>23&31),h+=WT[j]);var G=31&z;bI(t,h,D[G]),h+=R[G],G>3&&(bI(t,h,z>>5&8191),h+=qT[G])}else bI(t,h,I[z]),h+=P[z]}return bI(t,h,I[256]),h+P[256]},TI=new HT([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),II=new QT(0),PI=function(e,t,i,n,r,s){var a=s.z||e.length,o=new QT(n+a+5*(1+Math.ceil(a/7e3))+r),l=o.subarray(n,o.length-r),c=s.l,h=7&(s.r||0);if(t){h&&(l[0]=s.r>>3);for(var d=TI[t-1],u=d>>13,p=8191&d,m=(1<<i)-1,g=s.p||new VT(32768),f=s.h||new VT(m+1),A=Math.ceil(i/3),y=2*A,v=function(t){return(e[t]^e[t+1]<<A^e[t+2]<<y)&m},_=new HT(25e3),b=new VT(288),x=new VT(32),w=0,C=0,S=s.i||0,M=0,E=s.w||0,T=0;S+2<a;++S){var I=v(S),P=32767&S,D=f[I];if(g[P]=D,f[I]=P,E<=S){var R=a-S;if((w>7e3||M>24576)&&(R>423||!c)){h=EI(e,l,0,_,b,x,C,M,T,S-T,h),M=w=C=0,T=S;for(var B=0;B<286;++B)b[B]=0;for(B=0;B<30;++B)x[B]=0}var L=2,O=0,U=p,F=P-D&32767;if(R>2&&I==v(S-F))for(var k=Math.min(u,R)-1,N=Math.min(32767,S),j=Math.min(258,R);F<=N&&--U&&P!=D;){if(e[S+L]==e[S+L-F]){for(var z=0;z<j&&e[S+z]==e[S+z-F];++z);if(z>L){if(L=z,O=F,z>k)break;var G=Math.min(F,z-2),Q=0;for(B=0;B<G;++B){var V=S-F+B&32767,H=V-g[V]&32767;H>Q&&(Q=H,D=V)}}}F+=(P=D)-(D=g[P])&32767}if(O){_[M++]=268435456|ZT[L]<<18|tI[O];var W=31&ZT[L],q=31&tI[O];C+=WT[W]+qT[q],++b[257+W],++x[q],E=S+L,++w}else _[M++]=e[S],++b[e[S]]}}for(S=Math.max(S,E);S<a;++S)_[M++]=e[S],++b[e[S]];h=EI(e,l,c,_,b,x,C,M,T,S-T,h),c||(s.r=7&h|l[h/8|0]<<3,h-=7,s.h=f,s.p=g,s.i=S,s.w=E)}else{for(S=s.w||0;S<a+c;S+=65535){var X=S+65535;X>=a&&(l[h/8|0]=c,X=a),h=MI(l,h+1,e.subarray(S,X))}s.i=a}return fI(o,0,n+gI(h)+r)},DI=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var i=t,n=9;--n;)i=(1&i&&-306674912)^i>>>1;e[t]=i}return e}(),RI=function(){var e=-1;return{p:function(t){for(var i=e,n=0;n<t.length;++n)i=DI[255&i^t[n]]^i>>>8;e=i},d:function(){return~e}}},BI=function(){var e=1,t=0;return{p:function(i){for(var n=e,r=t,s=0|i.length,a=0;a!=s;){for(var o=Math.min(a+2655,s);a<o;++a)r+=n+=i[a];n=(65535&n)+15*(n>>16),r=(65535&r)+15*(r>>16)}e=n,t=r},d:function(){return(255&(e%=65521))<<24|(65280&e)<<8|(255&(t%=65521))<<8|t>>8}}},LI=function(e,t,i,n,r){if(!r&&(r={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),a=new QT(s.length+e.length);a.set(s),a.set(e,s.length),e=a,r.w=s.length}return PI(e,null==t.level?6:t.level,null==t.mem?r.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,i,n,r)},OI=function(e,t){var i={};for(var n in e)i[n]=e[n];for(var n in t)i[n]=t[n];return i},UI=function(e,t,i){for(var n=e(),r=e.toString(),s=r.slice(r.indexOf("[")+1,r.lastIndexOf("]")).replace(/\s+/g,"").split(","),a=0;a<n.length;++a){var o=n[a],l=s[a];if("function"==typeof o){t+=";"+l+"=";var c=o.toString();if(o.prototype)if(-1!=c.indexOf("[native code]")){var h=c.indexOf(" ",8)+1;t+=c.slice(h,c.indexOf("(",h))}else for(var d in t+=c,o.prototype)t+=";"+l+".prototype."+d+"="+o.prototype[d].toString();else t+=c}else i[l]=o}return t},FI=[],kI=function(e,t,i,n){if(!FI[i]){for(var r="",s={},a=e.length-1,o=0;o<a;++o)r=UI(e[o],r,s);FI[i]={c:UI(e[a],r,s),e:s}}var l=OI({},FI[i].e);return function(e,t,i,n,r){var s=new Worker(GT[t]||(GT[t]=URL.createObjectURL(new Blob([e+';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'],{type:"text/javascript"}))));return s.onmessage=function(e){var t=e.data,i=t.$e$;if(i){var n=new Error(i[0]);n.code=i[1],n.stack=i[2],r(n,null)}else r(null,t)},s.postMessage(i,n),s}(FI[i].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",i,l,function(e){var t=[];for(var i in e)e[i].buffer&&t.push((e[i]=new e[i].constructor(e[i])).buffer);return t}(l),n)},NI=function(){return[QT,VT,HT,WT,qT,XT,JT,eI,cI,dI,iI,AI,sI,uI,pI,mI,gI,fI,yI,vI,mP,HI,WI]},jI=function(){return[QT,VT,HT,WT,qT,XT,ZT,tI,lI,aI,hI,oI,iI,TI,II,sI,_I,bI,xI,wI,CI,SI,MI,EI,gI,fI,PI,LI,hP,HI]},zI=function(){return[eP,nP,$I,RI,DI]},GI=function(){return[tP,iP]},QI=function(){return[rP,$I,BI]},VI=function(){return[sP]},HI=function(e){return postMessage(e,[e.buffer])},WI=function(e){return e&&{out:e.size&&new QT(e.size),dictionary:e.dictionary}},qI=function(e,t,i,n,r,s){var a=kI(i,n,r,function(e,t){a.terminate(),s(e,t)});return a.postMessage([e,t],t.consume?[e.buffer]:[]),function(){a.terminate()}},XI=function(e){return e.ondata=function(e,t){return postMessage([e,t],[e.buffer])},function(t){t.data.length?(e.push(t.data[0],t.data[1]),postMessage([t.data[0].length])):e.flush()}},YI=function(e,t,i,n,r,s,a){var o,l=kI(e,n,r,function(e,i){e?(l.terminate(),t.ondata.call(t,e)):Array.isArray(i)?1==i.length?(t.queuedSize-=i[0],t.ondrain&&t.ondrain(i[0])):(i[1]&&l.terminate(),t.ondata.call(t,e,i[0],i[1])):a(i)});l.postMessage(i),t.queuedSize=0,t.push=function(e,i){t.ondata||yI(5),o&&t.ondata(yI(4,0,1),null,!!i),t.queuedSize+=e.length,l.postMessage([e,o=i],[e.buffer])},t.terminate=function(){l.terminate()},s&&(t.flush=function(){l.postMessage([])})},KI=function(e,t){return e[t]|e[t+1]<<8},JI=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},ZI=function(e,t){return JI(e,t)+4294967296*JI(e,t+4)},$I=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8},eP=function(e,t){var i=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=t.level<2?4:9==t.level?2:0,e[9]=3,0!=t.mtime&&$I(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),i){e[3]=8;for(var n=0;n<=i.length;++n)e[n+10]=i.charCodeAt(n)}},tP=function(e){(31!=e[0]||139!=e[1]||8!=e[2])&&yI(6,"invalid gzip data");var t=e[3],i=10;4&t&&(i+=2+(e[10]|e[11]<<8));for(var n=(t>>3&1)+(t>>4&1);n>0;n-=!e[i++]);return i+(2&t)},iP=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},nP=function(e){return 10+(e.filename?e.filename.length+1:0)},rP=function(e,t){var i=t.level,n=0==i?0:i<6?1:9==i?3:2;if(e[0]=120,e[1]=n<<6|(t.dictionary&&32),e[1]|=31-(e[0]<<8|e[1])%31,t.dictionary){var r=BI();r.p(t.dictionary),$I(e,2,r.d())}},sP=function(e,t){return(8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31)&&yI(6,"invalid zlib data"),(e[1]>>5&1)==+!t&&yI(6,"invalid zlib data: "+(32&e[1]?"need":"unexpected")+" dictionary"),2+(e[1]>>3&4)};function aP(e,t){return"function"==typeof e&&(t=e,e={}),this.ondata=t,e}var oP=function(){function e(e,t){if("function"==typeof e&&(t=e,e={}),this.ondata=t,this.o=e||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new QT(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 e.prototype.p=function(e,t){this.ondata(LI(e,this.o,0,0,this.s),t)},e.prototype.push=function(e,t){this.ondata||yI(5),this.s.l&&yI(4);var i=e.length+this.s.z;if(i>this.b.length){if(i>2*this.b.length-32768){var n=new QT(-32768&i);n.set(this.b.subarray(0,this.s.z)),this.b=n}var r=this.b.length-this.s.z;this.b.set(e.subarray(0,r),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(r),32768),this.s.z=e.length-r+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=1&t,(this.s.z>this.s.w+8191||t)&&(this.p(this.b,t||!1),this.s.w=this.s.i,this.s.i-=2)},e.prototype.flush=function(){this.ondata||yI(5),this.s.l&&yI(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},e}(),lP=function(e,t){YI([jI,function(){return[XI,oP]}],this,aP.call(this,e,t),function(e){var t=new oP(e.data);onmessage=XI(t)},6,1)};function cP(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&yI(7),qI(e,t,[jI],function(e){return HI(hP(e.data[0],e.data[1]))},0,i)}function hP(e,t){return LI(e,t||{},0,0)}var dP=function(){function e(e,t){"function"==typeof e&&(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 QT(32768),this.p=new QT(0),i&&this.o.set(i)}return e.prototype.e=function(e){if(this.ondata||yI(5),this.d&&yI(4),this.p.length){if(e.length){var t=new QT(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}}else this.p=e},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,i=vI(this.p,this.s,this.o);this.ondata(fI(i,t,this.s.b),this.d),this.o=fI(i,this.s.b-32768),this.s.b=this.o.length,this.p=fI(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),uP=function(e,t){YI([NI,function(){return[XI,dP]}],this,aP.call(this,e,t),function(e){var t=new dP(e.data);onmessage=XI(t)},7,0)};function pP(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&yI(7),qI(e,t,[NI],function(e){return HI(mP(e.data[0],WI(e.data[1])))},1,i)}function mP(e,t){return vI(e,{i:2},t&&t.out,t&&t.dictionary)}var gP=function(){function e(e,t){this.c=RI(),this.l=0,this.v=1,oP.call(this,e,t)}return e.prototype.push=function(e,t){this.c.p(e),this.l+=e.length,oP.prototype.push.call(this,e,t)},e.prototype.p=function(e,t){var i=LI(e,this.o,this.v&&nP(this.o),t&&8,this.s);this.v&&(eP(i,this.o),this.v=0),t&&($I(i,i.length-8,this.c.d()),$I(i,i.length-4,this.l)),this.ondata(i,t)},e.prototype.flush=function(){oP.prototype.flush.call(this)},e}(),fP=function(e,t){YI([jI,zI,function(){return[XI,oP,gP]}],this,aP.call(this,e,t),function(e){var t=new gP(e.data);onmessage=XI(t)},8,1)};function AP(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&yI(7),qI(e,t,[jI,zI,function(){return[yP]}],function(e){return HI(yP(e.data[0],e.data[1]))},2,i)}function yP(e,t){t||(t={});var i=RI(),n=e.length;i.p(e);var r=LI(e,t,nP(t),8),s=r.length;return eP(r,t),$I(r,s-8,i.d()),$I(r,s-4,n),r}var vP=function(){function e(e,t){this.v=1,this.r=0,dP.call(this,e,t)}return e.prototype.push=function(e,t){if(dP.prototype.e.call(this,e),this.r+=e.length,this.v){var i=this.p.subarray(this.v-1),n=i.length>3?tP(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}dP.prototype.c.call(this,t),this.s.f&&!this.s.l&&!t&&(this.v=gI(this.s.p)+9,this.s={i:0},this.o=new QT(0),this.push(new QT(0),t))},e}(),_P=function(e,t){var i=this;YI([NI,GI,function(){return[XI,dP,vP]}],this,aP.call(this,e,t),function(e){var t=new vP(e.data);t.onmember=function(e){return postMessage(e)},onmessage=XI(t)},9,0,function(e){return i.onmember&&i.onmember(e)})};function bP(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&yI(7),qI(e,t,[NI,GI,function(){return[xP]}],function(e){return HI(xP(e.data[0],e.data[1]))},3,i)}function xP(e,t){var i=tP(e);return i+8>e.length&&yI(6,"invalid gzip data"),vI(e.subarray(i,-8),{i:2},t&&t.out||new QT(iP(e)),t&&t.dictionary)}var wP=function(){function e(e,t){this.c=BI(),this.v=1,oP.call(this,e,t)}return e.prototype.push=function(e,t){this.c.p(e),oP.prototype.push.call(this,e,t)},e.prototype.p=function(e,t){var i=LI(e,this.o,this.v&&(this.o.dictionary?6:2),t&&4,this.s);this.v&&(rP(i,this.o),this.v=0),t&&$I(i,i.length-4,this.c.d()),this.ondata(i,t)},e.prototype.flush=function(){oP.prototype.flush.call(this)},e}(),CP=function(e,t){YI([jI,QI,function(){return[XI,oP,wP]}],this,aP.call(this,e,t),function(e){var t=new wP(e.data);onmessage=XI(t)},10,1)};function SP(e,t){t||(t={});var i=BI();i.p(e);var n=LI(e,t,t.dictionary?6:2,4);return rP(n,t),$I(n,n.length-4,i.d()),n}var MP=function(){function e(e,t){dP.call(this,e,t),this.v=e&&e.dictionary?2:1}return e.prototype.push=function(e,t){if(dP.prototype.e.call(this,e),this.v){if(this.p.length<6&&!t)return;this.p=this.p.subarray(sP(this.p,this.v-1)),this.v=0}t&&(this.p.length<4&&yI(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),dP.prototype.c.call(this,t)},e}(),EP=function(e,t){YI([NI,VI,function(){return[XI,dP,MP]}],this,aP.call(this,e,t),function(e){var t=new MP(e.data);onmessage=XI(t)},11,0)};function TP(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&yI(7),qI(e,t,[NI,VI,function(){return[IP]}],function(e){return HI(IP(e.data[0],WI(e.data[1])))},5,i)}function IP(e,t){return vI(e.subarray(sP(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}var PP=function(){function e(e,t){this.o=aP.call(this,e,t)||{},this.G=vP,this.I=dP,this.Z=MP}return e.prototype.i=function(){var e=this;this.s.ondata=function(t,i){e.ondata(t,i)}},e.prototype.push=function(e,t){if(this.ondata||yI(5),this.s)this.s.push(e,t);else{if(this.p&&this.p.length){var i=new QT(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=31==this.p[0]&&139==this.p[1]&&8==this.p[2]?new this.G(this.o):8!=(15&this.p[0])||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)}},e}(),DP=function(){function e(e,t){PP.call(this,e,t),this.queuedSize=0,this.G=_P,this.I=uP,this.Z=EP}return e.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)}},e.prototype.push=function(e,t){this.queuedSize+=e.length,PP.prototype.push.call(this,e,t)},e}();var RP=function(e,t,i,n){for(var r in e){var s=e[r],a=t+r,o=n;Array.isArray(s)&&(o=OI(n,s[1]),s=s[0]),s instanceof QT?i[a]=[s,o]:(i[a+="/"]=[new QT(0),o],RP(s,a,i,n))}},BP=typeof TextEncoder<"u"&&new TextEncoder,LP=typeof TextDecoder<"u"&&new TextDecoder,OP=0;try{LP.decode(II,{stream:!0}),OP=1}catch{}var UP=function(e){for(var t="",i=0;;){var n=e[i++],r=(n>127)+(n>223)+(n>239);if(i+r>e.length)return{s:t,r:fI(e,i-1)};r?3==r?(n=((15&n)<<18|(63&e[i++])<<12|(63&e[i++])<<6|63&e[i++])-65536,t+=String.fromCharCode(55296|n>>10,56320|1023&n)):t+=1&r?String.fromCharCode((31&n)<<6|63&e[i++]):String.fromCharCode((15&n)<<12|(63&e[i++])<<6|63&e[i++]):t+=String.fromCharCode(n)}},FP=function(){function e(e){this.ondata=e,OP?this.t=new TextDecoder:this.p=II}return e.prototype.push=function(e,t){if(this.ondata||yI(5),t=!!t,this.t)return this.ondata(this.t.decode(e,{stream:!0}),t),void(t&&(this.t.decode().length&&yI(8),this.t=null));this.p||yI(4);var i=new QT(this.p.length+e.length);i.set(this.p),i.set(e,this.p.length);var n=UP(i),r=n.s,s=n.r;t?(s.length&&yI(8),this.p=null):this.p=s,this.ondata(r,t)},e}(),kP=function(){function e(e){this.ondata=e}return e.prototype.push=function(e,t){this.ondata||yI(5),this.d&&yI(4),this.ondata(NP(e),this.d=t||!1)},e}();function NP(e,t){if(t){for(var i=new QT(e.length),n=0;n<e.length;++n)i[n]=e.charCodeAt(n);return i}if(BP)return BP.encode(e);var r=e.length,s=new QT(e.length+(e.length>>1)),a=0,o=function(e){s[a++]=e};for(n=0;n<r;++n){if(a+5>s.length){var l=new QT(a+8+(r-n<<1));l.set(s),s=l}var c=e.charCodeAt(n);c<128||t?o(c):c<2048?(o(192|c>>6),o(128|63&c)):c>55295&&c<57344?(o(240|(c=65536+(1047552&c)|1023&e.charCodeAt(++n))>>18),o(128|c>>12&63),o(128|c>>6&63),o(128|63&c)):(o(224|c>>12),o(128|c>>6&63),o(128|63&c))}return fI(s,0,a)}function jP(e,t){if(t){for(var i="",n=0;n<e.length;n+=16384)i+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return i}if(LP)return LP.decode(e);var r=UP(e),s=r.s;return(i=r.r).length&&yI(8),s}var zP=function(e){return 1==e?3:e<6?2:9==e?1:0},GP=function(e,t){return t+30+KI(e,t+26)+KI(e,t+28)},QP=function(e,t,i){var n=KI(e,t+28),r=jP(e.subarray(t+46,t+46+n),!(2048&KI(e,t+8))),s=t+46+n,a=JI(e,t+20),o=i&&4294967295==a?VP(e,s):[a,JI(e,t+24),JI(e,t+42)],l=o[0],c=o[1],h=o[2];return[KI(e,t+10),l,c,r,s+KI(e,t+30)+KI(e,t+32),h]},VP=function(e,t){for(;1!=KI(e,t);t+=4+KI(e,t+2));return[ZI(e,t+12),ZI(e,t+4),ZI(e,t+20)]},HP=function(e){var t=0;if(e)for(var i in e){var n=e[i].length;n>65535&&yI(9),t+=n+4}return t},WP=function(e,t,i,n,r,s,a,o){var l=n.length,c=i.extra,h=o&&o.length,d=HP(c);$I(e,t,null!=a?33639248:67324752),t+=4,null!=a&&(e[t++]=20,e[t++]=i.os),e[t]=20,t+=2,e[t++]=i.flag<<1|(s<0&&8),e[t++]=r&&8,e[t++]=255&i.compression,e[t++]=i.compression>>8;var u=new Date(null==i.mtime?Date.now():i.mtime),p=u.getFullYear()-1980;if((p<0||p>119)&&yI(10),$I(e,t,p<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),t+=4,-1!=s&&($I(e,t,i.crc),$I(e,t+4,s<0?-s-2:s),$I(e,t+8,i.size)),$I(e,t+12,l),$I(e,t+14,d),t+=16,null!=a&&($I(e,t,h),$I(e,t+6,i.attrs),$I(e,t+10,a),t+=14),e.set(n,t),t+=l,d)for(var m in c){var g=c[m],f=g.length;$I(e,t,+m),$I(e,t+2,f),e.set(g,t+4),t+=4+f}return h&&(e.set(o,t),t+=h),t},qP=function(e,t,i,n,r){$I(e,t,101010256),$I(e,t+8,i),$I(e,t+10,i),$I(e,t+12,n),$I(e,t+16,r)},XP=function(){function e(e){this.filename=e,this.c=RI(),this.size=0,this.compression=0}return e.prototype.process=function(e,t){this.ondata(null,e,t)},e.prototype.push=function(e,t){this.ondata||yI(5),this.c.p(e),this.size+=e.length,t&&(this.crc=this.c.d()),this.process(e,t||!1)},e}(),YP=function(){function e(e,t){var i=this;t||(t={}),XP.call(this,e),this.d=new oP(t,function(e,t){i.ondata(null,e,t)}),this.compression=8,this.flag=zP(t.level)}return e.prototype.process=function(e,t){try{this.d.push(e,t)}catch(e){this.ondata(e,null,t)}},e.prototype.push=function(e,t){XP.prototype.push.call(this,e,t)},e}(),KP=function(){function e(e,t){var i=this;t||(t={}),XP.call(this,e),this.d=new lP(t,function(e,t,n){i.ondata(e,t,n)}),this.compression=8,this.flag=zP(t.level),this.terminate=this.d.terminate}return e.prototype.process=function(e,t){this.d.push(e,t)},e.prototype.push=function(e,t){XP.prototype.push.call(this,e,t)},e}(),JP=function(){function e(e){this.ondata=e,this.u=[],this.d=1}return e.prototype.add=function(e){var t=this;if(this.ondata||yI(5),2&this.d)this.ondata(yI(4+8*(1&this.d),0,1),null,!1);else{var i=NP(e.filename),n=i.length,r=e.comment,s=r&&NP(r),a=n!=e.filename.length||s&&r.length!=s.length,o=n+HP(e.extra)+30;n>65535&&this.ondata(yI(11,0,1),null,!1);var l=new QT(o);WP(l,0,e,i,a,-1);var c=[l],h=function(){for(var e=0,i=c;e<i.length;e++){var n=i[e];t.ondata(null,n,!1)}c=[]},d=this.d;this.d=0;var u=this.u.length,p=OI(e,{f:i,u:a,o:s,t:function(){e.terminate&&e.terminate()},r:function(){if(h(),d){var e=t.u[u+1];e?e.r():t.d=1}d=1}}),m=0;e.ondata=function(i,n,r){if(i)t.ondata(i,n,r),t.terminate();else if(m+=n.length,c.push(n),r){var s=new QT(16);$I(s,0,134695760),$I(s,4,e.crc),$I(s,8,m),$I(s,12,e.size),c.push(s),p.c=m,p.b=o+m+16,p.crc=e.crc,p.size=e.size,d&&p.r(),d=1}else d&&h()},this.u.push(p)}},e.prototype.end=function(){var e=this;2&this.d?this.ondata(yI(4+8*(1&this.d),0,1),null,!0):(this.d?this.e():this.u.push({r:function(){1&e.d&&(e.u.splice(-1,1),e.e())},t:function(){}}),this.d=3)},e.prototype.e=function(){for(var e=0,t=0,i=0,n=0,r=this.u;n<r.length;n++){i+=46+(l=r[n]).f.length+HP(l.extra)+(l.o?l.o.length:0)}for(var s=new QT(i+22),a=0,o=this.u;a<o.length;a++){var l=o[a];WP(s,e,l,l.f,l.u,-l.c-2,t,l.o),e+=46+l.f.length+HP(l.extra)+(l.o?l.o.length:0),t+=l.b}qP(s,e,this.u.length,i,t),this.ondata(null,s,!0),this.d=2},e.prototype.terminate=function(){for(var e=0,t=this.u;e<t.length;e++){t[e].t()}this.d=2},e}();function ZP(e,t){t||(t={});var i={},n=[];RP(e,"",i,t);var r=0,s=0;for(var a in i){var o=i[a],l=o[0],c=o[1],h=0==c.level?0:8,d=(w=NP(a)).length,u=c.comment,p=u&&NP(u),m=p&&p.length,g=HP(c.extra);d>65535&&yI(11);var f=h?hP(l,c):l,A=f.length,y=RI();y.p(l),n.push(OI(c,{size:l.length,crc:y.d(),c:f,f:w,m:p,u:d!=a.length||p&&u.length!=m,o:r,compression:h})),r+=30+d+g+A,s+=76+2*(d+g)+(m||0)+A}for(var v=new QT(s+22),_=r,b=s-r,x=0;x<n.length;++x){var w=n[x];WP(v,w.o,w,w.f,w.u,w.c.length);var C=30+w.f.length+HP(w.extra);v.set(w.c,w.o+C),WP(v,r,w,w.f,w.u,w.c.length,w.o,w.m),r+=16+C+(w.m?w.m.length:0)}return qP(v,r,n.length,b,_),v}var $P=function(){function e(){}return e.prototype.push=function(e,t){this.ondata(null,e,t)},e.compression=0,e}(),eD=function(){function e(){var e=this;this.i=new dP(function(t,i){e.ondata(null,t,i)})}return e.prototype.push=function(e,t){try{this.i.push(e,t)}catch(e){this.ondata(e,null,t)}},e.compression=8,e}(),tD=function(){function e(e,t){var i=this;t<32e4?this.i=new dP(function(e,t){i.ondata(null,e,t)}):(this.i=new uP(function(e,t,n){i.ondata(e,t,n)}),this.terminate=this.i.terminate)}return e.prototype.push=function(e,t){this.i.terminate&&(e=fI(e,0)),this.i.push(e,t)},e.compression=8,e}(),iD=function(){function e(e){this.onfile=e,this.k=[],this.o={0:$P},this.p=II}return e.prototype.push=function(e,t){var i=this;if(this.onfile||yI(5),this.p||yI(4),this.c>0){var n=Math.min(this.c,e.length),r=e.subarray(0,n);if(this.c-=n,this.d?this.d.push(r,!this.c):this.k[0].push(r),(e=e.subarray(n)).length)return this.push(e,t)}else{var s=0,a=0,o=void 0,l=void 0;this.p.length?e.length?((l=new QT(this.p.length+e.length)).set(this.p),l.set(e,this.p.length)):l=this.p:l=e;for(var c=l.length,h=this.c,d=h&&this.d,u=function(){var e,t=JI(l,a);if(67324752==t){s=1,o=a,p.d=null,p.c=0;var n=KI(l,a+6),r=KI(l,a+8),d=2048&n,u=8&n,m=KI(l,a+26),g=KI(l,a+28);if(c>a+30+m+g){var f=[];p.k.unshift(f),s=2;var A=JI(l,a+18),y=JI(l,a+22),v=jP(l.subarray(a+30,a+=30+m),!d);4294967295==A?(e=u?[-2]:VP(l,a),A=e[0],y=e[1]):u&&(A=-1),a+=g,p.c=A;var _,b={name:v,compression:r,start:function(){if(b.ondata||yI(5),A){var e=i.o[r];e||b.ondata(yI(14,"unknown compression type "+r,1),null,!1),(_=A<0?new e(v):new e(v,A,y)).ondata=function(e,t,i){b.ondata(e,t,i)};for(var t=0,n=f;t<n.length;t++){var s=n[t];_.push(s,!1)}i.k[0]==f&&i.c?i.d=_:_.push(II,!0)}else b.ondata(null,II,!0)},terminate:function(){_&&_.terminate&&_.terminate()}};A>=0&&(b.size=A,b.originalSize=y),p.onfile(b)}return"break"}if(h){if(134695760==t)return o=a+=12+(-2==h&&8),s=3,p.c=0,"break";if(33639248==t)return o=a-=4,s=3,p.c=0,"break"}},p=this;a<c-4;++a){if("break"===u())break}if(this.p=II,h<0){var m=s?l.subarray(0,o-12-(-2==h&&8)-(134695760==JI(l,o-16)&&4)):l.subarray(0,a);d?d.push(m,!!s):this.k[+(2==s)].push(m)}if(2&s)return this.push(l.subarray(a),t);this.p=l.subarray(a)}t&&(this.c&&yI(13),this.p=null)},e.prototype.register=function(e){this.o[e.compression]=e},e}(),nD="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function rD(e,t){for(var i={},n=e.length-22;101010256!=JI(e,n);--n)(!n||e.length-n>65558)&&yI(13);var r=KI(e,n+8);if(!r)return{};var s=JI(e,n+16),a=4294967295==s||65535==r;if(a){var o=JI(e,n-12);(a=101075792==JI(e,o))&&(r=JI(e,o+32),s=JI(e,o+48))}for(var l=t&&t.filter,c=0;c<r;++c){var h=QP(e,s,a),d=h[0],u=h[1],p=h[2],m=h[3],g=h[4],f=h[5],A=GP(e,f);s=g,(!l||l({name:m,size:u,originalSize:p,compression:d}))&&(d?8==d?i[m]=mP(e.subarray(A,A+u),{out:new QT(p)}):yI(14,"unknown compression type "+d):i[m]=fI(e,A,A+u))}return i}function sD(e,t,i){const n=i.length-e-1;if(t>=i[n])return n-1;if(t<=i[e])return e;let r=e,s=n,a=Math.floor((r+s)/2);for(;t<i[a]||t>=i[a+1];)t<i[a]?s=a:r=a,a=Math.floor((r+s)/2);return a}function aD(e,t){let i=1;for(let t=2;t<=e;++t)i*=t;let n=1;for(let e=2;e<=t;++e)n*=e;for(let i=2;i<=e-t;++i)n*=i;return i/n}function oD(e,t,i,n,r){const s=function(e,t,i,n,r){const s=r<e?r:e,a=[],o=sD(e,n,t),l=function(e,t,i,n,r){const s=[];for(let e=0;e<=i;++e)s[e]=0;const a=[];for(let e=0;e<=n;++e)a[e]=s.slice(0);const o=[];for(let e=0;e<=i;++e)o[e]=s.slice(0);o[0][0]=1;const l=s.slice(0),c=s.slice(0);for(let n=1;n<=i;++n){l[n]=t-r[e+1-n],c[n]=r[e+n]-t;let i=0;for(let e=0;e<n;++e){const t=c[e+1],r=l[n-e];o[n][e]=t+r;const s=o[e][n-1]/o[n][e];o[e][n]=i+t*s,i=r*s}o[n][n]=i}for(let e=0;e<=i;++e)a[0][e]=o[e][i];for(let e=0;e<=i;++e){let t=0,r=1;const l=[];for(let e=0;e<=i;++e)l[e]=s.slice(0);l[0][0]=1;for(let s=1;s<=n;++s){let n=0;const c=e-s,h=i-s;e>=s&&(l[r][0]=l[t][0]/o[h+1][c],n=l[r][0]*o[c][h]);const d=e-1<=h?s-1:i-e;for(let e=c>=-1?1:-c;e<=d;++e)l[r][e]=(l[t][e]-l[t][e-1])/o[h+1][c+e],n+=l[r][e]*o[c+e][h];e<=h&&(l[r][s]=-l[t][s-1]/o[h+1][e],n+=l[r][s]*o[e][h]),a[s][e]=n;const u=t;t=r,r=u}}let h=i;for(let e=1;e<=n;++e){for(let t=0;t<=i;++t)a[e][t]*=h;h*=i-e}return a}(o,n,e,s,t),c=[];for(let e=0;e<i.length;++e){const t=i[e].clone(),n=t.w;t.x*=n,t.y*=n,t.z*=n,c[e]=t}for(let t=0;t<=s;++t){const i=c[o-e].clone().multiplyScalar(l[t][0]);for(let n=1;n<=e;++n)i.add(c[o-e+n].clone().multiplyScalar(l[t][n]));a[t]=i}for(let e=s+1;e<=r+1;++e)a[e]=new Gi(0,0,0);return a}(e,t,i,n,r);return function(e){const t=e.length,i=[],n=[];for(let r=0;r<t;++r){const t=e[r];i[r]=new Xi(t.x,t.y,t.z),n[r]=t.w}const r=[];for(let e=0;e<t;++e){const t=i[e].clone();for(let i=1;i<=e;++i)t.sub(r[e-i].clone().multiplyScalar(aD(e,i)*n[i]));r[e]=t.divideScalar(n[0])}return r}(s)}class lD extends nh{constructor(e,t,i,n,r){super(),this.degree=e,this.knots=t,this.controlPoints=[],this.startKnot=n||0,this.endKnot=r||this.knots.length-1;for(let e=0;e<i.length;++e){const t=i[e];this.controlPoints[e]=new Gi(t.x,t.y,t.z,t.w)}}getPoint(e,t=new Xi){const i=t,n=this.knots[this.startKnot]+e*(this.knots[this.endKnot]-this.knots[this.startKnot]),r=function(e,t,i,n){const r=sD(e,n,t),s=function(e,t,i,n){const r=[],s=[],a=[];r[0]=1;for(let o=1;o<=i;++o){s[o]=t-n[e+1-o],a[o]=n[e+o]-t;let i=0;for(let e=0;e<o;++e){const t=a[e+1],n=s[o-e],l=r[e]/(t+n);r[e]=i+t*l,i=n*l}r[o]=i}return r}(r,n,e,t),a=new Gi(0,0,0,0);for(let t=0;t<=e;++t){const n=i[r-e+t],o=s[t],l=n.w*o;a.x+=n.x*l,a.y+=n.y*l,a.z+=n.z*l,a.w+=n.w*o}return a}(this.degree,this.knots,this.controlPoints,n);return 1!==r.w&&r.divideScalar(r.w),i.set(r.x,r.y,r.z)}getTangent(e,t=new Xi){const i=t,n=this.knots[0]+e*(this.knots[this.knots.length-1]-this.knots[0]),r=oD(this.degree,this.knots,this.controlPoints,n,1);return i.copy(r[1]).normalize(),i}}let cD,hD,dD;class uD extends su{constructor(e){super(e)}load(e,t,i,n){const r=this,s=""===r.path?Bu.extractUrlBase(e):r.path,a=new lu(this.manager);a.setPath(r.path),a.setResponseType("arraybuffer"),a.setRequestHeader(r.requestHeader),a.setWithCredentials(r.withCredentials),a.load(e,function(i){try{t(r.parse(i,s))}catch(t){n?n(t):console.error(t),r.manager.itemError(e)}},i,n)}parse(e,t){if(function(e){const t="Kaydara FBX Binary  \0";return e.byteLength>=t.length&&t===ID(e,0,t.length)}(e))cD=(new AD).parse(e);else{const t=ID(e);if(!function(e){const t=["K","a","y","d","a","r","a","\\","F","B","X","\\","B","i","n","a","r","y","\\","\\"];let i=0;function n(t){const n=e[t-1];return e=e.slice(i+t),i++,n}for(let e=0;e<t.length;++e)if(n(1)===t[e])return!1;return!0}(t))throw new Error("THREE.FBXLoader: Unknown format.");if(_D(t)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+_D(t));cD=(new fD).parse(t)}const i=new uu(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin),n=new pD(i,this.manager).parse(cD);return cD=null,hD=null,dD=null,n}}class pD{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){hD=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),i=this.parseMaterials(t),n=this.parseDeformers(),r=(new mD).parse(n);return this.parseScene(n,r,i),dD}parseConnections(){const e=new Map;return"Connections"in cD&&cD.Connections.connections.forEach(function(t){const i=t[0],n=t[1],r=t[2];e.has(i)||e.set(i,{parents:[],children:[]});const s={ID:n,relationship:r};e.get(i).parents.push(s),e.has(n)||e.set(n,{parents:[],children:[]});const a={ID:i,relationship:r};e.get(n).children.push(a)}),e}parseImages(){const e={},t={};if("Video"in cD.Objects){const i=cD.Objects.Video;for(const n in i){const r=i[n];if(e[parseInt(n)]=r.RelativeFilename||r.Filename,"Content"in r){const e=r.Content instanceof ArrayBuffer&&r.Content.byteLength>0,s="string"==typeof r.Content&&""!==r.Content;if(e||s){const e=this.parseImage(i[n]);t[r.RelativeFilename||r.Filename]=e}}}}for(const i in e){const n=e[i];void 0!==t[n]?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 r;switch(n){case"bmp":r="image/bmp";break;case"jpg":case"jpeg":r="image/jpeg";break;case"png":r="image/png";break;case"tif":r="image/tiff";break;case"tga":null===this.manager.getHandler(".tga")&&console.warn("FBXLoader: TGA loader not found, skipping ",i),r="image/tga";break;default:return void console.warn('FBXLoader: Image type "'+n+'" is not supported.')}if("string"==typeof t)return"data:"+r+";base64,"+t;{const e=new Uint8Array(t);return window.URL.createObjectURL(new Blob([e],{type:r}))}}parseTextures(e){const t=new Map;if("Texture"in cD.Objects){const i=cD.Objects.Texture;for(const n in i){const r=this.parseTexture(i[n],e);t.set(parseInt(n),r)}}return t}parseTexture(e,t){const i=this.loadTexture(e,t);i.ID=e.id,i.name=e.attrName;const n=e.WrapModeU,r=e.WrapModeV,s=void 0!==n?n.value:0,a=void 0!==r?r.value:0;if(i.wrapS=0===s?ge:fe,i.wrapT=0===a?ge:fe,"Scaling"in e){const t=e.Scaling.value;i.repeat.x=t[0],i.repeat.y=t[1]}if("Translation"in e){const t=e.Translation.value;i.offset.x=t[0],i.offset.y=t[1]}return i}loadTexture(e,t){const i=new Set(["tga","tif","tiff","exr","dds","hdr","ktx2"]),n=e.FileName.split(".").pop().toLowerCase(),r=i.has(n)?this.manager.getHandler(`.${n}`):this.textureLoader;if(!r)return console.warn(`FBXLoader: ${n.toUpperCase()} loader not found, creating placeholder texture for`,e.RelativeFilename),new Ni;const s=r.path;s||r.setPath(this.textureLoader.path);const a=hD.get(e.id).children;let o;void 0!==a&&a.length>0&&void 0!==t[a[0].ID]&&(o=t[a[0].ID],(0===o.indexOf("blob:")||0===o.indexOf("data:"))&&r.setPath(void 0));const l=r.load(o);return r.setPath(s),l}parseMaterials(e){const t=new Map;if("Material"in cD.Objects){const i=cD.Objects.Material;for(const n in i){const r=this.parseMaterial(i[n],e);null!==r&&t.set(parseInt(n),r)}}return t}parseMaterial(e,t){const i=e.id,n=e.attrName;let r=e.ShadingModel;if("object"==typeof r&&(r=r.value),!hD.has(i))return null;const s=this.parseParameters(e,t,i);let a;switch(r.toLowerCase()){case"phong":a=new Pd;break;case"lambert":a=new Bd;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',r),a=new Pd}return a.setValues(s),a.name=n,a}parseParameters(e,t,i){const n={};e.BumpFactor&&(n.bumpScale=e.BumpFactor.value),e.Diffuse?n.color=(new mr).fromArray(e.Diffuse.value).convertSRGBToLinear():e.DiffuseColor&&("Color"===e.DiffuseColor.type||"ColorRGB"===e.DiffuseColor.type)&&(n.color=(new mr).fromArray(e.DiffuseColor.value).convertSRGBToLinear()),e.DisplacementFactor&&(n.displacementScale=e.DisplacementFactor.value),e.Emissive?n.emissive=(new mr).fromArray(e.Emissive.value).convertSRGBToLinear():e.EmissiveColor&&("Color"===e.EmissiveColor.type||"ColorRGB"===e.EmissiveColor.type)&&(n.emissive=(new mr).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 mr).fromArray(e.Specular.value).convertSRGBToLinear():e.SpecularColor&&"Color"===e.SpecularColor.type&&(n.specular=(new mr).fromArray(e.SpecularColor.value).convertSRGBToLinear());const r=this;return hD.get(i).children.forEach(function(e){const i=e.relationship;switch(i){case"Bump":n.bumpMap=r.getTexture(t,e.ID);break;case"Maya|TEX_ao_map":n.aoMap=r.getTexture(t,e.ID);break;case"DiffuseColor":case"Maya|TEX_color_map":n.map=r.getTexture(t,e.ID),void 0!==n.map&&(n.map.colorSpace=Ot);break;case"DisplacementColor":n.displacementMap=r.getTexture(t,e.ID);break;case"EmissiveColor":n.emissiveMap=r.getTexture(t,e.ID),void 0!==n.emissiveMap&&(n.emissiveMap.colorSpace=Ot);break;case"NormalMap":case"Maya|TEX_normal_map":n.normalMap=r.getTexture(t,e.ID);break;case"ReflectionColor":n.envMap=r.getTexture(t,e.ID),void 0!==n.envMap&&(n.envMap.mapping=ue,n.envMap.colorSpace=Ot);break;case"SpecularColor":n.specularMap=r.getTexture(t,e.ID),void 0!==n.specularMap&&(n.specularMap.colorSpace=Ot);break;case"TransparentColor":case"TransparencyFactor":n.alphaMap=r.getTexture(t,e.ID),n.transparent=!0;break;default:console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",i)}}),n}getTexture(e,t){return"LayeredTexture"in cD.Objects&&t in cD.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=hD.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in cD.Objects){const i=cD.Objects.Deformer;for(const n in i){const r=i[n],s=hD.get(parseInt(n));if("Skin"===r.attrType){const t=this.parseSkeleton(s,i);t.ID=n,s.parents.length>1&&console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported."),t.geometryID=s.parents[0].ID,e[n]=t}else if("BlendShape"===r.attrType){const e={id:n};e.rawTargets=this.parseMorphTargets(s,i),e.id=n,s.parents.length>1&&console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported."),t[n]=e}}}return{skeletons:e,morphTargets:t}}parseSkeleton(e,t){const i=[];return e.children.forEach(function(e){const n=t[e.ID];if("Cluster"!==n.attrType)return;const r={ID:e.ID,indices:[],weights:[],transformLink:(new Sn).fromArray(n.TransformLink.a)};"Indexes"in n&&(r.indices=n.Indexes.a,r.weights=n.Weights.a),i.push(r)}),{rawBones:i,bones:[]}}parseMorphTargets(e,t){const i=[];for(let n=0;n<e.children.length;n++){const r=e.children[n],s=t[r.ID],a={name:s.attrName,initialWeight:s.DeformPercent,id:s.id,fullWeights:s.FullWeights.a};if("BlendShapeChannel"!==s.attrType)return;a.geoID=hD.get(parseInt(r.ID)).children.filter(function(e){return void 0===e.relationship})[0].ID,i.push(a)}return i}parseScene(e,t,i){dD=new ll;const n=this.parseModels(e.skeletons,t,i),r=cD.Objects.Model,s=this;n.forEach(function(e){const t=r[e.ID];s.setLookAtProperties(e,t),hD.get(e.ID).parents.forEach(function(t){const i=n.get(t.ID);void 0!==i&&i.add(e)}),null===e.parent&&dD.add(e)}),this.bindSkeleton(e.skeletons,t,n),this.addGlobalSceneSettings(),dD.traverse(function(e){if(e.userData.transformData){e.parent&&(e.userData.transformData.parentMatrix=e.parent.matrix,e.userData.transformData.parentMatrixWorld=e.parent.matrixWorld);const t=MD(e.userData.transformData);e.applyMatrix4(t),e.updateWorldMatrix()}});const a=(new gD).parse();1===dD.children.length&&dD.children[0].isGroup&&(dD.children[0].animations=a,dD=dD.children[0]),dD.animations=a}parseModels(e,t,i){const n=new Map,r=cD.Objects.Model;for(const s in r){const a=parseInt(s),o=r[s],l=hD.get(a);let c=this.buildSkeleton(l,e,a,o.attrName);if(!c){switch(o.attrType){case"Camera":c=this.createCamera(l);break;case"Light":c=this.createLight(l);break;case"Mesh":c=this.createMesh(l,t,i);break;case"NurbsCurve":c=this.createCurve(l,t);break;case"LimbNode":case"Root":c=new $l;break;default:c=new ll}c.name=o.attrName?mp.sanitizeNodeName(o.attrName):"",c.userData.originalName=o.attrName,c.ID=a}this.getTransformData(c,o),n.set(a,c)}return n}buildSkeleton(e,t,i,n){let r=null;return e.parents.forEach(function(e){for(const s in t){const a=t[s];a.rawBones.forEach(function(t,s){if(t.ID===e.ID){const e=r;r=new $l,r.matrixWorld.copy(t.transformLink),r.name=n?mp.sanitizeNodeName(n):"",r.userData.originalName=n,r.ID=i,a.bones[s]=r,null!==e&&r.add(e)}})}}),r}createCamera(e){let t,i;if(e.children.forEach(function(e){const t=cD.Objects.NodeAttribute[e.ID];void 0!==t&&(i=t)}),void 0===i)t=new Zn;else{let e=0;void 0!==i.CameraProjectionType&&1===i.CameraProjectionType.value&&(e=1);let n=1;void 0!==i.NearPlane&&(n=i.NearPlane.value/1e3);let r=1e3;void 0!==i.FarPlane&&(r=i.FarPlane.value/1e3);let s=window.innerWidth,a=window.innerHeight;void 0!==i.AspectWidth&&void 0!==i.AspectHeight&&(s=i.AspectWidth.value,a=i.AspectHeight.value);const o=s/a;let l=45;void 0!==i.FieldOfView&&(l=i.FieldOfView.value);const c=i.FocalLength?i.FocalLength.value:null;switch(e){case 0:t=new ps(l,o,n,r),null!==c&&t.setFocalLength(c);break;case 1:t=new zs(-s/2,s/2,a/2,-a/2,n,r);break;default:console.warn("THREE.FBXLoader: Unknown camera type "+e+"."),t=new Zn}}return t}createLight(e){let t,i;if(e.children.forEach(function(e){const t=cD.Objects.NodeAttribute[e.ID];void 0!==t&&(i=t)}),void 0===i)t=new Zn;else{let e;e=void 0===i.LightType?0:i.LightType.value;let n=16777215;void 0!==i.Color&&(n=(new mr).fromArray(i.Color.value).convertSRGBToLinear());let r=void 0===i.Intensity?1:i.Intensity.value/100;void 0!==i.CastLightOnObject&&0===i.CastLightOnObject.value&&(r=0);let s=0;void 0!==i.FarAttenuationEnd&&(s=void 0!==i.EnableFarAttenuation&&0===i.EnableFarAttenuation.value?0:i.FarAttenuationEnd.value);const a=1;switch(e){case 0:t=new Su(n,r,s,a);break;case 1:t=new Eu(n,r);break;case 2:let e=Math.PI/3;void 0!==i.InnerAngle&&(e=gi.degToRad(i.InnerAngle.value));let o=0;void 0!==i.OuterAngle&&(o=gi.degToRad(i.OuterAngle.value),o=Math.max(o,1)),t=new _u(n,r,s,e,o,a);break;default:console.warn("THREE.FBXLoader: Unknown light type "+i.LightType.value+", defaulting to a PointLight."),t=new Su(n,r)}void 0!==i.CastShadows&&1===i.CastShadows.value&&(t.castShadow=!0)}return t}createMesh(e,t,i){let n,r=null,s=null;const a=[];return e.children.forEach(function(e){t.has(e.ID)&&(r=t.get(e.ID)),i.has(e.ID)&&a.push(i.get(e.ID))}),a.length>1?s=a:a.length>0?s=a[0]:(s=new Pd({name:su.DEFAULT_MATERIAL_NAME,color:13421772}),a.push(s)),"color"in r.attributes&&a.forEach(function(e){e.vertexColors=!0}),r.FBX_Deformer?(n=new Zl(r,s),n.normalizeSkinWeights()):n=new ts(r,s),n}createCurve(e,t){const i=e.children.reduce(function(e,i){return t.has(i.ID)&&(e=t.get(i.ID)),e},null),n=new Dc({name:su.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new Nc(i,n)}getTransformData(e,t){const i={};"InheritType"in t&&(i.inheritType=parseInt(t.InheritType.value)),i.eulerOrder="RotationOrder"in t?ED(t.RotationOrder.value):"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&&hD.get(e.ID).children.forEach(function(t){if("LookAtProperty"===t.relationship){const i=cD.Objects.Model[t.ID];if("Lcl_Translation"in i){const t=i.Lcl_Translation.value;void 0!==e.target?(e.target.position.fromArray(t),dD.add(e.target)):e.lookAt((new Xi).fromArray(t))}}})}bindSkeleton(e,t,i){const n=this.parsePoseNodes();for(const r in e){const s=e[r];hD.get(parseInt(s.ID)).parents.forEach(function(e){if(t.has(e.ID)){const t=e.ID;hD.get(t).parents.forEach(function(e){i.has(e.ID)&&i.get(e.ID).bind(new nc(s.bones),n[e.ID])})}})}}parsePoseNodes(){const e={};if("Pose"in cD.Objects){const t=cD.Objects.Pose;for(const i in t)if("BindPose"===t[i].attrType&&t[i].NbPoseNodes>0){const n=t[i].PoseNode;Array.isArray(n)?n.forEach(function(t){e[t.Node]=(new Sn).fromArray(t.Matrix.a)}):e[n.Node]=(new Sn).fromArray(n.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in cD){if("AmbientColor"in cD.GlobalSettings){const e=cD.GlobalSettings.AmbientColor.value,t=e[0],i=e[1],n=e[2];if(0!==t||0!==i||0!==n){const e=new mr(t,i,n).convertSRGBToLinear();dD.add(new Tu(e,1))}}"UnitScaleFactor"in cD.GlobalSettings&&(dD.userData.unitScaleFactor=cD.GlobalSettings.UnitScaleFactor.value)}}}class mD{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in cD.Objects){const i=cD.Objects.Geometry;for(const n in i){const r=hD.get(parseInt(n)),s=this.parseGeometry(r,i[n],e);t.set(parseInt(n),s)}}return!0===this.negativeMaterialIndices&&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,r=[],s=e.parents.map(function(e){return cD.Objects.Model[e.ID]});if(0===s.length)return;const a=e.children.reduce(function(e,t){return void 0!==n[t.ID]&&(e=n[t.ID]),e},null);e.children.forEach(function(e){void 0!==i.morphTargets[e.ID]&&r.push(i.morphTargets[e.ID])});const o=s[0],l={};"RotationOrder"in o&&(l.eulerOrder=ED(o.RotationOrder.value)),"InheritType"in o&&(l.inheritType=parseInt(o.InheritType.value)),"GeometricTranslation"in o&&(l.translation=o.GeometricTranslation.value),"GeometricRotation"in o&&(l.rotation=o.GeometricRotation.value),"GeometricScaling"in o&&(l.scale=o.GeometricScaling.value);const c=MD(l);return this.genGeometry(t,a,r,c)}genGeometry(e,t,i,n){const r=new Fr;e.attrName&&(r.name=e.attrName);const s=this.parseGeoNode(e,t),a=this.genBuffers(s),o=new Ir(a.vertex,3);if(o.applyMatrix4(n),r.setAttribute("position",o),a.colors.length>0&&r.setAttribute("color",new Ir(a.colors,3)),t&&(r.setAttribute("skinIndex",new Er(a.weightsIndices,4)),r.setAttribute("skinWeight",new Ir(a.vertexWeights,4)),r.FBX_Deformer=t),a.normal.length>0){const e=(new Ai).getNormalMatrix(n),t=new Ir(a.normal,3);t.applyNormalMatrix(e),r.setAttribute("normal",t)}if(a.uvs.forEach(function(e,t){const i=0===t?"uv":`uv${t}`;r.setAttribute(i,new Ir(a.uvs[t],2))}),s.material&&"AllSame"!==s.material.mappingType){let e=a.materialIndex[0],t=0;if(a.materialIndex.forEach(function(i,n){i!==e&&(r.addGroup(t,n-t,e),e=i,t=n)}),r.groups.length>0){const t=r.groups[r.groups.length-1],i=t.start+t.count;i!==a.materialIndex.length&&r.addGroup(i,a.materialIndex.length-i,e)}0===r.groups.length&&r.addGroup(0,a.materialIndex.length,a.materialIndex[0])}return this.addMorphTargets(r,e,i,n),r}parseGeoNode(e,t){const i={};if(i.vertexPositions=void 0!==e.Vertices?e.Vertices.a:[],i.vertexIndices=void 0!==e.PolygonVertexIndex?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 t=0;for(;e.LayerElementUV[t];)e.LayerElementUV[t].UV&&i.uv.push(this.parseUVs(e.LayerElementUV[t])),t++}return i.weightTable={},null!==t&&(i.skeleton=t,t.rawBones.forEach(function(e,t){e.indices.forEach(function(n,r){void 0===i.weightTable[n]&&(i.weightTable[n]=[]),i.weightTable[n].push({id:t,weight:e.weights[r]})})})),i}genBuffers(e){const t={vertex:[],normal:[],colors:[],uvs:[],materialIndex:[],vertexWeights:[],weightsIndices:[]};let i=0,n=0,r=!1,s=[],a=[],o=[],l=[],c=[],h=[];const d=this;return e.vertexIndices.forEach(function(u,p){let m,g=!1;u<0&&(u^=-1,g=!0);let f=[],A=[];if(s.push(3*u,3*u+1,3*u+2),e.color){const t=wD(p,i,u,e.color);o.push(t[0],t[1],t[2])}if(e.skeleton){if(void 0!==e.weightTable[u]&&e.weightTable[u].forEach(function(e){A.push(e.weight),f.push(e.id)}),A.length>4){r||(console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."),r=!0);const e=[0,0,0,0],t=[0,0,0,0];A.forEach(function(i,n){let r=i,s=f[n];t.forEach(function(t,i,n){if(r>t){n[i]=r,r=t;const a=e[i];e[i]=s,s=a}})}),f=e,A=t}for(;A.length<4;)A.push(0),f.push(0);for(let e=0;e<4;++e)c.push(A[e]),h.push(f[e])}if(e.normal){const t=wD(p,i,u,e.normal);a.push(t[0],t[1],t[2])}e.material&&"AllSame"!==e.material.mappingType&&(m=wD(p,i,u,e.material)[0],m<0&&(d.negativeMaterialIndices=!0,m=0)),e.uv&&e.uv.forEach(function(e,t){const n=wD(p,i,u,e);void 0===l[t]&&(l[t]=[]),l[t].push(n[0]),l[t].push(n[1])}),n++,g&&(d.genFace(t,e,s,m,a,o,l,c,h,n),i++,n=0,s=[],a=[],o=[],l=[],c=[],h=[])}),t}getNormalNewell(e){const t=new Xi(0,0,0);for(let i=0;i<e.length;i++){const n=e[i],r=e[(i+1)%e.length];t.x+=(n.y-r.y)*(n.z+r.z),t.y+=(n.z-r.z)*(n.x+r.x),t.z+=(n.x-r.x)*(n.y+r.y)}return t.normalize(),t}getNormalTangentAndBitangent(e){const t=this.getNormalNewell(e),i=(Math.abs(t.z)>.5?new Xi(0,1,0):new Xi(0,0,1)).cross(t).normalize(),n=t.clone().cross(i).normalize();return{normal:t,tangent:i,bitangent:n}}flattenVertex(e,t,i){return new fi(e.dot(t),e.dot(i))}genFace(e,t,i,n,r,s,a,o,l,c){let h;if(c>3){const e=[],n=t.baseVertexPositions||t.vertexPositions;for(let t=0;t<i.length;t+=3)e.push(new Xi(n[i[t]],n[i[t+1]],n[i[t+2]]));const{tangent:r,bitangent:s}=this.getNormalTangentAndBitangent(e),a=[];for(const t of e)a.push(this.flattenVertex(t,r,s));h=cd.triangulateShape(a,[])}else h=[[0,1,2]];for(const[c,d,u]of h)e.vertex.push(t.vertexPositions[i[3*c]]),e.vertex.push(t.vertexPositions[i[3*c+1]]),e.vertex.push(t.vertexPositions[i[3*c+2]]),e.vertex.push(t.vertexPositions[i[3*d]]),e.vertex.push(t.vertexPositions[i[3*d+1]]),e.vertex.push(t.vertexPositions[i[3*d+2]]),e.vertex.push(t.vertexPositions[i[3*u]]),e.vertex.push(t.vertexPositions[i[3*u+1]]),e.vertex.push(t.vertexPositions[i[3*u+2]]),t.skeleton&&(e.vertexWeights.push(o[4*c]),e.vertexWeights.push(o[4*c+1]),e.vertexWeights.push(o[4*c+2]),e.vertexWeights.push(o[4*c+3]),e.vertexWeights.push(o[4*d]),e.vertexWeights.push(o[4*d+1]),e.vertexWeights.push(o[4*d+2]),e.vertexWeights.push(o[4*d+3]),e.vertexWeights.push(o[4*u]),e.vertexWeights.push(o[4*u+1]),e.vertexWeights.push(o[4*u+2]),e.vertexWeights.push(o[4*u+3]),e.weightsIndices.push(l[4*c]),e.weightsIndices.push(l[4*c+1]),e.weightsIndices.push(l[4*c+2]),e.weightsIndices.push(l[4*c+3]),e.weightsIndices.push(l[4*d]),e.weightsIndices.push(l[4*d+1]),e.weightsIndices.push(l[4*d+2]),e.weightsIndices.push(l[4*d+3]),e.weightsIndices.push(l[4*u]),e.weightsIndices.push(l[4*u+1]),e.weightsIndices.push(l[4*u+2]),e.weightsIndices.push(l[4*u+3])),t.color&&(e.colors.push(s[3*c]),e.colors.push(s[3*c+1]),e.colors.push(s[3*c+2]),e.colors.push(s[3*d]),e.colors.push(s[3*d+1]),e.colors.push(s[3*d+2]),e.colors.push(s[3*u]),e.colors.push(s[3*u+1]),e.colors.push(s[3*u+2])),t.material&&"AllSame"!==t.material.mappingType&&(e.materialIndex.push(n),e.materialIndex.push(n),e.materialIndex.push(n)),t.normal&&(e.normal.push(r[3*c]),e.normal.push(r[3*c+1]),e.normal.push(r[3*c+2]),e.normal.push(r[3*d]),e.normal.push(r[3*d+1]),e.normal.push(r[3*d+2]),e.normal.push(r[3*u]),e.normal.push(r[3*u+1]),e.normal.push(r[3*u+2])),t.uv&&t.uv.forEach(function(t,i){void 0===e.uvs[i]&&(e.uvs[i]=[]),e.uvs[i].push(a[i][2*c]),e.uvs[i].push(a[i][2*c+1]),e.uvs[i].push(a[i][2*d]),e.uvs[i].push(a[i][2*d+1]),e.uvs[i].push(a[i][2*u]),e.uvs[i].push(a[i][2*u+1])})}addMorphTargets(e,t,i,n){if(0===i.length)return;e.morphTargetsRelative=!0,e.morphAttributes.position=[];const r=this;i.forEach(function(i){i.rawTargets.forEach(function(i){const s=cD.Objects.Geometry[i.geoID];void 0!==s&&r.genMorphGeometry(e,t,s,n,i.name)})})}genMorphGeometry(e,t,i,n,r){const s=void 0!==t.Vertices?t.Vertices.a:[],a=void 0!==t.PolygonVertexIndex?t.PolygonVertexIndex.a:[],o=void 0!==i.Vertices?i.Vertices.a:[],l=void 0!==i.Indexes?i.Indexes.a:[],c=3*e.attributes.position.count,h=new Float32Array(c);for(let e=0;e<l.length;e++){const t=3*l[e];h[t]=o[3*e],h[t+1]=o[3*e+1],h[t+2]=o[3*e+2]}const d={vertexIndices:a,vertexPositions:h,baseVertexPositions:s},u=this.genBuffers(d),p=new Ir(u.vertex,3);p.name=r||i.attrName,p.applyMatrix4(n),e.morphAttributes.position.push(p)}parseNormals(e){const t=e.MappingInformationType,i=e.ReferenceInformationType,n=e.Normals.a;let r=[];return"IndexToDirect"===i&&("NormalIndex"in e?r=e.NormalIndex.a:"NormalsIndex"in e&&(r=e.NormalsIndex.a)),{dataSize:3,buffer:n,indices:r,mappingType:t,referenceType:i}}parseUVs(e){const t=e.MappingInformationType,i=e.ReferenceInformationType,n=e.UV.a;let r=[];return"IndexToDirect"===i&&(r=e.UVIndex.a),{dataSize:2,buffer:n,indices:r,mappingType:t,referenceType:i}}parseVertexColors(e){const t=e.MappingInformationType,i=e.ReferenceInformationType,n=e.Colors.a;let r=[];"IndexToDirect"===i&&(r=e.ColorIndex.a);for(let e=0,t=new mr;e<n.length;e+=4)t.fromArray(n,e).convertSRGBToLinear().toArray(n,e);return{dataSize:4,buffer:n,indices:r,mappingType:t,referenceType:i}}parseMaterialIndices(e){const t=e.MappingInformationType,i=e.ReferenceInformationType;if("NoMappingInformation"===t)return{dataSize:1,buffer:[0],indices:[0],mappingType:"AllSame",referenceType:i};const n=e.Materials.a,r=[];for(let e=0;e<n.length;++e)r.push(e);return{dataSize:1,buffer:n,indices:r,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 Fr;const i=t-1,n=e.KnotVector.a,r=[],s=e.Points.a;for(let e=0,t=s.length;e<t;e+=4)r.push((new Gi).fromArray(s,e));let a,o;if("Closed"===e.Form)r.push(r[0]);else if("Periodic"===e.Form){a=i,o=n.length-1-a;for(let e=0;e<i;++e)r.push(r[e])}const l=new lD(i,n,r,a,o).getPoints(12*r.length);return(new Fr).setFromPoints(l)}}class gD{parse(){const e=[],t=this.parseClips();if(void 0!==t)for(const i in t){const n=t[i],r=this.addClip(n);e.push(r)}return e}parseClips(){if(void 0===cD.Objects.AnimationCurve)return;const e=this.parseAnimationCurveNodes();this.parseAnimationCurves(e);const t=this.parseAnimationLayers(e);return this.parseAnimStacks(t)}parseAnimationCurveNodes(){const e=cD.Objects.AnimationCurveNode,t=new Map;for(const i in e){const n=e[i];if(null!==n.attrName.match(/S|R|T|DeformPercent/)){const e={id:n.id,attr:n.attrName,curves:{}};t.set(e.id,e)}}return t}parseAnimationCurves(e){const t=cD.Objects.AnimationCurve;for(const i in t){const n={id:t[i].id,times:t[i].KeyTime.a.map(bD),values:t[i].KeyValueFloat.a},r=hD.get(n.id);if(void 0!==r){const t=r.parents[0].ID,i=r.parents[0].relationship;i.match(/X/)?e.get(t).curves.x=n:i.match(/Y/)?e.get(t).curves.y=n:i.match(/Z/)?e.get(t).curves.z=n:i.match(/DeformPercent/)&&e.has(t)&&(e.get(t).curves.morph=n)}}}parseAnimationLayers(e){const t=cD.Objects.AnimationLayer,i=new Map;for(const n in t){const t=[],r=hD.get(parseInt(n));void 0!==r&&(r.children.forEach(function(i,n){if(e.has(i.ID)){const r=e.get(i.ID);if(void 0!==r.curves.x||void 0!==r.curves.y||void 0!==r.curves.z){if(void 0===t[n]){const e=hD.get(i.ID).parents.filter(function(e){return void 0!==e.relationship})[0].ID;if(void 0!==e){const r=cD.Objects.Model[e.toString()];if(void 0===r)return void console.warn("THREE.FBXLoader: Encountered a unused curve.",i);const s={modelName:r.attrName?mp.sanitizeNodeName(r.attrName):"",ID:r.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};dD.traverse(function(e){e.ID===r.id&&(s.transform=e.matrix,e.userData.transformData&&(s.eulerOrder=e.userData.transformData.eulerOrder))}),s.transform||(s.transform=new Sn),"PreRotation"in r&&(s.preRotation=r.PreRotation.value),"PostRotation"in r&&(s.postRotation=r.PostRotation.value),t[n]=s}}t[n]&&(t[n][r.attr]=r)}else if(void 0!==r.curves.morph){if(void 0===t[n]){const e=hD.get(i.ID).parents.filter(function(e){return void 0!==e.relationship})[0].ID,r=hD.get(e).parents[0].ID,s=hD.get(r).parents[0].ID,a=hD.get(s).parents[0].ID,o=cD.Objects.Model[a],l={modelName:o.attrName?mp.sanitizeNodeName(o.attrName):"",morphName:cD.Objects.Deformer[e].attrName};t[n]=l}t[n][r.attr]=r}}}),i.set(parseInt(n),t))}return i}parseAnimStacks(e){const t=cD.Objects.AnimationStack,i={};for(const n in t){const r=hD.get(parseInt(n)).children;r.length>1&&console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");const s=e.get(r[0].ID);i[n]={name:t[n].attrName,layer:s}}return i}addClip(e){let t=[];const i=this;return e.layer.forEach(function(e){t=t.concat(i.generateTracks(e))}),new eu(e.name,-1,t)}generateTracks(e){const t=[];let i=new Xi,n=new Xi;if(e.transform&&e.transform.decompose(i,new qi,n),i=i.toArray(),n=n.toArray(),void 0!==e.T&&Object.keys(e.T.curves).length>0){const n=this.generateVectorTrack(e.modelName,e.T.curves,i,"position");void 0!==n&&t.push(n)}if(void 0!==e.R&&Object.keys(e.R.curves).length>0){const i=this.generateRotationTrack(e.modelName,e.R.curves,e.preRotation,e.postRotation,e.eulerOrder);void 0!==i&&t.push(i)}if(void 0!==e.S&&Object.keys(e.S.curves).length>0){const i=this.generateVectorTrack(e.modelName,e.S.curves,n,"scale");void 0!==i&&t.push(i)}if(void 0!==e.DeformPercent){const i=this.generateMorphTrack(e);void 0!==i&&t.push(i)}return t}generateVectorTrack(e,t,i,n){const r=this.getTimesForAllAxes(t),s=this.getKeyframeTrackValues(r,t,i);return new $d(e+"."+n,r,s)}generateRotationTrack(e,t,i,n,r){let s,a;if(void 0!==t.x&&void 0!==t.y&&void 0!==t.z){const e=this.interpolateRotations(t.x,t.y,t.z,r);s=e[0],a=e[1]}void 0!==i&&((i=i.map(gi.degToRad)).push(r),i=(new On).fromArray(i),i=(new qi).setFromEuler(i)),void 0!==n&&((n=n.map(gi.degToRad)).push(r),n=(new On).fromArray(n),n=(new qi).setFromEuler(n).invert());const o=new qi,l=new On,c=[];if(!a||!s)return new Jd(e+".quaternion",[0],[0]);for(let e=0;e<a.length;e+=3)l.set(a[e],a[e+1],a[e+2],r),o.setFromEuler(l),void 0!==i&&o.premultiply(i),void 0!==n&&o.multiply(n),e>2&&(new qi).fromArray(c,(e-3)/3*4).dot(o)<0&&o.set(-o.x,-o.y,-o.z,-o.w),o.toArray(c,e/3*4);return new Jd(e+".quaternion",s,c)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,i=t.values.map(function(e){return e/100}),n=dD.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new Yd(e.modelName+".morphTargetInfluences["+n+"]",t.times,i)}getTimesForAllAxes(e){let t=[];if(void 0!==e.x&&(t=t.concat(e.x.times)),void 0!==e.y&&(t=t.concat(e.y.times)),void 0!==e.z&&(t=t.concat(e.z.times)),t=t.sort(function(e,t){return e-t}),t.length>1){let e=1,i=t[0];for(let n=1;n<t.length;n++){const r=t[n];r!==i&&(t[e]=r,i=r,e++)}t=t.slice(0,e)}return t}getKeyframeTrackValues(e,t,i){const n=i,r=[];let s=-1,a=-1,o=-1;return e.forEach(function(e){if(t.x&&(s=t.x.times.indexOf(e)),t.y&&(a=t.y.times.indexOf(e)),t.z&&(o=t.z.times.indexOf(e)),-1!==s){const e=t.x.values[s];r.push(e),n[0]=e}else r.push(n[0]);if(-1!==a){const e=t.y.values[a];r.push(e),n[1]=e}else r.push(n[1]);if(-1!==o){const e=t.z.values[o];r.push(e),n[2]=e}else r.push(n[2])}),r}interpolateRotations(e,t,i,n){const r=[],s=[];r.push(e.times[0]),s.push(gi.degToRad(e.values[0])),s.push(gi.degToRad(t.values[0])),s.push(gi.degToRad(i.values[0]));for(let a=1;a<e.values.length;a++){const o=[e.values[a-1],t.values[a-1],i.values[a-1]];if(isNaN(o[0])||isNaN(o[1])||isNaN(o[2]))continue;const l=o.map(gi.degToRad),c=[e.values[a],t.values[a],i.values[a]];if(isNaN(c[0])||isNaN(c[1])||isNaN(c[2]))continue;const h=c.map(gi.degToRad),d=[c[0]-o[0],c[1]-o[1],c[2]-o[2]],u=[Math.abs(d[0]),Math.abs(d[1]),Math.abs(d[2])];if(u[0]>=180||u[1]>=180||u[2]>=180){const t=Math.max(...u)/180,i=new On(...l,n),o=new On(...h,n),c=(new qi).setFromEuler(i),d=(new qi).setFromEuler(o);c.dot(d)&&d.set(-d.x,-d.y,-d.z,-d.w);const p=e.times[a-1],m=e.times[a]-p,g=new qi,f=new On;for(let e=0;e<1;e+=1/t)g.copy(c.clone().slerp(d.clone(),e)),r.push(p+e*m),f.setFromQuaternion(g,n),s.push(f.x),s.push(f.y),s.push(f.z)}else r.push(e.times[a]),s.push(gi.degToRad(e.values[a])),s.push(gi.degToRad(t.values[a])),s.push(gi.degToRad(i.values[a]))}return[r,s]}}class fD{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 vD,this.nodeStack=[],this.currentProp=[],this.currentPropName="";const t=this,i=e.split(/[\r\n]+/);return i.forEach(function(e,n){const r=e.match(/^[\s\t]*;/),s=e.match(/^[\s\t]*$/);if(r||s)return;const a=e.match("^\\t{"+t.currentIndent+"}(\\w+):(.*){",""),o=e.match("^\\t{"+t.currentIndent+"}(\\w+):[\\s\\t\\r\\n](.*)"),l=e.match("^\\t{"+(t.currentIndent-1)+"}}");a?t.parseNodeBegin(e,a):o?t.parseNodeProperty(e,o,i[++n]):l?t.popStack():e.match(/^[^\s\t}]/)&&t.parseNodePropertyContinued(e)}),this.allNodes}parseNodeBegin(e,t){const i=t[1].trim().replace(/^"/,"").replace(/"$/,""),n=t[2].split(",").map(function(e){return e.trim().replace(/^"/,"").replace(/"$/,"")}),r={name:i},s=this.parseNodeAttr(n),a=this.getCurrentNode();0===this.currentIndent?this.allNodes.add(i,r):i in a?("PoseNode"===i?a.PoseNode.push(r):void 0!==a[i].id&&(a[i]={},a[i][a[i].id]=a[i]),""!==s.id&&(a[i][s.id]=r)):"number"==typeof s.id?(a[i]={},a[i][s.id]=r):"Properties70"!==i&&(a[i]="PoseNode"===i?[r]:r),"number"==typeof s.id&&(r.id=s.id),""!==s.name&&(r.attrName=s.name),""!==s.type&&(r.attrType=s.type),this.pushStack(r)}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(),r=t[2].replace(/^"/,"").replace(/"$/,"").trim();"Content"===n&&","===r&&(r=i.replace(/"/g,"").replace(/,$/,"").trim());const s=this.getCurrentNode();if("Properties70"!==s.name){if("C"===n){const e=r.split(",").slice(1),t=parseInt(e[0]),i=parseInt(e[1]);let a=r.split(",").slice(3);a=a.map(function(e){return e.trim().replace(/^"/,"")}),n="connections",r=[t,i],function(e,t){for(let i=0,n=e.length,r=t.length;i<r;i++,n++)e[n]=t[i]}(r,a),void 0===s[n]&&(s[n]=[])}"Node"===n&&(s.id=r),n in s&&Array.isArray(s[n])?s[n].push(r):"a"!==n?s[n]=r:s.a=r,this.setCurrentProp(s,n),"a"===n&&","!==r.slice(-1)&&(s.a=TD(r))}else this.parseNodeSpecialProperty(e,n,r)}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,","!==e.slice(-1)&&(t.a=TD(t.a))}parseNodeSpecialProperty(e,t,i){const n=i.split('",').map(function(e){return e.trim().replace(/^\"/,"").replace(/\s/,"_")}),r=n[0],s=n[1],a=n[2],o=n[3];let l=n[4];switch(s){case"int":case"enum":case"bool":case"ULongLong":case"double":case"Number":case"FieldOfView":l=parseFloat(l);break;case"Color":case"ColorRGB":case"Vector3D":case"Lcl_Translation":case"Lcl_Rotation":case"Lcl_Scaling":l=TD(l)}this.getPrevNode()[r]={type:s,type2:a,flag:o,value:l},this.setCurrentProp(this.getPrevNode(),r)}}class AD{parse(e){const t=new yD(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 vD;for(;!this.endOfContent(t);){const e=this.parseNode(t,i);null!==e&&n.add(e.name,e)}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(),r=t>=7500?e.getUint64():e.getUint32();t>=7500?e.getUint64():e.getUint32();const s=e.getUint8(),a=e.getString(s);if(0===n)return null;const o=[];for(let t=0;t<r;t++)o.push(this.parseProperty(e));const l=o.length>0?o[0]:"",c=o.length>1?o[1]:"",h=o.length>2?o[2]:"";for(i.singleProperty=1===r&&e.getOffset()===n;n>e.getOffset();){const n=this.parseNode(e,t);null!==n&&this.parseSubNode(a,i,n)}return i.propertyList=o,"number"==typeof l&&(i.id=l),""!==c&&(i.attrName=c),""!==h&&(i.attrType=h),""!==a&&(i.name=a),i}parseSubNode(e,t,i){if(!0===i.singleProperty){const e=i.propertyList[0];Array.isArray(e)?(t[i.name]=i,i.a=e):t[i.name]=e}else if("Connections"===e&&"C"===i.name){const e=[];i.propertyList.forEach(function(t,i){0!==i&&e.push(t)}),void 0===t.connections&&(t.connections=[]),t.connections.push(e)}else if("Properties70"===i.name)Object.keys(i).forEach(function(e){t[e]=i[e]});else if("Properties70"===e&&"P"===i.name){let e=i.propertyList[0],n=i.propertyList[1];const r=i.propertyList[2],s=i.propertyList[3];let a;0===e.indexOf("Lcl ")&&(e=e.replace("Lcl ","Lcl_")),0===n.indexOf("Lcl ")&&(n=n.replace("Lcl ","Lcl_")),a="Color"===n||"ColorRGB"===n||"Vector"===n||"Vector3D"===n||0===n.indexOf("Lcl_")?[i.propertyList[4],i.propertyList[5],i.propertyList[6]]:i.propertyList[4],t[e]={type:n,type2:r,flag:s,value:a}}else void 0===t[i.name]?"number"==typeof i.id?(t[i.name]={},t[i.name][i.id]=i):t[i.name]=i:"PoseNode"===i.name?(Array.isArray(t[i.name])||(t[i.name]=[t[i.name]]),t[i.name].push(i)):void 0===t[i.name][i.id]&&(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(),r=e.getUint32(),s=e.getUint32();if(0===r)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 a=IP(new Uint8Array(e.getArrayBuffer(s))),o=new yD(a.buffer);switch(t){case"b":case"c":return o.getBooleanArray(n);case"d":return o.getFloat64Array(n);case"f":return o.getFloat32Array(n);case"i":return o.getInt32Array(n);case"l":return o.getInt64Array(n)}break;default:throw new Error("THREE.FBXLoader: Unknown property type "+t)}}}class yD{constructor(e,t){this.dv=new DataView(e),this.offset=0,this.littleEndian=void 0===t||t,this._textDecoder=new TextDecoder}getOffset(){return this.offset}size(){return this.dv.buffer.byteLength}skip(e){this.offset+=e}getBoolean(){return!(1&~this.getUint8())}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()),2147483648&t?(t=4294967295&~t,e=4294967295&~e,4294967295===e&&(t=t+1&4294967295),e=e+1&4294967295,-(4294967296*t+e)):4294967296*t+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()),4294967296*t+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 vD{add(e,t){this[e]=t}}function _D(e){const t=e.match(/FBXVersion: (\d+)/);if(t)return parseInt(t[1]);throw new Error("THREE.FBXLoader: Cannot find the version number for the file given.")}function bD(e){return e/46186158e3}const xD=[];function wD(e,t,i,n){let r;switch(n.mappingType){case"ByPolygonVertex":r=e;break;case"ByPolygon":r=t;break;case"ByVertice":r=i;break;case"AllSame":r=n.indices[0];break;default:console.warn("THREE.FBXLoader: unknown attribute mapping type "+n.mappingType)}"IndexToDirect"===n.referenceType&&(r=n.indices[r]);const s=r*n.dataSize,a=s+n.dataSize;return function(e,t,i,n){for(let r=i,s=0;r<n;r++,s++)e[s]=t[r];return e}(xD,n.buffer,s,a)}const CD=new On,SD=new Xi;function MD(e){const t=new Sn,i=new Sn,n=new Sn,r=new Sn,s=new Sn,a=new Sn,o=new Sn,l=new Sn,c=new Sn,h=new Sn,d=new Sn,u=new Sn,p=e.inheritType?e.inheritType:0;if(e.translation&&t.setPosition(SD.fromArray(e.translation)),e.preRotation){const t=e.preRotation.map(gi.degToRad);t.push(e.eulerOrder||On.DEFAULT_ORDER),i.makeRotationFromEuler(CD.fromArray(t))}if(e.rotation){const t=e.rotation.map(gi.degToRad);t.push(e.eulerOrder||On.DEFAULT_ORDER),n.makeRotationFromEuler(CD.fromArray(t))}if(e.postRotation){const t=e.postRotation.map(gi.degToRad);t.push(e.eulerOrder||On.DEFAULT_ORDER),r.makeRotationFromEuler(CD.fromArray(t)),r.invert()}e.scale&&s.scale(SD.fromArray(e.scale)),e.scalingOffset&&o.setPosition(SD.fromArray(e.scalingOffset)),e.scalingPivot&&a.setPosition(SD.fromArray(e.scalingPivot)),e.rotationOffset&&l.setPosition(SD.fromArray(e.rotationOffset)),e.rotationPivot&&c.setPosition(SD.fromArray(e.rotationPivot)),e.parentMatrixWorld&&(d.copy(e.parentMatrix),h.copy(e.parentMatrixWorld));const m=i.clone().multiply(n).multiply(r),g=new Sn;g.extractRotation(h);const f=new Sn;f.copyPosition(h);const A=f.clone().invert().multiply(h),y=g.clone().invert().multiply(A),v=s,_=new Sn;if(0===p)_.copy(g).multiply(m).multiply(y).multiply(v);else if(1===p)_.copy(g).multiply(y).multiply(m).multiply(v);else{const e=(new Sn).scale((new Xi).setFromMatrixScale(d)).clone().invert(),t=y.clone().multiply(e);_.copy(g).multiply(m).multiply(t).multiply(v)}const b=c.clone().invert(),x=a.clone().invert();let w=t.clone().multiply(l).multiply(c).multiply(i).multiply(n).multiply(r).multiply(b).multiply(o).multiply(a).multiply(s).multiply(x);const C=(new Sn).copyPosition(w),S=h.clone().multiply(C);return u.copyPosition(S),w=u.clone().multiply(_),w.premultiply(h.invert()),w}function ED(e){const t=["ZYX","YZX","XZY","ZXY","YXZ","XYZ"];return 6===(e=e||0)?(console.warn("THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect."),t[0]):t[e]}function TD(e){return e.split(",").map(function(e){return parseFloat(e)})}function ID(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=e.byteLength),(new TextDecoder).decode(new Uint8Array(e,t,i))}class PD extends uD{async loadAsync(e,t){const i=Ni.DEFAULT_IMAGE;Ni.DEFAULT_IMAGE||(Ni.DEFAULT_IMAGE=cv);const n=await super.loadAsync(e,t);return Ni.DEFAULT_IMAGE=i,n}}class DD extends lu{load(e,t,i,n){return this.setResponseType("arraybuffer"),super.load(e,e=>{const i=rD(new Uint8Array(e)),n=new Map(Object.entries(i).map(([e,t])=>[e,new File([t],e)]));t?.(n)},i,n)}}const RD=["hdr","exr","webp","avif","ktx","hdrpng","svg","cube","ico","bmp","gif","tiff"],BD=class e extends wE{constructor(t){super(t),this.isGLTFLoader2=!0,this._resPathUrlModifier={oldResourcePath:"",newResourcePath:"",modify:t=>{if(!e._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(e,t)=>{const r=await n.call(i,e,t);return UD(r,i.bundledResources),r};const r=i.createUniqueName;i.createUniqueName=t=>{let n=!1;return n="auto"===(i.importOptions?.createUniqueNames??e.CreateUniqueNames)?!i.json?.scenes[i.json.scene??0]?.extras?.rootSceneModelRoot:!0===i.importOptions?.createUniqueNames||!0===e.CreateUniqueNames&&!1!==i.importOptions?.createUniqueNames,n?r.call(i,t):t};const s=Ky()+".drc",a=Ky()+".ktx2",o=i.json?.extensionsRequired?.includes?.("KHR_draco_mesh_compression");if(o){const e=t.assetManager.importer.registerFile(s);e&&this.setDRACOLoader(e)}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 l=t.assetManager.importer.registerFile(a);l&&(this.setKTX2Loader(l),i.options.ktx2Loader=l);const c=RD.map(e=>Ky()+"."+e);return c.forEach(e=>t.assetManager.importer.registerFile(e)),{name:"GLTF2_HELPER_PLUGIN",beforeRoot:async()=>{const n=i.json.extras?.[e.BundledResourcesKey];!n||n.__isLoadedResources||(i.bundledResources=await xE.ImportResources(n,i,t))},afterRoot:async e=>{e._bundledResources=i.bundledResources,await xE.ImportViewerConfig(i,t,e.scenes||[e.scene]),o&&t.assetManager.importer.unregisterFile(s),l&&t.assetManager.importer.unregisterFile(a),c.forEach(e=>t.assetManager.importer.unregisterFile(e)),t.assetManager.importer.removeURLModifier(this._resPathUrlModifier.modify)}}},this.preparsers.push(xT),wE.ObjectConstructors.DirectionalLight=JC,wE.ObjectConstructors.PointLight=rS,wE.ObjectConstructors.SpotLight=dS,wE.ObjectConstructors.MeshStandardMaterial=yC,wE.ObjectConstructors.MeshBasicMaterial=kw,wE.ObjectConstructors.MeshPhysicalMaterial=yC,wE.ObjectConstructors.LineBasicMaterial=xC,wE.ObjectConstructors.PerspectiveCamera=cC,wE.ObjectConstructors.OrthographicCamera=gC}async preparse(e,t){for(const i of this.preparsers)e=await i.process(e,t);return e}parse(t,i,n,r,s){this.preparse.call(this,t,s||i).then(t=>{if(!t||!t.byteLength&&"string"!=typeof t)return void(e.AllowEmptyFiles?n&&n({scene:new ll,scenes:[],animations:[],cameras:[]}):r&&r(new ErrorEvent("GLTFLoader2: empty file")));const s=Ni.DEFAULT_IMAGE;Ni.DEFAULT_IMAGE||(Ni.DEFAULT_IMAGE=cv);const a=this.importOptions?.useMeshLines??e.UseMeshLines;return wE.ObjectConstructors.LineBasicMaterial=a?MC:xC,t?super.parse(t,i,e=>{Ni.DEFAULT_IMAGE=s,wE.ObjectConstructors.LineBasicMaterial=a?MC:xC;for(const t of e.scenes)t.updateMatrixWorld();n&&n(e)},r):r&&r(new ErrorEvent("no data"))}).catch(e=>{console.error(e),r&&r(e??new ErrorEvent("unknown error"))})}transform(t,i){let n=t?t.scene||!!t.scenes&&t.scenes.length>0&&t.scenes[0]:void 0;if(!n)return;n&&1===n.children.length&&!n.userData?.rootSceneModelRoot&&!n.importedViewerConfig&&"AuxScene"===n.name&&!t.cameras?.length&&(n=n.children[0],n.removeFromParent()),n.userData||(n.userData={}),t.userData&&(n.userData.gltfExtras=t.userData),t.cameras&&t.cameras.forEach(e=>!e.parent&&n?.add(e)),t.asset&&(n.userData.gltfAsset=t.asset),i.importAsModelRoot?n.userData.rootSceneModelRoot=!0:!1===i.importAsModelRoot&&n.userData.rootSceneModelRoot&&delete n.userData.rootSceneModelRoot;const r=[],s=new Map,a=new Set;if(n.traverse(e=>{e.userData.gltfUUID&&(Tm(e,"uuid",e.userData.gltfUUID,!0,!0),delete e.userData.gltfUUID),e.isLine&&r.push(e),e.uuid&&(s.has(e.uuid)||s.set(e.uuid,[]),s.get(e.uuid).push(e)),e.name&&(s.has(e.name)||s.set(e.name,[]),s.get(e.name).push(e));const t=e;t.geometry&&t.geometry.isBufferGeometry&&(t.geometry.userData.isPlaceholder?t.geometry=$S.DummyGeometry:a.add(t.geometry));const i=Array.isArray(t.material)?t.material:t.material?[t.material]:[];for(let e=0;e<i.length;e++){const t=i[e];t?.userData.isPlaceholder&&(t.isLineBasicMaterial?i[e]=$S.DummyLineBasicMaterial:t.isLineMaterial?i[e]=$S.DummyLineMaterial:i[e]=$S.DummyMaterial)}Array.isArray(t.material)&&t.material.length?t.material=i:1===i.length&&(t.material=i[0])}),a.forEach(e=>{UD(e,t._bundledResources)}),t.animations.length>0){n.animations=[];for(const e of t.animations){let t=!1;if(e.userData.rootRefs){for(const i of e.userData.rootRefs){const n=s.get(i)||[];for(const i of n)i.animations||(i.animations=[]),i.animations.includes(e)||i.animations.push(e),t=!0}t&&delete e.userData.rootRefs}t||n.animations.push(e)}}if(this.importOptions?.useMeshLines??e.UseMeshLines)for(const e of r)OD(e);return n.importedBundledResources=t._bundledResources,n}register(e){return super.register(e)}setup(t,i){this.register(eE.Import(t.loadConfigResources));for(const e of i)this.register(e);for(const t of e.ImportExtensions)this.register(t);return this.register(this.gltfViewerParser(t)),this}};BD._EmbedResourcePath=!1,BD._UseResourcePath=!0,BD.ImportExtensions=[yE.Import,ZM.Import,aE.Import,hE.Import,mE.Import,iE.Import,e=>({name:"_EMBED_RESOURCE_PATH",afterRoot:async t=>{!BD._EmbedResourcePath||!t.scene||(t.userData.resourcePath=e.options.path)}})],BD.UseMeshLines=!0,BD.CreateUniqueNames="auto",BD.BundledResourcesKey="BundledResources",BD.AllowEmptyFiles=!0;let LD=BD;function OD(e){const t=e.parent;if(!t)return void console.warn("GLTFLoader2: Line has no parent",e);e.geometry.index&&(e.geometry=e.geometry.toNonIndexed());const i=e.isLineSegments?new OC(new NC,e.material):new LC(new FC,e.material);let n=e.geometry.attributes.position.array;if(e.isLineLoop){const e=new Float32Array(n.length+3);e.set(n),e.set(n.subarray(0,3),n.length),n=e}i.geometry.setPositions(n);const r=e.geometry.attributes.color?.array;r&&i.geometry.setColors&&i.geometry.setColors(r),i.geometry.name=e.geometry.name,Tm(i.geometry,"uuid",e.geometry.uuid,!0,!0),i.geometry.userData={...e.geometry.userData};const s=t.children.indexOf(e);t.add(i);const{geometry:a,material:o}=i,l=e.userData;e.userData={},e.userData.__keepShadowDef||(e.castShadow=i.castShadow,e.receiveShadow=i.receiveShadow),i.copy(e,!1),i.geometry=a,i.material=o,[...e.children].map(e=>{i.add(e)}),i.userData={...i.userData,...l},Tm(i,"uuid",e.uuid,!0,!0),e.removeFromParent(),i.computeLineDistances();const c=t.children.indexOf(i);c>=0&&c!==s&&(t.children.splice(c,1),t.children.splice(s,0,i))}function UD(e,t){if(e&&e.userData){const i=e.userData.gltfExtensions;delete e.userData.gltfExtensions,e.userData=f_.Deserialize(e.userData,{},t),e.userData.gltfExtensions=i}}const FD=new WeakMap;class kD extends su{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 r=new lu(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),r.setWithCredentials(this.withCredentials),r.load(e,e=>{this.parse(e,t,n)},i,n)}parse(e,t,i=()=>{}){this.decodeDracoFile(e,t,null,null,Ot,i).catch(i)}decodeDracoFile(e,t,i,n,r=Ut,s=()=>{}){const a={attributeIDs:i||this.defaultAttributeIDs,attributeTypes:n||this.defaultAttributeTypes,useUniqueIDs:!!i,vertexColorSpace:r};return this.decodeGeometry(e,a).then(t).catch(s)}decodeGeometry(e,t){const i=JSON.stringify(t);if(FD.has(e)){const t=FD.get(e);if(t.key===i)return t.promise;if(0===e.byteLength)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let n;const r=this.workerNextTaskID++,s=e.byteLength,a=this._getWorker(r,s).then(i=>(n=i,new Promise((i,s)=>{n._callbacks[r]={resolve:i,reject:s},n.postMessage({type:"decode",id:r,taskConfig:t,buffer:e},[e])}))).then(e=>this._createGeometry(e.geometry));return a.catch(()=>!0).then(()=>{n&&r&&this._releaseTask(n,r)}),FD.set(e,{key:i,promise:a}),a}_createGeometry(e){const t=new Fr;e.index&&t.setIndex(new Mr(e.index.array,1));for(let i=0;i<e.attributes.length;i++){const n=e.attributes[i],r=n.name,s=n.array,a=n.itemSize,o=new Mr(s,a);"color"===r&&(this._assignVertexColorSpace(o,n.vertexColorSpace),o.normalized=!(s instanceof Float32Array)),t.setAttribute(r,o)}return t}_assignVertexColorSpace(e,t){if(t!==Ot)return;const i=new mr;for(let t=0,n=e.count;t<n;t++)i.fromBufferAttribute(e,t).convertSRGBToLinear(),e.setXYZ(t,i.r,i.g,i.b)}_loadLibrary(e,t){const i=new lu(this.manager);return i.setPath(this.decoderPath),i.setResponseType(t),i.setWithCredentials(this.withCredentials),new Promise((t,n)=>{i.load(e,t,void 0,n)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e="object"!=typeof WebAssembly||"js"===this.decoderConfig.type,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(t=>{const i=t[0];e||(this.decoderConfig.wasmBinary=t[1]);const n=ND,r=["/* draco decoder */",i,"","/* worker */",n.substring(n.indexOf("{")+1,n.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([r]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const e=new Worker(this.workerSourceURL);e._callbacks={},e._taskCosts={},e._taskLoad=0,e.postMessage({type:"init",decoderConfig:this.decoderConfig}),e.onmessage=function(t){const i=t.data;switch(i.type){case"decode":e._callbacks[i.id].resolve(i);break;case"error":e._callbacks[i.id].reject(i);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+i.type+'"')}},this.workerPool.push(e)}else this.workerPool.sort(function(e,t){return e._taskLoad>t._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 ND="\nfunction DRACOWorker() {\n\n\tlet decoderConfig;\n\tlet decoderPending;\n\n\tonmessage = function ( e ) {\n\n\t\tconst message = e.data;\n\n\t\tswitch ( message.type ) {\n\n\t\t\tcase 'init':\n\t\t\t\tdecoderConfig = message.decoderConfig;\n\t\t\t\tdecoderPending = new Promise( function ( resolve/*, reject*/ ) {\n\n\t\t\t\t\tdecoderConfig.onModuleLoaded = function ( draco ) {\n\n\t\t\t\t\t\t// Module is Promise-like. Wrap before resolving to avoid loop.\n\t\t\t\t\t\tresolve( { draco: draco } );\n\n\t\t\t\t\t};\n\n\t\t\t\t\tDracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef\n\n\t\t\t\t} );\n\t\t\t\tbreak;\n\n\t\t\tcase 'decode':\n\t\t\t\tconst buffer = message.buffer;\n\t\t\t\tconst taskConfig = message.taskConfig;\n\t\t\t\tdecoderPending.then( ( module ) => {\n\n\t\t\t\t\tconst draco = module.draco;\n\t\t\t\t\tconst decoder = new draco.Decoder();\n\n\t\t\t\t\ttry {\n\n\t\t\t\t\t\tconst geometry = decodeGeometry( draco, decoder, new Int8Array( buffer ), taskConfig );\n\n\t\t\t\t\t\tconst buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );\n\n\t\t\t\t\t\tif ( geometry.index ) buffers.push( geometry.index.array.buffer );\n\n\t\t\t\t\t\tself.postMessage( { type: 'decode', id: message.id, geometry }, buffers );\n\n\t\t\t\t\t} catch ( error ) {\n\n\t\t\t\t\t\tconsole.error( error );\n\n\t\t\t\t\t\tself.postMessage( { type: 'error', id: message.id, error: error.message } );\n\n\t\t\t\t\t} finally {\n\n\t\t\t\t\t\tdraco.destroy( decoder );\n\n\t\t\t\t\t}\n\n\t\t\t\t} );\n\t\t\t\tbreak;\n\n\t\t}\n\n\t};\n\n\tfunction decodeGeometry( draco, decoder, array, taskConfig ) {\n\n\t\tconst attributeIDs = taskConfig.attributeIDs;\n\t\tconst attributeTypes = taskConfig.attributeTypes;\n\n\t\tlet dracoGeometry;\n\t\tlet decodingStatus;\n\n\t\tconst geometryType = decoder.GetEncodedGeometryType( array );\n\n\t\tif ( geometryType === draco.TRIANGULAR_MESH ) {\n\n\t\t\tdracoGeometry = new draco.Mesh();\n\t\t\tdecodingStatus = decoder.DecodeArrayToMesh( array, array.byteLength, dracoGeometry );\n\n\t\t} else if ( geometryType === draco.POINT_CLOUD ) {\n\n\t\t\tdracoGeometry = new draco.PointCloud();\n\t\t\tdecodingStatus = decoder.DecodeArrayToPointCloud( array, array.byteLength, dracoGeometry );\n\n\t\t} else {\n\n\t\t\tthrow new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );\n\n\t\t}\n\n\t\tif ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {\n\n\t\t\tthrow new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );\n\n\t\t}\n\n\t\tconst geometry = { index: null, attributes: [] };\n\n\t\t// Gather all vertex attributes.\n\t\tfor ( const attributeName in attributeIDs ) {\n\n\t\t\tconst attributeType = self[ attributeTypes[ attributeName ] ];\n\n\t\t\tlet attribute;\n\t\t\tlet attributeID;\n\n\t\t\t// A Draco file may be created with default vertex attributes, whose attribute IDs\n\t\t\t// are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,\n\t\t\t// a Draco file may contain a custom set of attributes, identified by known unique\n\t\t\t// IDs. glTF files always do the latter, and .drc files typically do the former.\n\t\t\tif ( taskConfig.useUniqueIDs ) {\n\n\t\t\t\tattributeID = attributeIDs[ attributeName ];\n\t\t\t\tattribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );\n\n\t\t\t} else {\n\n\t\t\t\tattributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );\n\n\t\t\t\tif ( attributeID === - 1 ) continue;\n\n\t\t\t\tattribute = decoder.GetAttribute( dracoGeometry, attributeID );\n\n\t\t\t}\n\n\t\t\tconst attributeResult = decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute );\n\n\t\t\tif ( attributeName === 'color' ) {\n\n\t\t\t\tattributeResult.vertexColorSpace = taskConfig.vertexColorSpace;\n\n\t\t\t}\n\n\t\t\tgeometry.attributes.push( attributeResult );\n\n\t\t}\n\n\t\t// Add index.\n\t\tif ( geometryType === draco.TRIANGULAR_MESH ) {\n\n\t\t\tgeometry.index = decodeIndex( draco, decoder, dracoGeometry );\n\n\t\t}\n\n\t\tdraco.destroy( dracoGeometry );\n\n\t\treturn geometry;\n\n\t}\n\n\tfunction decodeIndex( draco, decoder, dracoGeometry ) {\n\n\t\tconst numFaces = dracoGeometry.num_faces();\n\t\tconst numIndices = numFaces * 3;\n\t\tconst byteLength = numIndices * 4;\n\n\t\tconst ptr = draco._malloc( byteLength );\n\t\tdecoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );\n\t\tconst index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();\n\t\tdraco._free( ptr );\n\n\t\treturn { array: index, itemSize: 1 };\n\n\t}\n\n\tfunction decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {\n\n\t\tconst numComponents = attribute.num_components();\n\t\tconst numPoints = dracoGeometry.num_points();\n\t\tconst numValues = numPoints * numComponents;\n\t\tconst byteLength = numValues * attributeType.BYTES_PER_ELEMENT;\n\t\tconst dataType = getDracoDataType( draco, attributeType );\n\n\t\tconst ptr = draco._malloc( byteLength );\n\t\tdecoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );\n\t\tconst array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();\n\t\tdraco._free( ptr );\n\n\t\treturn {\n\t\t\tname: attributeName,\n\t\t\tarray: array,\n\t\t\titemSize: numComponents\n\t\t};\n\n\t}\n\n\tfunction getDracoDataType( draco, attributeType ) {\n\n\t\tswitch ( attributeType ) {\n\n\t\t\tcase Float32Array: return draco.DT_FLOAT32;\n\t\t\tcase Int8Array: return draco.DT_INT8;\n\t\t\tcase Int16Array: return draco.DT_INT16;\n\t\t\tcase Int32Array: return draco.DT_INT32;\n\t\t\tcase Uint8Array: return draco.DT_UINT8;\n\t\t\tcase Uint16Array: return draco.DT_UINT16;\n\t\t\tcase Uint32Array: return draco.DT_UINT32;\n\n\t\t}\n\n\t}\n\n}\n",jD=class e extends kD{constructor(t){super(t),this.encoderPending=null,this.decoderModulePending=null,this.encoderConfig={type:"js"},this.isDRACOLoader2=!0,this.setDecoderPath(e.DRACO_LIBRARY_PATH)}transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new ts(e,new yC({color:new mr(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="object"!=typeof WebAssembly||"js"===this.encoderConfig.type,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 t=>{const i=t[0];e||(this.encoderConfig.wasmBinary=t[1]);const n=(0,eval)(i+"\nDracoEncoderModule;");if("function"!=typeof n)throw new Error("DRACOLoader2: unable to find DracoEncoderModule");return new Promise(e=>{n({...this.encoderConfig,onModuleLoaded:e})})}),this.encoderPending}async initDecoder(){return this.decoderModulePending||(this.decoderModulePending=(async()=>{await this._initDecoder();const e=await fetch(this.workerSourceURL).then(async e=>e.text()).then(e=>{const t=e.indexOf("/* worker */");if(t<1)throw new Error("unable to load decoder module");return e.substring(0,t-1)}),t=(0,eval)(e+"\nDracoDecoderModule;");if("function"!=typeof t)throw new Error("DRACOLoader2: unable to find DracoDecoderModule");return new Promise(e=>{t({...this.decoderConfig,onModuleLoaded:e})})})()),this.decoderModulePending}async _loadLibrary(t,i){return e.LibraryValueMap[t]?e.LibraryValueMap[t]:e.LibraryValueMap[t]=await super._loadLibrary(t,i)}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}};jD.DRACO_LIBRARY_PATH="https://cdn.jsdelivr.net/gh/google/draco@1.5.6/javascript/",jD.LibraryValueMap={};let zD=jD;class GD extends du{constructor(e){super(e),this.type=De}parse(e){const t=Math.pow(2.7182818,2.2);const i={l:0,c:0,lc:0};function n(e,t,n,r,s){for(;n<e;)t=t<<8|F(r,s),n+=8;n-=e,i.l=t>>n&(1<<e)-1,i.c=t,i.lc=n}const r=new Array(59);function s(e,t,s,a,o,l){const c=t;let h=0,d=0;for(;a<=o;a++){if(c.value-t.value>s)return!1;n(6,h,d,e,c);const r=i.l;if(h=i.c,d=i.lc,l[a]=r,63==r){if(c.value-t.value>s)throw new Error("Something wrong with hufUnpackEncTable");n(8,h,d,e,c);let r=i.l+6;if(h=i.c,d=i.lc,a+r>o+1)throw new Error("Something wrong with hufUnpackEncTable");for(;r--;)l[a++]=0;a--}else if(r>=59){let e=r-59+2;if(a+e>o+1)throw new Error("Something wrong with hufUnpackEncTable");for(;e--;)l[a++]=0;a--}}!function(e){for(let e=0;e<=58;++e)r[e]=0;for(let t=0;t<65537;++t)r[e[t]]+=1;let t=0;for(let e=58;e>0;--e){const i=t+r[e]>>1;r[e]=t,t=i}for(let t=0;t<65537;++t){const i=e[t];i>0&&(e[t]=i|r[i]++<<6)}}(l)}function a(e){return 63&e}function o(e){return e>>6}const l={c:0,lc:0};function c(e,t,i,n){e=e<<8|F(i,n),t+=8,l.c=e,l.lc=t}const h={c:0,lc:0};function d(e,t,i,n,r,s,a,o,d){if(e==t){n<8&&(c(i,n,r,s),i=l.c,n=l.lc);let e=i>>(n-=8);if(e=new Uint8Array([e])[0],o.value+e>d)return!1;const t=a[o.value-1];for(;e-- >0;)a[o.value++]=t}else{if(!(o.value<d))return!1;a[o.value++]=e}h.c=i,h.lc=n}function u(e){return 65535&e}function p(e){const t=u(e);return t>32767?t-65536:t}const m={a:0,b:0};function g(e,t){const i=p(e),n=p(t),r=i+(1&n)+(n>>1),s=r,a=r-n;m.a=s,m.b=a}function f(e,t){const i=u(e),n=u(t),r=i-(n>>1)&65535,s=n+r-32768&65535;m.a=s,m.b=r}function A(e,t,i,n,r,s,a){const o=a<16384,l=i>r?r:i;let c,h,d=1;for(;d<=l;)d<<=1;for(d>>=1,c=d,d>>=1;d>=1;){h=0;const a=h+s*(r-c),l=s*d,u=s*c,p=n*d,A=n*c;let y,v,_,b;for(;h<=a;h+=u){let r=h;const s=h+n*(i-c);for(;r<=s;r+=A){const i=r+p,n=r+l,s=n+p;o?(g(e[r+t],e[n+t]),y=m.a,_=m.b,g(e[i+t],e[s+t]),v=m.a,b=m.b,g(y,v),e[r+t]=m.a,e[i+t]=m.b,g(_,b),e[n+t]=m.a,e[s+t]=m.b):(f(e[r+t],e[n+t]),y=m.a,_=m.b,f(e[i+t],e[s+t]),v=m.a,b=m.b,f(y,v),e[r+t]=m.a,e[i+t]=m.b,f(_,b),e[n+t]=m.a,e[s+t]=m.b)}if(i&d){const i=r+l;o?g(e[r+t],e[i+t]):f(e[r+t],e[i+t]),y=m.a,e[i+t]=m.b,e[r+t]=y}}if(r&d){let r=h;const s=h+n*(i-c);for(;r<=s;r+=A){const i=r+p;o?g(e[r+t],e[i+t]):f(e[r+t],e[i+t]),y=m.a,e[i+t]=m.b,e[r+t]=y}}c=d,d>>=1}return h}function y(e,t,i,n,r,u){const p=i.value,m=U(t,i),g=U(t,i);i.value+=4;const f=U(t,i);if(i.value+=4,m<0||m>=65537||g<0||g>=65537)throw new Error("Something wrong with HUF_ENCSIZE");const A=new Array(65537),y=new Array(16384);!function(e){for(let t=0;t<16384;t++)e[t]={},e[t].len=0,e[t].lit=0,e[t].p=null}(y);if(s(e,i,n-(i.value-p),m,g,A),f>8*(n-(i.value-p)))throw new Error("Something wrong with hufUncompress");(function(e,t,i,n){for(;t<=i;t++){const i=o(e[t]),r=a(e[t]);if(i>>r)throw new Error("Invalid table entry");if(r>14){const e=n[i>>r-14];if(e.len)throw new Error("Invalid table entry");if(e.lit++,e.p){const t=e.p;e.p=new Array(e.lit);for(let i=0;i<e.lit-1;++i)e.p[i]=t[i]}else e.p=new Array(1);e.p[e.lit-1]=t}else if(r){let e=0;for(let s=1<<14-r;s>0;s--){const s=n[(i<<14-r)+e];if(s.len||s.p)throw new Error("Invalid table entry");s.len=r,s.lit=t,e++}}}})(A,m,g,y),function(e,t,i,n,r,s,u,p,m){let g=0,f=0;const A=u,y=Math.trunc(n.value+(r+7)/8);for(;n.value<y;)for(c(g,f,i,n),g=l.c,f=l.lc;f>=14;){const r=t[g>>f-14&16383];if(r.len)f-=r.len,d(r.lit,s,g,f,i,n,p,m,A),g=h.c,f=h.lc;else{if(!r.p)throw new Error("hufDecode issues");let t;for(t=0;t<r.lit;t++){const u=a(e[r.p[t]]);for(;f<u&&n.value<y;)c(g,f,i,n),g=l.c,f=l.lc;if(f>=u&&o(e[r.p[t]])==(g>>f-u&(1<<u)-1)){f-=u,d(r.p[t],s,g,f,i,n,p,m,A),g=h.c,f=h.lc;break}}if(t==r.lit)throw new Error("hufDecode issues")}}const v=8-r&7;for(g>>=v,f-=v;f>0;){const e=t[g<<14-f&16383];if(!e.len)throw new Error("hufDecode issues");f-=e.len,d(e.lit,s,g,f,i,n,p,m,A),g=h.c,f=h.lc}}(A,y,e,i,f,g,u,r,{value:0})}function v(e){for(let t=1;t<e.length;t++){const i=e[t-1]+e[t]-128;e[t]=i}}function _(e,t){let i=0,n=Math.floor((e.length+1)/2),r=0;const s=e.length-1;for(;!(r>s||(t[r++]=e[i++],r>s));)t[r++]=e[n++]}function b(e){let t=e.byteLength;const i=new Array;let n=0;const r=new DataView(e);for(;t>0;){const e=r.getInt8(n++);if(e<0){const s=-e;t-=s+1;for(let e=0;e<s;e++)i.push(r.getUint8(n++))}else{const s=e;t-=2;const a=r.getUint8(n++);for(let e=0;e<s+1;e++)i.push(a)}}return i}function x(e,t,i){let n,r=1;for(;r<64;)n=t[e.value],65280==n?r=64:n>>8==255?r+=255&n:(i[r]=n,r++),e.value++}function w(e,t){t[0]=G(e[0]),t[1]=G(e[1]),t[2]=G(e[5]),t[3]=G(e[6]),t[4]=G(e[14]),t[5]=G(e[15]),t[6]=G(e[27]),t[7]=G(e[28]),t[8]=G(e[2]),t[9]=G(e[4]),t[10]=G(e[7]),t[11]=G(e[13]),t[12]=G(e[16]),t[13]=G(e[26]),t[14]=G(e[29]),t[15]=G(e[42]),t[16]=G(e[3]),t[17]=G(e[8]),t[18]=G(e[12]),t[19]=G(e[17]),t[20]=G(e[25]),t[21]=G(e[30]),t[22]=G(e[41]),t[23]=G(e[43]),t[24]=G(e[9]),t[25]=G(e[11]),t[26]=G(e[18]),t[27]=G(e[24]),t[28]=G(e[31]),t[29]=G(e[40]),t[30]=G(e[44]),t[31]=G(e[53]),t[32]=G(e[10]),t[33]=G(e[19]),t[34]=G(e[23]),t[35]=G(e[32]),t[36]=G(e[39]),t[37]=G(e[45]),t[38]=G(e[52]),t[39]=G(e[54]),t[40]=G(e[20]),t[41]=G(e[22]),t[42]=G(e[33]),t[43]=G(e[38]),t[44]=G(e[46]),t[45]=G(e[51]),t[46]=G(e[55]),t[47]=G(e[60]),t[48]=G(e[21]),t[49]=G(e[34]),t[50]=G(e[37]),t[51]=G(e[47]),t[52]=G(e[50]),t[53]=G(e[56]),t[54]=G(e[59]),t[55]=G(e[61]),t[56]=G(e[35]),t[57]=G(e[36]),t[58]=G(e[48]),t[59]=G(e[49]),t[60]=G(e[57]),t[61]=G(e[58]),t[62]=G(e[62]),t[63]=G(e[63])}function C(e){const t=.5*Math.cos(.7853975),i=.5*Math.cos(3.14159/16),n=.5*Math.cos(3.14159/8),r=.5*Math.cos(3*3.14159/16),s=.5*Math.cos(.981746875),a=.5*Math.cos(3*3.14159/8),o=.5*Math.cos(1.374445625),l=new Array(4),c=new Array(4),h=new Array(4),d=new Array(4);for(let u=0;u<8;++u){const p=8*u;l[0]=n*e[p+2],l[1]=a*e[p+2],l[2]=n*e[p+6],l[3]=a*e[p+6],c[0]=i*e[p+1]+r*e[p+3]+s*e[p+5]+o*e[p+7],c[1]=r*e[p+1]-o*e[p+3]-i*e[p+5]-s*e[p+7],c[2]=s*e[p+1]-i*e[p+3]+o*e[p+5]+r*e[p+7],c[3]=o*e[p+1]-s*e[p+3]+r*e[p+5]-i*e[p+7],h[0]=t*(e[p+0]+e[p+4]),h[3]=t*(e[p+0]-e[p+4]),h[1]=l[0]+l[3],h[2]=l[1]-l[2],d[0]=h[0]+h[1],d[1]=h[3]+h[2],d[2]=h[3]-h[2],d[3]=h[0]-h[1],e[p+0]=d[0]+c[0],e[p+1]=d[1]+c[1],e[p+2]=d[2]+c[2],e[p+3]=d[3]+c[3],e[p+4]=d[3]-c[3],e[p+5]=d[2]-c[2],e[p+6]=d[1]-c[1],e[p+7]=d[0]-c[0]}for(let u=0;u<8;++u)l[0]=n*e[16+u],l[1]=a*e[16+u],l[2]=n*e[48+u],l[3]=a*e[48+u],c[0]=i*e[8+u]+r*e[24+u]+s*e[40+u]+o*e[56+u],c[1]=r*e[8+u]-o*e[24+u]-i*e[40+u]-s*e[56+u],c[2]=s*e[8+u]-i*e[24+u]+o*e[40+u]+r*e[56+u],c[3]=o*e[8+u]-s*e[24+u]+r*e[40+u]-i*e[56+u],h[0]=t*(e[u]+e[32+u]),h[3]=t*(e[u]-e[32+u]),h[1]=l[0]+l[3],h[2]=l[1]-l[2],d[0]=h[0]+h[1],d[1]=h[3]+h[2],d[2]=h[3]-h[2],d[3]=h[0]-h[1],e[0+u]=d[0]+c[0],e[8+u]=d[1]+c[1],e[16+u]=d[2]+c[2],e[24+u]=d[3]+c[3],e[32+u]=d[3]-c[3],e[40+u]=d[2]-c[2],e[48+u]=d[1]-c[1],e[56+u]=d[0]-c[0]}function S(e){for(let t=0;t<64;++t){const i=e[0][t],n=e[1][t],r=e[2][t];e[0][t]=i+1.5747*r,e[1][t]=i-.1873*n-.4682*r,e[2][t]=i+1.8556*n}}function M(e,t,i){for(let n=0;n<64;++n)t[i+n]=wr.toHalfFloat(E(e[n]))}function E(e){return e<=1?Math.sign(e)*Math.pow(Math.abs(e),2.2):Math.sign(e)*Math.pow(t,Math.abs(e)-1)}function T(e){return new DataView(e.array.buffer,e.offset.value,e.size)}function I(e){const t=e.viewer.buffer.slice(e.offset.value,e.offset.value+e.size),i=new Uint8Array(b(t)),n=new Uint8Array(i.length);return v(i),_(i,n),new DataView(n.buffer)}function P(e){const t=IP(e.array.slice(e.offset.value,e.offset.value+e.size)),i=new Uint8Array(t.length);return v(t),_(t,i),new DataView(i.buffer)}function D(e){const t=e.viewer,i={value:e.offset.value},n=new Uint16Array(e.columns*e.lines*(e.inputChannels.length*e.type)),r=new Uint8Array(8192);let s=0;const a=new Array(e.inputChannels.length);for(let t=0,i=e.inputChannels.length;t<i;t++)a[t]={},a[t].start=s,a[t].end=a[t].start,a[t].nx=e.columns,a[t].ny=e.lines,a[t].size=e.type,s+=a[t].nx*a[t].ny*a[t].size;const o=Q(t,i),l=Q(t,i);if(l>=8192)throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");if(o<=l)for(let e=0;e<l-o+1;e++)r[e+o]=k(t,i);const c=new Uint16Array(65536),h=function(e,t){let i=0;for(let n=0;n<65536;++n)(0==n||e[n>>3]&1<<(7&n))&&(t[i++]=n);const n=i-1;for(;i<65536;)t[i++]=0;return n}(r,c),d=U(t,i);y(e.array,t,i,d,n,s);for(let t=0;t<e.inputChannels.length;++t){const e=a[t];for(let i=0;i<a[t].size;++i)A(n,e.start+i,e.nx,e.size,e.ny,e.nx*e.size,h)}!function(e,t,i){for(let n=0;n<i;++n)t[n]=e[t[n]]}(c,n,s);let u=0;const p=new Uint8Array(n.buffer.byteLength);for(let t=0;t<e.lines;t++)for(let t=0;t<e.inputChannels.length;t++){const e=a[t],i=e.nx*e.size,r=new Uint8Array(n.buffer,2*e.end,2*i);p.set(r,u),u+=2*i,e.end+=i}return new DataView(p.buffer)}function R(e){const t=IP(e.array.slice(e.offset.value,e.offset.value+e.size)),i=e.inputChannels.length*e.lines*e.columns*e.totalBytes,n=new ArrayBuffer(i),r=new DataView(n);let s=0,a=0;const o=new Array(4);for(let i=0;i<e.lines;i++)for(let i=0;i<e.inputChannels.length;i++){let n=0;switch(e.inputChannels[i].pixelType){case 1:o[0]=s,o[1]=o[0]+e.columns,s=o[1]+e.columns;for(let i=0;i<e.columns;++i){n+=t[o[0]++]<<8|t[o[1]++],r.setUint16(a,n,!0),a+=2}break;case 2:o[0]=s,o[1]=o[0]+e.columns,o[2]=o[1]+e.columns,s=o[2]+e.columns;for(let i=0;i<e.columns;++i){n+=t[o[0]++]<<24|t[o[1]++]<<16|t[o[2]++]<<8,r.setUint32(a,n,!0),a+=4}}}return r}function B(e){const t=e.viewer,i={value:e.offset.value},n=new Uint8Array(e.columns*e.lines*(e.inputChannels.length*e.type*2)),r={version:N(t,i),unknownUncompressedSize:N(t,i),unknownCompressedSize:N(t,i),acCompressedSize:N(t,i),dcCompressedSize:N(t,i),rleCompressedSize:N(t,i),rleUncompressedSize:N(t,i),rleRawSize:N(t,i),totalAcUncompressedCount:N(t,i),totalDcUncompressedCount:N(t,i),acCompression:N(t,i)};if(r.version<2)throw new Error("EXRLoader.parse: "+$.compression+" version "+r.version+" is unsupported");const s=new Array;let a=Q(t,i)-2;for(;a>0;){const e=L(t.buffer,i),n=k(t,i),r=n>>2&3,o=new Int8Array([(n>>4)-1])[0],l=k(t,i);s.push({name:e,index:o,type:l,compression:r}),a-=e.length+3}const o=$.channels,l=new Array(e.inputChannels.length);for(let t=0;t<e.inputChannels.length;++t){const i=l[t]={},n=o[t];i.name=n.name,i.compression=0,i.decoded=!1,i.type=n.pixelType,i.pLinear=n.pLinear,i.width=e.columns,i.height=e.lines}const c={idx:new Array(3)};for(let t=0;t<e.inputChannels.length;++t){const e=l[t];for(let i=0;i<s.length;++i){const n=s[i];e.name==n.name&&(e.compression=n.compression,n.index>=0&&(c.idx[n.index]=t),e.offset=t)}}let h,d,u;if(r.acCompressedSize>0)switch(r.acCompression){case 0:h=new Uint16Array(r.totalAcUncompressedCount),y(e.array,t,i,r.acCompressedSize,h,r.totalAcUncompressedCount);break;case 1:const n=IP(e.array.slice(i.value,i.value+r.totalAcUncompressedCount));h=new Uint16Array(n.buffer),i.value+=r.totalAcUncompressedCount}if(r.dcCompressedSize>0){const t={array:e.array,offset:i,size:r.dcCompressedSize};d=new Uint16Array(P(t).buffer),i.value+=r.dcCompressedSize}if(r.rleRawSize>0){u=b(IP(e.array.slice(i.value,i.value+r.rleCompressedSize)).buffer),i.value+=r.rleCompressedSize}let p=0;const m=new Array(l.length);for(let e=0;e<m.length;++e)m[e]=new Array;for(let t=0;t<e.lines;++t)for(let t=0;t<l.length;++t)m[t].push(p),p+=l[t].width*e.type*2;!function(e,t,i,n,r,s){let a=new DataView(s.buffer);const o=i[e.idx[0]].width,l=i[e.idx[0]].height,c=Math.floor(o/8),h=Math.ceil(o/8),d=Math.ceil(l/8),u=o-8*(h-1),p=l-8*(d-1),m={value:0},g=new Array(3),f=new Array(3),A=new Array(3),y=new Array(3),v=new Array(3);for(let i=0;i<3;++i)v[i]=t[e.idx[i]],g[i]=i<1?0:g[i-1]+h*d,f[i]=new Float32Array(64),A[i]=new Uint16Array(64),y[i]=new Uint16Array(64*h);for(let t=0;t<d;++t){let s=8;t==d-1&&(s=p);let o=8;for(let e=0;e<h;++e){e==h-1&&(o=u);for(let e=0;e<3;++e)A[e].fill(0),A[e][0]=r[g[e]++],x(m,n,A[e]),w(A[e],f[e]),C(f[e]);S(f);for(let t=0;t<3;++t)M(f[t],y[t],64*e)}let l=0;for(let n=0;n<3;++n){const r=i[e.idx[n]].type;for(let e=8*t;e<8*t+s;++e){l=v[n][e];for(let t=0;t<c;++t){const i=64*t+8*(7&e);a.setUint16(l+0*r,y[n][i+0],!0),a.setUint16(l+2*r,y[n][i+1],!0),a.setUint16(l+4*r,y[n][i+2],!0),a.setUint16(l+6*r,y[n][i+3],!0),a.setUint16(l+8*r,y[n][i+4],!0),a.setUint16(l+10*r,y[n][i+5],!0),a.setUint16(l+12*r,y[n][i+6],!0),a.setUint16(l+14*r,y[n][i+7],!0),l+=16*r}}if(c!=h)for(let e=8*t;e<8*t+s;++e){const t=v[n][e]+8*c*2*r,i=64*c+8*(7&e);for(let e=0;e<o;++e)a.setUint16(t+2*e*r,y[n][i+e],!0)}}}const _=new Uint16Array(o);a=new DataView(s.buffer);for(let t=0;t<3;++t){i[e.idx[t]].decoded=!0;const n=i[e.idx[t]].type;if(2==i[t].type)for(let e=0;e<l;++e){const i=v[t][e];for(let e=0;e<o;++e)_[e]=a.getUint16(i+2*e*n,!0);for(let e=0;e<o;++e)a.setFloat32(i+2*e*n,G(_[e]),!0)}}}(c,m,l,h,d,n);for(let t=0;t<l.length;++t){const i=l[t];if(!i.decoded){if(2!==i.compression)throw new Error("EXRLoader.parse: unsupported channel compression");{let r=0,s=0;for(let a=0;a<e.lines;++a){let e=m[t][r];for(let t=0;t<i.width;++t){for(let t=0;t<2*i.type;++t)n[e++]=u[s+t*i.width*i.height];s++}r++}}}}return new DataView(n.buffer)}function L(e,t){const i=new Uint8Array(e);let n=0;for(;0!=i[t.value+n];)n+=1;const r=(new TextDecoder).decode(i.slice(t.value,t.value+n));return t.value=t.value+n+1,r}function O(e,t){const i=e.getInt32(t.value,!0);return t.value=t.value+4,i}function U(e,t){const i=e.getUint32(t.value,!0);return t.value=t.value+4,i}function F(e,t){const i=e[t.value];return t.value=t.value+1,i}function k(e,t){const i=e.getUint8(t.value);return t.value=t.value+1,i}const N=function(e,t){let i;return i="getBigInt64"in DataView.prototype?Number(e.getBigInt64(t.value,!0)):e.getUint32(t.value+4,!0)+Number(e.getUint32(t.value,!0)<<32),t.value+=8,i};function j(e,t){const i=e.getFloat32(t.value,!0);return t.value+=4,i}function z(e,t){return wr.toHalfFloat(j(e,t))}function G(e){const t=(31744&e)>>10,i=1023&e;return(e>>15?-1:1)*(t?31===t?i?NaN:1/0:Math.pow(2,t-15)*(1+i/1024):i/1024*6103515625e-14)}function Q(e,t){const i=e.getUint16(t.value,!0);return t.value+=2,i}function V(e,t){return G(Q(e,t))}function H(e,t,i,n,r){return"string"===n||"stringvector"===n||"iccProfile"===n?function(e,t,i){const n=(new TextDecoder).decode(new Uint8Array(e).slice(t.value,t.value+i));return t.value=t.value+i,n}(t,i,r):"chlist"===n?function(e,t,i,n){const r=i.value,s=[];for(;i.value<r+n-1;){const n=L(t,i),r=O(e,i),a=k(e,i);i.value+=3;const o=O(e,i),l=O(e,i);s.push({name:n,pixelType:r,pLinear:a,xSampling:o,ySampling:l})}return i.value+=1,s}(e,t,i,r):"chromaticities"===n?function(e,t){return{redX:j(e,t),redY:j(e,t),greenX:j(e,t),greenY:j(e,t),blueX:j(e,t),blueY:j(e,t),whiteX:j(e,t),whiteY:j(e,t)}}(e,i):"compression"===n?function(e,t){return["NO_COMPRESSION","RLE_COMPRESSION","ZIPS_COMPRESSION","ZIP_COMPRESSION","PIZ_COMPRESSION","PXR24_COMPRESSION","B44_COMPRESSION","B44A_COMPRESSION","DWAA_COMPRESSION","DWAB_COMPRESSION"][k(e,t)]}(e,i):"box2i"===n?function(e,t){return{xMin:O(e,t),yMin:O(e,t),xMax:O(e,t),yMax:O(e,t)}}(e,i):"envmap"===n?function(e,t){return["ENVMAP_LATLONG","ENVMAP_CUBE"][k(e,t)]}(e,i):"tiledesc"===n?function(e,t){const i=U(e,t),n=U(e,t),r=k(e,t);return{xSize:i,ySize:n,levelMode:["ONE_LEVEL","MIPMAP_LEVELS","RIPMAP_LEVELS"][15&r],roundingMode:["ROUND_DOWN","ROUND_UP"][r>>4]}}(e,i):"lineOrder"===n?function(e,t){return["INCREASING_Y","DECREASING_Y","RANDOM_Y"][k(e,t)]}(e,i):"float"===n?j(e,i):"v2f"===n?function(e,t){return[j(e,t),j(e,t)]}(e,i):"v3f"===n?function(e,t){return[j(e,t),j(e,t),j(e,t)]}(e,i):"int"===n?O(e,i):"rational"===n?function(e,t){return[O(e,t),U(e,t)]}(e,i):"timecode"===n?function(e,t){return[U(e,t),U(e,t)]}(e,i):"preview"===n?(i.value+=r,"skipped"):void(i.value+=r)}function W(e,t,i){let n=0;switch(e.levelMode){case"ONE_LEVEL":n=1;break;case"MIPMAP_LEVELS":n=function(e,t){const i=Math.log2(e);return"ROUND_DOWN"==t?Math.floor(i):Math.ceil(i)}(Math.max(t,i),e.roundingMode)+1;break;case"RIPMAP_LEVELS":throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.")}return n}function q(e,t,i,n){const r=new Array(e);for(let s=0;s<e;s++){const e=1<<s;let a=t/e|0;"ROUND_UP"==n&&a*e<t&&(a+=1);const o=Math.max(a,1);r[s]=(o+i-1)/i|0}return r}function X(){const e=this,t=e.offset,i={value:0};for(let n=0;n<e.tileCount;n++){const n=O(e.viewer,t),r=O(e.viewer,t);t.value+=8,e.size=U(e.viewer,t);const s=n*e.blockWidth,a=r*e.blockHeight;e.columns=s+e.blockWidth>e.width?e.width-s:e.blockWidth,e.lines=a+e.blockHeight>e.height?e.height-a:e.blockHeight;const o=e.columns*e.totalBytes,l=e.size<e.lines*o?e.uncompress(e):T(e);t.value+=e.size;for(let t=0;t<e.lines;t++){const n=t*e.columns*e.totalBytes;for(let r=0;r<e.inputChannels.length;r++){const o=$.channels[r].name,c=e.channelByteOffsets[o]*e.columns,h=e.decodeChannels[o];if(void 0===h)continue;i.value=n+c;const d=(e.height-(1+a+t))*e.outLineWidth;for(let t=0;t<e.columns;t++){const n=d+(t+s)*e.outputChannels+h;e.byteArray[n]=e.getter(l,i)}}}}}function Y(){const e=this,t=e.offset,i={value:0};for(let n=0;n<e.height/e.blockHeight;n++){const r=O(e.viewer,t)-$.dataWindow.yMin;e.size=U(e.viewer,t),e.lines=r+e.blockHeight>e.height?e.height-r:e.blockHeight;const s=e.columns*e.totalBytes,a=e.size<e.lines*s?e.uncompress(e):T(e);t.value+=e.size;for(let t=0;t<e.blockHeight;t++){const r=n*e.blockHeight,o=t+e.scanOrder(r);if(o>=e.height)continue;const l=t*s,c=(e.height-1-o)*e.outLineWidth;for(let t=0;t<e.inputChannels.length;t++){const n=$.channels[t].name,r=e.channelByteOffsets[n]*e.columns,s=e.decodeChannels[n];if(void 0!==s){i.value=l+r;for(let t=0;t<e.columns;t++){const n=c+t*e.outputChannels+s;e.byteArray[n]=e.getter(a,i)}}}}}}const K={value:0},J=new DataView(e),Z=new Uint8Array(e),$=function(e,t,i){const n={};if(20000630!=e.getUint32(0,!0))throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");n.version=e.getUint8(4);const r=e.getUint8(5);n.spec={singleTile:!!(2&r),longName:!!(4&r),deepFormat:!!(8&r),multiPart:!!(16&r)},i.value=8;let s=!0;for(;s;){const r=L(t,i);if(0==r)s=!1;else{const s=L(t,i),a=H(e,t,i,s,U(e,i));void 0===a?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${s}'.`):n[r]=a}}if(-7&r)throw console.error("THREE.EXRHeader:",n),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return n}(J,e,K),ee=function(e,t,i,n,r){const s={size:0,viewer:t,array:i,offset:n,width:e.dataWindow.xMax-e.dataWindow.xMin+1,height:e.dataWindow.yMax-e.dataWindow.yMin+1,inputChannels:e.channels,channelByteOffsets:{},scanOrder:null,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:Ut};switch(e.compression){case"NO_COMPRESSION":s.blockHeight=1,s.uncompress=T;break;case"RLE_COMPRESSION":s.blockHeight=1,s.uncompress=I;break;case"ZIPS_COMPRESSION":s.blockHeight=1,s.uncompress=P;break;case"ZIP_COMPRESSION":s.blockHeight=16,s.uncompress=P;break;case"PIZ_COMPRESSION":s.blockHeight=32,s.uncompress=D;break;case"PXR24_COMPRESSION":s.blockHeight=16,s.uncompress=R;break;case"DWAA_COMPRESSION":s.blockHeight=32,s.uncompress=B;break;case"DWAB_COMPRESSION":s.blockHeight=256,s.uncompress=B;break;default:throw new Error("EXRLoader.parse: "+e.compression+" is unsupported")}const a={};for(const t of e.channels)switch(t.name){case"Y":case"R":case"G":case"B":case"A":a[t.name]=!0,s.type=t.pixelType}let o=!1;if(a.R&&a.G&&a.B)o=!a.A,s.outputChannels=4,s.decodeChannels={R:0,G:1,B:2,A:3};else{if(!a.Y)throw new Error("EXRLoader.parse: file contains unsupported data channels.");s.outputChannels=1,s.decodeChannels={Y:0}}if(1==s.type)switch(r){case Pe:s.getter=V;break;case De:s.getter=Q}else{if(2!=s.type)throw new Error("EXRLoader.parse: unsupported pixelType "+s.type+" for "+e.compression+".");switch(r){case Pe:s.getter=j;break;case De:s.getter=z}}s.columns=s.width;const l=s.width*s.height*s.outputChannels;switch(r){case Pe:s.byteArray=new Float32Array(l),o&&s.byteArray.fill(1,0,l);break;case De:s.byteArray=new Uint16Array(l),o&&s.byteArray.fill(15360,0,l);break;default:console.error("THREE.EXRLoader: unsupported type: ",r)}let c=0;for(const t of e.channels)void 0!==s.decodeChannels[t.name]&&(s.channelByteOffsets[t.name]=c),c+=2*t.pixelType;if(s.totalBytes=c,s.outLineWidth=s.width*s.outputChannels,"INCREASING_Y"===e.lineOrder?s.scanOrder=e=>e:s.scanOrder=e=>s.height-1-e,4==s.outputChannels?(s.format=Ue,s.colorSpace=Ut):(s.format=Ne,s.colorSpace=Lt),e.spec.singleTile){s.blockHeight=e.tiles.ySize,s.blockWidth=e.tiles.xSize;const i=W(e.tiles,s.width,s.height),r=q(i,s.width,e.tiles.xSize,e.tiles.roundingMode),a=q(i,s.height,e.tiles.ySize,e.tiles.roundingMode);s.tileCount=r[0]*a[0];for(let e=0;e<i;e++)for(let i=0;i<a[e];i++)for(let i=0;i<r[e];i++)N(t,n);s.decode=X.bind(s)}else{s.blockWidth=s.width;const e=Math.ceil(s.height/s.blockHeight);for(let i=0;i<e;i++)N(t,n);s.decode=Y.bind(s)}return s}($,J,Z,K,this.type);return ee.decode(),{header:$,width:ee.width,height:ee.height,data:ee.byteArray,format:ee.format,colorSpace:ee.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,i,n){return super.load(e,function(e,i){e.colorSpace=i.colorSpace,e.minFilter=be,e.magFilter=be,e.generateMipmaps=!1,e.flipY=!1,t&&t(e,i)},i,n)}}const QD=new WeakMap;class VD extends su{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 r=new lu(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),this.url=e,r.load(e,i=>{if(QD.has(i))return QD.get(i).promise.then(t).catch(n);this.decodeObjects(i,e).then(e=>{e.userData.warnings=this.warnings,this.warnings=[],t(e)}).catch(e=>n(e))},i,n)}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}decodeObjects(e,t){let i,n;const r=e.byteLength,s=this._getWorker(r).then(t=>(i=t,n=this.workerNextTaskID++,new Promise((t,r)=>{i._callbacks[n]={resolve:t,reject:r},i.postMessage({type:"decode",id:n,buffer:e},[e])}))).then(e=>this._createGeometry(e.data)).catch(e=>{throw e});return s.catch(()=>!0).then(()=>{i&&n&&this._releaseTask(i,n)}),QD.set(e,{url:t,promise:s}),s}parse(e,t,i){this.decodeObjects(e,"").then(e=>{e.userData.warnings=this.warnings,t(e)}).catch(e=>i(e))}_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 e=0;e<this.materials.length;e++){const t=this.materials[e],n={};if(n.name=t.name,n.color={},n.color.r=t.color.r,n.color.g=t.color.g,n.color.b=t.color.b,n.type=t.type,n.vertexColors=t.vertexColors,JSON.stringify(n)===i)return t}return this.materials.push(e),e}_createMaterial(e,t){if(void 0===e)return new Td({color:new mr(1,1,1),metalness:.8,name:su.DEFAULT_MATERIAL_NAME,side:x});const i=new Id({color:new mr(e.diffuseColor.r/255,e.diffuseColor.g/255,e.diffuseColor.b/255),emissive:new mr(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:x,specularColor:e.specularColor,transparent:e.transparency>0});if(i.userData.id=e.id,e.pbrSupported){const t=e.pbr;i.anisotropy=t.anisotropic,i.anisotropyRotation=t.anisotropicRotation,i.color=new mr(t.baseColor.r,t.baseColor.g,t.baseColor.b),i.clearcoat=t.clearcoat,i.clearcoatRoughness=t.clearcoatRoughness,i.metalness=t.metallic,i.transmission=1-t.opacity,i.roughness=t.roughness,i.sheen=t.sheen,i.specularIntensity=t.specular,i.thickness=t.subsurface}e.pbrSupported&&0===e.pbr.opacity&&1===e.transparency&&(i.opacity=.2,i.transmission=1);const n=new uu;for(let t=0;t<e.textures.length;t++){const r=e.textures[t];if(null!==r.image){const e=n.load(r.image);switch(r.type){case"Bump":i.bumpMap=e;break;case"Diffuse":case"PBR_BaseColor":i.map=e;break;case"Emap":i.envMap=e;break;case"Opacity":i.transmissionMap=e;break;case"Transparency":case"PBR_Alpha":i.alphaMap=e,i.transparent=!0;break;case"PBR_AmbientOcclusion":i.aoMap=e;break;case"PBR_Anisotropic":i.anisotropyMap=e;break;case"PBR_Clearcoat":i.clearcoatMap=e;break;case"PBR_ClearcoatBump":i.clearcoatNormalMap=e;break;case"PBR_ClearcoatRoughness":i.clearcoatRoughnessMap=e;break;case"PBR_Displacement":i.displacementMap=e;break;case"PBR_Emission":i.emissiveMap=e;break;case"PBR_Metallic":i.metalnessMap=e;break;case"PBR_Roughness":i.roughnessMap=e;break;case"PBR_Sheen":i.sheenColorMap=e;break;case"PBR_Specular":i.specularColorMap=e;break;case"PBR_Subsurface":i.thicknessMap=e;break;default:this.warnings.push({message:`THREE.3DMLoader: No conversion exists for 3dm ${r.type}.`,type:"no conversion"})}e.wrapS=0===r.wrapU?ge:fe,e.wrapT=0===r.wrapV?ge:fe,r.repeat&&e.repeat.set(r.repeat[0],r.repeat[1])}}return t&&(new GD).load(t.image,function(e){e.mapping=THREE.EquirectangularReflectionMapping,i.envMap=e}),i}_createGeometry(e){const t=new Zn,i=[],n=[],r=[];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 s=e.objects;const a=e.materials;for(let o=0;o<s.length;o++){const l=s[o],c=l.attributes;switch(l.objectType){case"InstanceDefinition":n.push(l);break;case"InstanceReference":r.push(l);break;default:let s=null;switch(c.materialSource.name){case"ObjectMaterialSource_MaterialFromLayer":c.layerIndex>=0&&(s=e.layers[c.layerIndex].renderMaterialIndex);break;case"ObjectMaterialSource_MaterialFromObject":c.materialIndex>=0&&(s=c.materialIndex)}let o=null;if(s>=0){const t=a[s];o=this._createMaterial(t,e.renderEnvironment)}const h=this._createObject(l,o);if(void 0===h)continue;const d=e.layers[c.layerIndex];h.visible=!d||d.visible,c.isInstanceDefinitionObject?i.push(h):t.add(h)}}for(let o=0;o<n.length;o++){const l=n[o];s=[];for(let e=0;e<l.attributes.objectIds.length;e++){const t=l.attributes.objectIds[e];for(let e=0;e<i.length;e++){t===i[e].userData.attributes.id&&s.push(i[e])}}for(let i=0;i<r.length;i++){const n=r[i];if(n.geometry.parentIdefId===l.attributes.id){const i=n.geometry.xform.array,r=new Sn;if(r.set(...i),1===s.length){const i=s[0].clone(!0);if(i.name=n.attributes.name||i.name,i.applyMatrix4(r),n.attributes.materialIndex>=0&&n.attributes.materialIndex!==s[0].userData.attributes.materialIndex){const e=a[n.attributes.materialIndex],t=this._createMaterial(e);i.material=this._compareMaterials(t)}if(i.userData.defAttributes=i.userData.attributes,i.userData.defObjectType=i.userData.objectType,i.userData.attributes={...i.userData.attributes,...n.attributes},i.userData.objectType=n.objectType,void 0!==n.attributes.layerIndex){const t=e.layers[n.attributes.layerIndex];i.visible=t?t.visible:i.visible}t.add(i)}else{console.warn("THREE.Rhino3dmLoader: InstanceReference with multiple/no objects, not all properties will be copied.");const e=new Zn;e.applyMatrix4(r);for(let t=0;t<s.length;t++)e.add(s[t].clone(!0));t.add(e)}}}}return t.userData.materials=this.materials,t.name="",t}_createObject(e,t){const i=new Ou,n=e.attributes;let r,s,a,o;switch(e.objectType){case"Point":case"PointSet":r=i.parse(e.geometry),r.attributes.hasOwnProperty("color")?s=new Hc({vertexColors:!0,sizeAttenuation:!1,size:2}):(a=n.drawColor,o=new mr(a.r/255,a.g/255,a.b/255),s=new Hc({color:o,sizeAttenuation:!1,size:2})),s=this._compareMaterials(s);const l=new Kc(r,s);return l.userData.attributes=n,l.userData.objectType=e.objectType,n.name&&(l.name=n.name),l;case"Mesh":case"Extrusion":case"SubD":case"Brep":if(null===e.geometry)return;r=i.parse(e.geometry),null===t&&(t=this._createMaterial()),r.attributes.hasOwnProperty("color")&&(t.vertexColors=!0),t=this._compareMaterials(t);const c=new ts(r,t);return c.castShadow=n.castsShadows,c.receiveShadow=n.receivesShadows,c.userData.attributes=n,c.userData.objectType=e.objectType,n.name&&(c.name=n.name,r.name=n.name),c;case"Curve":r=i.parse(e.geometry),a=n.drawColor,o=new mr(a.r/255,a.g/255,a.b/255),s=new Dc({color:o}),s=this._compareMaterials(s);const h=new Nc(r,s);return h.userData.attributes=n,h.userData.objectType=e.objectType,n.name&&(h.name=n.name),h;case"TextDot":r=e.geometry;const d=document.createElement("canvas").getContext("2d"),u=`${r.fontHeight}px ${r.fontFace}`;d.font=u;const p=d.measureText(r.text).width+10,m=r.fontHeight+10,g=window.devicePixelRatio;d.canvas.width=p*g,d.canvas.height=m*g,d.canvas.style.width=p+"px",d.canvas.style.height=m+"px",d.setTransform(g,0,0,g,0,0),d.font=u,d.textBaseline="middle",d.textAlign="center",o=n.drawColor,d.fillStyle=`rgba(${o.r},${o.g},${o.b},${o.a})`,d.fillRect(0,0,p,m),d.fillStyle="white",d.fillText(r.text,p/2,m/2);const f=new ih(d.canvas);f.minFilter=be,f.generateMipmaps=!1,f.wrapS=fe,f.wrapT=fe,s=new Cl({map:f,depthTest:!1});const A=new kl(s);return A.position.set(r.point[0],r.point[1],r.point[2]),A.scale.set(p/10,m/10,1),A.userData.attributes=n,A.userData.objectType=e.objectType,n.name&&(A.name=n.name),A;case"Light":let y;switch(r=e.geometry,r.lightStyle.name){case"LightStyle_WorldPoint":y=new Su,y.castShadow=n.castsShadows,y.position.set(r.location[0],r.location[1],r.location[2]),y.shadow.normalBias=.1;break;case"LightStyle_WorldSpot":y=new _u,y.castShadow=n.castsShadows,y.position.set(r.location[0],r.location[1],r.location[2]),y.target.position.set(r.direction[0],r.direction[1],r.direction[2]),y.angle=r.spotAngleRadians,y.shadow.normalBias=.1;break;case"LightStyle_WorldRectangular":y=new Iu;const e=Math.abs(r.width[2]),t=Math.abs(r.length[0]);y.position.set(r.location[0]-t/2,r.location[1],r.location[2]-e/2),y.height=t,y.width=e,y.lookAt(r.direction[0],r.direction[1],r.direction[2]);break;case"LightStyle_WorldDirectional":y=new Eu,y.castShadow=n.castsShadows,y.position.set(r.location[0],r.location[1],r.location[2]),y.target.position.set(r.direction[0],r.direction[1],r.direction[2]),y.shadow.normalBias=.1}return y&&(y.intensity=r.intensity,a=r.diffuse,o=new mr(a.r/255,a.g/255,a.b/255),y.color=o,y.userData.attributes=n,y.userData.objectType=e.objectType),y}}_initLibrary(){if(!this.libraryPending){const e=new lu(this.manager);e.setPath(this.libraryPath);const t=new Promise((t,i)=>{e.load("rhino3dm.js",t,void 0,i)}),i=new lu(this.manager);i.setPath(this.libraryPath),i.setResponseType("arraybuffer");const n=new Promise((e,t)=>{i.load("rhino3dm.wasm",e,void 0,t)});this.libraryPending=Promise.all([t,n]).then(([e,t])=>{this.libraryConfig.wasmBinary=t;const i=HD,n=["/* rhino3dm.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([n]))})}return this.libraryPending}_getWorker(e){return this._initLibrary().then(()=>{if(this.workerPool.length<this.workerLimit){const e=new Worker(this.workerSourceURL);e._callbacks={},e._taskCosts={},e._taskLoad=0,e.postMessage({type:"init",libraryConfig:this.libraryConfig}),e.onmessage=t=>{const i=t.data;switch(i.type){case"warning":this.warnings.push(i.data),console.warn(i.data);break;case"decode":e._callbacks[i.id].resolve(i);break;case"error":e._callbacks[i.id].reject(i);break;default:console.error('THREE.Rhino3dmLoader: Unexpected message, "'+i.type+'"')}},this.workerPool.push(e)}else this.workerPool.sort(function(e,t){return e._taskLoad>t._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 HD="\nfunction Rhino3dmWorker() {\n\n\tlet libraryPending;\n\tlet libraryConfig;\n\tlet rhino;\n\tlet taskID;\n\n\tonmessage = function ( e ) {\n\n\t\tconst message = e.data;\n\n\t\tswitch ( message.type ) {\n\n\t\t\tcase 'init':\n\n\t\t\t\tlibraryConfig = message.libraryConfig;\n\t\t\t\tconst wasmBinary = libraryConfig.wasmBinary;\n\t\t\t\tlet RhinoModule;\n\t\t\t\tlibraryPending = new Promise( function ( resolve ) {\n\n\t\t\t\t\t/* Like Basis Loader */\n\t\t\t\t\tRhinoModule = { wasmBinary, onRuntimeInitialized: resolve };\n\n\t\t\t\t\trhino3dm( RhinoModule ); // eslint-disable-line no-undef\n\n\t\t\t\t } ).then( () => {\n\n\t\t\t\t\trhino = RhinoModule;\n\n\t\t\t\t } );\n\n\t\t\t\tbreak;\n\n\t\t\tcase 'decode':\n\n\t\t\t\ttaskID = message.id;\n\t\t\t\tconst buffer = message.buffer;\n\t\t\t\tlibraryPending.then( () => {\n\n\t\t\t\t\ttry {\n\n\t\t\t\t\t\tconst data = decodeObjects( rhino, buffer );\n\t\t\t\t\t\tself.postMessage( { type: 'decode', id: message.id, data } );\n\n\t\t\t\t\t} catch ( error ) {\n\n\t\t\t\t\t\tself.postMessage( { type: 'error', id: message.id, error } );\n\n\t\t\t\t\t}\n\n\t\t\t\t} );\n\n\t\t\t\tbreak;\n\n\t\t}\n\n\t};\n\n\tfunction decodeObjects( rhino, buffer ) {\n\n\t\tconst arr = new Uint8Array( buffer );\n\t\tconst doc = rhino.File3dm.fromByteArray( arr );\n\n\t\tconst objects = [];\n\t\tconst materials = [];\n\t\tconst layers = [];\n\t\tconst views = [];\n\t\tconst namedViews = [];\n\t\tconst groups = [];\n\t\tconst strings = [];\n\n\t\t//Handle objects\n\n\t\tconst objs = doc.objects();\n\t\tconst cnt = objs.count;\n\n\t\tfor ( let i = 0; i < cnt; i ++ ) {\n\n\t\t\tconst _object = objs.get( i );\n\n\t\t\tconst object = extractObjectData( _object, doc );\n\n\t\t\t_object.delete();\n\n\t\t\tif ( object ) {\n\n\t\t\t\tobjects.push( object );\n\n\t\t\t}\n\n\t\t}\n\n\t\t// Handle instance definitions\n\t\t// console.log( `Instance Definitions Count: ${doc.instanceDefinitions().count()}` );\n\n\t\tfor ( let i = 0; i < doc.instanceDefinitions().count; i ++ ) {\n\n\t\t\tconst idef = doc.instanceDefinitions().get( i );\n\t\t\tconst idefAttributes = extractProperties( idef );\n\t\t\tidefAttributes.objectIds = idef.getObjectIds();\n\n\t\t\tobjects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );\n\n\t\t}\n\n\t\t// Handle materials\n\n\t\tconst textureTypes = [\n\t\t\t// rhino.TextureType.Bitmap,\n\t\t\trhino.TextureType.Diffuse,\n\t\t\trhino.TextureType.Bump,\n\t\t\trhino.TextureType.Transparency,\n\t\t\trhino.TextureType.Opacity,\n\t\t\trhino.TextureType.Emap\n\t\t];\n\n\t\tconst pbrTextureTypes = [\n\t\t\trhino.TextureType.PBR_BaseColor,\n\t\t\trhino.TextureType.PBR_Subsurface,\n\t\t\trhino.TextureType.PBR_SubsurfaceScattering,\n\t\t\trhino.TextureType.PBR_SubsurfaceScatteringRadius,\n\t\t\trhino.TextureType.PBR_Metallic,\n\t\t\trhino.TextureType.PBR_Specular,\n\t\t\trhino.TextureType.PBR_SpecularTint,\n\t\t\trhino.TextureType.PBR_Roughness,\n\t\t\trhino.TextureType.PBR_Anisotropic,\n\t\t\trhino.TextureType.PBR_Anisotropic_Rotation,\n\t\t\trhino.TextureType.PBR_Sheen,\n\t\t\trhino.TextureType.PBR_SheenTint,\n\t\t\trhino.TextureType.PBR_Clearcoat,\n\t\t\trhino.TextureType.PBR_ClearcoatBump,\n\t\t\trhino.TextureType.PBR_ClearcoatRoughness,\n\t\t\trhino.TextureType.PBR_OpacityIor,\n\t\t\trhino.TextureType.PBR_OpacityRoughness,\n\t\t\trhino.TextureType.PBR_Emission,\n\t\t\trhino.TextureType.PBR_AmbientOcclusion,\n\t\t\trhino.TextureType.PBR_Displacement\n\t\t];\n\n\t\tfor ( let i = 0; i < doc.materials().count; i ++ ) {\n\n\t\t\tconst _material = doc.materials().get( i );\n\n\t\t\tconst material = extractProperties( _material );\n\n\t\t\tconst textures = [];\n\n\t\t\ttextures.push( ...extractTextures( _material, textureTypes, doc ) );\n\n\t\t\tmaterial.pbrSupported = _material.physicallyBased().supported;\n\n\t\t\tif ( material.pbrSupported ) {\n\n\t\t\t\ttextures.push( ...extractTextures( _material, pbrTextureTypes, doc ) );\n\t\t\t\tmaterial.pbr = extractProperties( _material.physicallyBased() );\n\n\t\t\t}\n\n\t\t\tmaterial.textures = textures;\n\n\t\t\tmaterials.push( material );\n\n\t\t\t_material.delete();\n\n\t\t}\n\n\t\t// Handle layers\n\n\t\tfor ( let i = 0; i < doc.layers().count; i ++ ) {\n\n\t\t\tconst _layer = doc.layers().get( i );\n\t\t\tconst layer = extractProperties( _layer );\n\n\t\t\tlayers.push( layer );\n\n\t\t\t_layer.delete();\n\n\t\t}\n\n\t\t// Handle views\n\n\t\tfor ( let i = 0; i < doc.views().count; i ++ ) {\n\n\t\t\tconst _view = doc.views().get( i );\n\t\t\tconst view = extractProperties( _view );\n\n\t\t\tviews.push( view );\n\n\t\t\t_view.delete();\n\n\t\t}\n\n\t\t// Handle named views\n\n\t\tfor ( let i = 0; i < doc.namedViews().count; i ++ ) {\n\n\t\t\tconst _namedView = doc.namedViews().get( i );\n\t\t\tconst namedView = extractProperties( _namedView );\n\n\t\t\tnamedViews.push( namedView );\n\n\t\t\t_namedView.delete();\n\n\t\t}\n\n\t\t// Handle groups\n\n\t\tfor ( let i = 0; i < doc.groups().count; i ++ ) {\n\n\t\t\tconst _group = doc.groups().get( i );\n\t\t\tconst group = extractProperties( _group );\n\n\t\t\tgroups.push( group );\n\n\t\t\t_group.delete();\n\n\t\t}\n\n\t\t// Handle settings\n\n\t\tconst settings = extractProperties( doc.settings() );\n\n\t\t//TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.\n\n\t\t// Handle dimstyles\n\t\t// console.log( `Dimstyle Count: ${doc.dimstyles().count()}` );\n\n\t\t// Handle bitmaps\n\t\t// console.log( `Bitmap Count: ${doc.bitmaps().count()}` );\n\n\t\t// Handle strings\n\t\t// console.log( `Document Strings Count: ${doc.strings().count()}` );\n\t\t// Note: doc.strings().documentUserTextCount() counts any doc.strings defined in a section\n\t\t// console.log( `Document User Text Count: ${doc.strings().documentUserTextCount()}` );\n\n\t\tconst strings_count = doc.strings().count;\n\n\t\tfor ( let i = 0; i < strings_count; i ++ ) {\n\n\t\t\tstrings.push( doc.strings().get( i ) );\n\n\t\t}\n\n\t\t// Handle Render Environments for Material Environment\n\n\t\t// get the id of the active render environment skylight, which we'll use for environment texture\n\t\tconst reflectionId = doc.settings().renderSettings().renderEnvironments.reflectionId;\n\n\t\tconst rc = doc.renderContent();\n\n\t\tlet renderEnvironment = null;\n\n\t\tfor ( let i = 0; i < rc.count; i ++ ) {\n\n\t\t\tconst content = rc.get(i);\n\n\t\t\tswitch ( content.kind ) {\n\n\t\t\t\tcase 'environment':\n\n\t\t\t\t\tconst id = content.id;\n\n\t\t\t\t\t// there could be multiple render environments in a 3dm file\n\t\t\t\t\tif ( id !== reflectionId ) break;\n\n\t\t\t\t\tconst renderTexture = content.findChild( 'texture' );\n\t\t\t\t\tconst fileName = renderTexture.fileName;\n\n\t\t\t\t\tfor ( let j = 0; j < doc.embeddedFiles().count; j ++ ) {\n\n\t\t\t\t\t\tconst _fileName = doc.embeddedFiles().get( j ).fileName;\n\n\t\t\t\t\t\tif ( fileName === _fileName ) {\n\n\t\t\t\t\t\t\tconst background = doc.getEmbeddedFileAsBase64( fileName );\n\t\t\t\t\t\t\tconst backgroundImage = 'data:image/png;base64,' + background;\n\t\t\t\t\t\t\trenderEnvironment = { type: 'renderEnvironment', image: backgroundImage, name: fileName };\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t}\n\n\t\t// Handle Render Settings\n\n\t\tconst renderSettings = {\n\t\t\tambientLight: doc.settings().renderSettings().ambientLight,\n\t\t\tbackgroundColorTop: doc.settings().renderSettings().backgroundColorTop,\n\t\t\tbackgroundColorBottom: doc.settings().renderSettings().backgroundColorBottom,\n\t\t\tuseHiddenLights: doc.settings().renderSettings().useHiddenLights,\n\t\t\tdepthCue: doc.settings().renderSettings().depthCue,\n\t\t\tflatShade: doc.settings().renderSettings().flatShade,\n\t\t\trenderBackFaces: doc.settings().renderSettings().renderBackFaces,\n\t\t\trenderPoints: doc.settings().renderSettings().renderPoints,\n\t\t\trenderCurves: doc.settings().renderSettings().renderCurves,\n\t\t\trenderIsoParams: doc.settings().renderSettings().renderIsoParams,\n\t\t\trenderMeshEdges: doc.settings().renderSettings().renderMeshEdges,\n\t\t\trenderAnnotations: doc.settings().renderSettings().renderAnnotations,\n\t\t\tuseViewportSize: doc.settings().renderSettings().useViewportSize,\n\t\t\tscaleBackgroundToFit: doc.settings().renderSettings().scaleBackgroundToFit,\n\t\t\ttransparentBackground: doc.settings().renderSettings().transparentBackground,\n\t\t\timageDpi: doc.settings().renderSettings().imageDpi,\n\t\t\tshadowMapLevel: doc.settings().renderSettings().shadowMapLevel,\n\t\t\tnamedView: doc.settings().renderSettings().namedView,\n\t\t\tsnapShot: doc.settings().renderSettings().snapShot,\n\t\t\tspecificViewport: doc.settings().renderSettings().specificViewport,\n\t\t\tgroundPlane: extractProperties( doc.settings().renderSettings().groundPlane ),\n\t\t\tsafeFrame: extractProperties( doc.settings().renderSettings().safeFrame ),\n\t\t\tdithering: extractProperties( doc.settings().renderSettings().dithering ),\n\t\t\tskylight: extractProperties( doc.settings().renderSettings().skylight ),\n\t\t\tlinearWorkflow: extractProperties( doc.settings().renderSettings().linearWorkflow ),\n\t\t\trenderChannels: extractProperties( doc.settings().renderSettings().renderChannels ),\n\t\t\tsun: extractProperties( doc.settings().renderSettings().sun ),\n\t\t\trenderEnvironments: extractProperties( doc.settings().renderSettings().renderEnvironments ),\n\t\t\tpostEffects: extractProperties( doc.settings().renderSettings().postEffects ),\n\n\t\t};\n\n\t\tdoc.delete();\n\n\t\treturn { objects, materials, layers, views, namedViews, groups, strings, settings, renderSettings, renderEnvironment };\n\n\t}\n\n\tfunction extractTextures( m, tTypes, d ) {\n\n\t\tconst textures = [];\n\n\t\tfor ( let i = 0; i < tTypes.length; i ++ ) {\n\n\t\t\tconst _texture = m.getTexture( tTypes[ i ] );\n\t\t\tif ( _texture ) {\n\n\t\t\t\tlet textureType = tTypes[ i ].constructor.name;\n\t\t\t\ttextureType = textureType.substring( 12, textureType.length );\n\t\t\t\tconst texture = extractTextureData( _texture, textureType, d );\n\t\t\t\ttextures.push( texture );\n\t\t\t\t_texture.delete();\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn textures;\n\n\t}\n\n\tfunction extractTextureData( t, tType, d ) {\n\n\t\tconst texture = { type: tType };\n\n\t\tconst image = d.getEmbeddedFileAsBase64( t.fileName );\n\n\t\ttexture.wrapU = t.wrapU;\n\t\ttexture.wrapV = t.wrapV;\n\t\ttexture.wrapW = t.wrapW;\n\t\tconst uvw = t.uvwTransform.toFloatArray( true );\n\n\t\ttexture.repeat = [ uvw[ 0 ], uvw[ 5 ] ];\n\n\t\tif ( image ) {\n\n\t\t\ttexture.image = 'data:image/png;base64,' + image;\n\n\t\t} else {\n\n\t\t\tself.postMessage( { type: 'warning', id: taskID, data: {\n\t\t\t\tmessage: `THREE.3DMLoader: Image for ${tType} texture not embedded in file.`,\n\t\t\t\ttype: 'missing resource'\n\t\t\t}\n\n\t\t\t} );\n\n\t\t\ttexture.image = null;\n\n\t\t}\n\n\t\treturn texture;\n\n\t}\n\n\tfunction extractObjectData( object, doc ) {\n\n\t\tconst _geometry = object.geometry();\n\t\tconst _attributes = object.attributes();\n\t\tlet objectType = _geometry.objectType;\n\t\tlet geometry, attributes, position, data, mesh;\n\n\t\t// skip instance definition objects\n\t\t//if( _attributes.isInstanceDefinitionObject ) { continue; }\n\n\t\t// TODO: handle other geometry types\n\t\tswitch ( objectType ) {\n\n\t\t\tcase rhino.ObjectType.Curve:\n\n\t\t\t\tconst pts = curveToPoints( _geometry, 100 );\n\n\t\t\t\tposition = {};\n\t\t\t\tattributes = {};\n\t\t\t\tdata = {};\n\n\t\t\t\tposition.itemSize = 3;\n\t\t\t\tposition.type = 'Float32Array';\n\t\t\t\tposition.array = [];\n\n\t\t\t\tfor ( let j = 0; j < pts.length; j ++ ) {\n\n\t\t\t\t\tposition.array.push( pts[ j ][ 0 ] );\n\t\t\t\t\tposition.array.push( pts[ j ][ 1 ] );\n\t\t\t\t\tposition.array.push( pts[ j ][ 2 ] );\n\n\t\t\t\t}\n\n\t\t\t\tattributes.position = position;\n\t\t\t\tdata.attributes = attributes;\n\n\t\t\t\tgeometry = { data };\n\n\t\t\t\tbreak;\n\n\t\t\tcase rhino.ObjectType.Point:\n\n\t\t\t\tconst pt = _geometry.location;\n\n\t\t\t\tposition = {};\n\t\t\t\tconst color = {};\n\t\t\t\tattributes = {};\n\t\t\t\tdata = {};\n\n\t\t\t\tposition.itemSize = 3;\n\t\t\t\tposition.type = 'Float32Array';\n\t\t\t\tposition.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];\n\n\t\t\t\tconst _color = _attributes.drawColor( doc );\n\n\t\t\t\tcolor.itemSize = 3;\n\t\t\t\tcolor.type = 'Float32Array';\n\t\t\t\tcolor.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];\n\n\t\t\t\tattributes.position = position;\n\t\t\t\tattributes.color = color;\n\t\t\t\tdata.attributes = attributes;\n\n\t\t\t\tgeometry = { data };\n\n\t\t\t\tbreak;\n\n\t\t\tcase rhino.ObjectType.PointSet:\n\t\t\tcase rhino.ObjectType.Mesh:\n\n\t\t\t\tgeometry = _geometry.toThreejsJSON();\n\n\t\t\t\tbreak;\n\n\t\t\tcase rhino.ObjectType.Brep:\n\n\t\t\t\tconst faces = _geometry.faces();\n\t\t\t\tmesh = new rhino.Mesh();\n\n\t\t\t\tfor ( let faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {\n\n\t\t\t\t\tconst face = faces.get( faceIndex );\n\t\t\t\t\tconst _mesh = face.getMesh( rhino.MeshType.Any );\n\n\t\t\t\t\tif ( _mesh ) {\n\n\t\t\t\t\t\tmesh.append( _mesh );\n\t\t\t\t\t\t_mesh.delete();\n\n\t\t\t\t\t}\n\n\t\t\t\t\tface.delete();\n\n\t\t\t\t}\n\n\t\t\t\tif ( mesh.faces().count > 0 ) {\n\n\t\t\t\t\tmesh.compact();\n\t\t\t\t\tgeometry = mesh.toThreejsJSON();\n\t\t\t\t\tfaces.delete();\n\n\t\t\t\t}\n\n\t\t\t\tmesh.delete();\n\n\t\t\t\tbreak;\n\n\t\t\tcase rhino.ObjectType.Extrusion:\n\n\t\t\t\tmesh = _geometry.getMesh( rhino.MeshType.Any );\n\n\t\t\t\tif ( mesh ) {\n\n\t\t\t\t\tgeometry = mesh.toThreejsJSON();\n\t\t\t\t\tmesh.delete();\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase rhino.ObjectType.TextDot:\n\n\t\t\t\tgeometry = extractProperties( _geometry );\n\n\t\t\t\tbreak;\n\n\t\t\tcase rhino.ObjectType.Light:\n\n\t\t\t\tgeometry = extractProperties( _geometry );\n\n\t\t\t\tif ( geometry.lightStyle.name === 'LightStyle_WorldLinear' ) {\n\n\t\t\t\t\tself.postMessage( { type: 'warning', id: taskID, data: {\n\t\t\t\t\t\tmessage: `THREE.3DMLoader: No conversion exists for ${objectType.constructor.name} ${geometry.lightStyle.name}`,\n\t\t\t\t\t\ttype: 'no conversion',\n\t\t\t\t\t\tguid: _attributes.id\n\t\t\t\t\t}\n\n\t\t\t\t\t} );\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase rhino.ObjectType.InstanceReference:\n\n\t\t\t\tgeometry = extractProperties( _geometry );\n\t\t\t\tgeometry.xform = extractProperties( _geometry.xform );\n\t\t\t\tgeometry.xform.array = _geometry.xform.toFloatArray( true );\n\n\t\t\t\tbreak;\n\n\t\t\tcase rhino.ObjectType.SubD:\n\n\t\t\t\t// TODO: precalculate resulting vertices and faces and warn on excessive results\n\t\t\t\t_geometry.subdivide( 3 );\n\t\t\t\tmesh = rhino.Mesh.createFromSubDControlNet( _geometry, false );\n\t\t\t\tif ( mesh ) {\n\n\t\t\t\t\tgeometry = mesh.toThreejsJSON();\n\t\t\t\t\tmesh.delete();\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t\t/*\n\t\t\t\tcase rhino.ObjectType.Annotation:\n\t\t\t\tcase rhino.ObjectType.Hatch:\n\t\t\t\tcase rhino.ObjectType.ClipPlane:\n\t\t\t\t*/\n\n\t\t\tdefault:\n\n\t\t\t\tself.postMessage( { type: 'warning', id: taskID, data: {\n\t\t\t\t\tmessage: `THREE.3DMLoader: Conversion not implemented for ${objectType.constructor.name}`,\n\t\t\t\t\ttype: 'not implemented',\n\t\t\t\t\tguid: _attributes.id\n\t\t\t\t}\n\n\t\t\t\t} );\n\n\t\t\t\tbreak;\n\n\t\t}\n\n\t\tif ( geometry ) {\n\n\t\t\tattributes = extractProperties( _attributes );\n\t\t\tattributes.geometry = extractProperties( _geometry );\n\n\t\t\tif ( _attributes.groupCount > 0 ) {\n\n\t\t\t\tattributes.groupIds = _attributes.getGroupList();\n\n\t\t\t}\n\n\t\t\tif ( _attributes.userStringCount > 0 ) {\n\n\t\t\t\tattributes.userStrings = _attributes.getUserStrings();\n\n\t\t\t}\n\n\t\t\tif ( _geometry.userStringCount > 0 ) {\n\n\t\t\t\tattributes.geometry.userStrings = _geometry.getUserStrings();\n\n\t\t\t}\n\n\t\t\tif ( _attributes.decals().count > 0 ) {\n\n\t\t\t\tself.postMessage( { type: 'warning', id: taskID, data: {\n\t\t\t\t\tmessage: `THREE.3DMLoader: No conversion exists for the decals associated with this object.`,\n\t\t\t\t\ttype: 'no conversion',\n\t\t\t\t\tguid: _attributes.id\n\t\t\t\t}\n\n\t\t\t\t} );\n\n\t\t\t}\n\n\t\t\tattributes.drawColor = _attributes.drawColor( doc );\n\n\t\t\tobjectType = objectType.constructor.name;\n\t\t\tobjectType = objectType.substring( 11, objectType.length );\n\n\t\t\treturn { geometry, attributes, objectType };\n\n\t\t} else {\n\n\t\t\tself.postMessage( { type: 'warning', id: taskID, data: {\n\t\t\t\tmessage: `THREE.3DMLoader: ${objectType.constructor.name} has no associated mesh geometry.`,\n\t\t\t\ttype: 'missing mesh',\n\t\t\t\tguid: _attributes.id\n\t\t\t}\n\n\t\t\t} );\n\n\t\t}\n\n\t}\n\n\tfunction extractProperties( object ) {\n\n\t\tconst result = {};\n\n\t\tfor ( const property in object ) {\n\n\t\t\tconst value = object[ property ];\n\n\t\t\tif ( typeof value !== 'function' ) {\n\n\t\t\t\tif ( typeof value === 'object' && value !== null && value.hasOwnProperty( 'constructor' ) ) {\n\n\t\t\t\t\tresult[ property ] = { name: value.constructor.name, value: value.value };\n\n\t\t\t\t} else if ( typeof value === 'object' && value !== null ) {\n\n\t\t\t\t\tresult[ property ] = extractProperties( value );\n\n\t\t\t\t} else {\n\n\t\t\t\t\tresult[ property ] = value;\n\n\t\t\t\t}\n\n\t\t\t} else {\n\n\t\t\t\t// these are functions that could be called to extract more data.\n\t\t\t\t//console.log( `${property}: ${object[ property ].constructor.name}` );\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn result;\n\n\t}\n\n\tfunction curveToPoints( curve, pointLimit ) {\n\n\t\tlet pointCount = pointLimit;\n\t\tlet rc = [];\n\t\tconst ts = [];\n\n\t\tif ( curve instanceof rhino.LineCurve ) {\n\n\t\t\treturn [ curve.pointAtStart, curve.pointAtEnd ];\n\n\t\t}\n\n\t\tif ( curve instanceof rhino.PolylineCurve ) {\n\n\t\t\tpointCount = curve.pointCount;\n\t\t\tfor ( let i = 0; i < pointCount; i ++ ) {\n\n\t\t\t\trc.push( curve.point( i ) );\n\n\t\t\t}\n\n\t\t\treturn rc;\n\n\t\t}\n\n\t\tif ( curve instanceof rhino.PolyCurve ) {\n\n\t\t\tconst segmentCount = curve.segmentCount;\n\n\t\t\tfor ( let i = 0; i < segmentCount; i ++ ) {\n\n\t\t\t\tconst segment = curve.segmentCurve( i );\n\t\t\t\tconst segmentArray = curveToPoints( segment, pointCount );\n\t\t\t\trc = rc.concat( segmentArray );\n\t\t\t\tsegment.delete();\n\n\t\t\t}\n\n\t\t\treturn rc;\n\n\t\t}\n\n\t\tif ( curve instanceof rhino.ArcCurve ) {\n\n\t\t\tpointCount = Math.floor( curve.angleDegrees / 5 );\n\t\t\tpointCount = pointCount < 2 ? 2 : pointCount;\n\t\t\t// alternative to this hardcoded version: https://stackoverflow.com/a/18499923/2179399\n\n\t\t}\n\n\t\tif ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) {\n\n\t\t\tconst pLine = curve.tryGetPolyline();\n\n\t\t\tfor ( let i = 0; i < pLine.count; i ++ ) {\n\n\t\t\t\trc.push( pLine.get( i ) );\n\n\t\t\t}\n\n\t\t\tpLine.delete();\n\n\t\t\treturn rc;\n\n\t\t}\n\n\t\tconst domain = curve.domain;\n\t\tconst divisions = pointCount - 1.0;\n\n\t\tfor ( let j = 0; j < pointCount; j ++ ) {\n\n\t\t\tconst t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] );\n\n\t\t\tif ( t === domain[ 0 ] || t === domain[ 1 ] ) {\n\n\t\t\t\tts.push( t );\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t\tconst tan = curve.tangentAt( t );\n\t\t\tconst prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] );\n\n\t\t\t// Duplicated from THREE.Vector3\n\t\t\t// How to pass imports to worker?\n\n\t\t\tconst tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ];\n\t\t\tconst ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ];\n\n\t\t\tconst denominator = Math.sqrt( tS * ptS );\n\n\t\t\tlet angle;\n\n\t\t\tif ( denominator === 0 ) {\n\n\t\t\t\tangle = Math.PI / 2;\n\n\t\t\t} else {\n\n\t\t\t\tconst theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator;\n\t\t\t\tangle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) );\n\n\t\t\t}\n\n\t\t\tif ( angle < 0.1 ) continue;\n\n\t\t\tts.push( t );\n\n\t\t}\n\n\t\trc = ts.map( t => curve.pointAt( t ) );\n\t\treturn rc;\n\n\t}\n\n}\n",WD=class e extends VD{constructor(t){super(t),this.materials=[],this.setLibraryPath(e.LIBRARY_PATH)}_createMaterial(t){return e.ImportMaterials?super._createMaterial(t):this.materials[0]||new Td({color:new mr(1,1,1),metalness:.8,name:"default",side:x})}async loadAsync(t,i){const n=await super.loadAsync(t,i);n.rotateX(-Math.PI/2),n.userData.materials&&delete n.userData.materials;const r=n.userData.layers;return n.traverse(t=>{const i=t.userData.attributes?.castsShadows,s=t.userData.attributes?.receivesShadows;t.castShadow=i,t.receiveShadow=s;const a=t.userData.attributes?.layerIndex??t.userData.defAttributes?.layerIndex,o=r[a];o&&(t.userData.rhinoLayer=o),t.userData.rhino3dmRoot=n.uuid,e.LoadUserDataStrings||(t.userData.strings=[]),e.LoadUserDataWarnings||delete t.userData.warnings,this._hideLineMesh(t),this._useInstancedMesh(t),this._useMaterialSource(t,o)}),this.materials=[],n}_useMaterialSource(t,i){if(!e.ImportMaterials)return;const n=t;if("default"===n.material?.name||e.ForceLayerMaterials){const t=n.userData.attributes?.materialSource||n.userData.defAttributes?.materialSource,r=n.userData.attributes?.colorSource||n.userData.defAttributes?.colorSource;if(!e.ForceLayerMaterials&&!t&&!r)return;e.ForceLayerMaterials||0===t?.value||1===t?.value&&0===r?.value?i&&(n.material=this._compareMaterials(this._createMaterial({diffuseColor:i.color,name:i.name,transparency:0,textures:[]}))):3===t?.value||1===t?.value&&3===r?.value?n.traverseAncestors(e=>{e?.material&&(n.material=e.material)}):t&&1!==t.value&&console.warn("Unknown material source",t,n,n.userData.attributes)}}_useInstancedMesh(t){if(!e.ReplaceWithInstancedMesh||t.children.length<=0)return;const i=t.children,n=i.map(e=>e.geometry);n.filter((e,t)=>n.indexOf(e)===t).forEach(e=>{const n=i.filter(t=>t.geometry===e),r=n.length>0?n.filter(e=>e.material===n[0].material):[];if(r.length>1){const i=new uc(e,r[0].material,r.length);i.userData={...r[0].userData},i.userData.instanceUserData=[],i.userData.attributes=i.userData.defAttributes||i.userData.attributes,i.userData.defAttributes&&delete i.userData.defAttributes,i.name=i.userData.attributes?.name||r[0].name,r.forEach((e,n)=>{i.setMatrixAt(n,e.matrix),t.remove(e),i.userData.instanceUserData.push(e.userData)}),t.add(i)}})}_hideLineMesh(t){if(!e.HideLineMesh&&!e.HidePointMesh||t.children.length<=0)return;const i=[];t.traverse(t=>{(t&&e.HideLineMesh&&(t.isLine||t.isLineSegments)||e.HidePointMesh&&t.isPoints)&&i.push(t)}),i.forEach(e=>{e.userData.visible_3dm=e.visible,e.visible=!1})}};WD.LIBRARY_PATH=`https://cdn.jsdelivr.net/npm/rhino3dm@${dg("rhino3dm","8.0.1")}/`,WD.ImportMaterials=!0,WD.ForceLayerMaterials=!1,WD.ReplaceWithInstancedMesh=!1,WD.HideLineMesh=!1,WD.HidePointMesh=!1,WD.LoadUserDataStrings=!0,WD.LoadUserDataWarnings=!0;let qD=WD;const XD=class e extends su{constructor(e){super(e)}load(t,i,n,r){const s=e.USE_CANVAS_TEXTURE?document.createElement("canvas"):void 0,a=e.USE_CANVAS_TEXTURE?new ih(s):new Ni,o=new hu(this.manager);return o.setCrossOrigin(this.crossOrigin),o.setPath(this.path),o.load(t,function(t){s?e.CopyImageToCanvas(s,t):a.image=t,a.needsUpdate=!0,void 0!==i&&i(a)},n,r),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.")}};XD.USE_CANVAS_TEXTURE="true"!==dg("svg-load-disable-canvas");let YD=XD;class KD extends su{constructor(e){super(e)}load(e,t,i,n){void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,s=iu.get(e);if(void 0!==s)return r.manager.itemStart(e),setTimeout(function(){t&&t(s),r.manager.itemEnd(e)},0),s;const a=document.createElementNS("http://www.w3.org/1999/xhtml","video");function o(){a.removeEventListener("loadedmetadata",o,!1),a.removeEventListener("error",l,!1),iu.add(e,a),t&&t(a),r.manager.itemEnd(e)}function l(t){a.removeEventListener("loadedmetadata",o,!1),a.removeEventListener("error",l,!1),n&&n(t),r.manager.itemError(e),r.manager.itemEnd(e)}return a.addEventListener("loadedmetadata",o,!1),a.addEventListener("error",l,!1),"data:"!==e.substr(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),r.manager.itemStart(e),a.src=e,a.preload="auto",a.autoplay=!0,a.setAttribute("webkit-playsinline","webkit-playsinline"),a.setAttribute("playsinline",""),a}}class JD extends su{constructor(e){super(e)}load(e,t,i,n){const r=new KD(this.manager);let s;r.setCrossOrigin(this.crossOrigin),r.setPath(this.path);const a=r.load(e,function(e){s||(s=new Zc(e)),s.format=Ue,s.minFilter=be,s.magFilter=be,s.colorSpace=Ot,s.needsUpdate=!0,void 0!==t&&t(s)},i,n);return!s&&a&&(s=new Zc(a)),s}}const ZD=class e extends iM{constructor(){super(),this.processors=[],this.processors.push(bT)}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?e:await new Promise((i,n)=>this.parse(e,i,n,t));for(const e of this.processors)i=await e(i,t);if(i&&i instanceof Blob)return i;if(i&&"object"==typeof i&&!i.byteLength)return new Blob([JSON.stringify(i,(e,t)=>e.startsWith("__")?void 0:t,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 r={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};"glb"===n.exportExt&&(r.binary=!0);return super.parse(e,e=>{t(Object.assign(e,{__isGLTFOutput:!0}))},i,r,new KM)}setup(t,i){for(const t of e.ExportExtensions)this.register(t);if(i)for(const e of i)this.register(e);return this.register(this.gltfViewerWriter(t)),this}gltfViewerWriter(e){return t=>({afterParse:i=>{let n;if(i=Array.isArray(i)?i[0]:i,i?.userData?.rootSceneModelRoot&&!1!==t.options?.exporterOptions?.viewerConfig&&!1!==i?.userData?.__exportViewerConfig?n=xE.ExportViewerConfig(e,t):(n=S_(t.serializationMeta),xE.BundleExtraResources(t.json,n),xE.BundleArrayBuffers(n,t)),!n||0===Object.values(n).reduce((e,t)=>e+Object.keys(t).length,0))return;const r=t.json.extras||{};r[LD.BundledResourcesKey]=n,t.json.extras=r}})}};ZD.ExportExtensions=[eE.Export,yE.Export,ZM.Export,hE.Export,mE.Export,iE.Export,e=>({name:"_AssetPropsWriter",beforeParse:e=>{const t=Array.isArray(e)?e:[e];for(const e of t)e.userData.gltfExtras&&(e.__gltfExtras=e.userData.gltfExtras,delete e.userData.gltfExtras),e.userData.gltfAsset&&(e.__gltfAsset=e.userData.gltfAsset,delete e.userData.gltfAsset)},afterParse:t=>{const i=e.json.extras||{},n=Array.isArray(t)?t:[t];for(const e of n)e.__gltfAsset&&(e.userData.gltfAsset=e.__gltfAsset,delete e.__gltfAsset),e.__gltfExtras&&(e.userData.gltfExtras=e.__gltfExtras,Object.assign(i,e.userData.gltfExtras),delete e.__gltfExtras);Object.keys(i).length>0&&(e.json.extras=i)}})];let $D=ZD;class eR{async parseAsync(e,{jsonSpaces:t=2}){return new Blob([JSON.stringify(e,null,t)],{type:"application/json"})}}class tR{async parseAsync(e,t){return new Blob([e],{type:"text/plain"})}}const iR=new TextEncoder;class nR{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,r=t,s=i;!function(e){if(!e||!e.isWebGLRenderTarget)throw Error("EXRExporter.parse: Unsupported second parameter, expected instance of WebGLRenderTarget.");if(e.isWebGLCubeRenderTarget||e.isWebGL3DRenderTarget||e.isWebGLArrayRenderTarget)throw Error("EXRExporter.parse: Unsupported render target type, expected instance of WebGLRenderTarget.");if(e.texture.type!==Pe&&e.texture.type!==De)throw Error("EXRExporter.parse: Unsupported WebGLRenderTarget texture type.");if(e.texture.format!==Ue)throw Error("EXRExporter.parse: Unsupported WebGLRenderTarget texture format, expected RGBAFormat.")}(r);const a=function(e,t={}){const i={0:1,2:1,3:16},n=t.textureIndex||0,r=Array.isArray(e.textures)?e.textures[n]:e.texture,s=e.width,a=e.height,o=r.type,l=r.format,c=r.colorSpace,h=void 0!==t.compression?t.compression:3,d=void 0!==t.type?t.type:De,u=d===Pe?2:1,p=i[h];return{width:s,height:a,type:o,format:l,colorSpace:c,compression:h,blockLines:p,dataType:u,dataSize:2*u,numBlocks:Math.ceil(a/p),numInputChannels:4,numOutputChannels:4,flipY:!1,textureIndex:t.textureIndex||0}}(r,s),o=function(e,t,i){let n;return n=i.type===Pe?new Float32Array(i.width*i.height*i.numInputChannels):new Uint16Array(i.width*i.height*i.numInputChannels),e.readRenderTargetPixels(t,0,0,i.width,i.height,n,void 0,i.textureIndex),n}(n,r,a);return lR(sR(rR(o,a),a),a)}if(e.isDataTexture){const i=e,n=t;!function(e){if(e.type!==Pe&&e.type!==De)throw Error("EXRExporter.parse: Unsupported DataTexture texture type.");if(e.format!==Ue)throw Error("EXRExporter.parse: Unsupported DataTexture texture format, expected RGBAFormat.");if(!e.image.data)throw Error("EXRExporter.parse: Invalid DataTexture image data.");if(e.type===Pe&&"Float32Array"!==e.image.data.constructor.name)throw Error("EXRExporter.parse: DataTexture image data doesn't match type, expected 'Float32Array'.");if(e.type===De&&"Uint16Array"!==e.image.data.constructor.name)throw Error("EXRExporter.parse: DataTexture image data doesn't match type, expected 'Uint16Array'.")}(i);const r=function(e,t={}){const i={0:1,2:1,3:16},n=e.image.width,r=e.image.height,s=e.type,a=e.format,o=e.colorSpace,l=void 0!==t.compression?t.compression:3,c=void 0!==t.type?t.type:De,h=c===Pe?2:1,d=i[l];return{width:n,height:r,type:s,format:a,colorSpace:o,compression:l,blockLines:d,dataType:h,dataSize:2*h,numBlocks:Math.ceil(r/d),numInputChannels:4,numOutputChannels:4,flipY:e.isDataTexture&&e.flipY,textureIndex:t.textureIndex||0}}(i,n);return lR(sR(rR(i.image.data,r),r),r)}}}function rR(e,t){const i=t.width,n=t.height,r={r:0,g:0,b:0,a:0},s={value:0},a=4==t.numOutputChannels?1:0,o=t.type==Pe?AR:fR,l=1==t.dataType?uR:pR,c=new Uint8Array(t.width*t.height*t.numOutputChannels*t.dataSize),h=new DataView(c.buffer);for(let c=0;c<n;++c)for(let d=0;d<i;++d){const u=c*i*4+4*d,p=o(e,u),m=o(e,u+1),g=o(e,u+2),f=o(e,u+3),A=(t.flipY?c:n-c-1)*i*(3+a)*t.dataSize;cR(r,p,m,g,f),s.value=A+d*t.dataSize,l(h,r.a,s),s.value=A+a*i*t.dataSize+d*t.dataSize,l(h,r.b,s),s.value=A+(1+a)*i*t.dataSize+d*t.dataSize,l(h,r.g,s),s.value=A+(2+a)*i*t.dataSize+d*t.dataSize,l(h,r.r,s)}return c}function sR(e,t){let i,n,r=0;const s={data:new Array,totalSize:0},a=t.width*t.numOutputChannels*t.blockLines*t.dataSize;switch(t.compression){case 0:i=aR;break;case 2:case 3:i=oR}0!==t.compression&&(n=new Uint8Array(a));for(let o=0;o<t.numBlocks;++o){const t=e.subarray(a*o,a*(o+1));let l=i(t,n);l.length>=t.length&&(l=t),r+=l.length,s.data.push({dataChunk:l,size:l.length})}return s.totalSize=r,s}function aR(e){return e}function oR(e,t){t=t.subarray(0,e.length);let i=0,n=Math.floor((e.length+1)/2),r=0;const s=e.length-1;for(;!(r>s||(t[i++]=e[r++],r>s));)t[n++]=e[r++];let a=t[0];for(let e=1;e<t.length;e++){const i=t[e]-a+384;a=t[e],t[e]=i}return SP(t)}function lR(e,t){const i=8*t.numBlocks,n=259+18*t.numOutputChannels,r={value:n+i},s=new Uint8Array(n+i+e.totalSize+8*t.numBlocks),a=new DataView(s.buffer);!function(e,t,i){const n={value:0},r=new DataView(e.buffer);dR(r,20000630,n),dR(r,2,n),gR(r,"compression",n),gR(r,"compression",n),dR(r,1,n),hR(r,i.compression,n),gR(r,"screenWindowCenter",n),gR(r,"v2f",n),dR(r,8,n),dR(r,0,n),dR(r,0,n),gR(r,"screenWindowWidth",n),gR(r,"float",n),dR(r,4,n),pR(r,1,n),gR(r,"pixelAspectRatio",n),gR(r,"float",n),dR(r,4,n),pR(r,1,n),gR(r,"lineOrder",n),gR(r,"lineOrder",n),dR(r,1,n),hR(r,0,n),gR(r,"dataWindow",n),gR(r,"box2i",n),dR(r,16,n),dR(r,0,n),dR(r,0,n),dR(r,i.width-1,n),dR(r,i.height-1,n),gR(r,"displayWindow",n),gR(r,"box2i",n),dR(r,16,n),dR(r,0,n),dR(r,0,n),dR(r,i.width-1,n),dR(r,i.height-1,n),gR(r,"channels",n),gR(r,"chlist",n),dR(r,18*i.numOutputChannels+1,n),gR(r,"A",n),dR(r,i.dataType,n),n.value+=4,dR(r,1,n),dR(r,1,n),gR(r,"B",n),dR(r,i.dataType,n),n.value+=4,dR(r,1,n),dR(r,1,n),gR(r,"G",n),dR(r,i.dataType,n),n.value+=4,dR(r,1,n),dR(r,1,n),gR(r,"R",n),dR(r,i.dataType,n),n.value+=4,dR(r,1,n),dR(r,1,n),hR(r,0,n),hR(r,0,n);let s=n.value+8*i.numBlocks;for(let e=0;e<t.data.length;++e)mR(r,s,n),s+=t.data[e].size+8}(s,e,t);for(let i=0;i<e.data.length;++i){const n=e.data[i].dataChunk,o=e.data[i].size;dR(a,i*t.blockLines,r),dR(a,o,r),s.set(n,r.value),r.value+=o}return s}function cR(e,t,i,n,r){e.r=t,e.g=i,e.b=n,e.a=r}function hR(e,t,i){e.setUint8(i.value,t),i.value+=1}function dR(e,t,i){e.setUint32(i.value,t,!0),i.value+=4}function uR(e,t,i){e.setUint16(i.value,wr.toHalfFloat(t),!0),i.value+=2}function pR(e,t,i){e.setFloat32(i.value,t,!0),i.value+=4}function mR(e,t,i){e.setBigUint64(i.value,BigInt(t),!0),i.value+=8}function gR(e,t,i){const n=iR.encode(t+"\0");for(let t=0;t<n.length;++t)hR(e,n[t],i)}function fR(e,t){return function(e){const t=(31744&e)>>10,i=1023&e;return(e>>15?-1:1)*(t?31===t?i?NaN:1/0:Math.pow(2,t-15)*(1+i/1024):i/1024*6103515625e-14)}(e[t])}function AR(e,t){return e[t]}class yR extends nR{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&&void 0===t.textureIndex&&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 vR=(e,t)=>{const i=e.exportOptions||{},n=e.obj.isMaterial?e.obj:null,r=e.obj.isObject3D?e.obj:null;if("processing"===e.state){if(n){const e=t.replaceTexture?Nw.getMapsForMaterial.call(n):null,i=e&&t.replaceTexture?_R(e,n,n,t.replaceTexture):null;n.__exportState={savedMaps:i}}if(r){const{objectList:e,meshLines:n,fomMap:s,geomMap:a,matCloneMap:o,savedTextures:l}=r.__exportState={objectList:new Set,meshLines:new Map,fomMap:new Map,geomMap:new Map,matCloneMap:new Map,savedTextures:new Map};r.traverse(t=>{t?.isObject3D&&(e.add(t),t.children&&t._sChildren&&(t._tChildren=t.children,t.children=t._sChildren))});const c=new Map;e.forEach(e=>{!1!==i.preserveUUIDs&&e.uuid&&(e.userData.gltfUUID=e.uuid),t.object&&t.object(e,r),function(e,t){if(e.animations){t.animations||(t.animations=[]);for(const i of e.animations){if(!1===i.__gltfExport)continue;const n=i.userData.rootRefs||[];!1!==t.preserveUUIDs&&e.uuid?n.includes(e.uuid)||n.push(e.uuid):e.name&&(n.includes(e.name)||n.push(e.name)),i.userData.rootRefs=n,t.animations.includes(i)||t.animations.push(i)}}}(e,i);const l=function(e,t,i){const n=e.geometry;if(!n)return;let r=null;if(n.userData.isPlaceholder)r=$S.DummyGeometry;else if(i){const s=i(e,n,t);s&&(r=s)}if(r&&r!==n)return r}(e,r,t.objectGeometry);l&&(t.objectGeometryReplace&&t.objectGeometryReplace(e,l),a.set(e,e.forcedOverrideGeometry),e.forcedOverrideGeometry=l);const h=n.has(e)?null:function(e){const t=e,i=t.geometry;if("function"==typeof i?.getPositions&&void 0===e.isLine&&void 0===e.isLineSegments&&(e.isLine2||e.isLineSegments2)){const n=i.getPositions();if(n){const r=i.getColors&&t.geometry.getColors(),s=new Fr;s.attributes.position=new Mr(n,3),r&&(s.attributes.color=new Mr(r,3)),s.name=i.name,s.userData=i.userData,s.uuid=i.uuid;const a=e.geometry;return e.assetType?e._currentGeometry=s:e.geometry=s,t.isLine2?e.isLine=!0:t.isLineSegments2&&(e.isLine=!0,e.isLineSegments=!0),a}}}(e);h&&n.set(e,h),t.objectMaterials&&t.objectMaterials(e,r.material);const d=function(e,t,i,n,r){if(!e.material)return;const s=e.material,a=Array.isArray(s),o=a?s:[s];let l=a?[...s]:s;const c=(e,i,n)=>{let r=t.get(i);r||(r=n(),t.set(i,r)),a?l[e]=r:l=r};if(o.forEach((t,s)=>{if(t.userData.isPlaceholder)c(s,t,()=>$S.DummyMaterial);else{const a=r?r(e,t,n,s):null;if(a)c(s,t,a);else{const e=Nw.getMapsForMaterial.call(t);i.set(t,e),void 0!==t.userData.sProperties&&c(s,t,()=>{const e=new t.constructor;e.name=t.name;return P_(I_(t,t.userData.sProperties),e),e.userData.uuid=t.uuid,e.userData.sProperties=t.userData.sProperties,e.userData.rootPath=t.userData.rootPath,e.userData.rootPathOptions=t.userData.rootPathOptions,e})}}}),a?l.some((e,t)=>e!==s[t]):l!==s)return l}(e,o,c,r,t.objectMaterial);void 0!==d&&(t.objectMaterialsReplace&&t.objectMaterialsReplace(e,d),s.set(e,e.forcedOverrideMaterial),e.forcedOverrideMaterial=d);const u=qw.getMapsForObject3D.call(e);c.set(e,u)}),t.replaceTexture&&c.forEach((e,i)=>{const n=_R(e,i,r,t.replaceTexture);l.set(i,n)}),c.clear()}}if(("done"===e.state||"error"===e.state)&&(n&&n.__exportState&&(t.revertTextures&&t.revertTextures(n),bR(n.__exportState.savedMaps,n),delete n.__exportState),r&&r.__exportState)){const{objectList:e,meshLines:n,fomMap:s,geomMap:a,matCloneMap:o,savedTextures:l}=r.__exportState;delete r.__exportState,e.forEach(e=>{!1!==i.preserveUUIDs&&e.userData.gltfUUID&&delete e.userData.gltfUUID,function(e,t){if(t&&e.geometry){const i=e.geometry;e.assetType?e._currentGeometry=t:e.geometry=t,i.dispose(!0),e.isLine&&delete e.isLine,e.isLineSegments&&delete e.isLineSegments}}(e,n.get(e)),t.revertObject&&t.revertObject(e),e._tChildren&&(e.children=e._tChildren,delete e._tChildren)}),n.clear(),e.clear(),new Set([...o.values()]).forEach(e=>{e.dispose&&e.dispose()}),o.clear(),s.forEach((e,t)=>{void 0!==e?t.forcedOverrideMaterial=e:delete t.forcedOverrideMaterial}),s.clear(),a.forEach((e,t)=>{void 0!==e?t.forcedOverrideGeometry=e:delete t.forcedOverrideGeometry}),a.clear(),t.revertTextures&&l.forEach((e,i)=>{t.revertTextures&&t.revertTextures(i),bR(e,i)}),l.clear()}};function _R(e,t,i,n){const r={},s={};return e.forEach((e,a)=>{if(!n)return;const o=n(t,e,a,i);o!==e&&(r[a]=o,s[a]=e)}),P_(r,t),s}function bR(e,t){e&&P_(e,t)}class xR extends ri{constructor(){super(),this.exporters=[{ctor:()=>new eR,ext:["json"]},{ctor:()=>new tR,ext:["txt","text"]},{ctor:()=>new yR,ext:["exr"]}],this.exportHooks={},this._cachedWriters=[],this.addEventListener("exportFile",e=>vR(e,this.exportHooks))}addExporter(...e){for(const t of e){if(this.exporters.includes(t))return void console.warn("Exporter already added",t);this.exporters.push(t)}}removeExporter(...e){for(const t of e){const e=this.exporters.indexOf(t);e>=0&&this.exporters.splice(e,1)}}getExporter(...e){return this.exporters.find(t=>t.ext.some(t=>e.includes(t)))}async exportObject(e,t={}){if(!e?.assetType)return void console.error("Object has no asset type");const i=[];"model"===e.assetType&&e.traverse(e=>{e.userData.excludeFromExport&&e.visible&&(e.visible=!1,i.push(e))});const n=await this._exportFile(e,t);return"model"===e.assetType&&i.forEach(e=>e.visible=!0),e?.userData?.rootSceneModelRoot&&!1===t.viewerConfig&&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),r=n?.typeExt||n?.ext;if(!n||!r)throw console.error(n,t,e),new Error(`AssetExporter - Unable to preprocess before export ${r}`);if(n.blob)i=n.blob;else{const s=this._getWriter(r);this.dispatchEvent({type:"exportFile",obj:e,state:"exporting",exportOptions:t}),i=await s.parseAsync(n.obj,{exportExt:n.ext??r,...t}),i.ext=n.ext}i=await this.processAfterExport(i,e,t),this.dispatchEvent({type:"exportFile",obj:e,state:"done",exportOptions:t})}catch(i){throw console.error("AssetExporter: Unable to Export file",e),this.dispatchEvent({type:"exportFile",obj:e,state:"error",error:i,exportOptions:t}),i}return i}_createParser(e){const t=this.exporters.find(t=>t.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":return void console.error("AssetExporter: light export not implemented");case"model":return{obj:e,ext:t.exportExt??"glb"};case"material":return{obj:wR(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&&"auto"!==t.exportExt?"exr"===t.exportExt?"image/x-exr":"image/"+t.exportExt:"auto";let n;if(e.textures.length>1){const t={};for(let n=0;n<e.textures.length;n++){const r=e.renderManager.exportRenderTarget(e,i,n);t[`texture_${n}.${r.ext}`]=new Uint8Array(r.__buffer||await r.arrayBuffer())}const r=ZP(t);n=new Blob([r],{type:"application/zip"}),n.ext="zip",n.__buffer=r.buffer}else n=e.renderManager.exportRenderTarget(e,i);return{obj:e,ext:n.ext,blob:n}}return{obj:e,ext:"exr"};default:console.error("AssetExporter: unknown asset type",e.assetType)}}async processAfterExport(e,t,i={}){return e}dispose(){}}function wR(e){return e.toJSON()}class CR extends ri{constructor(){super(),this._materials=[],this._disposeMaterial=e=>{const t=e.target;!t||"material"!==t.assetType||this.unregisterMaterial(t)},this._registerMaterial=e=>{const t=e.target;!t||"material"!==t.assetType||this.registerMaterial(t)},this.unregisterExtensionsOnRemove=!1,this._materialExtensions=[],function(){const e="\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n";Ts.bumpmap_pars_fragment=R_(Ts.bumpmap_pars_fragment,e,`\n    #ifdef BUMP_MAP_SCALE_LEGACY\n        ${e.replace(/normalize/g,"")}\n    #else\n        ${e}\n    #endif\n    `)}()}findOrCreate(e,t){let i=this.findMaterial(e);return i||(i=this.create(e,t)),i}create(e,t={},i=!0,n){const r=this.findTemplate(e);if(!r)return void console.error("No material template found for type",e);const s=this._create(r,t);return n&&Tm(s,"uuid",n,!0,!0),s&&i&&this.registerMaterial(s),s}_create(e,t){if(!e)return void console.error("No material template provided");const i=new e;return t&&i&&i.setValues(t,!0),i}registerMaterial(e){e&&!this._materials.includes(e)&&(e.assetType||Qw.call(e),this.findMaterial(e.uuid)&&(Tm(e,"uuid",Ky(),!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(e=>this.registerMaterial(e))}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)e||!i.userData.runtimeMaterial?i.dispose():this._materials.push(i)}findMaterial(e){return e?this._materials.find(t=>t.uuid===e):void 0}findMaterialsByName(e,t=!1){return this._materials.filter(i=>"string"!=typeof e||t?null!==i.name.match("string"==typeof e?"^"+e+"$":e):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 r=e.userData?.uuid||e.uuid;let s=this.findMaterial(r);if(s||!1===n)s&&(console.warn("Material with the same uuid already exists, copying properties"),e.type!==s.type&&console.error("Material type mismatch, delete previous material first?",e,s),s.setValues(e));else{const n=!1===t||!e.isMaterial,r=i||!n&&e.type&&e.type||"physical";s=this.create(r,n?void 0:e)}return s?(s.uuid=r,s.userData.uuid=r,e.iMaterial=s):(console.warn("Failed to convert material to IMaterial, just upgrading",e,t,i),s=Nw.upgradeMaterial.call(e)),s}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 t of this._materials)t.unregisterMaterialExtensions?.([e])}}clearExtensions(){[...this._materialExtensions].forEach(e=>this.unregisterMaterialExtension(e))}exportMaterial(e,t,i=!0,n=!1){const r=e.toJSON(),s=JSON.stringify(r,null,i?0:2),a=(t||e.name||"physical_material")+"."+e.constructor.TypeSlug,o=new File([s],a,{type:"application/json"});return n&&wm(o),o}applyMaterial(e,t,i=!0,n){let r=this.findMaterialsByName(t,i);(!r||r.length<1)&&(r=[this.findMaterial(t)]);let s=!1;for(const t of r)t&&t!==e&&!t.userData.__isVariation&&this.copyMaterialProps(t,e,n)&&(s=!0);return s}copyMaterialProps(e,t,i){let n=!1;const r=Object.getPrototypeOf(t).constructor.TYPE;if(Object.getPrototypeOf(e).constructor.TYPE===r){const r=e.name;e.setValues(t,void 0,void 0,i),e.name=r,n=!0}else{const i=e["__"+r]||this.create(r);if(i){const s=e.name;i.setValues?i.setValues(t):Object.assign(i,t),i.name=s;const a=e.appliedMeshes;for(const e of[...a??[]])e&&(e.material=i,n=!0);e["__"+r]=i}}return n}registerMaterialTemplate(e){if(!e||f_.SerializableMaterials.has(e))return;const t=[...f_.SerializableMaterials.values()].find(t=>t.TYPE===e.TYPE);t&&console.warn("Material template with the same type already exists",e,t),f_.SerializableMaterials.add(e)}unregisterMaterialTemplate(e){e&&f_.SerializableMaterials.delete(e)}findTemplate(e){if(e)return[...f_.SerializableMaterials.values()].find(t=>t.TYPE===e)||[...f_.SerializableMaterials.values()].find(t=>t.TypeAlias?.includes(e))}}class SR extends du{constructor(e){super(e),this.type=De}parse(e){const t=function(e,t){switch(e){case 1:throw new Error("THREE.RGBELoader: Read Error: "+(t||""));case 2:throw new Error("THREE.RGBELoader: Write Error: "+(t||""));case 3:throw new Error("THREE.RGBELoader: Bad File Format: "+(t||""));default:throw new Error("THREE.RGBELoader: Memory Error: "+(t||""))}},i=function(e,t,i){t=t||1024;let n=e.pos,r=-1,s=0,a="",o=String.fromCharCode.apply(null,new Uint16Array(e.subarray(n,n+128)));for(;0>(r=o.indexOf("\n"))&&s<t&&n<e.byteLength;)a+=o,s+=o.length,n+=128,o+=String.fromCharCode.apply(null,new Uint16Array(e.subarray(n,n+128)));return-1<r&&(e.pos+=s+r+1,a+o.slice(0,r))},n=function(e,t,i,n){const r=e[t+3],s=Math.pow(2,r-128)/255;i[n+0]=e[t+0]*s,i[n+1]=e[t+1]*s,i[n+2]=e[t+2]*s,i[n+3]=1},r=function(e,t,i,n){const r=e[t+3],s=Math.pow(2,r-128)/255;i[n+0]=wr.toHalfFloat(Math.min(e[t+0]*s,65504)),i[n+1]=wr.toHalfFloat(Math.min(e[t+1]*s,65504)),i[n+2]=wr.toHalfFloat(Math.min(e[t+2]*s,65504)),i[n+3]=wr.toHalfFloat(1)},s=new Uint8Array(e);s.pos=0;const a=function(e){const n=/^#\?(\S+)/,r=/^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,s=/^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,a=/^\s*FORMAT=(\S+)\s*$/,o=/^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,l={valid:0,string:"",comments:"",programtype:"RGBE",format:"",gamma:1,exposure:1,width:0,height:0};let c,h;for((e.pos>=e.byteLength||!(c=i(e)))&&t(1,"no header found"),(h=c.match(n))||t(3,"bad initial token"),l.valid|=1,l.programtype=h[1],l.string+=c+"\n";c=i(e),!1!==c;)if(l.string+=c+"\n","#"!==c.charAt(0)){if((h=c.match(r))&&(l.gamma=parseFloat(h[1])),(h=c.match(s))&&(l.exposure=parseFloat(h[1])),(h=c.match(a))&&(l.valid|=2,l.format=h[1]),(h=c.match(o))&&(l.valid|=4,l.height=parseInt(h[1],10),l.width=parseInt(h[2],10)),2&l.valid&&4&l.valid)break}else l.comments+=c+"\n";return 2&l.valid||t(3,"missing format specifier"),4&l.valid||t(3,"missing image size specifier"),l}(s),o=a.width,l=a.height,c=function(e,i,n){const r=i;if(r<8||r>32767||2!==e[0]||2!==e[1]||128&e[2])return new Uint8Array(e);r!==(e[2]<<8|e[3])&&t(3,"wrong scanline width");const s=new Uint8Array(4*i*n);s.length||t(4,"unable to allocate buffer space");let a=0,o=0;const l=4*r,c=new Uint8Array(4),h=new Uint8Array(l);let d=n;for(;d>0&&o<e.byteLength;){o+4>e.byteLength&&t(1),c[0]=e[o++],c[1]=e[o++],c[2]=e[o++],c[3]=e[o++],(2!=c[0]||2!=c[1]||(c[2]<<8|c[3])!=r)&&t(3,"bad rgbe scanline format");let i,n=0;for(;n<l&&o<e.byteLength;){i=e[o++];const r=i>128;if(r&&(i-=128),(0===i||n+i>l)&&t(3,"bad scanline data"),r){const t=e[o++];for(let e=0;e<i;e++)h[n++]=t}else h.set(e.subarray(o,o+i),n),n+=i,o+=i}const u=r;for(let e=0;e<u;e++){let t=0;s[a]=h[e+t],t+=r,s[a+1]=h[e+t],t+=r,s[a+2]=h[e+t],t+=r,s[a+3]=h[e+t],a+=4}d--}return s}(s.subarray(s.pos),o,l);let h,d,u;switch(this.type){case Pe:u=c.length/4;const e=new Float32Array(4*u);for(let t=0;t<u;t++)n(c,4*t,e,4*t);h=e,d=Pe;break;case De:u=c.length/4;const t=new Uint16Array(4*u);for(let e=0;e<u;e++)r(c,4*e,t,4*e);h=t,d=De;break;default:throw new Error("THREE.RGBELoader: Unsupported type: "+this.type)}return{width:o,height:l,data:h,header:a.string,gamma:a.gamma,exposure:a.exposure,type:d}}setDataType(e){return this.type=e,this}load(e,t,i,n){return super.load(e,function(e,i){switch(e.type){case Pe:case De:e.colorSpace=Ut,e.minFilter=be,e.magFilter=be,e.generateMipmaps=!1,e.flipY=!0}t&&t(e,i)},i,n)}}class MR extends wE{constructor(e){super(e),wE.ObjectConstructors.MeshStandardMaterial=yC,wE.ObjectConstructors.MeshBasicMaterial=kw,wE.ObjectConstructors.MeshPhysicalMaterial=yC,wE.ObjectConstructors.LineBasicMaterial=xC}transform(e,t){let i;return e.scene.traverse(e=>{if(i)return;const t=e.material;t&&t.isPhysicalMaterial&&(i=t)}),i}}const ER=class extends ri{constructor(e,t){super(),this._gltfExporter={ext:["gltf","glb"],extensions:[],ctor:(e,t)=>{const i=new $D;return i.setup(this.viewer,t.extensions),i}},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 $S(!!e.getPlugin("debug"),t),this.exporter=new xR,this.materials=new CR,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 t="string"==typeof e?e:e?.path;return t&&!t.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 r=Array.isArray(e)?e:[e];let s=Array.isArray(e)?[]:void 0;if(!1!==n?.importConfig){const e=r.find(e=>"config"===e?.assetType)||r.find(e=>e&&!!e.importedViewerConfig)?.importedViewerConfig;e&&function(e,t){const i=(e.version?e.version:"0.0.0").split(".").map(e=>parseInt(e));if("ViewerApp"!==e.type||0!==i[0]||!(i[1]<7||7===i[1]&&i[2].toString()[0]<"6"))return;const n=new Set;t.forEach(e=>e.traverse(e=>{e.material&&n.add(e.material)})),n.forEach(e=>{const t=e.map;if(!t)return;const i=t.repeat,n=t.offset,r=t.center,s=t.rotation;["alphaMap","aoMap","bumpMap","displacementMap","emissiveMap","lightMap","metalnessMap","normalMap","roughnessMap","transmissionMap"].forEach(t=>{const a=e[t];a&&(a.repeat.copy(i),a.offset.copy(n),a.center.copy(r),a.rotation=s,a.needsUpdate=!0)}),e.needsUpdate=!0})}(e,r.filter(e=>e?.isObject3D))}for(const e of r){if(!e){Array.isArray(s)&&s.push(void 0);continue}let r=e;const a=e?.__rootBlob?e.__rootBlob.filePath||e.__rootBlob.name:e.__rootPath||e.userData?.rootPath||e.name||"";switch(e.assetType){case"material":this.materials.registerMaterial(e);break;case"texture":t&&(a?.endsWith(".hdr")||a?.endsWith(".exr"))&&(this.viewer.scene.environment=e),i&&(this.viewer.scene.background=e);break;case"model":case"light":case"camera":r=await this.viewer.addSceneObject(e,n);break;case"config":!1!==n?.importConfig&&await this.viewer.importConfig(e);break;default:e.type&&"string"==typeof e.type&&(Array.isArray(e.plugins)||"ThreeViewer"===e.type||this.viewer.getPlugin(e.type))&&await this.viewer.importConfig(e)}this.dispatchEvent({type:"loadAsset",data:e}),Array.isArray(s)?s.push(r):s=r}return s}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("addSceneObject"===e.type){const t=e.object;"material"===t.assetType&&this.materials.registerMaterial(t)}else if("materialChanged"===e.type){const t=e.material,i=Array.isArray(t)?t:t?[t]:[];for(const e of i)this.materials.registerMaterial(e)}else if("beforeDeserialize"===e.type){const t=e,i=t.data,n=t.meta;i.metadata||console.warn("Invalid data(no metadata)",i),t.material&&("Material"!==i.metadata?.type&&console.warn("Invalid material data",i),MT.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 qS(class extends CT{async parseAsync(i){if("config"===i.assetType)return i;const n=i.type||i.metadata?.type,r=t.importers.filter(e=>{const t=e.cls?.SupportedJSONTypes;if(t)return Im(t)?.includes(n)});for(const e of r){if(!e)continue;const n=e.ctor(t),r=await n.parseAsync(i);if(n.dispose&&n.dispose(),r)return r}if(i.serializableClassId){const t=i.resources;i.resources&&delete i.resources;const n=t?await e.loadConfigResources(t):void 0,r=f_.Deserialize(i,void 0,n);if(n&&(i.resources=n),r)return r}return super.parseAsync(i)}},["json","vjson"],["application/json"],!1),new qS(YD,["svg","data:image/svg"],["image/svg+xml"],!1),new qS(uu,["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 qS(MT,MT.SupportedJSONExtensions,[],!1,e=>(e&&(e.viewer=this.viewer),e)),new qS(class extends SR{constructor(t){super(t),this.setDataType($y(e.renderManager.renderer))}},["hdr"],["image/vnd.radiance"],!1),new qS(class extends GD{constructor(t){super(t),this.setDataType($y(e.renderManager.renderer))}},["exr"],["image/x-exr"],!1),new qS(PD,["fbx"],["model/fbx"],!0),new qS(DD,["zip","glbz","gltfz"],["application/zip","model/gltf+zip","model/zip"],!0),new qS(zT,["obj"],["model/obj"],!0),new qS(ET,["mtl"],["model/mtl"],!1),new qS(LD,["gltf","glb","data:model/gltf","data:model/glb"],["model/gltf","model/gltf+json","model/gltf-binary","model/glb"],!0,(e,t,i)=>e?.setup(this.viewer,i.extensions)),new qS(zD,["drc"],["model/mesh+draco","model/drc"],!0),new qS(JD,["mp4","ogg","mov","webm","data:video"],["video/mp4","video/ogg","video/quicktime","video/webm"],!0),new qS(MR,["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 t=e.data;return void this._loadObjectDependencies(t)}const t=e.data;t&&t.isMaterial&&t.uuid&&this.materials.registerMaterial(t)}),this.importer.addEventListener("processRawStart",e=>IR(e,this))}_setupObjectExport(){}async _loadObjectDependencies(e){const t=[];if(!e.traverseModels)return void this.viewer.console.error("AssetManager - Object not upgraded, cannot load dependencies",e);e.traverseModels&&e.traverseModels(e=>!(e.userData.rootPathRefresh&&!e._rootPathRefreshed&&!e._rootPathRefreshing&&e.userData.rootPath)||(t.push(e),!1),{visible:!1,widgets:!0});const i=t.map(async e=>{e._rootPathRefreshing=!0;const t=e.userData.rootPath;if(!t)return null;const i=e.userData.rootPathOptions,n=await this.importer.import(t,{...i});if(!n)throw new Error(`Unable to load asset from url - ${t}`);return n}),n=await Promise.allSettled(i);for(let e=0;e<n.length;e++){const i=n[e],r=t[e];if(delete r._rootPathRefreshing,r._rootPathRefreshed=!0,"rejected"===i.status){this.viewer.console.error(`ThreeViewer - Failed to load root path for object ${r.name}`,i.reason);continue}if("fulfilled"!==i.status)continue;const s=i.value;if(!s||!s.length)continue;const a=s.find(e=>e?.isObject3D);if(!a){this.viewer.console.warn("AssetManager - No valid model found in root path",i.value);continue}const o=s.filter(e=>e&&e!==a),l=r.parent,c=l?l.children.indexOf(r):-1;if(l&&r.removeFromParent(),this.viewer.object3dManager.unregisterObject(r),!a.isObject3D){this.viewer.console.warn("Non model dependency loaded. Not fully supported yet.");continue}if(!l){this.viewer.console.error("AssetManager - Unexpected error, no parent found for object when loading dependency",r);continue}a._copyFromEmbedded?a._copyFromEmbedded(r):(r.matrix.decompose(a.position,a.quaternion,a.scale),a.name=r.name,a.userData={...r.userData,...a.userData},a._rootPathRefreshed=!0,a.uuid=r.uuid),l.add(a);const h=l.children.indexOf(a);if(c>=0&&h>=0&&c!==h&&(l.children.splice(h,1),l.children.splice(c,0,a)),o.length)for(const e of o)e?.isObject3D?l.add(e):this.viewer.console.warn("Non model dependency loaded. Not fully supported yet.",e)}}setProcessState(e,t){void 0===t?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,"done"!==e.state?{state:e.state,progress:e.progress?100*e.progress: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,"done"!==e.state?{state:e.state,progress:e.progress?100*e.progress: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(t=>t.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(t=>t.name===e);if(t<0)return;this.gltfExtensions.splice(t,1);const i=this._gltfExporter.extensions.findIndex(t=>t.name===e);i>=0&&this._gltfExporter.extensions.splice(i,1);const n=this.exporter.getExporter("gltf","glb");if(n?.extensions&&n!==this._gltfExporter){const t=n.extensions.findIndex(t=>t.name===e);t>=0&&n.extensions?.splice(t,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)}};ER.PluginType="AssetManager";let TR=ER;const IR=(e,t)=>{const i=e.data,n=e.options;if(i.isObject3D){const e=[],r=[];i.traverse(i=>{if(i.material){const e=Array.isArray(i.material)?i.material:[i.material],r=[],s=[];for(const i of e){const e=t.materials.convertToIMaterial(i,{createFromTemplate:!1!==n.replaceMaterials})||i;e.uuid=i.uuid,e.userData.uuid=i.uuid,r.push(e);const a=Nw.getMapsForMaterial.call(e);s.push(...Array.from(a.values()))}Array.isArray(i.material)?i.material=r:i.material=r[0],new Set(s).forEach(e=>{"string"==typeof e.userData.rootPath&&e.userData.rootPath.startsWith("blob:")&&delete e.userData.rootPath,e.userData.rootPath&&!e.__rootPath?(e.__rootPath=e.userData.rootPath,t.importer.processRawSingle(e,{})):uS.call(e)})}i.isCamera&&e.push(i),i.isLight&&r.push(i)});for(const i of e)if("camera"!==i.assetType)if(i.parent&&!1!==n.replaceCameras){const e=i.iCamera??!i.isOrthographicCamera?new lC("",t.viewer.canvas):new mC("",t.viewer.canvas);if(i===e)continue;i.parent.children.splice(i.parent.children.indexOf(i),1,e),e.parent=i.parent,e.copy(i),i.parent=null,e.uuid=i.uuid,e.userData.uuid=i.uuid,i.iCamera=e}else nC.upgradeCamera.call(i);for(const e of r)if("light"!==e.assetType)if(e.parent&&!1!==n.replaceLights){const t=e.iLight??e.isDirectionalLight?new JC:e.isPointLight?new rS:e.isSpotLight?new dS:e.isAmbientLight?new qC:e.isHemisphereLight?new eS:e.isRectAreaLight?new oS:void 0;if(e===t||!t)continue;e.parent.children.splice(e.parent.children.indexOf(e),1,t),t.parent=e.parent,t.copy(e),e.parent=null,t.uuid=e.uuid,t.userData.uuid=e.uuid,e.iLight=t}else VC.upgradeLight.call(e);qw.upgradeObject3D.call(i)}else i.isMaterial?i.assetType||Nw.upgradeMaterial.call(i):i.isTexture&&(uS.call(i),void 0!==e?.options?.generateMipmaps&&(i.generateMipmaps=e?.options.generateMipmaps),!i.generateMipmaps&&!i.isRenderTargetTexture&&(i.minFilter=i.minFilter===we?be:i.minFilter,i.magFilter=i.magFilter===we?be:i.magFilter))},PR=class extends ri{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(e=>{e===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 e of i)this._unregisterTexture(e,t);const n=e.textures;if(n)for(const e of n)this._registerTexture(e,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,r=i?.delay||0,s=i?.scale||1,a=i?.start||0,o=n.duration||1,l=o-(i?.end||0);let c=e.time;if(c-=r,c*=s,c<a&&(c=a),c>l&&(c=l),c<0&&(c=0),c>o&&(c=o),Math.abs(c-n.currentTime)>1/60&&(n.currentTime=c,n.paused)){const e=(t._playid||0)+1;t._playid=e,n.play().then(()=>{t._playid===e&&(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)return;console.warn("Object3DManager - Object with the same uuid already registered",e,t),Tm(e,"uuid",Ky(),!0,!0)}e.assetType||qw.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=qw.getMapsForObject3D.call(e);if(i)for(const t of i.values())this._registerTexture(t,e);e.objectExtensions||(e.objectExtensions=[]);const n=e.objectExtensions;for(const t of this._objectExtensions)n.includes(t)||(!t.isCompatible||t.isCompatible(e))&&(n.push(t),t.onRegister&&t.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=qw.getMapsForObject3D.call(e);if(i)for(const t of i.values())this._unregisterTexture(t,e);return this.autoDisposeObjects&&!1!==e.userData?.disposeOnIdle&&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=Ky()),!this._objectExtensions.includes(e))){this._objectExtensions.push(e);for(const t of this._objects.values())t.objectExtensions&&!t.objectExtensions.includes(e)&&(!e.isCompatible||e.isCompatible(t))&&t.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(e=>this._registerMaterial(e,t))}_unregisterMaterials(e,t){return e&&e.forEach(e=>this._unregisterMaterial(e,t))}_registerMaterial(e,t){if(!(e&&e.isMaterial&&t&&e.uuid))return;e.assetType||Nw.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),Tm(e,"uuid",Ky(),!0,!0));const r=!this._materials.has(e.uuid);i.add(t),this._materials.set(e.uuid,e),r&&e.addEventListener("texturesChanged",this._texturesChanged);const s=Nw.getMapsForMaterial.call(e);if(s)for(const t of s.values())this._registerTexture(t,e);r&&(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);else if(0===i.size&&n){this._materials.delete(e.uuid),e.removeEventListener("texturesChanged",this._texturesChanged);const t=Nw.getMapsForMaterial.call(e);if(t)for(const i of t.values())this._unregisterTexture(i,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||dw.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),Tm(e,"uuid",Ky(),!0,!0));const r=!this._geometries.has(e.uuid);i.add(t),this._geometries.set(e.uuid,e),r&&(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),0===i.size&&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||uS.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),Tm(e,"uuid",Ky(),!0,!0));const r=!this._textures.has(e.uuid);i.add(t),this._textures.set(e.uuid,e),e.isVideoTexture&&this._registerVideo(e),r&&(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);n&&e!==n?console.error("Object3DManager - Texture to unregister is not the same as the registered texture",e,n):0===i.size&&this._textures.has(e.uuid)&&(this._textures.delete(e.uuid),e.isVideoTexture&&this._videos.delete(e.uuid),this.dispatchEvent({type:"textureRemove",texture:e}),!1!==e.userData?.disposeOnIdle&&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))return i[0];console.warn("Multiple objects found with name:",e,i)}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))return i[0];console.warn("Multiple materials found with name:",e,i)}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)}};PR.MaterialTextureProperties=zw,PR.MaterialTexturePropertiesUserData=Gw,PR.SceneTextureProperties=Jw,PR.Object3DTextureProperties=Zw,new Set([...kw.MapProperties,...xC.MapProperties,...yC.MapProperties,...TC.MapProperties]).forEach(e=>PR.MaterialTextureProperties.add(e));let DR=PR;var RR=Object.defineProperty,BR=Object.getOwnPropertyDescriptor,LR=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?BR(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&RR(t,i,s),s};e.RenderManager=class extends WS{constructor({canvas:e,alpha:t=!0,renderScale:i=1,powerPreference:n,targetOptions:r}){super(),this._renderSize=new fi(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 e of this._passes)e.enabled&&e.onPostFrame&&e.onPostFrame?.(this)},this.animationLoop=this.animationLoop.bind(this),this._renderSize=new fi(e.clientWidth,e.clientHeight),this._renderScale=i,this._renderer=this._initWebGLRenderer(e,t,r?.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 s=this.createTarget(r,!1);s.texture.name="EffectComposer.rt1",this._composer=new VS(this._renderer,s)}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=jS(e)}catch(e){console.error("RenderManager: Unable to sort rendering passes",e)}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(t,i,n,r){const s=new Al({canvas:t,antialias:!1,alpha:i,premultipliedAlpha:!1,preserveDrawingBuffer:!0,powerPreference:r??e.RenderManager.POWER_PREFERENCE,stencil:n});return s.setAnimationLoop(this.animationLoop),s.onContextLost=e=>{this.dispatchEvent({type:"contextLost",event:e})},s.onContextRestore=()=>{this.dispatchEvent({type:"contextRestored"})},s.setSize(this._renderSize.width,this._renderSize.height,!1),s.setPixelRatio(this._renderScale),s.toneMapping=0,s.toneMappingExposure=1,s.outputColorSpace=Lt,s.shadowMap.enabled=!0,s.shadowMap.type=1,s.shadowMap.autoUpdate=!1,pS.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 t of this._passes)t.enabled&&t.beforeRender&&t.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)&&(this._dirty=this._dirty||this._passes.findIndex(e=>Im(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(e=>e.passId===t);i?e.push(i):console.warn("Unable to find pass: ",t)}[...this._composer.passes].forEach(e=>this._composer.removePass(e)),e.forEach(e=>this._composer.addPass(e)),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 t of[...this._passes])e.passId===t.passId&&this.unregisterPass(t);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:r=!0,respectColorSpace:s=!1,blending:a=w,transparent:o=!0,opacity:l,blendAlpha:c}={}){const h=s?this._composer.copyPass2:this._composer.copyPass,{renderToScreen:d,material:u,uniforms:p,clear:m}=h;n&&(h.material=n);const g=h.material.transparent,f=e?e.viewport.clone():this._renderer.getViewport(new Gi),A=e?e.scissor.clone():this._renderer.getScissor(new Gi),y=e?e.scissorTest:this._renderer.getScissorTest(),v=this._renderer.autoClear,_=this._renderer.getRenderTarget(),b=h.material.blending,x=h.material.uniforms.opacity?.value??1,S=h.material.blendAlpha,M=h.material.blendSrc,E=h.material.blendDst,P=h.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,h.material.blending=o?a:C,h.uniforms=h.material.uniforms,h.renderToScreen=!1,h.clear=r,h.material.transparent=o,h.material.needsUpdate=!0,h.material.uniforms.opacity&&void 0!==l&&(h.material.uniforms.opacity.value=l),void 0!==c&&(h.material.blending=T,h.material.blendSrc=q,h.material.blendDst=X,h.material.blendEquation=I,h.material.blendAlpha=c),this._renderer.renderWithModes({sceneRender:!0,opaqueRender:!0,shadowMapRender:!1,backgroundRender:!1,transparentRender:!0,transmissionRender:!1},()=>{h.render(this._renderer,e||null,{texture:t},0,!1)}),h.material.uniforms.opacity&&void 0!==l&&(h.material.uniforms.opacity.value=x),h.renderToScreen=d,h.clear=m,h.material.blending=b,h.material.blendSrc=M,h.material.blendDst=E,h.material.blendEquation=P,h.material.blendAlpha=S,h.material.transparent=g,h.material=u,h.uniforms=p,this._renderer.autoClear=v,i&&(e?(e.viewport.copy(f),e.scissor.copy(A),e.scissorTest=y):(this._renderer.setViewport(f),this._renderer.setScissor(A),this._renderer.setScissorTest(y))),this._renderer.setRenderTarget(_)}clearColor({r:e,g:t,b:i,a:n,target:r,depth:s=!0,stencil:a=!0,viewport:o}){const l=this._renderer.getClearColor(new mr),c=this._renderer.getClearAlpha();this._renderer.setClearColor(new mr(e??l.r,t??l.g,i??l.b),n??c);const h=this._renderer.getRenderTarget(),d=this._renderer.getActiveCubeFace(),u=this._renderer.getActiveMipmapLevel(),p=r?r.viewport.clone():this._renderer.getViewport(new Gi),m=r?r.scissor.clone():this._renderer.getScissor(new Gi),g=r?r.scissorTest:this._renderer.getScissorTest();o&&(r?(r.viewport.copy(o),r.scissor.copy(o),r.scissorTest=!0):(this._renderer.setViewport(o),this._renderer.setScissor(o),this._renderer.setScissorTest(!0))),this._renderer.setRenderTarget(r??null),this._renderer.clear(!0,s,a),r&&"function"==typeof r.clear?r.clear(this._renderer,!0,s,a):(this._renderer.setRenderTarget(r??null),this._renderer.clear(!0,s,a)),o&&(r?(r.viewport.copy(p),r.scissor.copy(m),r.scissorTest=g):(this._renderer.setViewport(p),this._renderer.setScissor(m),this._renderer.setScissorTest(g))),this._renderer.setRenderTarget(h,d,u),this._renderer.setClearColor(l,c)}_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 r=n.image?.width||n.source?.data?.width,s=n.image?.height||n.source?.data?.height,a=this.getTempTarget(r&&s?{size:{width:r,height:s},type:n.type}:{sizeMultiplier:1,type:n.type});this.blit(a,{source:n,clear:!0});const o=i(a);return this.releaseTempTarget(a),o}renderTargetToCanvas(e,t=0,i){const n=this._withResolvedTarget(e,t,e=>this.renderTargetToCanvas(e,0,i));if(n)return n;i=i??document.createElement("canvas");const r=e.textures?.[t]??e.texture;i.width=e.width,i.height=e.height;const s=i.getContext("2d");if(!s)throw new Error("Unable to get 2d context");const a=s.createImageData(i.width,i.height,{colorSpace:["display-p3","srgb"].includes(r.colorSpace)?r.colorSpace:void 0});if(r.type===De||r.type===Pe){ev({data:this.renderTargetToBuffer(e,t),width:i.width,height:i.height},r.colorSpace,a)}else this._renderer.readRenderTargetPixels(e,0,0,i.width,i.height,a.data,void 0,t);return s.putImageData(a,0,0),i}renderTargetToDataUrl(e,t="image/png",i=90,n=0){const r=e.textures?.[n]??e.texture,s=this.renderTargetToCanvas(e,n),a=(r.flipY?s:tg(s)).toDataURL(t,i);return s.remove(),a}renderTargetToBuffer(e,t=0){const i=e.textures?.[t]??e.texture,n=i.type===De?new Uint16Array(e.width*e.height*4):i.type===Pe?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,e=>this.exportRenderTarget(e,t,0));if(n)return n;const r=e,s=r.textures?.[i]??r.texture;let a,o=s.type===De||s.type===Pe;if("auto"===t&&(t=o?"image/x-exr":"image/png"),["image/x-exr"].includes(t)||(o=!1),o)"image/x-exr"!==t&&(console.warn("RenderManager: mimeType ",t," is not supported for HDR. Using EXR instead"),t="image/x-exr"),a=(new yR).parse(this._renderer,r,{textureIndex:i}).buffer;else{const e=this.renderTargetToDataUrl(r,"auto"===t?void 0:t,90,i);a=hm(e.split(",")[1]),t=e.split(";")[0].split(":")[1]}const l=new Blob([a],{type:t});return l.ext="image/x-exr"===t?"exr":t.split("/")[1],l.__buffer=a,l}_updated(e){this.dispatchEvent({...e,type:"update"})}_createTargetClass(e,t,i){const n=this._processNewTarget,r=this.disposeTarget.bind(this);return new class extends e{constructor(e,...t){super(...t),this.renderManager=e,this.assetType="renderTarget",this.name="RenderTarget",this._ui_isPrimitive=!0,this.uuid=Ky();const i=t[t.length-1]?.colorSpace;this._initTexture(i)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}_initTexture(e){const t=t=>{void 0!==e&&(t.colorSpace=e),t.userData||(t.userData={}),t._target=this,t.toJSON=()=>({isRenderTargetTexture:!0})};Array.isArray(this.textures)&&this.textures.length>1?this.textures.forEach(t):t(this.texture)}setSize(e,t,i){return super.setSize(Math.floor(e),Math.floor(t),i),this}clone(e=!0){if(this.isTemporary)throw"Cloning temporary render targets not supported";if(Array.isArray(this.texture))throw"Cloning multiple render targets not supported";const t=new this.constructor(this.renderManager);t.copy(this),t._initTexture((Array.isArray(this.texture)?this.texture[0]:this.texture)?.colorSpace);const i=t.texture;return Array.isArray(i)?i.forEach(e=>e.isRenderTargetTexture=!0):i.isRenderTargetTexture=!0,n(t,this.sizeMultiplier||1,e)}dispose(e=!1){!0===e?r(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}},e.RenderManager.POWER_PREFERENCE="high-performance",e.RenderManager.ShaderChunk=Ts,e.RenderManager.ShaderLib=Ps,LR([Ug("Render Size")],e.RenderManager.prototype,"_renderSize",2),LR([Fg("Render Scale",[.1,8],.05)],e.RenderManager.prototype,"renderScale",1),LR([qm(),Ng("Shadow Map Type",["BasicShadowMap","PCFShadowMap","PCFSoftShadowMap","VSMShadowMap"].map((e,t)=>({label:e,value:t})),{tags:["advanced"]}),zy({obj:"shadowMap",key:"type",onChange:e.RenderManager.prototype._shadowMapTypeChanged})],e.RenderManager.prototype,"shadowMapType",2),LR([zy({obj:"renderer",key:"shadowMap"})],e.RenderManager.prototype,"shadowMap",2),LR([Lg(void 0,{label:"Passes",tags:["advanced"],order:1e3})],e.RenderManager.prototype,"_passes",2),LR([Hg(),qm()],e.RenderManager.prototype,"stableNoise",2),LR([Vm(e.RenderManager.prototype.rebuildPipeline)],e.RenderManager.prototype,"autoBuildPipeline",2),LR([jg("Rebuild Pipeline",{sendArgs:!1,tags:["advanced"]})],e.RenderManager.prototype,"rebuildPipeline",1),e.RenderManager=LR([Xm("RenderManager"),qg("Render Manager")],e.RenderManager);var OR=Object.defineProperty,UR=Object.getOwnPropertyDescriptor,FR=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?UR(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&OR(t,i,s),s};e.ViewerRenderManager=class extends e.RenderManager{constructor({rgbm:t=!0,msaa:i=!1,depthBuffer:n=!0,stencilBuffer:r=!1,...s}){super({...s,targetOptions:{samples:0,colorSpace:t?Nt:Lt,type:t?Ce:De,depthBuffer:n,stencilBuffer:r,generateMipmaps:!1,minFilter:be}}),this.rgbm=t,this.msaa=i&&this.isWebGL2,this.depthBuffer=n,this.zPrepass=s.zPrepass||!1,this.maxHDRIntensity=s.maxHDRIntensity??(t?16:72);let a=!0;this._renderer.userData||(a=!1,this._renderer.userData={__isIWebGLRenderer:!0}),this._renderer.userData.renderTransmissionPass=!a,this.renderPass=new DS(this),this.screenPass=new e.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 t=!e.background&&!e.backgroundColor;t!==i&&(this.screenPass.clipBackgroundForce=t)}super.render(e,t)}},e.ViewerRenderManager.DEFAULT_MSAA_SAMPLES=4,FR([Hm(e.ViewerRenderManager.prototype._gbufferUnpackExtensionChanged)],e.ViewerRenderManager.prototype,"gbufferUnpackExtension",2),e.ViewerRenderManager=FR([qg("Render Manager")],e.ViewerRenderManager);const kR=class extends sw{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)return this._lastFrameTime=0,void(this._fadeDisabled&&(this._viewer.getPlugin("FrameFade")?.enable(this),this._fadeDisabled=!1));let e;if(this.autoIncrementTime){const t=$p()/1e3;this._lastFrameTime<1&&(this._lastFrameTime=t-1/60),e=t-this._lastFrameTime,this._lastFrameTime=t;const i=this._viewer.getPlugin("Progressive")?.postFrameConvergedRecordingDelta();i&&i>0&&(e=i),0===i&&(e=0)}else{const t=this._viewer.timeline.time;e=t-this._lastFrameTime,this._lastFrameTime=t}if(e*=1e3,!(Math.abs(e)<=1e-4)&&(this._updaters.forEach(t=>{let i=e;t.time+i<0&&(i=-t.time),t.time+=i,Math.abs(i)>.001&&t.u(i)}),!this._fadeDisabled&&this.disableFrameFade)){const e=this._viewer.getPlugin("FrameFade");e&&(e.disable(this),this._fadeDisabled=!0)}},this._preFrame=()=>{if(!this._viewer)return;if(this.isDisabled()||Object.keys(this._timelineUpdaters).length<1)return void(this._lastPreFrameTime=0);const e=1e3*this._viewer.timeline.time,t=e-this._lastPreFrameTime;this._lastPreFrameTime=e,!(Math.abs(t)<=1e-4)&&this._timelineUpdaters.forEach(i=>{let n=t;i.time!==e&&(n=e-i.time),i.time+n<0&&(n=-i.time),i.time+=n,Math.abs(n)>.001&&i.u(n)})},this.defaultDriver=e=>({start:()=>this._updaters.push({u:e,time:0}),stop:()=>{const t=this._updaters.findIndex(t=>t.u===e);t>=0&&this._updaters.splice(t,1)}}),this.timelineDriver=e=>({start:()=>this._timelineUpdaters.push({u:e,time:0}),stop:()=>{const t=this._timelineUpdaters.findIndex(t=>t.u===e);t>=0&&this._timelineUpdaters.splice(t,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,...r}={...e};let s=r.from,a=r.to;if(void 0!==i){if(void 0===n)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]=s??0);const e=wx(i,n),t=()=>i[n];r.lastOnUpdate=r.onUpdate,r.onUpdate=t=>{e(t),r.lastOnUpdate&&r.lastOnUpdate(t)},void 0===s&&(!Array.isArray(a)||a.length<2)&&(s=t())}const o=this.createAnimationResult(r);return o.promise=new Promise((e,i)=>{const n=()=>{try{r.onEnd&&r.onEnd()}catch(e){return i(e),!1}return!0},l=s??(Array.isArray(a)?a[0]:s);if(void 0===l)return console.warn("from is undefined",r),void e();const c="boolean"==typeof l;Array.isArray(a)&&a.length<2&&(a=a[0]);const h={...r,driver:r.driver||this.defaultDriver,to:a,from:s,onUpdate:e=>{r.onUpdate&&(c?r.onUpdate(e>=1):r.onUpdate(e))},onComplete:async()=>{try{r.onComplete&&await r.onComplete()}catch(e){if(!n())return;return void i(e)}n()&&e()},onStop:async()=>{try{r.onStop&&await r.onStop()}catch(e){if(!n())return;return void i(e)}e()}},d=t?t(h):bx(h);o._stop=d.stop,o.options=h}).then(()=>(delete this.animations[o.id],o.id)),o}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 r=this.animate({...i,target:e,key:t});return n&&n.push(r),r.promise}animateTarget(e,t,i){return this.animate({...i,target:e,key:t})}animateCamera(e,t,i=!0,n){const r=i?Ix(e,t):Px(e,t);let s=(n?.duration??1e3)*(t.duration??1);if(n?.normalizeDuration&&s>0){const i=e.getWorldPosition(new Xi),n=i.distanceTo(t.position)+e.target.distanceTo(t.target);if(n<.001){r.onComplete?.();const e=this.createAnimationResult();return e.promise=Promise.resolve(e.id).then(()=>(delete this.animations[e.id],e.id)),e}const a=Math.max(i.distanceTo(e.target),.1);s=Math.max(100,s*Math.min(1,n/a))}return this.animate({ease:xx.linear,...r,...n,duration:s})}async animateCameraAsync(e,t,i=!0,n,r){const s=this.animateCamera(e,t,i,n);return r&&r.push(s),s.promise}createAnimationResult(e={}){const t=Ky();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?"function"==typeof t._stop&&t._stop():console.warn("Animation not started"),t.anims?.forEach(e=>e.stop()),t.stopped=!0)}animateObject(e,t,i=!0,n,r){const{key:s,tar:a,onChange:o}=Hx(e);let l=s;a&&l&&!(l in a)&&(console.error("PopmotionPlugin invalid key",l,a,e),l=void 0);const c=this.createAnimationResult(e.options);i&&(e.result=c),t=(t||0)+((r??e.delay)||0),c.anims=e.animSet?[...c.anims,this.animateSet(e.animSet,e.animSetParallel??!1,t,i,n)]:c.anims;const h=e.updater??[],d=l&&a?{target:a,key:l,to:e.values,offset:e.offsets}:{to:[0,1]};return c.anims.push(this.animate({...d,driver:n,ease:"string"==typeof e.ease?xx[e.ease]:e.ease,duration:e.duration,...e.options,canComplete:i,delay:t,onUpdate:t=>{e.options.onUpdate&&e.options.onUpdate(t),o&&o(),h.forEach(e=>e&&e())}},Ex)),c.promise=Promise.all(c.anims.map(async e=>e.promise)).then(()=>(c.anims=[],delete this.animations[c.id],e.result===c&&(e.result=void 0),c.id)),c}animateSet(e,t=!1,i=0,n=!0,r){const s=this.createAnimationResult();if(t)s.anims=e.map(e=>this.animateObject(e,i,n,r));else{let t=i;for(const i of e){s.anims.push(this.animateObject(i,t,n,r));const{delay:e=0,duration:a=0,options:o}=i;t+=e+a+(a+(o.repeatDelay||0))*(o.repeat||0)}}return s.promise=Promise.all(s.anims.map(async e=>e.promise)).then(()=>(s.anims=[],delete this.animations[s.id],s.id)),s}};kR.PluginType="PopmotionPlugin";let NR=kR;var jR=Object.defineProperty,zR=Object.getOwnPropertyDescriptor,GR=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?zR(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&jR(t,i,s),s};e.InteractionPromptPlugin=class extends sw{constructor(t=!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">\n    <defs>\n        <path id="A" d="M.001.232h24.997V36H.001z"></path>\n    </defs>\n    <g transform="translate(-11 -4)" fill="none" fill-rule="evenodd">\n        <path fill-opacity="0" fill="#fff" d="M0 0h44v44H0z"></path>\n        <g transform="translate(11 3)">\n            <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>\n            <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>\n            <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>\n            <g transform="translate(0 .769)">\n                <mask id="B" fill="#fff">\n                    <use xlink:href="#A"></use>\n                </mask>\n                <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>\n            </g>\n        </g>\n    </g>\n</svg>',this._mainCameraUpdate=e=>{this.isDisabled()||("deserialize"===e.change&&this.animationRunning?(this.stopAnimation({reset:!1}),this.startAnimation()):this._startedOnce&&(this.lastActionTime=$p()))},this._startedOnce=!1,this._addSceneObject=()=>{this.autoStartOnObjectLoad&&!this._startedOnce&&(this.lastActionTime=$p()-this.autoStartDelay+this.autoStartOnObjectLoadDelay)},this.onlyOnOrbitControls=!0,this._orbitWarning=!1,this.startAnimation=()=>{if(this._viewer&&this.cursorEl&&!this.isDisabled()){if("OrbitControls"!==this._viewer.scene.mainCamera.controls?.type&&this.onlyOnOrbitControls)return this._orbitWarning||console.warn("InteractionPromptPlugin requires OrbitControls, to run anyway, set onlyOnOrbitControls to false"),void(this._orbitWarning=!0);0!==this._viewer.scene.modelRoot.children.length&&(this.currentSphericalPosition=(new Sp).setFromVector3((new Xi).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,e.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,e.InteractionPromptPlugin.PluginType),this._viewer.doOnce("postFrame")},this._pointerDown=()=>{this.isDisabled()||(this.autoStop&&this.stopAnimation({reset:!1}),this.lastActionTime=$p())},this._x=0,this._preFrame=async e=>{if(!this._viewer||!this.cursorEl||(this.isDisabled()&&this.animationRunning&&this.stopAnimation(),this.isDisabled())||(!this.animationRunning&&this.autoStart&&this.lastActionTime+this.autoStartDelay<$p()&&this.startAnimation(),!this.animationRunning))return;if(this.currentTime<=this.animationDuration){this.cursorEl.style.opacity="1";const e=this.currentTime/this.animationDuration;this._x=Math.sin(2*Math.PI*e),(e<.25||e>.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 e=this.currentSphericalPosition.clone();e.theta+=this._x*this.rotationDistance,this._viewer.scene.mainCamera.position.setFromSpherical(e).add(this._viewer.scene.mainCamera.target),this._viewer.scene.mainCamera.setDirty()}const t=this._viewer.container.getBoundingClientRect(),i=t.width/2+-this._x*Math.min(this.animationDistance,t.width/4),n=t.height/2+this.yOffset*t.height/2;this.cursorEl.style.transform=`translate(${Math.floor(i)}px, ${Math.floor(n)}px)`,this.currentTime+=e.deltaTime,this.currentTime>this.animationDuration+this.animationPauseDuration&&(this.currentTime=0)},this.enabled=t}onAdded(e){super.onAdded(e);{Om(e.plugins,"InteractionPointerPlugin")&&delete e.plugins.InteractionPointerPlugin;const t=this;Object.defineProperty(e.plugins,"InteractionPointerPlugin",{get:()=>(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)}},e.InteractionPromptPlugin.PluginType="InteractionPromptPlugin",GR([qm(),Hg()],e.InteractionPromptPlugin.prototype,"enabled",2),GR([qm(),zg()],e.InteractionPromptPlugin.prototype,"animationDuration",2),GR([qm(),zg()],e.InteractionPromptPlugin.prototype,"animationDistance",2),GR([qm(),zg()],e.InteractionPromptPlugin.prototype,"animationPauseDuration",2),GR([qm(),zg()],e.InteractionPromptPlugin.prototype,"rotationDistance",2),GR([qm(),zg()],e.InteractionPromptPlugin.prototype,"yOffset",2),GR([qm(),Hg()],e.InteractionPromptPlugin.prototype,"autoStart",2),GR([qm(),zg()],e.InteractionPromptPlugin.prototype,"autoStartDelay",2),GR([qm(),Hg()],e.InteractionPromptPlugin.prototype,"autoStop",2),GR([qm(),Hg()],e.InteractionPromptPlugin.prototype,"autoStartOnObjectLoad",2),GR([qm(),Hg()],e.InteractionPromptPlugin.prototype,"autoStartOnObjectLoadDelay",2),GR([Ug()],e.InteractionPromptPlugin.prototype,"currentTime",2),GR([Ug()],e.InteractionPromptPlugin.prototype,"lastActionTime",2),GR([Qm(e.InteractionPromptPlugin.prototype._pointerIconChanged)],e.InteractionPromptPlugin.prototype,"pointerIcon",2),GR([qm()],e.InteractionPromptPlugin.prototype,"onlyOnOrbitControls",2),GR([jg()],e.InteractionPromptPlugin.prototype,"startAnimation",2),GR([jg()],e.InteractionPromptPlugin.prototype,"stopAnimation",2),e.InteractionPromptPlugin=GR([qg("Interaction Prompt")],e.InteractionPromptPlugin);var QR=Object.defineProperty,VR=Object.getOwnPropertyDescriptor,HR=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?VR(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&QR(t,i,s),s};const WR=(r=class extends sw{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=[NR],this.focusNext=(e=!0)=>{if(this._animating||this._cameraViews.length<2)return;let t=this._cameraViews.findIndex(e=>e===this._currentView);t<0&&(t=-1),t+=1,e?t%=this._cameraViews.length:t=Math.min(t,this._cameraViews.length-1),this.animateToView(t)},this.focusPrevious=(e=!0)=>{if(this._animating||this._cameraViews.length<2||!this._currentView)return;let t=this._cameraViews.findIndex(e=>e===this._currentView);t<0&&(t=0),t-=1,t=e?(t+this._cameraViews.length)%this._cameraViews.length:Math.max(t,0),this.animateToView(t)},this._popAnimations=[],this.uiConfig={type:"folder",label:"Camera Views",children:[()=>[...this._cameraViews.map(e=>e.uiConfig)],...Rg(this)||[]]},this._viewQueue=[],this._animationLooping=!1,this._infiniteLooping=!0,this._viewSetView=({view:e,camera:t})=>{e?this.setView(e,t):this._viewer?.console.warn("Invalid view",e)},this._viewUpdateView=({view:e,camera:t})=>{if(!e)return void this._viewer?.console.warn("Invalid view",e);const i=e.name;this.getView(t,e.isWorldSpace??!0,e),e.name=i},this._viewDeleteView=({view:e})=>{e?this.deleteView(e):this._viewer?.console.warn("Invalid view",e)},this._viewAnimateView=async({view:e,camera:t,duration:i,easing:n,throwOnStop:r})=>{if(e)return this.animateToView(e,i||this.animDuration,n||this.animEase,t,r);this._viewer?.console.warn("Invalid view",e)},this._viewUpdated=async e=>{this._cameraViews.includes(e.target)&&(this.dispatchEvent({type:"viewUpdate",view:e.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",e=>{}),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 Zp(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(t,i=!0,n){return(t=t||this._viewer?.scene.mainCamera)?t.getView(i,n):n??new e.CameraView}setView(e,t){(t=t||this._viewer?.scene.mainCamera)&&t.setView(e)}async animateToView(t,i,n,s,a=!1,o){if(!(s=s||this._viewer?.scene.mainCamera))return;if(this._animating){this._popAnimations.forEach(e=>e?.stop&&e.stop()),this._popAnimations=[];let e=0;for(;this._animating&&(await Zp(100),!(e++>20)););if(this._animating)return void console.warn("Unable to stop all animations, maybe because of viewLooping?")}const l="number"==typeof t?this._cameraViews[t]:"string"==typeof t?this._cameraViews.find(e=>e.name===t):t;if(!l)return void this._viewer?.console.warn("Invalid view",t);o=o??void 0===i;const c=this._viewer?.getPlugin(e.InteractionPromptPlugin);c&&c.animationRunning&&await c.stopAnimation({reset:!0}),this._currentView=l,this._animating=!0,s.setInteractions&&s.setInteractions(!1,r.PluginType),s.userData.autoLookAtTarget||console.warn("CameraViewPlugin: camera autoLookAtTarget is disabled, camera look at might not be correct during animation"),this.dispatchEvent({type:"startViewChange",view:l});const h=this._viewer?.getPlugin(NR);if(!h)throw new Error("PopmotionPlugin not found");const d="function"==typeof n?n:xx[n||this.animEase];this._popAnimations=[],await h.animateCameraAsync(s,l,"spherical"===this.interpolateMode,{ease:d,duration:i,normalizeDuration:o},this._popAnimations).catch(e=>{if(a)throw e}),this._viewer?.scene.mainCamera.setInteractions(!0,r.PluginType),this._animating=!1,this._viewer?.setDirty(),this.dispatchEvent({type:"viewChange",view:l}),await Zp(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 Zp(100)}fromJSON(e,t){return this._cameraViews.forEach(e=>this.deleteView(e)),super.fromJSON(e,t)?(this._cameraViews.forEach(e=>this.addView(e,!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,r={min:.5,max:5}){if(!this._viewer)return;const s=(new Ly).expandByObject(e||this._viewer.scene.modelRoot,!1,!0),a=s.getCenter(new Xi),o=s.getSize(new Xi).length()/2;await this.animateToTarget(Math.min(r.max,Math.max(r.min,o*t)),a,i,n)}_resolveSelectedObjects(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap(e=>e?.isTexture?[...e.appliedObjects?.values()||[]]:e).flatMap(e=>e?.isMaterial||e?.isBufferGeometry?[...e.appliedMeshes?.values()||[]]:e).filter(Boolean)}async animateToFitObject(e,t=1.5,i,n,r={min:.5,max:50}){if(!this._viewer)return;const s=this._resolveSelectedObjects(e),a=s.length?s:[this._viewer.scene.modelRoot];if(0===i)return void this._viewer.scene.mainCamera.fitObject(a,t,r);const o=(new Ly).expandByObject(a[0],!1,!0);for(let e=1;e<a.length;e++)o.expandByObject(a[e],!1,!0);const l=p_(this._viewer.scene.mainCamera,o),c=o.getCenter(new Xi);o.getSize(new Xi).lengthSq()<=0&&a[0].getWorldPosition(c),await this.animateToTarget(Math.min(r.max,Math.max(r.min,l*t)),c,i,n)}async animateToTarget(e,t,i,n){const r=this.getView();r.target.copy(t);const s=(new Xi).subVectors(r.target,r.position).normalize();if(r.position.copy(s.multiplyScalar(-e).add(r.target)),0===i)return this.setView(r),void this._viewer?.setDirty();await this.animateToView(r,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(0===this._viewQueue.length){if(!this._infiniteLooping)break;this._viewQueue.push(...this._cameraViews)}await this.animateToView(this._viewQueue.shift()),await Zp(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)return e.setInteractions(!0,r.PluginType+"-postFrame"),void(this._lastAnimTime=-1);e.setInteractions(!1,r.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 e=0;e<a.length;e++){const t=a[e],r=Math.max(2,t.duration*n)/1e3;i.push({time:o,index:e,duration:r}),o+=r+s/1e3}const l=i.sort((e,t)=>-e.time+t.time).find(e=>e.time<=t);if(!l)return;const c=l.index,h=l.time,d=l.duration??.5,u=d<1e-6?1:(t-h)/d;if(u>1)return;const{getPosition:p,getTarget:m}=iC(this.camViews);return p(u,c,e.position),m(u,c,e.target),e.setDirty(),!0}},r.PluginType="CameraViews",r);HR([qm("cameraViews")],WR.prototype,"_cameraViews",2),HR([Qm(WR.prototype._animationLoop),qm(),Hg("Loop All Views")],WR.prototype,"viewLooping",2),HR([Hm("setDirty"),qm(),zg("View Pause Time")],WR.prototype,"viewPauseTime",2),HR([Hm("setDirty"),qm(),Ng("Ease",Object.keys(xx).map(e=>({label:e})))],WR.prototype,"animEase",2),HR([Hm("setDirty"),qm(),Fg("Duration",[10,1e4],10)],WR.prototype,"animDuration",2),HR([Hm("setDirty"),qm(),Ng("Interpolation",["spherical","linear"].map(e=>({label:e,value:e.split(" ")[0]})))],WR.prototype,"interpolateMode",2),HR([qm()],WR.prototype,"rotationOffset",2),HR([jg("Reset To First View",{sendArgs:!1})],WR.prototype,"resetToFirstView",1),HR([jg("Add Current View")],WR.prototype,"addCurrentView",1),HR([jg("Focus Next",{sendArgs:!1})],WR.prototype,"focusNext",2),HR([jg("Focus Previous",{sendArgs:!1})],WR.prototype,"focusPrevious",2),HR([jg("Animate All Views")],WR.prototype,"animateAllViews",1),HR([jg("Stop All Animations")],WR.prototype,"stopAllAnimations",1);let qR=WR;var XR=Object.defineProperty,YR=Object.getOwnPropertyDescriptor,KR=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?YR(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&XR(t,i,s),s};e.DropzonePlugin=class extends sw{constructor(e){super(),this.enabled=!0,this._allowedExtensions=void 0,this.autoImport=!0,this.autoAdd=!0,this.importOptions={autoImportZipContents:!0,forceImporterReprocess:!1,useMeshLines:LD.UseMeshLines,createUniqueNames:LD.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(e=>"."+e).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){if(this.autoImport){const n=this._viewer.assetManager,r=mm(e);if(this._allowedExtensions&&!this._allowedExtensions.includes(r))return void(i&&await this._viewer.dialog.alert(`DropzonePlugin: file extension ${r} not allowed`));const s=[...await n.importer.import(e,{...this.importOptions,...t??{}})??[]].flat(2).filter(e=>!!e)??[];return this.autoAdd?await n.loadImported(s,{...this.addOptions,...t??{}}):s}i&&await this._viewer.dialog.alert("DropzonePlugin: autoImport is disabled, file was not imported")}else console.warn("DropzonePlugin: viewer not set")}onAdded(e){super.onAdded(e),this._inputEl=document.createElement("input"),this._inputEl.type="file",this._domElement||(this._domElement=e.canvas),this._dropzone=new pf(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(void 0!==this._allowedExtensions)for(const t of e.keys())this._allowedExtensions.includes(t.split(".").pop()?.toLowerCase()??"")||e.delete(t);if(e.size<1)return;const n=i.assetManager;let r,s;if(this.autoImport&&(r=await n.importer.importFiles(e,{allowedExtensions:this.allowedExtensions,...this.importOptions}),this.autoAdd)){const e=[...r?.values()??[]].flat(2).filter(e=>!!e)??[];s=await n.loadImported(e,{...this.addOptions})}this.dispatchEvent({type:"drop",files:e,imported:r,assets:s,nativeEvent:t})}},e.DropzonePlugin.PluginType="Dropzone",e.DropzonePlugin.OldPluginType="DropzonePlugin",KR([Hg(),qm()],e.DropzonePlugin.prototype,"enabled",2),KR([qm()],e.DropzonePlugin.prototype,"autoImport",2),KR([Hg(),qm()],e.DropzonePlugin.prototype,"autoAdd",2),KR([Lg(),qm()],e.DropzonePlugin.prototype,"importOptions",2),KR([Lg(),qm()],e.DropzonePlugin.prototype,"addOptions",2),KR([jg("Select Local files")],e.DropzonePlugin.prototype,"promptForFile",1),KR([jg("Import from URL")],e.DropzonePlugin.prototype,"promptForUrl",1),e.DropzonePlugin=KR([qg("Dropzone")],e.DropzonePlugin);var JR=Object.defineProperty,ZR=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&JR(t,i,s),s};const $R=class extends sw{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)}onAdded(e){super.onAdded(e),this._pass=this._createPass(),this._pass.onDirty?.push(e.setDirty),this._pass.beforeRender=Bm(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)}};ZR([qm(),Hg("Enabled"),Qm($R.prototype.setDirty)],$R.prototype,"enabled"),ZR([qm("pass")],$R.prototype,"_pass");let eB=$R;const tB="#ifndef UNPACK_GBUFFER_SNIPPET\n#define UNPACK_GBUFFER_SNIPPET\nuniform 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;}\n#define getDepth(uv) unpackDepth(texture2D(tNormalDepth, uv).xy)\nvoid 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);}\n#if defined(GBUFFER_HAS_FLAGS) && GBUFFER_HAS_FLAGS == 1\nuniform sampler2D tGBufferFlags;\n#endif\nivec4 getGBufferFlags(const in vec2 uv){\n#if defined(GBUFFER_HAS_FLAGS) && GBUFFER_HAS_FLAGS == 1\nreturn ivec4(texture2D(tGBufferFlags,uv)*255.);\n#else\nreturn ivec4(1);\n#endif\n}\n#if defined(GBUFFER_HAS_DEPTH_TEXTURE) && GBUFFER_HAS_DEPTH_TEXTURE == 1\nuniform 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);}\n#endif\n#endif\n";var iB=Object.defineProperty,nB=Object.getOwnPropertyDescriptor,rB=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?nB(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&iB(t,i,s),s};e.GBufferPlugin=class extends eB{constructor(e=Ce,t=!0,i=!0,n=!0,r=!1,s=Ie){super(),this.renderFlagsBuffer=n,this.renderDepthTexture=r,this.depthTextureType=s,this.passId="gbuffer",this.textures=[],this.unpackExtension={shaderExtender:e=>{const t=["gbuffer_unpack","packing"].find(t=>e.fragmentShader.includes(`#include <${t}>`));e.fragmentShader=R_(e.fragmentShader,`#include <${t}>`,"\n"+tB+"\n",{append:"packing"===t})},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 Ww(e,{blending:w,transparent:!0})}_createTargetAndMaterial(t=!0){if(!this._viewer)return;t&&this._disposeTarget();const i=this._viewer?.renderManager.isWebGL2&&this.renderFlagsBuffer;if(!this.target){const t=this._viewer.renderManager;this.target=this._viewer.renderManager.createTarget({depthBuffer:!0,samples:this._viewer.renderManager.zPrepass&&this.isPrimaryGBuffer&&t.msaa?"number"!=typeof t.msaa?e.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:t.msaa:0,type:this.bufferType,textureCount:i?2:1,depthTexture:this.renderDepthTexture,depthTextureType:this.depthTextureType,wrapS:fe,wrapT:fe}),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 t=new e.GBufferRenderPass(this.passId,()=>this.target,this.material,new mr(1,1,1),1),i=t.preprocessMaterial;return t.preprocessMaterial=e=>i(e,e.userData.renderToDepth),t.preprocessObject=e=>{if(e.customGBufferMaterial){const t=e.customGBufferMaterial;t.allowOverride=!1;const i=e.material;e.forcedOverrideMaterial=t;const n=Array.isArray(i)?i[0]:i;return n&&(t.userData.renderToGBuffer=n.userData.renderToGBuffer,t.userData.renderToDepth=n.userData.renderToDepth,t.userData.pluginsDisabled=n.userData.pluginsDisabled,t.side=n.side),t}return e.material},t.postprocessObject=e=>{e.customGBufferMaterial&&delete e.forcedOverrideMaterial},t.before=["render"],t.after=[],t.required=["render"],t}_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 tB}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}},e.GBufferPlugin.PluginType="GBuffer",rB([Vg(void 0,{readOnly:!0})],e.GBufferPlugin.prototype,"normalDepthTexture",1),rB([Vg(void 0,{readOnly:!0})],e.GBufferPlugin.prototype,"flagsTexture",1),rB([Vg(void 0,{readOnly:!0})],e.GBufferPlugin.prototype,"depthTexture",1),e.GBufferPlugin=rB([qg("G-Buffer Plugin")],e.GBufferPlugin);class sB extends sw{constructor(e=""){super(),this.priority=-100,this._shaderPatch="",this.computeCacheKey=e=>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=R_(e.fragmentShader,"#glMarker","\n"+this._shaderPatch+"\n",{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}).extension={...e.pass},delete e.extension.enabled,delete e.pass),e.extension&&delete(e={...e,...e.extension}).extension,super.fromJSON(e,t)}onAdded(t){super.onAdded(t),t.forPlugin(e.GBufferPlugin,e=>{e.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this))},e=>{e.unregisterGBufferUpdater(this.constructor.PluginType)},this),t.renderManager.screenPass.material.registerMaterialExtensions([this])}onRemove(t){t.getPlugin(e.GBufferPlugin)?.unregisterGBufferUpdater(this.constructor.PluginType),t.renderManager.screenPass.material.unregisterMaterialExtensions([this]),super.onRemove(t)}updateGBufferFlags(e,t){}}var aB=Object.defineProperty,oB=Object.getOwnPropertyDescriptor,lB=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?oB(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&aB(t,i,s),s};const cB=5;e.TonemapPlugin=class extends sB{constructor(){super(...arguments),this.extraUniforms={toneMappingContrast:{value:1},toneMappingSaturation:{value:1}},this.extraDefines={TONEMAP_BACKGROUND:()=>!1===this.tonemapBackground||!1===this._viewer?.scene.backgroundTonemap?"0":"1"},this.enabled=!0,this.toneMapping=ae,this.tonemapBackground=!0,this.exposure=1,this.priority=-100,this.parsFragmentSnippet=()=>this.isDisabled()?"":ym`
            uniform float toneMappingContrast;
            uniform float toneMappingSaturation;
            ${"int getToneMapBit(in int number){\n#ifdef WebGL2Context\nreturn(number/2)% 2;\n#else\nreturn int(mod(floor(float(number)/2.),2.));\n#endif\n}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;\n#if defined( TONE_MAPPING )\noutColor.rgb=toneMapping(outColor.rgb);outColor.rgb=TonemappingContrast(outColor.rgb);outColor.rgb=TonemappingSaturation(outColor.rgb);\n#endif\nreturn outColor;}"}
        `,this._shaderPatch="bool doTonemap=true;\n#ifdef HAS_GBUFFER\n#ifdef GBUFFER_HAS_FLAGS\ndoTonemap=getToneMapBit(getGBufferFlags(vUv).a)>0;\n#endif\n#if TONEMAP_BACKGROUND < 1\nif(isBackground)doTonemap=false;\n#endif\n#endif\nif(doTonemap)diffuseColor=ToneMapping(diffuseColor);",this._rendererState={}}onObjectRender(e,t,i){if(this.isDisabled())return;const{toneMapping:n,toneMappingExposure:r}=i;this._rendererState.toneMapping=n,this._rendererState.toneMappingExposure=r,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&&void 0!==e.clipBackground&&(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=!1===(t.material.userData.gBufferData?.tonemapEnabled??t.material?.userData.postTonemap)?0:1;e.w=cg(e.w,1,i),super.updateGBufferFlags(e,t)}},e.TonemapPlugin.PluginType="Tonemap",Ts.tonemapping_pars_fragment=Ts.tonemapping_pars_fragment.replace("vec3 CustomToneMapping( vec3 color ) { return color; }","\n#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 ) )\nvec3 Uncharted2ToneMapping(vec3 color){color*=toneMappingExposure;return saturate(Uncharted2Helper(color)/Uncharted2Helper(vec3(1.0)));}vec3 CustomToneMapping(vec3 color){return Uncharted2ToneMapping(color);}"),lB([qm(),Qm(e.TonemapPlugin.prototype.setDirty),Hg("Enabled")],e.TonemapPlugin.prototype,"enabled",2),lB([Ng("Mode",[["Linear",ne],["Reinhard",re],["Cineon",se],["ACESFilmic",ae],["Uncharted2",cB],["AgX",oe]].map(e=>({label:e[0],value:e[1]}))),Qm(e.TonemapPlugin.prototype.setDirty),qm()],e.TonemapPlugin.prototype,"toneMapping",2),lB([Qm(e.TonemapPlugin.prototype.setDirty),qm()],e.TonemapPlugin.prototype,"tonemapBackground",2),lB([Qm(e.TonemapPlugin.prototype.setDirty),Fg("Exposure",[0,2*Math.PI],.01),qm()],e.TonemapPlugin.prototype,"exposure",2),lB([Fg("Saturation",[0,2],.01),ky({propKey:"toneMappingSaturation"}),qm()],e.TonemapPlugin.prototype,"saturation",2),lB([Fg("Contrast",[0,2],.01),ky({propKey:"toneMappingContrast"}),qm()],e.TonemapPlugin.prototype,"contrast",2),e.TonemapPlugin=lB([qg("Tonemapping")],e.TonemapPlugin);var hB=Object.defineProperty,dB=Object.getOwnPropertyDescriptor,uB=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?dB(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&hB(t,i,s),s};function pB(e){const t=[];let i=Object.getPrototypeOf(e);for(;i;)i.constructor?.PluginType&&t.push(i.constructor.PluginType),i.constructor?.OldPluginType&&t.push(i.constructor.OldPluginType),i=Object.getPrototypeOf(i);return t}e.ThreeViewer=class extends ri{constructor({debug:t=!1,...i}){super(),this.type="ThreeViewer",this.enabled=!0,this.renderEnabled=!0,this.timeline=new e.ViewerTimeline,this.plugins={},this.maxFramePerLoop=1,this.rendersPerFrame=1,this.resizeObserver=window?.ResizeObserver?new window.ResizeObserver(e=>this.resize()):void 0,this._needsResize=!1,this._isRenderingFrame=!1,this._needsReset=!0,this._lastCameraPosition=new Xi,this._lastCameraQuat=new qi,this._lastCameraTarget=new Xi,this._tempVec=new Xi,this._tempQuat=new qi,this._lastMainCamera=void 0,this.serializePluginsIgnored=[],this.resize=()=>{this._needsResize=!0,this.setDirty()},this.deleteImportedViewerConfigOnLoad=!0,this.deleteImportedViewerConfigOnLoadWait=2e3,this.loadConfigResources=async(e,t)=>{if(e.__isLoadedResources)return e;const i=M_(e,this);return await C_.ImportMeta(i,t)},this._setActiveCameraView=e=>{if("setView"===e.type){if(!e.camera)return void this.console.warn("Cannot find camera",e);this._scene.mainCamera.setViewFromCamera(e.camera)}else if("activateMain"===e.type){let t=e.camera;void 0===t&&this._lastMainCamera&&(this._lastMainCamera.parent&&(t=this._lastMainCamera),this._lastMainCamera=void 0),t&&this._scene.mainCamera!==t&&(this._lastMainCamera=this._scene.mainCamera),t?.setCanvas(this._canvas,!1),this._scene.mainCamera=null===t?void 0:t||void 0}},this._defaultConfig={assetType:"config",type:this.type,version:e.ThreeViewer.VERSION,metadata:{generator:"ThreePipe",version:2},plugins:[]},this._lastSize=new fi,this._onContextRestore=e=>{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=e=>{this._lastSize.set(this._canvas.width,this._canvas.height),this._canvas.width=2,this._canvas.height=2,this.resize(),this.enabled=!1},this._stopPropagation=e=>{this.scene.mainCamera.canUserInteract&&e.stopPropagation()},this._onListeners={},this._pluginListeners={add:[],remove:[]},this.debug=t,t&&(e.ThreeViewer.ViewerDebugging=!0),this._canvas=i.canvas||rm();const n=getComputedStyle(this._canvas);!this._canvas.style.width&&"none"===n.maxWidth&&(this._canvas.style.width="100%"),!this._canvas.style.height&&"none"===n.maxHeight&&(this._canvas.style.height="100%");let r,s=i.container;if(s&&!i.canvas&&s.appendChild(this._canvas),s||(s=this._canvas.parentElement??void 0),s||(s=globalThis.document?.body),!s)throw new Error("No container(or canvas).");if(this._container=s,this.setDirty=this.setDirty.bind(this),this._animationLoop=this._animationLoop.bind(this),t&&!1!==i.statsJS&&(this.renderStats=new cf(this._container),this.renderStats.show()),window.threeViewers||(window.threeViewers=[]),window.threeViewers.push(this),i.camera?.isCamera)r=i.camera,r.assetType||nC.upgradeCamera.call(r);else{r="orthographic"===i.camera?.type?new mC(i.camera?.controlsMode??"orbit",this._canvas):new lC(i.camera?.controlsMode??"orbit",this._canvas),r.name="Default Camera"+("OrthographicCamera"===r.type?" (Ortho)":"");const e=i.camera?.position||[0,0,5];Array.isArray(e)?r.position.fromArray(e):r.position.copy(e);const t=i.camera?.target||[0,0,0];Array.isArray(t)?r.target.fromArray(t):r.target.copy(t),r.setDirty(),r.userData.autoLookAtTarget=!0,i.rootScene&&this.console.error("ThreeViewer: Camera must also be passed in options when rootScene is passed in options.")}this.addEventListener("postFrame",()=>{const e=this._scene.mainCamera;if(e&&e.canUserInteract){const t=this.getPlugin("ProgressivePlugin")?.postFrameConvergedRecordingDelta();if(void 0!==t&&0===t)return;"function"==typeof e.controls?.update&&e.controls?.update()}}),this.addEventListener("preFrame",()=>{const e=this._scene.mainCamera;e.getWorldPosition(this._tempVec).sub(this._lastCameraPosition).lengthSq()+this._tempVec.subVectors(e.target,this._lastCameraTarget).lengthSq()+e.getWorldQuaternion(this._tempQuat).angleTo(this._lastCameraQuat)>1e-6&&e.setDirty()}),this.object3dManager=new DR,this._scene=i.rootScene??new e.RootScene(r,Wx(this)),this._scene.mainCamera!==r&&(this._scene.mainCamera=r),this._scene.setBackgroundColor(i.backgroundColor??"#ffffff"),this._scene.addEventListener("setView",this._setActiveCameraView),this._scene.addEventListener("activateMain",this._setActiveCameraView),this._scene.addEventListener("materialUpdate",e=>this.setDirty(this._scene,e)),this._scene.addEventListener("materialChanged",e=>this.setDirty(this._scene,e)),this._scene.addEventListener("objectUpdate",e=>this.setDirty(this._scene,e)),this._scene.addEventListener("textureUpdate",e=>this.setDirty(this._scene,e)),this._scene.addEventListener("sceneUpdate",e=>{this.setDirty(this._scene,e),!1!==e.geometryChanged&&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(i.modelRootScale??1),this.object3dManager.setRoot(this._scene),(void 0!==i.isAntialiased||void 0!==i.useRgbm||void 0!==i.useGBufferDepth)&&this.console.warn("isAntialiased, useRgbm and useGBufferDepth are deprecated, use msaa, rgbm and zPrepass instead.");const a=i.rmClass??e.ViewerRenderManager;this.renderManager=new a({canvas:this._canvas,msaa:i.msaa??i.isAntialiased??!1,rgbm:i.rgbm??i.useRgbm??!0,zPrepass:i.zPrepass??i.useGBufferDepth??!1,depthBuffer:!(i.zPrepass??i.useGBufferDepth),stencilBuffer:i.stencil,screenShader:i.screenShader,renderScale:"string"==typeof i.renderScale?"auto"===i.renderScale?Math.min(i.maxRenderScale||2,window.devicePixelRatio):parseFloat(i.renderScale):i.renderScale,maxHDRIntensity:i.maxHDRIntensity,powerPreference:i.powerPreference}),this.renderManager.addEventListener("animationLoop",this._animationLoop),this.renderManager.addEventListener("resize",()=>this._scene.mainCamera.refreshAspect()),this.renderManager.addEventListener("update",e=>{"registerPass"===e.change&&e.pass?.materialExtension?this.assetManager.materials.registerMaterialExtension(e.pass.materialExtension):"unregisterPass"===e.change&&e.pass?.materialExtension&&this.assetManager.materials.unregisterMaterialExtension(e.pass.materialExtension),this.setDirty(this.renderManager,e)}),this.assetManager=new TR(this,i.assetManager),void 0!==i.cacheImportedAssets&&(this.assetManager.importer.cacheImportedAssets=i.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),i.dropzone&&this.addPluginSync(new e.DropzonePlugin("object"==typeof i.dropzone?i.dropzone:void 0)),!1!==i.tonemap&&this.addPluginSync(new e.TonemapPlugin);for(const e of i.plugins??[])this.addPluginSync(e);if(this.console.log("ThreePipe Viewer instance initialized, version: ",e.ThreeViewer.VERSION),i.load){const e=[i.load.src].flat().filter(e=>e).map(async e=>e&&this.load(e));i.load.environment&&e.push(this.setEnvironmentMap(i.load.environment)),i.load.background&&e.push(this.setBackgroundMap(i.load.background)),Promise.all(e).then(i.onLoad)}i.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 e.ThreeViewer.Console}get dialog(){return e.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?E_(e.exportConfig()):e.constructor?.PluginType?E_(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(i=>{this._canvas.toBlob(e=>{i(e)},e,t)});return this.renderEnabled?await this.doOnce("postFrame",async()=>{this.renderEnabled=!1;const e=await n();return this.renderEnabled=!0,e}):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 e=[],t=[];for(const[i,n]of[...Object.entries(this.plugins)])i!==n.constructor.OldPluginType&&(n.isViewerPluginSync?e.push(n):t.push(n));for(const t of e)this.removePluginSync(t,!0);for(const e of t)this.removePlugin(e,!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)return void this.console.warn("animation loop: frame skip");this._isRenderingFrame=!0,this.renderStats?.begin();for(let t=0;t<this.maxFramePerLoop;t++){let t=!1;if(this.renderEnabled&&(this._needsReset&&(this.renderManager.reset(),this._needsReset=!1),this._needsResize)){const i=[Math.floor(this._canvas.clientWidth),Math.floor(this._canvas.clientHeight)];if(e.xrFrame){const e=this.renderManager.webglRenderer.xr.getCamera()?.cameras[0]?.viewport;e?((0!==e.x||0!==e.y)&&this.console.warn("x and y must be 0?"),i[0]=e.width,i[1]=e.height,this.console.log("resize for xr",i)):this._needsResize=!1}this._needsResize&&(this.renderManager.setSize(...i),this._needsResize=!1,t=!0)}if(this.dispatchEvent({...e,type:"preFrame",target:this}),this.dispatch("preFrame",{time:e.time,deltaTime:e.deltaTime,timeline:this.timeline,resized:t}),this.renderEnabled){const e=Object.entries(this.plugins).filter(([e,t])=>t.dirty&&e!==t.constructor.OldPluginType);if(e.length>0&&this.setDirty(e),this._needsReset&&(this.renderManager.reset(),this._needsReset=!1),this.renderManager.needsRender)for(let e=0;e<this.rendersPerFrame;e++){this._scene._isMainRendering=!0,this.dispatchEvent({type:"preRender",target:this});const e=()=>{const e=this._scene.mainCamera;this._scene.renderCamera=e,e.visible&&this.renderManager.render(this._scene,this.renderManager.defaultRenderToScreen)};if(this.debug)e();else try{e()}catch(e){if(this.console.error("ThreeViewer: Uncaught error while rendering frame."),this.console.error(e),this.debug)throw e;this.renderEnabled=!1,this.dispatchEvent({type:"renderError",error:e})}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["string"==typeof e?e:e.PluginType]}getPlugins(e){const t="string"==typeof e?e:e.PluginType,i=Object.values(this.plugins),n=[];for(const e of i)pB(e).includes(t)&&n.push(e);return n}async getOrAddPlugin(e,...t){return this.getPlugin(e)||this.addPlugin(e,...t)}getOrAddPluginSync(e,...t){return this.getPlugin(e)||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 e of i.dependencies||[])await this.getOrAddPlugin(e);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 r=i.constructor.OldPluginType;return r&&this.plugins[r]&&this.console.error(`ThreeViewer: Plugin type mismatch ${r}`),r&&(this.plugins[r]=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 e of i.dependencies||[])this.getOrAddPluginSync(e);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 r=()=>{this.plugins[n]=i;const e=i.constructor.OldPluginType;e&&this.plugins[e]&&this.console.error(`ThreeViewer: Plugin type mismatch ${e}`),e&&(this.plugins[e]=i),i.onAdded(this)};if(this.debug)r();else try{r()}catch(e){this.console.error("ThreeViewer: Error adding plugin, check console for details",e),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 r=n||this.container.getBoundingClientRect(),s=r.height,a=r.width,o=Math.floor(e.width),l=Math.floor(e.height),c=o/l,h=a/s,d=i;let u,p;switch(t){case"contain":h>c?(u=s*c,p=s):(u=a,p=a/c);break;case"cover":h>c?(u=a,p=a/c):(u=s*c,p=s);break;case"fill":u=a,p=s;break;case"scale-down":o<a&&l<s?(u=o,p=l):h>c?(u=s*c,p=s):(u=a,p=a/c);break;case"none":u=o,p=l;break;default:throw new Error(`Invalid mode: ${t}`)}this.setSize({width:u,height:p}),this.renderManager.renderScale=d*l/p}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),!1!==t?.importConfig&&(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&&0===t.length?[]:t?.map(t=>{const i=this.getPlugin(t);return i?this.serializePlugin(i,e):void 0}).filter(e=>!!e)??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(e=>!!e)}serializePlugin(e,t){if(!this.serializePluginsIgnored.includes(e.constructor.PluginType))return!1!==e.serializeWithViewer?e.toJSON?.(t):void 0}deserializePlugins(e,t){return e.forEach(e=>{if(!e.type)return void this.console.warn("Invalid plugin to import ",e);if(this.serializePluginsIgnored.includes(e.type))return;const i=this.getPlugin(e.type);i&&i.fromJSON&&i.fromJSON(e,t)}),this}exportPluginConfig(e){if((e&&"string"==typeof e||e.PluginType)&&(e=this.getPlugin(e)),!e)return{};const t=w_(),i=e.toJSON?.(t);return i?(i.resources=S_(t),i):{}}async importPluginConfig(e,t){const i=e.type;if(!(t=t||this.getPlugin(i)))return void this.console.warn(`No plugin found for type ${i} to import config`);if(!t.fromJSON)return void this.console.warn(`Plugin ${i} does not support importing presets`);const n=e.resources||{};e.resources&&delete e.resources;const r=await this.loadConfigResources(n);return await t.fromJSON(e,r),r&&(e.resources=r),t}exportPluginsConfig(e){const t=w_(),i=this.serializePlugins(t,e);return b_(t),{...this._defaultConfig,plugins:i,resources:S_(t)}}exportConfig(e=!1,t){return this.toJSON(e,t)}async importConfig(e,t){if(e.type!==this.type&&"ViewerApp"!==e.type&&"ThreeViewer"!==e.type)return this.getPlugin(e.type)?this.importPluginConfig(e):void this.console.error(`Unknown config type ${e.type} to import`);let i=await this.loadConfigResources(e.resources||{});if(t){const e={_context:i._context},n=[...Object.keys(i),...Object.keys(t||{})];for(const r of n)e[r]="object"===r?i[r]||t[r]:{...i[r],...t[r]};i=e}return e.resources=i,this.fromJSON(e,i),this}toJSON(e=!0,t,i){"boolean"!=typeof e&&(e=!0),void 0!==t&&!Array.isArray(t)&&(t=void 0),i=i||w_();const n=Object.assign({...this._defaultConfig,metadata:{...this._defaultConfig.metadata},plugins:this.serializePlugins(i,t)},f_.Serialize(this,i,!0));return e||b_(i),n.resources=S_(i),n}fromJSON(e,t){const i={...e};return t&&i.metadata&&"ViewerApp"===i.type&&(t._configMetadata={...i.metadata,viewerVersion:i.version}),void 0!==i.backgroundIntensity&&void 0===i.scene?.backgroundIntensity&&(this.console.warn("old file format, backgroundIntensity moved to RootScene"),this._scene.backgroundIntensity=i.backgroundIntensity,delete i.backgroundIntensity),void 0!==i.useLegacyLights&&(i.useLegacyLights&&this.console.warn("useLegacyLights support removed since threepipe v0.5.0"),delete i.useLegacyLights),void 0!==i.background&&void 0===i.scene?.background&&(this.console.warn("old file format, background moved to RootScene"),"envMapBackground"===i.background?i.background="environment":"number"==typeof i.background?i.background=(new mr).setHex(i.background,Ut):"string"==typeof i.background?i.background=(new mr).setStyle(i.background,Ut):i.background?.isColor&&(i.background=new mr(i.background)),i.background?.isColor?(this._scene.backgroundColor=i.background,this._scene.background=null):i.background?(this._scene.backgroundColor=new mr("#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),f_.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(...r)=>{this.removeEventListener(e,n),i(await(t?.(...r)))};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");t=t??e.name??"file",i?await i.exportFile(e,t):bm(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(e){return void this.console.error("ThreeViewer: Error creating plugin",e)}}else i=e;return i}_renderEnabledChanged(){this.dispatchEvent({type:this.renderEnabled?"renderEnabled":"renderDisabled"})}async fitToView(e,t=1.5,i,n){await(this.getOrAddPluginSync(qR)?.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 ih(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;-1!==i&&this._onListeners[e]?.splice(i,1)}dispatch(e,t){const i=this._onListeners[e];if(i){const n=i.slice().sort((e,t)=>(e.order??0)-(t.order??0));for(const i of n)i.callback({...t,type:e,target:this})}}_onPluginAdd(e){const t={type:"addPlugin",target:this,plugin:e};this.dispatchEvent(t);const i=pB(e);this._pluginListeners.add.filter(e=>!e.p.length||e.p.find(e=>i.includes(e))).forEach(e=>e.l(t)),this.setDirty(e)}_onPluginRemove(e,t=!1){const i={type:"removePlugin",target:this,plugin:e};this.dispatchEvent(i);const n=pB(e);this._pluginListeners.remove.filter(e=>!e.p.length||e.p.find(e=>n.includes(e))).forEach(e=>e.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(e=>!!e),l:t})}removePluginListener(e,t){this._pluginListeners[e]=this._pluginListeners[e].filter(e=>e.l!==t)}forPlugin(e,t,i,n){const r=()=>{if(i){const t=()=>{const n=this.getPlugin(e);n&&(this.removePluginListener("remove",t),i(n))};this.addPluginListener("remove",t,"string"==typeof e?e:e.PluginType),n?.constructor.PluginType&&this.addPluginListener("remove",t,n.constructor.PluginType)}},s=this.getPlugin(e);if(s)t(s),r();else{const i=()=>{const n=this.getPlugin(e);n&&(this.removePluginListener("add",i),t(n),r())};this.addPluginListener("add",i,"string"==typeof e?e:e.PluginType,"string"==typeof e?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]}},e.ThreeViewer.VERSION="0.6.0",e.ThreeViewer.ConfigTypeSlug="vjson",e.ThreeViewer.Console={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},e.ThreeViewer.Dialog=ug,e.ThreeViewer.ViewerDebugging=!1,uB([qm()],e.ThreeViewer.prototype,"type",2),uB([Qm(e.ThreeViewer.prototype._renderEnabledChanged),Hg("Enable Rendering",{tags:["advanced"]})],e.ThreeViewer.prototype,"renderEnabled",2),uB([Lg(void 0,{label:"Rendering",expanded:!0}),qm("renderManager")],e.ThreeViewer.prototype,"renderManager",2),uB([Lg(void 0,{label:"Scene",expanded:!0}),qm("scene")],e.ThreeViewer.prototype,"_scene",2),uB([Lg(void 0,{label:"Timeline",expanded:!0,tags:["advanced"]}),qm("timeline")],e.ThreeViewer.prototype,"timeline",2),e.ThreeViewer=uB([Wg("Viewer")],e.ThreeViewer);const mB=new Xi,gB=new Xi,fB=new Gi;class AB extends ts{constructor(e=new wv,t=new Cv({color:16777215*Math.random()})){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 e=0,r=0,s=t.count;e<s;e++,r+=2)mB.fromBufferAttribute(t,e),gB.fromBufferAttribute(i,e),n[r]=0===r?0:n[r-1],n[r+1]=n[r]+mB.distanceTo(gB);const r=new _p(n,2,1);return e.setAttribute("instanceDistanceStart",new wl(r,1,0)),e.setAttribute("instanceDistanceEnd",new wl(r,1,1)),this}onBeforeRender(e){const t=this.material.uniforms;t&&t.resolution&&(e.getViewport(fB),this.material.uniforms.resolution.value.set(fB.z,fB.w))}}function yB(e,t=1024){const i=new fi,n=new fi,r=[new fi,new fi,new fi],s=[],a=document.createElement("canvas"),o=t,l=t;a.width=o,a.height=l;const c=a.getContext("2d");c.lineWidth=1,c.strokeStyle="rgb( 63, 63, 63 )",c.textAlign="center",c.fillStyle="rgb( 255, 255, 255 )",c.fillRect(0,0,o,l);const h=e.index,d=e.attributes.uv;if(h)for(let e=0,t=h.count;e<t;e+=3)s[0]=h.getX(e),s[1]=h.getX(e+1),s[2]=h.getX(e+2),r[0].fromBufferAttribute(d,s[0]),r[1].fromBufferAttribute(d,s[1]),r[2].fromBufferAttribute(d,s[2]),u(s,r,e/3);else for(let e=0,t=d.count;e<t;e+=3)s[0]=e,s[1]=e+1,s[2]=e+2,r[0].fromBufferAttribute(d,s[0]),r[1].fromBufferAttribute(d,s[1]),r[2].fromBufferAttribute(d,s[2]),u(s,r,e/3);return a;function u(e,t,r){c.beginPath(),i.set(0,0);for(let e=0,n=t.length;e<n;e++){const n=t[e];i.x+=n.x,i.y+=n.y,0===e?c.moveTo(n.x*(o-2)+.5,(1-n.y)*(l-2)+.5):c.lineTo(n.x*(o-2)+.5,(1-n.y)*(l-2)+.5)}c.closePath(),c.stroke(),i.divideScalar(t.length),c.font="18px Arial",c.fillStyle="rgb( 63, 63, 63 )",c.fillText(r,i.x*o,(1-i.y)*l),i.x>.95&&c.fillText(r,i.x%1*o,(1-i.y)*l),c.font="12px Arial",c.fillStyle="rgb( 191, 191, 191 )";for(let r=0,s=t.length;r<s;r++){const s=t[r];n.addVectors(i,s).divideScalar(2);const a=e[r];c.fillText("abc"[r]+a,n.x*o,(1-n.y)*l),n.x>.95&&c.fillText("abc"[r]+a,n.x%1*o,(1-n.y)*l)}}}class vB{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:t,msg:i,transfer:n}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(i,n)}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();-1!==n?(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 _B=9,bB=15,xB=16,wB=22,CB=37,SB=43,MB=76,EB=83,TB=97,IB=100,PB=103,DB=109,RB=165,BB=166;class LB{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 OB{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 UB=[171,75,84,88,32,50,48,187,13,10,26,10];function FB(e){return typeof TextDecoder<"u"?(new TextDecoder).decode(e):Buffer.from(e).toString("utf8")}let kB,NB,jB;const zB={env:{emscripten_notify_memory_growth:function(e){jB=new Uint8Array(NB.exports.memory.buffer)}}};class GB{init(){return kB||(kB=typeof fetch<"u"?fetch("data:application/wasm;base64,"+QB).then(e=>e.arrayBuffer()).then(e=>WebAssembly.instantiate(e,zB)).then(this._init):WebAssembly.instantiate(Buffer.from(QB,"base64"),zB).then(this._init),kB)}_init(e){NB=e.instance,zB.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!NB)throw new Error("ZSTDDecoder: Await .init() before decoding.");const i=e.byteLength,n=NB.exports.malloc(i);jB.set(e,n),t=t||Number(NB.exports.ZSTD_findDecompressedSize(n,i));const r=NB.exports.malloc(t),s=NB.exports.ZSTD_decompress(r,t,n,i),a=jB.slice(r,r+s);return NB.exports.free(n),NB.exports.free(r),a}}const QB="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",VB=new WeakMap;let HB,WB=0;class qB extends su{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new vB,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!0===e.isWebGPURenderer?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 lu(this.manager);e.setPath(this.transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new lu(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(([e,t])=>{const i=qB.BasisWorker,n=["/* constants */","let _EngineFormat = "+JSON.stringify(qB.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(qB.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(qB.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this.workerSourceURL=URL.createObjectURL(new Blob([n])),this.transcoderBinary=t,this.workerPool.setWorkerCreator(()=>{const e=new Worker(this.workerSourceURL),t=this.transcoderBinary.slice(0);return e.postMessage({type:"init",config:this.workerConfig,transcoderBinary:t},[t]),e})}),WB>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),WB++}return this.transcoderPending}load(e,t,i,n){if(null===this.workerConfig)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");const r=new lu(this.manager);r.setResponseType("arraybuffer"),r.setCrossOrigin(this.crossOrigin),r.setWithCredentials(this.withCredentials),r.load(e,e=>{this.parse(e,t,n)},i,n)}parse(e,t,i){if(null===this.workerConfig)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(VB.has(e))return VB.get(e).promise.then(t).catch(i);this.createTexture(e).then(e=>t?t(e):null).catch(i)}_createTextureFrom(e,t){const{faces:i,width:n,height:r,format:s,type:a,error:o,dfdFlags:l}=e;if("error"===a)return Promise.reject(o);let c;if(6===t.faceCount)c=new th(i,s,Ce);else{const e=i[0].mipmaps;c=t.layerCount>1?new eh(e,n,r,t.layerCount,s,Ce):new $c(e,n,r,s,Ce)}return c.minFilter=1===i[0].mipmaps.length?be:we,c.magFilter=be,c.generateMipmaps=!1,c.needsUpdate=!0,c.colorSpace=JB(t),c.premultiplyAlpha=!!(1&l),c}async createTexture(e,t={}){const i=function(e){const t=new Uint8Array(e.buffer,e.byteOffset,UB.length);if(t[0]!==UB[0]||t[1]!==UB[1]||t[2]!==UB[2]||t[3]!==UB[3]||t[4]!==UB[4]||t[5]!==UB[5]||t[6]!==UB[6]||t[7]!==UB[7]||t[8]!==UB[8]||t[9]!==UB[9]||t[10]!==UB[10]||t[11]!==UB[11])throw new Error("Missing KTX 2.0 identifier.");const i=new LB,n=17*Uint32Array.BYTES_PER_ELEMENT,r=new OB(e,UB.length,n,!0);i.vkFormat=r._nextUint32(),i.typeSize=r._nextUint32(),i.pixelWidth=r._nextUint32(),i.pixelHeight=r._nextUint32(),i.pixelDepth=r._nextUint32(),i.layerCount=r._nextUint32(),i.faceCount=r._nextUint32();const s=r._nextUint32();i.supercompressionScheme=r._nextUint32();const a=r._nextUint32(),o=r._nextUint32(),l=r._nextUint32(),c=r._nextUint32(),h=r._nextUint64(),d=r._nextUint64(),u=new OB(e,UB.length+n,3*s*8,!0);for(let t=0;t<s;t++)i.levels.push({levelData:new Uint8Array(e.buffer,e.byteOffset+u._nextUint64(),u._nextUint64()),uncompressedByteLength:u._nextUint64()});const p=new OB(e,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:[]},g=(m.descriptorBlockSize/4-6)/4;for(let e=0;e<g;e++){const t={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&t.channelType?(t.sampleLower=p._nextInt32(),t.sampleUpper=p._nextInt32()):(t.sampleLower=p._nextUint32(),t.sampleUpper=p._nextUint32()),m.samples[e]=t}i.dataFormatDescriptor.length=0,i.dataFormatDescriptor.push(m);const f=new OB(e,l,c,!0);for(;f._offset<c;){const e=f._nextUint32(),t=f._scan(e),n=FB(t),r=f._scan(e-t.byteLength);i.keyValue[n]=n.match(/^ktx/i)?FB(r):r,f._offset%4&&f._skip(4-f._offset%4)}if(d<=0)return i;const A=new OB(e,h,d,!0),y=A._nextUint16(),v=A._nextUint16(),_=A._nextUint32(),b=A._nextUint32(),x=A._nextUint32(),w=A._nextUint32(),C=[];for(let e=0;e<s;e++)C.push({imageFlags:A._nextUint32(),rgbSliceByteOffset:A._nextUint32(),rgbSliceByteLength:A._nextUint32(),alphaSliceByteOffset:A._nextUint32(),alphaSliceByteLength:A._nextUint32()});const S=h+A._offset,M=S+_,E=M+b,T=E+x,I=new Uint8Array(e.buffer,e.byteOffset+S,_),P=new Uint8Array(e.buffer,e.byteOffset+M,b),D=new Uint8Array(e.buffer,e.byteOffset+E,x),R=new Uint8Array(e.buffer,e.byteOffset+T,w);return i.globalData={endpointCount:y,selectorCount:v,imageDescs:C,endpointsData:I,selectorsData:P,tablesData:D,extendedData:R},i}(new Uint8Array(e));if(0!==i.vkFormat)return async function(e){const{vkFormat:t}=e;if(void 0===YB[t])throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");let i;2===e.supercompressionScheme&&(HB||(HB=new Promise(async e=>{const t=new GB;await t.init(),e(t)})),i=await HB);const n=[];for(let r=0;r<e.levels.length;r++){const s=Math.max(1,e.pixelWidth>>r),a=Math.max(1,e.pixelHeight>>r),o=e.pixelDepth?Math.max(1,e.pixelDepth>>r):0,l=e.levels[r];let c,h;if(0===e.supercompressionScheme)c=l.levelData;else{if(2!==e.supercompressionScheme)throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");c=i.decode(l.levelData,l.uncompressedByteLength)}h=KB[t]===Pe?new Float32Array(c.buffer,c.byteOffset,c.byteLength/Float32Array.BYTES_PER_ELEMENT):KB[t]===De?new Uint16Array(c.buffer,c.byteOffset,c.byteLength/Uint16Array.BYTES_PER_ELEMENT):c,n.push({data:h,width:s,height:a,depth:o})}let r;if(XB.has(YB[t]))r=0===e.pixelDepth?new ec(n[0].data,e.pixelWidth,e.pixelHeight):new Wi(n[0].data,e.pixelWidth,e.pixelHeight,e.pixelDepth);else{if(e.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");r=new $c(n,e.pixelWidth,e.pixelHeight)}return r.mipmaps=n,r.type=KB[t],r.format=YB[t],r.colorSpace=JB(e),r.needsUpdate=!0,Promise.resolve(r)}(i);const n=t,r=this.init().then(()=>this.workerPool.postMessage({type:"transcode",buffer:e,taskConfig:n},[e])).then(e=>this._createTextureFrom(e.data,i));return VB.set(e,{promise:r}),r}dispose(){return this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),WB--,this}}qB.BasisFormat={ETC1S:0,UASTC_4x4:1},qB.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},qB.EngineFormat={RGBAFormat:Ue,RGBA_ASTC_4x4_Format:tt,RGBA_BPTC_Format:gt,RGBA_ETC2_EAC_Format:et,RGBA_PVRTC_4BPPV1_Format:Ke,RGBA_S3TC_DXT5_Format:qe,RGB_ETC1_Format:Ze,RGB_ETC2_Format:$e,RGB_PVRTC_4BPPV1_Format:Xe,RGBA_S3TC_DXT1_Format:He},qB.BasisWorker="function () {\n\n\tlet config;\n\tlet transcoderPending;\n\tlet BasisModule;\n\n\tconst EngineFormat = _EngineFormat; // eslint-disable-line no-undef\n\tconst TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef\n\tconst BasisFormat = _BasisFormat; // eslint-disable-line no-undef\n\n\tself.addEventListener( 'message', function ( e ) {\n\n\t\tconst message = e.data;\n\n\t\tswitch ( message.type ) {\n\n\t\t\tcase 'init':\n\t\t\t\tconfig = message.config;\n\t\t\t\tinit( message.transcoderBinary );\n\t\t\t\tbreak;\n\n\t\t\tcase 'transcode':\n\t\t\t\ttranscoderPending.then( () => {\n\n\t\t\t\t\ttry {\n\n\t\t\t\t\t\tconst { faces, buffers, width, height, hasAlpha, format, dfdFlags } = transcode( message.buffer );\n\n\t\t\t\t\t\tself.postMessage( { type: 'transcode', id: message.id, faces, width, height, hasAlpha, format, dfdFlags }, buffers );\n\n\t\t\t\t\t} catch ( error ) {\n\n\t\t\t\t\t\tconsole.error( error );\n\n\t\t\t\t\t\tself.postMessage( { type: 'error', id: message.id, error: error.message } );\n\n\t\t\t\t\t}\n\n\t\t\t\t} );\n\t\t\t\tbreak;\n\n\t\t}\n\n\t} );\n\n\tfunction init( wasmBinary ) {\n\n\t\ttranscoderPending = new Promise( ( resolve ) => {\n\n\t\t\tBasisModule = { wasmBinary, onRuntimeInitialized: resolve };\n\t\t\tBASIS( BasisModule ); // eslint-disable-line no-undef\n\n\t\t} ).then( () => {\n\n\t\t\tBasisModule.initializeBasis();\n\n\t\t\tif ( BasisModule.KTX2File === undefined ) {\n\n\t\t\t\tconsole.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );\n\n\t\t\t}\n\n\t\t} );\n\n\t}\n\n\tfunction transcode( buffer ) {\n\n\t\tconst ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );\n\n\t\tfunction cleanup() {\n\n\t\t\tktx2File.close();\n\t\t\tktx2File.delete();\n\n\t\t}\n\n\t\tif ( ! ktx2File.isValid() ) {\n\n\t\t\tcleanup();\n\t\t\tthrow new Error( 'THREE.KTX2Loader:\tInvalid or unsupported .ktx2 file' );\n\n\t\t}\n\n\t\tconst basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;\n\t\tconst width = ktx2File.getWidth();\n\t\tconst height = ktx2File.getHeight();\n\t\tconst layerCount = ktx2File.getLayers() || 1;\n\t\tconst levelCount = ktx2File.getLevels();\n\t\tconst faceCount = ktx2File.getFaces();\n\t\tconst hasAlpha = ktx2File.getHasAlpha();\n\t\tconst dfdFlags = ktx2File.getDFDFlags();\n\n\t\tconst { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );\n\n\t\tif ( ! width || ! height || ! levelCount ) {\n\n\t\t\tcleanup();\n\t\t\tthrow new Error( 'THREE.KTX2Loader:\tInvalid texture' );\n\n\t\t}\n\n\t\tif ( ! ktx2File.startTranscoding() ) {\n\n\t\t\tcleanup();\n\t\t\tthrow new Error( 'THREE.KTX2Loader: .startTranscoding failed' );\n\n\t\t}\n\n\t\tconst faces = [];\n\t\tconst buffers = [];\n\n\t\tfor ( let face = 0; face < faceCount; face ++ ) {\n\n\t\t\tconst mipmaps = [];\n\n\t\t\tfor ( let mip = 0; mip < levelCount; mip ++ ) {\n\n\t\t\t\tconst layerMips = [];\n\n\t\t\t\tlet mipWidth, mipHeight;\n\n\t\t\t\tfor ( let layer = 0; layer < layerCount; layer ++ ) {\n\n\t\t\t\t\tconst levelInfo = ktx2File.getImageLevelInfo( mip, layer, face );\n\n\t\t\t\t\tif ( face === 0 && mip === 0 && layer === 0 && ( levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0 ) ) {\n\n\t\t\t\t\t\tconsole.warn( 'THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions.' );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( levelCount > 1 ) {\n\n\t\t\t\t\t\tmipWidth = levelInfo.origWidth;\n\t\t\t\t\t\tmipHeight = levelInfo.origHeight;\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t// Handles non-multiple-of-four dimensions in textures without mipmaps. Textures with\n\t\t\t\t\t\t// mipmaps must use multiple-of-four dimensions, for some texture formats and APIs.\n\t\t\t\t\t\t// See mrdoob/three.js#25908.\n\t\t\t\t\t\tmipWidth = levelInfo.width;\n\t\t\t\t\t\tmipHeight = levelInfo.height;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tconst dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, layer, 0, transcoderFormat ) );\n\t\t\t\t\tconst status = ktx2File.transcodeImage( dst, mip, layer, face, transcoderFormat, 0, - 1, - 1 );\n\n\t\t\t\t\tif ( ! status ) {\n\n\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\tthrow new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );\n\n\t\t\t\t\t}\n\n\t\t\t\t\tlayerMips.push( dst );\n\n\t\t\t\t}\n\n\t\t\t\tconst mipData = concat( layerMips );\n\n\t\t\t\tmipmaps.push( { data: mipData, width: mipWidth, height: mipHeight } );\n\t\t\t\tbuffers.push( mipData.buffer );\n\n\t\t\t}\n\n\t\t\tfaces.push( { mipmaps, width, height, format: engineFormat } );\n\n\t\t}\n\n\t\tcleanup();\n\n\t\treturn { faces, buffers, width, height, hasAlpha, format: engineFormat, dfdFlags };\n\n\t}\n\n\t//\n\n\t// Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),\n\t// device capabilities, and texture dimensions. The list below ranks the formats separately\n\t// for ETC1S and UASTC.\n\t//\n\t// In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at\n\t// significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently\n\t// chooses RGBA32 only as a last resort and does not expose that option to the caller.\n\tconst FORMAT_OPTIONS = [\n\t\t{\n\t\t\tif: 'astcSupported',\n\t\t\tbasisFormat: [ BasisFormat.UASTC_4x4 ],\n\t\t\ttranscoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],\n\t\t\tengineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],\n\t\t\tpriorityETC1S: Infinity,\n\t\t\tpriorityUASTC: 1,\n\t\t\tneedsPowerOfTwo: false,\n\t\t},\n\t\t{\n\t\t\tif: 'bptcSupported',\n\t\t\tbasisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],\n\t\t\ttranscoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],\n\t\t\tengineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],\n\t\t\tpriorityETC1S: 3,\n\t\t\tpriorityUASTC: 2,\n\t\t\tneedsPowerOfTwo: false,\n\t\t},\n\t\t{\n\t\t\tif: 'dxtSupported',\n\t\t\tbasisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],\n\t\t\ttranscoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],\n\t\t\tengineFormat: [ EngineFormat.RGBA_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],\n\t\t\tpriorityETC1S: 4,\n\t\t\tpriorityUASTC: 5,\n\t\t\tneedsPowerOfTwo: false,\n\t\t},\n\t\t{\n\t\t\tif: 'etc2Supported',\n\t\t\tbasisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],\n\t\t\ttranscoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],\n\t\t\tengineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],\n\t\t\tpriorityETC1S: 1,\n\t\t\tpriorityUASTC: 3,\n\t\t\tneedsPowerOfTwo: false,\n\t\t},\n\t\t{\n\t\t\tif: 'etc1Supported',\n\t\t\tbasisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],\n\t\t\ttranscoderFormat: [ TranscoderFormat.ETC1 ],\n\t\t\tengineFormat: [ EngineFormat.RGB_ETC1_Format ],\n\t\t\tpriorityETC1S: 2,\n\t\t\tpriorityUASTC: 4,\n\t\t\tneedsPowerOfTwo: false,\n\t\t},\n\t\t{\n\t\t\tif: 'pvrtcSupported',\n\t\t\tbasisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],\n\t\t\ttranscoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],\n\t\t\tengineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],\n\t\t\tpriorityETC1S: 5,\n\t\t\tpriorityUASTC: 6,\n\t\t\tneedsPowerOfTwo: true,\n\t\t},\n\t];\n\n\tconst ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {\n\n\t\treturn a.priorityETC1S - b.priorityETC1S;\n\n\t} );\n\tconst UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {\n\n\t\treturn a.priorityUASTC - b.priorityUASTC;\n\n\t} );\n\n\tfunction getTranscoderFormat( basisFormat, width, height, hasAlpha ) {\n\n\t\tlet transcoderFormat;\n\t\tlet engineFormat;\n\n\t\tconst options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;\n\n\t\tfor ( let i = 0; i < options.length; i ++ ) {\n\n\t\t\tconst opt = options[ i ];\n\n\t\t\tif ( ! config[ opt.if ] ) continue;\n\t\t\tif ( ! opt.basisFormat.includes( basisFormat ) ) continue;\n\t\t\tif ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;\n\t\t\tif ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;\n\n\t\t\ttranscoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];\n\t\t\tengineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];\n\n\t\t\treturn { transcoderFormat, engineFormat };\n\n\t\t}\n\n\t\tconsole.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );\n\n\t\ttranscoderFormat = TranscoderFormat.RGBA32;\n\t\tengineFormat = EngineFormat.RGBAFormat;\n\n\t\treturn { transcoderFormat, engineFormat };\n\n\t}\n\n\tfunction isPowerOfTwo( value ) {\n\n\t\tif ( value <= 2 ) return true;\n\n\t\treturn ( value & ( value - 1 ) ) === 0 && value !== 0;\n\n\t}\n\n\t/** Concatenates N byte arrays. */\n\tfunction concat( arrays ) {\n\n\t\tif ( arrays.length === 1 ) return arrays[ 0 ];\n\n\t\tlet totalByteLength = 0;\n\n\t\tfor ( let i = 0; i < arrays.length; i ++ ) {\n\n\t\t\tconst array = arrays[ i ];\n\t\t\ttotalByteLength += array.byteLength;\n\n\t\t}\n\n\t\tconst result = new Uint8Array( totalByteLength );\n\n\t\tlet byteOffset = 0;\n\n\t\tfor ( let i = 0; i < arrays.length; i ++ ) {\n\n\t\t\tconst array = arrays[ i ];\n\t\t\tresult.set( array, byteOffset );\n\n\t\t\tbyteOffset += array.byteLength;\n\n\t\t}\n\n\t\treturn result;\n\n\t}\n\n}";const XB=new Set([Ue,ze,Ne]),YB={[DB]:Ue,[TB]:Ue,[CB]:Ue,[SB]:Ue,[PB]:ze,[EB]:ze,[xB]:ze,[wB]:ze,[IB]:Ne,[MB]:Ne,[bB]:Ne,[_B]:Ne,[BB]:st,[RB]:st},KB={[DB]:Pe,[TB]:De,[CB]:Ce,[SB]:Ce,[PB]:Pe,[EB]:De,[xB]:Ce,[wB]:Ce,[IB]:Pe,[MB]:De,[bB]:Ce,[_B]:Ce,[BB]:Ce,[RB]:Ce};function JB(e){const t=e.dataFormatDescriptor[0];return 1===t.colorPrimaries?2===t.transferFunction?Ot:Ut:10===t.colorPrimaries?2===t.transferFunction?Ft:kt:(0===t.colorPrimaries||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${t.colorPrimaries}"`),Lt)}class ZB extends cu{constructor(e){super(e)}parse(e,t){const i=new $B(e,1);return{mipmaps:i.mipmaps(t),width:i.pixelWidth,height:i.pixelHeight,format:i.glInternalFormat,isCubemap:6===i.numberOfFaces,mipmapCount:i.numberOfMipmapLevels}}}class $B{constructor(e,t){this.arrayBuffer=e;const i=new Uint8Array(this.arrayBuffer,0,12);if(171!==i[0]||75!==i[1]||84!==i[2]||88!==i[3]||32!==i[4]||49!==i[5]||49!==i[6]||187!==i[7]||13!==i[8]||10!==i[9]||26!==i[10]||10!==i[11])return void console.error("texture missing KTX identifier");const n=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.arrayBuffer,12,13*n),s=67305985===r.getUint32(0,!0);this.glType=r.getUint32(1*n,s),this.glTypeSize=r.getUint32(2*n,s),this.glFormat=r.getUint32(3*n,s),this.glInternalFormat=r.getUint32(4*n,s),this.glBaseInternalFormat=r.getUint32(5*n,s),this.pixelWidth=r.getUint32(6*n,s),this.pixelHeight=r.getUint32(7*n,s),this.pixelDepth=r.getUint32(8*n,s),this.numberOfArrayElements=r.getUint32(9*n,s),this.numberOfFaces=r.getUint32(10*n,s),this.numberOfMipmapLevels=r.getUint32(11*n,s),this.bytesOfKeyValueData=r.getUint32(12*n,s),0===this.glType?(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0!==this.pixelHeight&&0===this.pixelDepth?0===this.numberOfArrayElements?this.numberOfFaces===t?this.loadType=0:console.warn("number of faces expected"+t+", but found "+this.numberOfFaces):console.warn("texture arrays not currently supported"):console.warn("only 2D textures currently supported")):console.warn("only compressed formats currently supported")}mipmaps(e){const t=[];let i=64+this.bytesOfKeyValueData,n=this.pixelWidth,r=this.pixelHeight;const s=e?this.numberOfMipmapLevels:1;for(let e=0;e<s;e++){const e=new Int32Array(this.arrayBuffer,i,1)[0];i+=4;for(let s=0;s<this.numberOfFaces;s++){const s=new Uint8Array(this.arrayBuffer,i,e);t.push({data:s,width:n,height:r}),i+=e,i+=3-(e+3)%4}n=Math.max(1,.5*n),r=Math.max(1,.5*r)}return t}}class eL{parse(e){const t={},i=e.split("\n");let n=null,r=t;const s=[t];for(const e of i)if(e.includes("=")){const t=e.split("="),i=t[0].trim(),n=t[1].trim();if(n.endsWith("{")){const e={};s.push(e),r[i]=e,r=e}else if(n.endsWith("(")){const e=n.slice(0,-1);r[i]=e;const t={};s.push(t),r=t}else r[i]=n}else if(e.endsWith("{")){const e=r[n]||{};s.push(e),r[n]=e,r=e}else if(e.endsWith("}")){if(s.pop(),0===s.length)continue;r=s[s.length-1]}else if(e.endsWith("(")){const t={};s.push(t),n=e.split("(")[0].trim()||n,r[n]=t,r=t}else e.endsWith(")")?(s.pop(),r=s[s.length-1]):n=e.trim();return t}}class tL extends su{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new lu(r.manager);s.setPath(r.path),s.setResponseType("arraybuffer"),s.setRequestHeader(r.requestHeader),s.setWithCredentials(r.withCredentials),s.load(e,function(i){try{t(r.parse(i))}catch(t){n?n(t):console.error(t),r.manager.itemError(e)}},i,n)}parse(e){const t=new eL;function i(e){const t=e.slice(0,7),i=new Uint8Array([80,88,82,45,85,83,68,67]);return t.every((e,t)=>e===i[t])}const n=rD(new Uint8Array(e)),r=function(e){const n={};(new lu).setResponseType("arraybuffer");for(const r in e){if(r.endsWith("png")){const t=new Blob([e[r]],{type:{type:"image/png"}});n[r]=URL.createObjectURL(t)}if(r.endsWith("usd")||r.endsWith("usda")){if(i(e[r]))throw Error("THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.");const s=jP(e[r]);n[r]=t.parse(s)}}return n}(n),s=jP(function(e){if(e.length<1)return;const t=Object.keys(e)[0];let n=!1;if(t.endsWith("usda"))return e[t];if(t.endsWith("usdc"))n=!0;else if(t.endsWith("usd")){if(!i(e[t]))return e[t];n=!0}if(n)throw Error("THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.")}(n)),a=t.parse(s);function o(e,t){if(e){if(void 0!==t){const i=`def Mesh "${t}"`;if(i in e)return e[i]}for(const t in e){const i=e[t];if(t.startsWith("def Mesh"))return i;if("object"==typeof i){const e=o(i);if(e)return e}}}}function l(e,t){const i=[];for(let n=0;n<t.length;n++){const r=t[n],s=n*r;if(3===r){const t=e[s+0],n=e[s+1],r=e[s+2];i.push(t,n,r)}else if(4===r){const t=e[s+0],n=e[s+1],r=e[s+2],a=e[s+3];i.push(t,n,r),i.push(t,r,a)}else console.warn("THREE.USDZLoader: Face vertex count of %s unsupported.",r)}return i}function c(e,t){const i=e.array,n=e.itemSize,r=new i.constructor(t.length*n);let s=0,a=0;for(let e=0,o=t.length;e<o;e++){s=t[e]*n;for(let e=0;e<n;e++)r[a++]=i[s++]}return new Mr(r,n)}function h(e,t=""){for(const i in e){const n=e[i];if(i.startsWith("def Material"+t))return n;if("object"==typeof n){const e=h(n,t);if(e)return e}}}function d(e,t){t["float inputs:rotation"]&&(e.rotation=parseFloat(t["float inputs:rotation"])),t["float2 inputs:scale"]&&(e.repeat=(new fi).fromArray(JSON.parse("["+t["float2 inputs:scale"].replace(/[()]*/g,"")+"]"))),t["float2 inputs:translation"]&&(e.offset=(new fi).fromArray(JSON.parse("["+t["float2 inputs:translation"].replace(/[()]*/g,"")+"]")))}function u(e,t){for(const i in e){const n=e[i];if(i.startsWith(`def Shader "${t}"`))return n;if("object"==typeof n){const e=u(n,t);if(e)return e}}}function p(e){if("asset inputs:file"in e){const t=e["asset inputs:file"].replace(/@*/g,"").trim(),i=(new uu).load(r[t]),n={'"clamp"':fe,'"mirror"':Ae,'"repeat"':ge};return"token inputs:wrapS"in e&&(i.wrapS=n[e["token inputs:wrapS"]]),"token inputs:wrapT"in e&&(i.wrapT=n[e["token inputs:wrapT"]]),i}return null}function m(e){const t=function(e){if(!e)return;const t=new Fr;let i=null,n=null,r=null,s=-1;if("int[] faceVertexIndices"in e&&(i=JSON.parse(e["int[] faceVertexIndices"])),"int[] faceVertexCounts"in e&&(n=JSON.parse(e["int[] faceVertexCounts"]),i=l(i,n)),"point3f[] points"in e){const n=JSON.parse(e["point3f[] points"].replace(/[()]*/g,""));s=n.length;let r=new Mr(new Float32Array(n),3);null!==i&&(r=c(r,i)),t.setAttribute("position",r)}if("float2[] primvars:st"in e&&(e["texCoord2f[] primvars:st"]=e["float2[] primvars:st"]),"texCoord2f[] primvars:st"in e){r=JSON.parse(e["texCoord2f[] primvars:st"].replace(/[()]*/g,""));let n=new Mr(new Float32Array(r),2);null!==i&&(n=c(n,i)),t.setAttribute("uv",n)}if("int[] primvars:st:indices"in e&&null!==r){const i=new Mr(new Float32Array(r),2);let s=JSON.parse(e["int[] primvars:st:indices"]);s=l(s,n),t.setAttribute("uv",c(i,s))}if("normal3f[] normals"in e){const r=JSON.parse(e["normal3f[] normals"].replace(/[()]*/g,""));let a=new Mr(new Float32Array(r),3);if(r.length===s)null!==i&&(a=c(a,i));else{let e=Array.from(Array(r.length/3).keys());e=l(e,n),a=c(a,e)}t.setAttribute("normal",a)}else t.computeVertexNormals();return t}(function(e){if(e){if("prepend references"in e){const t=e["prepend references"].split("@"),i=t[1].replace(/^.\//,""),n=t[2].replace(/^<\//,"").replace(/>$/,"");return o(r[i],n)}return o(e)}}(e)),i=function(e){const t=new Id;if(void 0!==e){const i=e["token outputs:surface.connect"],n=e[`def Shader "${/(\w+).output/.exec(i)[1]}"`];if(void 0!==n){if("color3f inputs:diffuseColor.connect"in n){const i=n["color3f inputs:diffuseColor.connect"],r=u(a,/(\w+).output/.exec(i)[1]);t.map=p(r),t.map.colorSpace=Ot,'def Shader "Transform2d_diffuse"'in e&&d(t.map,e['def Shader "Transform2d_diffuse"'])}else if("color3f inputs:diffuseColor"in n){const e=n["color3f inputs:diffuseColor"].replace(/[()]*/g,"");t.color.fromArray(JSON.parse("["+e+"]"))}if("color3f inputs:emissiveColor.connect"in n){const i=n["color3f inputs:emissiveColor.connect"],r=u(a,/(\w+).output/.exec(i)[1]);t.emissiveMap=p(r),t.emissiveMap.colorSpace=Ot,t.emissive.set(16777215),'def Shader "Transform2d_emissive"'in e&&d(t.emissiveMap,e['def Shader "Transform2d_emissive"'])}else if("color3f inputs:emissiveColor"in n){const e=n["color3f inputs:emissiveColor"].replace(/[()]*/g,"");t.emissive.fromArray(JSON.parse("["+e+"]"))}if("normal3f inputs:normal.connect"in n){const i=n["normal3f inputs:normal.connect"],r=u(a,/(\w+).output/.exec(i)[1]);t.normalMap=p(r),t.normalMap.colorSpace=Lt,'def Shader "Transform2d_normal"'in e&&d(t.normalMap,e['def Shader "Transform2d_normal"'])}if("float inputs:roughness.connect"in n){const i=n["float inputs:roughness.connect"],r=u(a,/(\w+).output/.exec(i)[1]);t.roughness=1,t.roughnessMap=p(r),t.roughnessMap.colorSpace=Lt,'def Shader "Transform2d_roughness"'in e&&d(t.roughnessMap,e['def Shader "Transform2d_roughness"'])}else"float inputs:roughness"in n&&(t.roughness=parseFloat(n["float inputs:roughness"]));if("float inputs:metallic.connect"in n){const i=n["float inputs:metallic.connect"],r=u(a,/(\w+).output/.exec(i)[1]);t.metalness=1,t.metalnessMap=p(r),t.metalnessMap.colorSpace=Lt,'def Shader "Transform2d_metallic"'in e&&d(t.metalnessMap,e['def Shader "Transform2d_metallic"'])}else"float inputs:metallic"in n&&(t.metalness=parseFloat(n["float inputs:metallic"]));if("float inputs:clearcoat.connect"in n){const i=n["float inputs:clearcoat.connect"],r=u(a,/(\w+).output/.exec(i)[1]);t.clearcoat=1,t.clearcoatMap=p(r),t.clearcoatMap.colorSpace=Lt,'def Shader "Transform2d_clearcoat"'in e&&d(t.clearcoatMap,e['def Shader "Transform2d_clearcoat"'])}else"float inputs:clearcoat"in n&&(t.clearcoat=parseFloat(n["float inputs:clearcoat"]));if("float inputs:clearcoatRoughness.connect"in n){const i=n["float inputs:clearcoatRoughness.connect"],r=u(a,/(\w+).output/.exec(i)[1]);t.clearcoatRoughness=1,t.clearcoatRoughnessMap=p(r),t.clearcoatRoughnessMap.colorSpace=Lt,'def Shader "Transform2d_clearcoatRoughness"'in e&&d(t.clearcoatRoughnessMap,e['def Shader "Transform2d_clearcoatRoughness"'])}else"float inputs:clearcoatRoughness"in n&&(t.clearcoatRoughness=parseFloat(n["float inputs:clearcoatRoughness"]));if("float inputs:ior"in n&&(t.ior=parseFloat(n["float inputs:ior"])),"float inputs:occlusion.connect"in n){const i=n["float inputs:occlusion.connect"],r=u(a,/(\w+).output/.exec(i)[1]);t.aoMap=p(r),t.aoMap.colorSpace=Lt,'def Shader "Transform2d_occlusion"'in e&&d(t.aoMap,e['def Shader "Transform2d_occlusion"'])}}}return t}(function(e){if(e){if("rel material:binding"in e){const t=e["rel material:binding"].replace(/^<\//,"").replace(/>$/,"").split("/");return h(a,` "${t[1]}"`)}return h(e)}}(e)),n=t?new ts(t,i):new Zn;if("matrix4d xformOp:transform"in e){const t=JSON.parse("["+e["matrix4d xformOp:transform"].replace(/[()]*/g,"")+"]");n.matrix.fromArray(t),n.matrix.decompose(n.position,n.quaternion,n.scale)}return n}const g=new ll;return function e(t,i){for(const n in t)if(n.startsWith("def Scope"))e(t[n],i);else if(n.startsWith("def Xform")){const r=m(t[n]);/def Xform "(\w+)"/.test(n)&&(r.name=/def Xform "(\w+)"/.exec(n)[1]),i.add(r),e(t[n],r)}}(a,g),g}}const iL=new mr;class nL extends su{constructor(e){super(e),this.propertyNameMapping={},this.customPropertyMapping={}}load(e,t,i,n){const r=this,s=new lu(this.manager);s.setPath(this.path),s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(i){try{t(r.parse(i))}catch(t){n?n(t):console.error(t),r.manager.itemError(e)}},i,n)}setPropertyNameMapping(e){this.propertyNameMapping=e}setCustomPropertyNameMapping(e){this.customPropertyMapping=e}parse(e){function t(e,t=0){let i="";const n=/^ply([\s\S]*)end_header(\r\n|\r|\n)/.exec(e);null!==n&&(i=n[1]);const r={comments:[],elements:[],headerLength:t,objInfo:""},s=i.split(/\r\n|\r|\n/);let a;function o(e,t){const i={type:e[0]};return"list"===i.type?(i.name=e[3],i.countType=e[1],i.itemType=e[2]):i.name=e[1],i.name in t&&(i.name=t[i.name]),i}for(let e=0;e<s.length;e++){let t=s[e];if(t=t.trim(),""===t)continue;const i=t.split(/\s+/),n=i.shift();switch(t=i.join(" "),n){case"format":r.format=i[0],r.version=i[1];break;case"comment":r.comments.push(t);break;case"element":void 0!==a&&r.elements.push(a),a={},a.name=i[0],a.count=parseInt(i[1]),a.properties=[];break;case"property":a.properties.push(o(i,u.propertyNameMapping));break;case"obj_info":r.objInfo=t;break;default:console.log("unhandled",n,i)}}return void 0!==a&&r.elements.push(a),r}function i(e,t){switch(t){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(e);case"float":case"double":case"float32":case"float64":return parseFloat(e)}}function n(e,t){const n={};for(let r=0;r<e.length;r++){if(t.empty())return null;if("list"===e[r].type){const s=[],a=i(t.next(),e[r].countType);for(let n=0;n<a;n++){if(t.empty())return null;s.push(i(t.next(),e[r].itemType))}n[e[r].name]=s}else n[e[r].name]=i(t.next(),e[r].type)}return n}function r(){const e={indices:[],vertices:[],normals:[],uvs:[],faceVertexUvs:[],colors:[],faceVertexColors:[]};for(const t of Object.keys(u.customPropertyMapping))e[t]=[];return e}function s(e){const t=e.map(e=>e.name);function i(e){for(let i=0,n=e.length;i<n;i++){const n=e[i];if(t.includes(n))return n}return null}return{attrX:i(["x","px","posx"])||"x",attrY:i(["y","py","posy"])||"y",attrZ:i(["z","pz","posz"])||"z",attrNX:i(["nx","normalx"]),attrNY:i(["ny","normaly"]),attrNZ:i(["nz","normalz"]),attrS:i(["s","u","texture_u","tx"]),attrT:i(["t","v","texture_v","ty"]),attrR:i(["red","diffuse_red","r","diffuse_r"]),attrG:i(["green","diffuse_green","g","diffuse_g"]),attrB:i(["blue","diffuse_blue","b","diffuse_b"])}}function a(e,t){const i=r();let a,c;a=null!==(c=/end_header\s+(\S[\s\S]*\S|\S)\s*$/.exec(e))?c[1].split(/\s+/):[];const h=new rL(a);e:for(let e=0;e<t.elements.length;e++){const r=t.elements[e],a=s(r.properties);for(let e=0;e<r.count;e++){const e=n(r.properties,h);if(!e)break e;l(i,r.name,e,a)}}return o(i)}function o(e){let t=new Fr;e.indices.length>0&&t.setIndex(e.indices),t.setAttribute("position",new Ir(e.vertices,3)),e.normals.length>0&&t.setAttribute("normal",new Ir(e.normals,3)),e.uvs.length>0&&t.setAttribute("uv",new Ir(e.uvs,2)),e.colors.length>0&&t.setAttribute("color",new Ir(e.colors,3)),(e.faceVertexUvs.length>0||e.faceVertexColors.length>0)&&(t=t.toNonIndexed(),e.faceVertexUvs.length>0&&t.setAttribute("uv",new Ir(e.faceVertexUvs,2)),e.faceVertexColors.length>0&&t.setAttribute("color",new Ir(e.faceVertexColors,3)));for(const i of Object.keys(u.customPropertyMapping))e[i].length>0&&t.setAttribute(i,new Ir(e[i],u.customPropertyMapping[i].length));return t.computeBoundingSphere(),t}function l(e,t,i,n){if("vertex"===t){e.vertices.push(i[n.attrX],i[n.attrY],i[n.attrZ]),null!==n.attrNX&&null!==n.attrNY&&null!==n.attrNZ&&e.normals.push(i[n.attrNX],i[n.attrNY],i[n.attrNZ]),null!==n.attrS&&null!==n.attrT&&e.uvs.push(i[n.attrS],i[n.attrT]),null!==n.attrR&&null!==n.attrG&&null!==n.attrB&&(iL.setRGB(i[n.attrR]/255,i[n.attrG]/255,i[n.attrB]/255).convertSRGBToLinear(),e.colors.push(iL.r,iL.g,iL.b));for(const t of Object.keys(u.customPropertyMapping))for(const n of u.customPropertyMapping[t])e[t].push(i[n])}else if("face"===t){const t=i.vertex_indices||i.vertex_index,r=i.texcoord;3===t.length?(e.indices.push(t[0],t[1],t[2]),r&&6===r.length&&(e.faceVertexUvs.push(r[0],r[1]),e.faceVertexUvs.push(r[2],r[3]),e.faceVertexUvs.push(r[4],r[5]))):4===t.length&&(e.indices.push(t[0],t[1],t[3]),e.indices.push(t[1],t[2],t[3])),null!==n.attrR&&null!==n.attrG&&null!==n.attrB&&(iL.setRGB(i[n.attrR]/255,i[n.attrG]/255,i[n.attrB]/255).convertSRGBToLinear(),e.faceVertexColors.push(iL.r,iL.g,iL.b),e.faceVertexColors.push(iL.r,iL.g,iL.b),e.faceVertexColors.push(iL.r,iL.g,iL.b))}}function c(e,t){const i={};let n=0;for(let r=0;r<t.length;r++){const s=t[r],a=s.valueReader;if("list"===s.type){const t=[],r=s.countReader.read(e+n);n+=s.countReader.size;for(let i=0;i<r;i++)t.push(a.read(e+n)),n+=a.size;i[s.name]=t}else i[s.name]=a.read(e+n),n+=a.size}return[i,n]}function h(e,t,i){function n(e,t,i){switch(t){case"int8":case"char":return{read:t=>e.getInt8(t),size:1};case"uint8":case"uchar":return{read:t=>e.getUint8(t),size:1};case"int16":case"short":return{read:t=>e.getInt16(t,i),size:2};case"uint16":case"ushort":return{read:t=>e.getUint16(t,i),size:2};case"int32":case"int":return{read:t=>e.getInt32(t,i),size:4};case"uint32":case"uint":return{read:t=>e.getUint32(t,i),size:4};case"float32":case"float":return{read:t=>e.getFloat32(t,i),size:4};case"float64":case"double":return{read:t=>e.getFloat64(t,i),size:8}}}for(let r=0,s=e.length;r<s;r++){const s=e[r];"list"===s.type?(s.countReader=n(t,s.countType,i),s.valueReader=n(t,s.itemType,i)):s.valueReader=n(t,s.type,i)}}let d;const u=this;if(e instanceof ArrayBuffer){const i=new Uint8Array(e),{headerText:n,headerLength:u}=function(e){let t=0,i=!0,n="";const r=[],s=(new TextDecoder).decode(e.subarray(0,5)),a=/^ply\r\n/.test(s);do{const s=String.fromCharCode(e[t++]);"\n"!==s&&"\r"!==s?n+=s:("end_header"===n&&(i=!1),""!==n&&(r.push(n),n=""))}while(i&&t<e.length);return!0===a&&t++,{headerText:r.join("\r")+"\r",headerLength:t}}(i),p=t(n,u);if("ascii"===p.format){d=a((new TextDecoder).decode(i),p)}else d=function(e,t){const i=r(),n="binary_little_endian"===t.format,a=new DataView(e,t.headerLength);let d,u=0;for(let e=0;e<t.elements.length;e++){const r=t.elements[e],o=r.properties,p=s(o);h(o,a,n);for(let e=0;e<r.count;e++){d=c(u,o),u+=d[1];const e=d[0];l(i,r.name,e,p)}}return o(i)}(e,p)}else d=a(e,t(e));return d}}class rL{constructor(e){this.arr=e,this.i=0}empty(){return this.i>=this.arr.length}next(){return this.arr[this.i++]}}class sL extends su{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new lu(this.manager);s.setPath(this.path),s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(i){try{t(r.parse(i))}catch(t){n?n(t):console.error(t),r.manager.itemError(e)}},i,n)}parse(e){function t(e,t,i){for(let n=0,r=e.length;n<r;n++)if(e[n]!==t.getUint8(i+n))return!1;return!0}const i=function(e){if("string"==typeof e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=255&e.charCodeAt(i);return t.buffer||t}return e}(e);return function(e){const i=new DataView(e);if(84+50*i.getUint32(80,!0)===i.byteLength)return!0;const n=[115,111,108,105,100];for(let e=0;e<5;e++)if(t(n,i,e))return!1;return!0}(i)?function(e){const t=new DataView(e),i=t.getUint32(80,!0);let n,r,s,a,o,l,c,h,d=!1;for(let e=0;e<70;e++)1129270351==t.getUint32(e,!1)&&82==t.getUint8(e+4)&&61==t.getUint8(e+5)&&(d=!0,a=new Float32Array(3*i*3),o=t.getUint8(e+6)/255,l=t.getUint8(e+7)/255,c=t.getUint8(e+8)/255,h=t.getUint8(e+9)/255);const u=new Fr,p=new Float32Array(3*i*3),m=new Float32Array(3*i*3),g=new mr;for(let e=0;e<i;e++){const i=84+50*e,h=t.getFloat32(i,!0),u=t.getFloat32(i+4,!0),f=t.getFloat32(i+8,!0);if(d){const e=t.getUint16(i+48,!0);32768&e?(n=o,r=l,s=c):(n=(31&e)/31,r=(e>>5&31)/31,s=(e>>10&31)/31)}for(let o=1;o<=3;o++){const l=i+12*o,c=3*e*3+3*(o-1);p[c]=t.getFloat32(l,!0),p[c+1]=t.getFloat32(l+4,!0),p[c+2]=t.getFloat32(l+8,!0),m[c]=h,m[c+1]=u,m[c+2]=f,d&&(g.set(n,r,s).convertSRGBToLinear(),a[c]=g.r,a[c+1]=g.g,a[c+2]=g.b)}}return u.setAttribute("position",new Mr(p,3)),u.setAttribute("normal",new Mr(m,3)),d&&(u.setAttribute("color",new Mr(a,3)),u.hasColors=!0,u.alpha=h),u}(i):function(e){const t=new Fr,i=/solid([\s\S]*?)endsolid/g,n=/facet([\s\S]*?)endfacet/g,r=/solid\s(.+)/;let s=0;const a=/[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source,o=new RegExp("vertex"+a+a+a,"g"),l=new RegExp("normal"+a+a+a,"g"),c=[],h=[],d=[],u=new Xi;let p,m=0,g=0,f=0;for(;null!==(p=i.exec(e));){g=f;const e=p[0],i=null!==(p=r.exec(e))?p[1]:"";for(d.push(i);null!==(p=n.exec(e));){let e=0,t=0;const i=p[0];for(;null!==(p=l.exec(i));)u.x=parseFloat(p[1]),u.y=parseFloat(p[2]),u.z=parseFloat(p[3]),t++;for(;null!==(p=o.exec(i));)c.push(parseFloat(p[1]),parseFloat(p[2]),parseFloat(p[3])),h.push(u.x,u.y,u.z),e++,f++;1!==t&&console.error("THREE.STLLoader: Something isn't right with the normal of face number "+s),3!==e&&console.error("THREE.STLLoader: Something isn't right with the vertices of face number "+s),s++}const a=g,A=f-g;t.userData.groupNames=d,t.addGroup(a,A,m),m++}return t.setAttribute("position",new Ir(c,3)),t.setAttribute("normal",new Ir(h,3)),t}("string"!=typeof(n=e)?(new TextDecoder).decode(n):n);var n}}const aL=new cr,oL=new Xi,lL=new fi,cL=new fi,hL=new fi;const dL=new Xi,uL=new Dp,pL=new bs,mL=new Xi,gL=new cr;class fL{constructor(){this.normal=new Xi,this.midpoint=new Xi,this.area=0,this.constant=0,this.outside=null,this.mark=0,this.edge=null}static create(e,t,i){const n=new fL,r=new AL(e,n),s=new AL(t,n),a=new AL(i,n);return r.next=a.prev=s,s.next=r.prev=a,a.next=s.prev=r,n.edge=r,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 gL.set(e.point,t.point,i.point),gL.getNormal(this.normal),gL.getMidpoint(this.midpoint),this.area=gL.getArea(),this.constant=this.normal.dot(this.midpoint),this}distanceToPoint(e){return this.normal.dot(e)-this.constant}}class AL{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 null!==t?t.point.distanceTo(e.point):-1}lengthSquared(){const e=this.head(),t=this.tail();return null!==t?t.point.distanceToSquared(e.point):-1}setTwin(e){return this.twin=e,e.twin=this,this}}class yL{constructor(e){this.point=e,this.prev=null,this.next=null,this.face=null}}class vL{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,null===t.prev?this.head=t:t.prev.next=t,e.prev=t,this}insertAfter(e,t){return t.prev=e,t.next=e.next,null===t.next?this.tail=t:t.next.prev=t,e.next=t,this}append(e){return null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e,this}appendChain(e){for(null===this.head?this.head=e:this.tail.next=e,e.prev=this.tail;null!==e.next;)e=e.next;return this.tail=e,this}remove(e){return null===e.prev?this.head=e.next:e.prev.next=e.next,null===e.next?this.tail=e.prev:e.next.prev=e.prev,this}removeSubList(e,t){return null===e.prev?this.head=t.next:e.prev.next=t.next,null===t.next?this.tail=e.prev:t.next.prev=e.prev,this}isEmpty(){return null===this.head}}class _L{constructor(){this.toJSON=null}onAdded(e){e.assetManager.importer.addImporter(this._importer)}onRemove(e){e.assetManager.importer.removeImporter(this._importer)}dispose(){}}var bL=Object.defineProperty,xL=Object.getOwnPropertyDescriptor,wL=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?xL(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&bL(t,i,s),s};e.BaseGroundPlugin=class extends sw{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=dw.upgradeGeometry.call(new Es(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){"widget"===e?.object?.assetType||e?.object?.userData?.isWidgetRoot||!1!==e?.geometryChanged&&!1!==e?.updateGround&&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(void 0===e.maxPolarAngle)return void console.warn("refreshCameraLimits only available with orbit controls.");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 t=!1;if(this.visible!==this._mesh.visible&&(this._mesh.visible=this.visible,t=!0),this.isDisabled())return t&&this._viewer?.scene.setDirty(),!1;if(this.autoAdjustTransform){this._mesh.userData.bboxVisible=!1;const e=this.useModelBounds?this._viewer.scene.getModelBounds(!0,!0,!0):this._viewer.scene.getBounds(!0,!0,!0);this._mesh.userData.bboxVisible=!0;const i=e.getCenter(new Xi).sub(new Xi(0,e.getSize(new Xi).y/2+this.yOffset,0));t=t||i.clone().sub(this._mesh.position).length()>1e-4,t&&this._mesh.position.copy(i)}return t=t||Math.abs(this._mesh.scale.x-this.size)>1e-4,t&&(this._mesh.scale.setScalar(this.size),this._mesh.setRotationFromEuler(new On(-Math.PI/2,0,this._mesh.rotation.z)),this._mesh.matrixWorldNeedsUpdate=!0,this._mesh.setDirty({refreshScene:!1,source:e.BaseGroundPlugin.PluginType})),this._mesh.visible=this.size>=1e-4,this._transformNeedRefresh=!1,!0}_createMesh(e){return e?e.geometry=this._geometry:e=new DC(this._geometry,this._createMaterial()),e}setGeometry(e){e?this._geometry&&this._geometry.dispose():e=this._geometry,e&&(this._geometry=e,dw.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 yC({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()),void 0===this._material.userData.__renderToDepth&&(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={}),void 0===this._material.userData.gBufferData.__tonemapEnabled&&(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}},e.BaseGroundPlugin.PluginType="BaseGroundPlugin",e.BaseGroundPlugin.OldPluginType="Ground",wL([Hg("Visible"),Qm(e.BaseGroundPlugin.prototype.refreshTransform),qm()],e.BaseGroundPlugin.prototype,"visible",2),wL([Gg("Size"),Vm(e.BaseGroundPlugin.prototype._onSceneUpdate),qm()],e.BaseGroundPlugin.prototype,"size",2),wL([Gg("Height (yOffset)"),Vm(e.BaseGroundPlugin.prototype._onSceneUpdate),qm()],e.BaseGroundPlugin.prototype,"yOffset",2),wL([Hg("Render to Depth"),Qm(e.BaseGroundPlugin.prototype._refresh2),qm()],e.BaseGroundPlugin.prototype,"renderToDepth",2),wL([Hg("Tonemap Ground"),Qm(e.BaseGroundPlugin.prototype._refresh2),qm()],e.BaseGroundPlugin.prototype,"tonemapGround",2),wL([Hg("Limit Camera Above Ground"),Qm(e.BaseGroundPlugin.prototype._refreshCameraLimits),qm()],e.BaseGroundPlugin.prototype,"limitCameraAboveGround",2),wL([Hg("Auto Adjust Transform"),Qm(e.BaseGroundPlugin.prototype.refreshTransform),qm()],e.BaseGroundPlugin.prototype,"autoAdjustTransform",2),wL([qm("material"),Lg(),zy({obj:"mesh",key:"material",allowUndefined:!0})],e.BaseGroundPlugin.prototype,"_material",2),e.BaseGroundPlugin=wL([qg("Ground Plane")],e.BaseGroundPlugin);class CL extends sw{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 SL=Object.defineProperty;const ML=class extends sw{constructor(e,t){super(),this.container=t,this.enabled=!0,this._mainDiv=sm({id:"assetManager"+e,addToBody:!1,innerHTML:""}),this._contentDiv=sm({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)}};((e,t,i)=>{for(var n,r=void 0,s=e.length-1;s>=0;s--)(n=e[s])&&(r=n(t,i,r)||r);r&&SL(t,i,r)})([Hg("Enabled"),Qm(ML.prototype._onEnabledChange),qm()],ML.prototype,"enabled");let EL=ML;class TL extends TS{constructor(e,t=120){super({vertexShader:CS.vertexShader,fragmentShader:ym`
                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 Gi(1,1,1,1)},weight2:{value:new Gi(1,1,1,1)}},defines:{MAX_INTENSITY:t}},"tDiffuse","tDiffuse2"),this.clear=!1,this.needsSwap=!0}}var IL=Object.defineProperty,PL=Object.getOwnPropertyDescriptor,DL=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?PL(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&IL(t,i,s),s};e.SSAAPlugin=class extends sw{constructor(t=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=[e.ProgressivePlugin],this._objectAdd=e=>{const t=e.object;t&&t.shadow&&t.shadow.camera&&t.shadow.mapSize&&this.trackedJitterCameras.set(t.shadow.camera,t.shadow.mapSize)},this._objectRemove=e=>{const t=e.object;if(t&&t.shadow&&t.shadow.camera){const e=t.shadow.camera;this._clearJitter(e),this.trackedJitterCameras.delete(e)}},this._preRender=()=>{const e=this._viewer;if(!e||!this.enabled||e.renderManager.frameCount<=1)return;this.rendersPerFrame=e.rendersPerFrame;const t=e.scene.renderCamera;this.jitterRenderCamera&&this._jitter(t,{width:e.renderManager.renderSize.x*e.renderManager.renderScale,height:e.renderManager.renderSize.y*e.renderManager.renderScale},e.renderManager.frameCount,!0),this.jitterLightCameras&&Array.from(this.trackedJitterCameras.entries()).forEach(t=>this._jitter(...t,e.renderManager.frameCount)),this._hasSetOffsetRC=this.jitterRenderCamera,this._hasSetOffsetLC=this.jitterLightCameras,e.renderManager.resetShadows()},this._postRender=()=>{const e=this._viewer;e&&(this._hasSetOffsetRC&&(this._clearJitter(e.scene.renderCamera),this._hasSetOffsetRC=!1),this._hasSetOffsetLC&&(Array.from(this.trackedJitterCameras.keys()).forEach(e=>this._clearJitter(e)),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=t}onAdded(e){super.onAdded(e),e.addEventListener("preRender",this._preRender),e.addEventListener("postRender",this._postRender),e.object3dManager.getObjects().forEach(e=>this._objectAdd({object:e})),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(e=>this._objectRemove({object:e})),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)return void this._viewer?.console.warn("SSAAPlugin: Camera already jittered");const r={...this.jitterOffsets[i%this.jitterOffsets.length]},s=e.aspect,a=e.autoAspect||!n?t.height:t.width/s;e.setViewOffset(t.width,a,r.x,r.y,t.width,a),e.userData.__jittered=!0}_clearJitter(e){e.userData.__jittered&&(e.clearViewOffset(),delete e.userData.__jittered)}},e.SSAAPlugin.PluginType="SSAAPlugin",DL([qm(),Hg("Enabled"),Qm(e.SSAAPlugin.prototype.setDirty)],e.SSAAPlugin.prototype,"enabled",2),DL([qm(),Fg("Renders/Frame",[1,32],1),Qm(e.SSAAPlugin.prototype.setDirty)],e.SSAAPlugin.prototype,"rendersPerFrame",2),DL([qm(),Hg("Render Camera"),Qm(e.SSAAPlugin.prototype.setDirty)],e.SSAAPlugin.prototype,"jitterRenderCamera",2),DL([qm(),Hg("Light Cameras"),Qm(e.SSAAPlugin.prototype.setDirty)],e.SSAAPlugin.prototype,"jitterLightCameras",2),e.SSAAPlugin=DL([qg("SSAA Plugin")],e.SSAAPlugin);var RL=Object.defineProperty,BL=Object.getOwnPropertyDescriptor,LL=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?BL(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&RL(t,i,s),s};e.ProgressivePlugin=class extends eB{constructor(e=32,t=Ce,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){const t=this._targets.get(e.uuid);t&&(this._viewer.renderManager.disposeTarget(t),this._targets.delete(e.uuid))}else this._targets.forEach(e=>this._viewer.renderManager.disposeTarget(e)),this._targets.clear()}_createPass(){const e=new OL(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(t,i){if(void 0!==t.jitter){const i=this._viewer?.getPlugin(e.SSAAPlugin);i?(t={...t},i.enabled=t.jitter,delete t.jitter):console.warn("Loading old webgi v0 file, add SSAAPlugin to get anti-aliasing")}return super.fromJSON(t,i)}},e.ProgressivePlugin.PluginType="ProgressivePlugin",e.ProgressivePlugin.OldPluginType="Progressive",LL([qm(),zg("Frame count")],e.ProgressivePlugin.prototype,"maxFrameCount",2),LL([Vg("Last Texture",{readOnly:!0})],e.ProgressivePlugin.prototype,"mainTexture",1),e.ProgressivePlugin=LL([qg("Progressive Plugin")],e.ProgressivePlugin);class OL extends TL{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,r){if(!this.enabled)return;const s=Im(this.target);s?(this.needsSwap=!1,e.renderManager.frameCount<1?i?.texture&&e.renderManager.blit(s,{source:i.texture,respectColorSpace:!1}):(super.render(e,t,i,n,r),this.copyToWriteBuffer&&(e.renderManager.blit(s,{source:t.texture,respectColorSpace:!1}),this.needsSwap=!0))):console.warn("ProgressiveBlendPass: target not defined")}beforeRender(e,t,i){if(!this.enabled)return;if(!this.target)return void console.error("ProgressiveBlendPass: render target undefined");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=Im(this.target)?.texture,this.material.uniformsNeedUpdate=!0}}var UL=Object.defineProperty,FL=Object.getOwnPropertyDescriptor,kL=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?FL(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&UL(t,i,s),s};e.DepthBufferPlugin=class extends eB{constructor(e=Ce,t=!1,i=!0,n=Dt){super(),this.passId="depth",this.material=new NL({depthPacking:Dt,blending:w,transparent:!0}),this.unpackExtension={shaderExtender:e=>{const t=["depth_buffer_unpack","gbuffer_unpack","packing"].find(t=>e.fragmentShader.includes(`#include <${t}>`));e.fragmentShader=R_(e.fragmentShader,`#include <${t}>`,"\n#if defined(HAS_DEPTH_BUFFER)\n#if DEPTH_PACKING == 3200\n#define unpackDepth(rgba_depth) (1.0 - rgba_depth.r)\n#elif DEPTH_PACKING == 3201\n#define unpackDepth(rgba_depth) unpackRGBAToDepth(rgba_depth)\n#elif DEPTH_PACKING == 3202\n#define unpackDepth(rgba_depth) unpackRGBToDepth(rgba_depth.rgb)\n#elif DEPTH_PACKING == 3203\n#define unpackDepth(rgba_depth) unpackRGToDepth(rgba_depth.rg)\n#endif\nuniform sampler2D tDepthBuffer;\n#define getDepth(uv) unpackDepth(texture2D(tDepthBuffer, uv))\n#endif\n\n",{append:"packing"===t})},extraUniforms:{tDepthBuffer:()=>({value:this.target?.texture})},extraDefines:{DEPTH_PACKING:Dt,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===Pt?new mr(0,0,0):new mr(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(t=!0){if(!this._viewer)return;t&&this._disposeTarget();const i=this._viewer.renderManager;this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!0,samples:this._viewer.renderManager.zPrepass&&this.isPrimaryGBuffer&&i.msaa?"number"!=typeof i.msaa?e.ViewerRenderManager.DEFAULT_MSAA_SAMPLES:i.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 t=new e.GBufferRenderPass(this.passId,()=>this.target,this.material,this._getClearColor(),1),i=t.preprocessMaterial;return t.preprocessMaterial=e=>i(e,e.userData.renderToDepth),t.before=["render"],t.after=[],t.required=["render"],t}onRemove(e){return this._disposeTarget(),super.onRemove(e)}},e.DepthBufferPlugin.PluginType="DepthBufferPlugin",kL([Vg("Depth Buffer",{readOnly:!0})],e.DepthBufferPlugin.prototype,"texture",2),kL([Qm(e.DepthBufferPlugin.prototype._depthPackingChanged),Ng("Depth Packing",lv.DepthPackingStrategies.uiConfig)],e.DepthBufferPlugin.prototype,"depthPacking",2),e.DepthBufferPlugin=kL([qg("Depth Buffer Plugin")],e.DepthBufferPlugin);class NL extends el{constructor(e){super(e),this.reset()}onBeforeRender(e,t,i,n,r,s){super.onBeforeRender(e,t,i,n,r,s);let a=r.material;Array.isArray(a)&&(a=a[0]),a&&(void 0!==a.map&&(this.map=a.map),void 0!==a.side&&(this.side=a.side??_),void 0!==a.alphaMap&&(this.alphaMap=a.alphaMap),void 0!==a.alphaTest&&(this.alphaTest=a.alphaTest<1e-4?1e-4:a.alphaTest),void 0!==a.alphaHash&&(this.alphaHash=a.alphaHash),void 0!==a.displacementMap&&(this.displacementMap=a.displacementMap),void 0!==a.displacementScale&&(this.displacementScale=a.displacementScale),void 0!==a.displacementBias&&(this.displacementBias=a.displacementBias),void 0!==a.wireframe&&(this.wireframe=a.wireframe),void 0!==a.wireframeLinewidth&&(this.wireframeLinewidth=a.wireframeLinewidth),this.needsUpdate=!0,e.resetCurrentMaterial&&e.resetCurrentMaterial())}onAfterRender(e,t,i,n,r,s){super.onAfterRender(e,t,i,n,r,s),this.reset()}reset(){this.map=null,this.side=x,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 jL=Object.defineProperty,zL=Object.getOwnPropertyDescriptor,GL=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?zL(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&jL(t,i,s),s};e.NormalBufferPlugin=class extends eB{constructor(e=De,t=!0){super(),this.passId="normal",this.material=new QL({blending:w}),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:ye,minFilter:ye,generateMipmaps:!1,colorSpace:Ut})),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 t=new e.GBufferRenderPass(this.passId,()=>this.target,this.material,new mr(0,0,0),1),i=t.preprocessMaterial;return t.preprocessMaterial=e=>i(e,!!this.renderTransparent||e.userData.renderToDepth),t.preprocessObject=e=>{if(e.customNormalMaterial){const t=e.customNormalMaterial;return t.allowOverride=!1,void(e.forcedOverrideMaterial=t)}return e.material},t.postprocessObject=e=>{e.customNormalMaterial&&delete e.forcedOverrideMaterial},t.before=["render"],t.after=[],t.required=["render"],t}onRemove(e){return this._disposeTarget(),super.onRemove(e)}},e.NormalBufferPlugin.PluginType="NormalBufferPlugin",GL([Vg("Normal Buffer",{readOnly:!0})],e.NormalBufferPlugin.prototype,"texture",2),GL([Hg("Render Transparent"),Vm(e.NormalBufferPlugin.prototype.setDirty),qm()],e.NormalBufferPlugin.prototype,"renderTransparent",2),e.NormalBufferPlugin=GL([qg("Normal Buffer Plugin")],e.NormalBufferPlugin);class QL extends Rd{constructor(e){super(e),this.reset()}onBeforeRender(e,t,i,n,r,s){if(super.onBeforeRender(e,t,i,n,r,s),!r.material)return;const a=r.material;void 0!==a.bumpMap&&(this.bumpMap=a.bumpMap),void 0!==a.bumpScale&&(this.bumpScale=a.bumpScale),void 0!==a.alphaTest&&(this.alphaTest=a.alphaTest<1e-4?1e-4:a.alphaTest),void 0!==a.alphaHash&&(this.alphaHash=a.alphaHash),void 0!==a.normalMap&&(this.normalMap=a.normalMap),void 0!==a.normalMapType&&(this.normalMapType=a.normalMapType),void 0!==a.normalScale&&this.normalScale.copy(a.normalScale),void 0!==a.displacementMap&&(this.displacementMap=a.displacementMap),void 0!==a.displacementScale&&(this.displacementScale=a.displacementScale),void 0!==a.displacementBias&&(this.displacementBias=a.displacementBias),void 0!==a.flatShading&&(this.flatShading=a.flatShading),void 0!==a.side&&(this.side=a.side),void 0!==a.wireframe&&(this.wireframe=a.wireframe),void 0!==a.wireframeLinewidth&&(this.wireframeLinewidth=a.wireframeLinewidth),e.resetCurrentMaterial&&e.resetCurrentMaterial()}onAfterRender(e,t,i,n,r,s){super.onAfterRender(e,t,i,n,r,s),this.reset()}reset(){this.bumpMap=null,this.bumpScale=1,this.alphaTest=0,this.normalMap=null,this.normalMapType=Rt,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.flatShading=!1,this.side=x,this.wireframe=!1,this.wireframeLinewidth=1}}var VL=Object.defineProperty,HL=Object.getOwnPropertyDescriptor,WL=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?HL(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&VL(t,i,s),s};e.FrameFadePlugin=class extends eB{constructor(t=!0){super(),this.passId="frameFade",this.dependencies=[e.ProgressivePlugin],this.isEditor=!1,this.fadeOnActiveCameraChange=!0,this.fadeOnMaterialUpdate=!0,this.fadeOnSceneUpdate=!0,this._pointerEnabled=!0,this.saveFrameTimeThreshold=500,this._fadeCam=async e=>!1!==e.frameFade&&!this.isEditor&&this.fadeOnActiveCameraChange&&this.startTransition(e.fadeDuration||1e3),this._fadeMat=async e=>!1!==e.frameFade&&!this.isEditor&&this.fadeOnMaterialUpdate&&this.startTransition(e.fadeDuration||200),this._fadeScene=async e=>!1!==e.frameFade&&!this.isEditor&&this.fadeOnSceneUpdate&&this.startTransition(e.fadeDuration||500),this._fadeObjectUpdate=async e=>e.frameFade&&!this.isEditor&&this.startTransition(e.fadeDuration||500),this._onPointerMove=e=>{const t=this._viewer?.canvas;if(!t)return void(this._pointerEnabled=!1);if(!e.buttons||e.target!==t)return void(this._pointerEnabled=!0);const i=t.getBoundingClientRect(),n=(e.clientX-i.left)/i.width,r=(e.clientY-i.top)/i.height;this._pointerEnabled=n<0||n>1||r<0||r>1},this.enabled=t,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=(e=>()=>!this._pointerEnabled||e())(this.isDisabled)}async startTransition(e){!this._viewer||!this._pass||this.isDisabled()||(this._target||(this._target=this._viewer.renderManager.getTempTarget({sizeMultiplier:1,minFilter:be,magFilter:be,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 Zp(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 qL(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(e.ProgressivePlugin)?.texture}get target(){return this._target}_beforeRender(){return!(!super._beforeRender()||!this._pass)&&(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)}},e.FrameFadePlugin.PluginType="FrameFadePlugin",WL([qm(),Hg()],e.FrameFadePlugin.prototype,"fadeOnActiveCameraChange",2),WL([qm(),Hg()],e.FrameFadePlugin.prototype,"fadeOnMaterialUpdate",2),WL([qm(),Hg()],e.FrameFadePlugin.prototype,"fadeOnSceneUpdate",2),e.FrameFadePlugin=WL([qg("FrameFade Plugin")],e.FrameFadePlugin);class qL extends TL{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,r){this.needsSwap=!1;const s=this.plugin.target;if(!this.plugin.canFrameFade||!s)return;const a=this.plugin.lastFrame;this.toSaveFrame&&a&&(e.renderManager.blit(s,{source:a,respectColorSpace:!1}),this._lastTime=0,this.toSaveFrame=!1),this.uniforms.tDiffuse2.value=s.texture;const o=this.fadeTimeState/this.fadeTime;this.uniforms.weight2.value.setScalar(o),this.uniforms.weight2.value.w=1,this.uniforms.weight.value.setScalar(1-o),this.uniforms.weight.value.w=1,super.render(e,t,i,n,r),this.needsSwap=!0;const l=$p();this._lastTime<10&&(this._lastTime=l-10);const c=l-this._lastTime;this._lastTime=l,this.fadeTimeState-=c}}var XL=Object.defineProperty,YL=Object.getOwnPropertyDescriptor,KL=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?YL(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&XL(t,i,s),s};e.SSAOPlugin=class extends eB{constructor(t=Ce,i=1,n=!0,r=1){super(),this.passId="ssao",this.dependencies=[e.GBufferPlugin],this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("SSAOPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this._pass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this._pass.material.registerMaterialExtensions([this._gbufferUnpackExtension]):this._viewer.console.warn("SSAOPlugin: GBuffer unpack extension removed"))},this.enabled=n,this.bufferType=t,this.sizeMultiplier=i,this.packing=r}_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:Ut})),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 e.SSAOPluginPass(this.passId,()=>this.target,this.packing)}onAdded(t){super.onAdded(t),t.forPlugin(e.GBufferPlugin,e=>{e.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this))},e=>{e.unregisterGBufferUpdater(this.constructor.PluginType)},this),this._gbufferUnpackExtensionChanged(),t.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged)}onRemove(e){return this._disposeTarget(),super.onRemove(e)}fromJSON(e,t){return e.passes?.ssao&&((e={...e}).pass=e.passes.ssao,delete e.passes,void 0!==e.pass.enabled&&(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=cg(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}},e.SSAOPlugin.PluginType="SSAOPlugin",e.SSAOPlugin.OldPluginType="SSAO",KL([Vg("SSAO Buffer",{readOnly:!0,tags:["debug"]})],e.SSAOPlugin.prototype,"texture",2),KL([Lg(void 0,{unwrapContents:!0})],e.SSAOPlugin.prototype,"_pass",2),e.SSAOPlugin=KL([qg("SSAO Plugin")],e.SSAOPlugin),e.SSAOPluginPass=class extends TS{constructor(t,i,n=1){super({defines:{LINEAR_DEPTH:1,NUM_SAMPLES:11,NUM_SPIRAL_TURNS:3,SSAO_PACKING:n,PERSPECTIVE_CAMERA:1,CHECK_GBUFFER_FLAG:0},uniforms:{screenSize:{value:new fi(0,0)},saoData:{value:new Gi},frameCount:{value:0},cameraNearFar:{value:new fi(.1,1e3)},projection:{value:new Sn},saoBiasEpsilon:{value:new Gi(1,1,1,1)},sceneBoundingRadius:{value:0},ssaoSplitX:{value:.5}},vertexShader:Tg.defaultVertex,fragmentShader:"#include <randomHelpers>\n#include <common>\n#include <packing>\n#define THREE_PACKING_INCLUDED\n#include <cameraHelpers>\nvarying vec2 vUv;uniform sampler2D tLastThis;\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nuniform vec4 saoData;uniform vec4 saoBiasEpsilon;uniform vec2 screenSize;const float INV_NUM_SAMPLES=1.0/float(NUM_SAMPLES);int getSelectionBit(in int number){\n#ifdef WebGL2Context\nreturn(number/8)% 2;\n#else\nreturn int(mod(floor(float(number)/8.),2.));\n#endif\n}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){\n#if defined(HAS_DEPTH_BUFFER) || defined(HAS_NORMAL_DEPTH_BUFFER)\nfloat d=getDepth(uvOffset);\n#else\nfloat d=0.5;\n#endif\n#if LINEAR_DEPTH == 0\nfloat centerViewZ=viewZFromNDCZ(d);return screenToView3(uvOffset,centerViewZ);\n#else\nd=mix(-cameraNearFar.x,-cameraNearFar.y,d);return screenToView3(uvOffset,d);\n#endif\n}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;\n#if CHECK_GBUFFER_FLAG == 1\nif(getSelectionBit(getGBufferFlags(uvOffset.xy).a)<1)return 0.0;\n#endif\nvec3 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);\n#ifdef HAS_NORMAL_DEPTH_BUFFER\ngetDepthNormal(vUv,centerDepth,centerNormal);\n#else\n#ifdef HAS_DEPTH_BUFFER\ncenterDepth=getDepth(vUv);\n#endif\n#endif\n#if LINEAR_DEPTH == 0\nfloat centerViewZ=viewZFromNDCZ(centerDepth);\n#else\nfloat centerViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,centerDepth);\n#endif\nvec3 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);\n#if NUM_SAMPLES > 1\nsum+=getOcclusion(vUv,1,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);\n#endif\n#if NUM_SAMPLES > 2\nsum+=getOcclusion(vUv,2,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);\n#endif\n#if NUM_SAMPLES > 3\nsum+=getOcclusion(vUv,3,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);\n#endif\n#if NUM_SAMPLES > 4\nsum+=getOcclusion(vUv,4,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);\n#endif\n#if NUM_SAMPLES > 5\nsum+=getOcclusion(vUv,5,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);\n#endif\n#if NUM_SAMPLES > 6\nsum+=getOcclusion(vUv,6,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);\n#endif\n#if NUM_SAMPLES > 7\nsum+=getOcclusion(vUv,7,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);\n#endif\n#if NUM_SAMPLES > 8\nsum+=getOcclusion(vUv,8,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);\n#endif\n#if NUM_SAMPLES > 9\nsum+=getOcclusion(vUv,9,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);\n#endif\n#if NUM_SAMPLES > 10\nsum+=getOcclusion(vUv,10,randomAngle,occlusionSphereScreenRadius,centerPosition,centerNormal);\n#endif\nfloat aoValue=sum*saoData.y*INV_NUM_SAMPLES;aoValue=1.-clamp(aoValue,0.,1.);\n#if SSAO_PACKING == 1\ngl_FragColor.gba=packFloatToRGB(centerDepth);gl_FragColor.r=aoValue;\n#elif SSAO_PACKING == 2\ngl_FragColor.rgb=vec3(aoValue);gl_FragColor.a=1.;\n#elif SSAO_PACKING == 3\ngl_FragColor.rgba=packDepthToRGBA(aoValue);\n#elif SSAO_PACKING == 4\ngl_FragColor.rgb=packFloatToRGB(aoValue);gl_FragColor.a=1.;\n#endif\n}"},"tDiffuse"),this.passId=t,this.target=i,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:Im(this.target)?.texture??null}),ssaoSplitX:this.material.uniforms.ssaoSplitX},shaderExtender:(e,t,i)=>{e.defines?.SSAO_ENABLED&&(e.fragmentShader=R_(e.fragmentShader,"#include <aomap_fragment>","\n#ifndef USE_TRANSMISSION\n#if defined(SSAO_ENABLED) && SSAO_ENABLED > 0\nvec3 screenPos_ao=viewToScreen(vViewPosition.xyz);\n#if SSAO_ENABLED == 2\nif(screenPos_ao.x>ssaoSplitX){\n#endif\nfloat ambientOcclusion=tSSAOMapTexelToLinear(texture2D(tSSAOMap,viewToScreen(vViewPosition.xyz).xy)).r;reflectedLight.indirectDiffuse*=ambientOcclusion;\n#if defined( USE_ENVMAP )\nfloat dotNV=saturate(dot(geometryNormal,geometryViewDir));reflectedLight.indirectSpecular*=computeSpecularOcclusion(dotNV,ambientOcclusion,material.roughness);\n#endif\n#else\n#include <aomap_fragment>\n#endif\n#if SSAO_ENABLED == 2\n}\n#endif\n#endif\n"))},onObjectRender:(e,t,i)=>{const n=!this.enabled||!1===i.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.ssaoDisabled?0:this.split>0?2:1;t.defines.SSAO_ENABLED!==n&&(t.defines.SSAO_ENABLED=n,t.needsUpdate=!0)},parsFragmentSnippet:()=>ym`
             uniform sampler2D tSSAOMap;
            #if defined(SSAO_ENABLED) && SSAO_ENABLED == 2
            uniform float ssaoSplitX;
            #endif
             ${Qy("tSSAOMap",Im(this.target)?.texture.colorSpace)}
             #include <simpleCameraHelpers>
        `,computeCacheKey:()=>(this.enabled?"1":"0")+Im(this.target)?.texture?.colorSpace,uuid:e.SSAOPlugin.PluginType,..._w(this._getUiConfig.bind(this),e.SSAOPlugin.PluginType),isCompatible:e=>e.isPhysicalMaterial},this.needsSwap=!1,this.clear=!0}render(e,t,i,n,r){if(this.needsSwap=!1,!this.enabled)return;const s=Im(this.target);s?(this._updateParameters(),super.render(e,s,i,n,r),this.copyToWriteBuffer&&(e.renderManager.blit(t,{source:s.texture,respectColorSpace:!0}),this.needsSwap=!0)):console.warn("SSAOPluginPass: target not defined")}_updateParameters(){const e=this.material.uniforms.saoData.value;e.y=this.intensity,e.z=this.occlusionWorldRadius,e.z*=.25*this._projScale;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),r=i?.webglRenderer.domElement.height||1;this._projScale=r/(2*Math.tan(.5*n*gi.DEG2RAD))}_getUiConfig(e){return{type:"folder",label:"SSAO",children:[{type:"checkbox",label:"Enabled",get value(){return!e.userData.ssaoDisabled},set value(t){t!==!e.userData.ssaoDisabled&&(e.userData.ssaoDisabled=!t,e.setDirty())},onChange:this.setDirty},{type:"checkbox",label:"Cast SSAO",get value(){return!e.userData.ssaoCastDisabled},set value(t){t!==!e.userData.ssaoCastDisabled&&(e.userData.ssaoCastDisabled=!t,e.setDirty())},onChange:this.setDirty}]}}},KL([qm(),Fg("Intensity",[0,4],1e-4),Vm(e.SSAOPluginPass.prototype.setDirty)],e.SSAOPluginPass.prototype,"intensity",2),KL([qm(),Fg("Occlusion World Radius",[.1,8],.01),Vm(e.SSAOPluginPass.prototype.setDirty)],e.SSAOPluginPass.prototype,"occlusionWorldRadius",2),KL([qm(),Vm(e.SSAOPluginPass.prototype.setDirty),Hg()],e.SSAOPluginPass.prototype,"autoRadius",2),KL([qm(),Fg("Bias",[1e-5,.01],1e-5),Vm(e.SSAOPluginPass.prototype.setDirty)],e.SSAOPluginPass.prototype,"bias",2),KL([qm(),Fg("Falloff",[.01,3],.01),Vm(e.SSAOPluginPass.prototype.setDirty)],e.SSAOPluginPass.prototype,"falloff",2),KL([qm(),Fg("Num Samples",[1,11],1,{tags:["performance"]}),Ny("NUM_SAMPLES",void 0,void 0,e.SSAOPluginPass.prototype.setDirty)],e.SSAOPluginPass.prototype,"numSamples",2),KL([jy("CHECK_GBUFFER_FLAG")],e.SSAOPluginPass.prototype,"checkGBufferFlag",2),KL([Fg("Split",[0,1],.01,{tags:["debug"]}),qm(),ky({propKey:"ssaoSplitX",onChange:e.SSAOPluginPass.prototype.setDirty})],e.SSAOPluginPass.prototype,"split",2),e.SSAOPluginPass=KL([qg("SSAO Pass")],e.SSAOPluginPass);var JL=Object.defineProperty,ZL=Object.getOwnPropertyDescriptor,$L=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?ZL(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&JL(t,i,s),s};e.RenderTargetPreviewPlugin=class extends sw{constructor(e=!0){super(),this.enabled=!0,this.toJSON=null,this.mainDiv=sm({id:"RenderTargetPreviewPluginContainer",addToBody:!1}),this.targetBlocks=[],this._postRender=()=>{if(this._viewer)for(const e of this.targetBlocks){if(!e.visible)continue;const t=Im(e.target);if(!t)continue;const i=e.div.getBoundingClientRect();let n=void 0!==e.textureIndex&&t.textures?.[e.textureIndex]?t.textures[e.textureIndex]:t.texture;const r=this._viewer.canvas.getBoundingClientRect();i.x=i.x-r.x,i.y=r.height+r.y-i.y-i.height,Array.isArray(n)&&(n=n[0]);const s=this._viewer.renderManager.webglRenderer.outputColorSpace;e.originalColorSpace||(this._viewer.renderManager.webglRenderer.outputColorSpace=Ot),this._viewer.renderManager.blit(null,{source:n,clear:!e.transparent,respectColorSpace:!e.originalColorSpace,viewport:new Gi(i.x,i.y,i.width,i.height),material:e.material}),this._viewer.renderManager.webglRenderer.outputColorSpace=s}},this.enabled=e}onAdded(e){super.onAdded(e),e.addEventListener("postRender",this._postRender),this.stylesheet=om('#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}',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,r=!0,s,a){if(!e)return this;const o=document.createElement("div"),l={target:e,name:t,transparent:i,div:o,originalColorSpace:n,visible:r,textureIndex:a};s&&(l.material=s?.isMaterial?s:new RS(s).material),o.classList.add("RenderTargetPreviewPluginTarget"),l.visible||o.classList.add("RenderTargetPreviewPluginCollapsed");const c=document.createElement("div");return c.classList.add("RenderTargetPreviewPluginTargetHeader"),c.innerText=t,c.onclick=()=>{l.visible=!l.visible,l.visible?o.classList.remove("RenderTargetPreviewPluginCollapsed"):o.classList.add("RenderTargetPreviewPluginCollapsed"),this._viewer?.setDirty()},c.oncontextmenu=t=>{t.preventDefault(),t.stopPropagation(),df.Create({Download:()=>this.downloadTarget(e,a),Remove:()=>this.removeTarget(e)},t.clientX,t.clientY)},o.appendChild(c),this.mainDiv.appendChild(o),this.targetBlocks.push(l),this.refreshUi(),this}removeTarget(e){const t=this.targetBlocks.findIndex(t=>t.target===e);if(t>=0){const e=this.targetBlocks[t];this.targetBlocks.splice(t,1),e.div.remove()}return this.refreshUi(),this}downloadTarget(e,t){if(!this._viewer)return this;const i=Im(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)return this.mainDiv.parentElement&&this.mainDiv.remove(),this.mainDiv.style.display="none",void(this.mainDiv.style.zIndex="1000");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()}},e.RenderTargetPreviewPlugin.PluginType="RenderTargetPreviewPlugin",$L([Hg("Enabled"),Qm(e.RenderTargetPreviewPlugin.prototype.refreshUi)],e.RenderTargetPreviewPlugin.prototype,"enabled",2),e.RenderTargetPreviewPlugin=$L([qg("Render Target Preview Plugin")],e.RenderTargetPreviewPlugin);var eO=Object.defineProperty,tO=Object.getOwnPropertyDescriptor,iO=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?tO(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&eO(t,i,s),s};e.GeometryUVPreviewPlugin=class extends sw{constructor(e=!0){super(),this.enabled=!0,this.toJSON=null,this.mainDiv=sm({id:"GeometryUVPreviewPluginContainer",addToBody:!1}),this.targetBlocks=[],this._postRender=()=>{if(this._viewer)for(const e of this.targetBlocks){if(!e.visible)continue;const t=Im(e.target);t?.attributes?.uv&&(e.uvCanvas||(e.uvCanvas=yB(t,1024),e.uvCanvas.style.width="100%",e.uvCanvas.style.height="100%"),e.uvCanvas&&e.uvCanvas.parentElement!==e.div&&e.div.appendChild(e.uvCanvas))}},this.enabled=e}onAdded(e){super.onAdded(e),e.addEventListener("postRender",this._postRender),this.stylesheet=om('#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}',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"),r={target:e,name:t,div:n,visible:i};n.classList.add("GeometryUVPreviewPluginTarget"),r.visible||n.classList.add("GeometryUVPreviewPluginCollapsed");const s=document.createElement("div");return s.classList.add("GeometryUVPreviewPluginTargetHeader"),s.innerText=t,s.onclick=()=>{r.visible=!r.visible,r.visible?n.classList.remove("GeometryUVPreviewPluginCollapsed"):n.classList.add("GeometryUVPreviewPluginCollapsed"),this._viewer?.setDirty()},s.oncontextmenu=t=>{t.preventDefault(),t.stopPropagation(),df.Create({Download:()=>this.downloadGeometryUV(r),Remove:()=>this.removeGeometry(e)},t.clientX,t.clientY)},n.appendChild(s),this.mainDiv.appendChild(n),this.targetBlocks.push(r),this.refreshUi(),this}removeGeometry(e){const t=this.targetBlocks.findIndex(t=>t.target===e);if(t>=0){const e=this.targetBlocks[t];this.targetBlocks.splice(t,1),e.div.remove()}return this.refreshUi(),this}downloadGeometryUV(e){if(!this._viewer)return this;if(!e.uvCanvas)return this;const t=e.uvCanvas.toDataURL("image/png"),i=document.createElement("a");return document.body.appendChild(i),i.style.display="none",i.href=t,i.download="renderTarget.png",i.click(),document.body.removeChild(i),URL.revokeObjectURL(t),this}refreshUi(){if(this.mainDiv){if(!this._viewer)return this.mainDiv.parentElement&&this.mainDiv.remove(),this.mainDiv.style.display="none",void(this.mainDiv.style.zIndex="1000");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()}},e.GeometryUVPreviewPlugin.PluginType="GeometryUVPreviewPlugin",iO([Hg("Enabled"),Qm(e.GeometryUVPreviewPlugin.prototype.refreshUi)],e.GeometryUVPreviewPlugin.prototype,"enabled",2),e.GeometryUVPreviewPlugin=iO([qg("Render Target Preview Plugin")],e.GeometryUVPreviewPlugin);var nO=Object.defineProperty;const rO=class extends sw{constructor(){super(),this.enabled=!0,this.serializeWithViewer=!1,this.uiConfig={}}onAdded(e){super.onAdded(e),this.uiConfig=e.uiConfig,this.uiConfig.expanded=!0}};rO.PluginType="ViewerUiConfigPlugin";let sO=rO;((e,t,i)=>{for(var n,r=void 0,s=e.length-1;s>=0;s--)(n=e[s])&&(r=n(t,i,r)||r);r&&nO(t,i,r)})([qm("viewer")],sO.prototype,"_viewer");var aO=Object.defineProperty;const oO=class extends sw{constructor(){super(),this.enabled=!0,this.serializeWithViewer=!1,this.uiConfig={}}onAdded(e){super.onAdded(e),this.uiConfig=e.scene.uiConfig,this._scene=e.scene}};oO.PluginType="SceneUiConfigPlugin";let lO=oO;((e,t,i)=>{for(var n,r=void 0,s=e.length-1;s>=0;s--)(n=e[s])&&(r=n(t,i,r)||r);r&&aO(t,i,r)})([qm("scene")],lO.prototype,"_scene");var cO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,dO=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?hO(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&cO(t,i,s),s};e.FullScreenPlugin=class extends sw{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 e=this._lastFsElement||this._viewer?.canvas;e&&(e.style.width=this._lastSize[0],e.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(){return document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen?document.webkitExitFullscreen():document.msExitFullscreen?document.msExitFullscreen():void 0}async toggle(e){return this.isFullScreen()?this.exit():this.enter(e)}isFullScreen(){return document.webkitIsFullScreen||document.mozFullScreen||void 0!==document.msFullscreenElement}},e.FullScreenPlugin.PluginType="FullScreenPlugin",dO([jg("Enter FullScreen",{sendArgs:!1})],e.FullScreenPlugin.prototype,"enter",1),dO([jg("Exit FullScreen",{sendArgs:!1})],e.FullScreenPlugin.prototype,"exit",1),dO([jg("Toggle FullScreen",{sendArgs:!1})],e.FullScreenPlugin.prototype,"toggle",1),e.FullScreenPlugin=dO([qg("Full Screen")],e.FullScreenPlugin);var uO=Object.defineProperty,pO=Object.getOwnPropertyDescriptor,mO=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?pO(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&uO(t,i,s),s};e.LoadingScreenPlugin=class extends EL{constructor(t){super("LoadingScreen",t),this.styles='#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}',this.spinners=[{styles:".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)}}",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=e.LoadingScreenPlugin.LS_DEFAULT_LOGO,this._isPreviewing=!1,this._previewState=new Map([["file.glb",{state:"downloading",progress:50}],["environment.hdr",{state:"adding"}]]),this.loadingElement=sm({classList:["loadingScreenLoadingElement"],addToBody:!1}),this.filesElement=sm({classList:["loadingScreenFilesElement"],addToBody:!1}),this.logoElement=sm({classList:["loadingScreenLogoElement"],addToBody:!1}),this._isHidden=!1,this._temp=document.createElement("template"),this.isEditor=!1,this._sceneUpdate=e=>{if(!this._viewer||!e.hierarchyChanged)return;const t=this._viewer.scene.modelRoot.children;if(0===t.length&&this.showOnSceneEmpty&&!this.isEditor&&this.show(),t.length>0){const e=this._viewer.assetManager.processState,t=[...e.values()].filter(e=>"error"===e.state);this._updateVisibility(e,t.length)||(this.hideOnSceneObjectLoad?this.hideWithDelay():this.minimizeOnSceneObjectLoad&&this._viewer.scene.environment&&Zp(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 Zp(502),this._isHidden&&(this._mainDiv.style.display="none",this._showMainDiv())}async hideWithDelay(){if(this._isHidden=!0,await Zp(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)return void(this._mainDiv.style.display="none");if(this.showFileNames){let t="";e.forEach((e,i)=>{t+=(this.showProcessStates?`<span class="loadingScreenProcessState">${Am(e.state)}</span>: `:"")+Am((i||"").split("/").pop()||"")+(this.showProgress&&e.progress?" - "+e.progress.toFixed(0)+"%":"")+"<br>"}),this._setHTML(this.filesElement,t)}else this._setHTML(this.filesElement,"");const i=[...e.values()].filter(e=>"error"===e.state);i.length>0&&i.length===e.size&&!this.hideOnOnlyErrors?this._setHTML(this._contentDiv,Am(this.errorTextHeader)):this._setHTML(this._contentDiv,Am(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&&(0===e.size||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))}onAdded(e){this.stylesheet=om(this.styles,e.container),this.stylesheetLoader=this.spinners.map(t=>om(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(e=>e.remove()),this.stylesheetLoader=void 0,super.onRemove(e)}},e.LoadingScreenPlugin.PluginType="LoadingScreenPlugin",e.LoadingScreenPlugin.LS_DEFAULT_LOGO="https://threepipe.org/logo.svg",mO([Ng("Loader",["Spinner 1"].map((e,t)=>({value:t,label:e}))),qm()],e.LoadingScreenPlugin.prototype,"loader",2),mO([zg("Loading text header"),Qm(e.LoadingScreenPlugin.prototype.refresh),qm()],e.LoadingScreenPlugin.prototype,"loadingTextHeader",2),mO([zg("Error text header"),qm()],e.LoadingScreenPlugin.prototype,"errorTextHeader",2),mO([Hg("Show file names"),Qm(e.LoadingScreenPlugin.prototype.refresh),qm()],e.LoadingScreenPlugin.prototype,"showFileNames",2),mO([Hg("Show process states"),Qm(e.LoadingScreenPlugin.prototype.refresh),qm()],e.LoadingScreenPlugin.prototype,"showProcessStates",2),mO([Hg("Show progress"),Qm(e.LoadingScreenPlugin.prototype.refresh),qm()],e.LoadingScreenPlugin.prototype,"showProgress",2),mO([Hg("Hide on only errors"),qm()],e.LoadingScreenPlugin.prototype,"hideOnOnlyErrors",2),mO([Hg("Hide on files load"),qm()],e.LoadingScreenPlugin.prototype,"hideOnFilesLoad",2),mO([Hg("Hide on scene object load"),qm()],e.LoadingScreenPlugin.prototype,"hideOnSceneObjectLoad",2),mO([Hg("Minimize on scene object load"),qm()],e.LoadingScreenPlugin.prototype,"minimizeOnSceneObjectLoad",2),mO([Hg("Show when files start loading"),qm()],e.LoadingScreenPlugin.prototype,"showOnFilesLoading",2),mO([Hg("Show when scene empty"),qm()],e.LoadingScreenPlugin.prototype,"showOnSceneEmpty",2),mO([zg("Hide delay (ms)"),qm()],e.LoadingScreenPlugin.prototype,"hideDelay",2),mO([Fg("Background Opacity",[0,1]),Qm(e.LoadingScreenPlugin.prototype.refresh),qm()],e.LoadingScreenPlugin.prototype,"backgroundOpacity",2),mO([Fg("Background Blur",[0,100]),Qm(e.LoadingScreenPlugin.prototype.refresh),qm()],e.LoadingScreenPlugin.prototype,"backgroundBlur",2),mO([zg("Background Color"),Qm(e.LoadingScreenPlugin.prototype.refresh),qm()],e.LoadingScreenPlugin.prototype,"background",2),mO([zg("Text Color"),Qm(e.LoadingScreenPlugin.prototype.refresh),qm()],e.LoadingScreenPlugin.prototype,"textColor",2),mO([zg("Logo Image"),Qm(e.LoadingScreenPlugin.prototype.refresh),qm()],e.LoadingScreenPlugin.prototype,"logoImage",2),mO([jg("Toggle preview")],e.LoadingScreenPlugin.prototype,"togglePreview",1),mO([jg("Minimize")],e.LoadingScreenPlugin.prototype,"minimize",1),mO([jg("Maximize")],e.LoadingScreenPlugin.prototype,"maximize",1),e.LoadingScreenPlugin=mO([qg("Loading Screen")],e.LoadingScreenPlugin);class gO extends PC{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 Ly).expandByObject(e,!1);t.getCenter(this.position);let i=t.getBoundingSphere(new fn).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(e=>e.isRootScene&&(t=!0)),t&&e?(this._object=e,this._object.addEventListener("objectUpdate",this._updater),this._object.addEventListener("geometryUpdate",this._updater),this._updater(),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 fO=Object.defineProperty;const AO=class extends PC{constructor(e,t=!0){super(),this.isWidget=!0,this.assetType="widget",this.visible=!0,this._objectUpdated=!1,this.uiConfig=Bg("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(e=>{e.userData.__keepShadowDef=!0,e.castShadow=!1,e.receiveShadow=!1}),this.renderOrder=100}update(e=!0){e&&qw.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 e=this.object;e.addEventListener("beforeRender",this._objectBeforeRender),e.addEventListener("objectUpdate",this._objectUpdate),e.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 e=this.object.uiConfig?.children?.indexOf(this.uiConfig);void 0!==e&&e>=0&&this.object.uiConfig?.children?.splice(e,1)}return this.object=void 0,this.visible=!1,this}dispose(){this.detach()}};((e,t,i)=>{for(var n,r=void 0,s=e.length-1;s>=0;s--)(n=e[s])&&(r=n(t,i,r)||r);r&&fO(t,i,r)})([Hg(),Vm(AO.prototype.update)],AO.prototype,"visible");let yO=AO;class vO extends yO{constructor(e){super(e),this.camera=e,this.traverse(e=>{e.userData.__keepShadowDef=!0,e.castShadow=!1,e.receiveShadow=!1})}preRender(){this.visible&&this._objectBeforeRender()}attach(e){return super.attach(e),this}detach(){return super.detach()}}class _O extends yO{constructor(e){super(e),this.light=e,this.traverse(e=>{e.userData.__keepShadowDef=!0,e.castShadow=!1,e.receiveShadow=!1})}preRender(){this.visible&&this._objectBeforeRender()}}var bO=Object.defineProperty,xO=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&bO(t,i,s),s};const wO=class e extends yO{constructor(e,t,i){super(e),this._vector=new Xi,this._boneMatrix=new Sn,this._matrixWorldInv=new Sn,this.lineWidth=5,this.color1=new mr(0,0,1),this.color2=new mr(0,1,0),this.autoUpdate=!0,t&&this.color1.set(t),i&&this.color2.set(i);const n=new wv;this.hMaterial=new MC({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 zv(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 r=this.lineSegments.geometry;i.length>0?(r.setPositions(i),r.setColors(n)):(r.setPositions([0,0,0,0,0,0]),r.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(t){return new e(t)}};xO([Vm(wO.prototype.update)],wO.prototype,"hMaterial"),xO([Vm(wO.prototype.update),Fg(void 0,[.1,20],.01)],wO.prototype,"lineWidth"),xO([Vm(wO.prototype.update),Qg()],wO.prototype,"color1"),xO([Vm(wO.prototype.update),Qg()],wO.prototype,"color2"),xO([Hg(),Vm(wO.prototype.update)],wO.prototype,"autoUpdate");let CO=wO;class SO extends gO{constructor(){super();const e=new MC({color:"#ff2222",transparent:!0,opacity:.9,linewidth:5,resolution:new fi(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 wv;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(e=>e-.5));const i=new zv(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 t=(new Ly).expandByObject(e,!1).getSize(this.scale);t.lengthSq()<=0&&(e.getWorldPosition(this.position),t.set(2,2,2)),t.multiplyScalar(this.boundingScaleMultiplier).clampScalar(.01,1e8),this.setVisible(!0)}}}var MO=Object.defineProperty;const EO=class e extends vO{constructor(e){super(e),this._vector=new Xi,this._camera=new cs,this._colorFrustum=new mr(16755200),this._colorCone=new mr(16711680),this._colorUp=new mr(43775),this._colorTarget=new mr(16777215),this._colorCross=new mr(3355443),this.showFar=!1;const t=new wv,i=new MC({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:r,pointMap:s}=function(){const e=[],t=[],i={};function n(e,t){r(e),r(t)}function r(n){e.push(0,0,0),t.push(0,0,0),void 0===i[n]&&(i[n]=[]),i[n].push(e.length/3-1)}return n("u1","u2"),n("u2","u3"),n("u3","u1"),n("cn1","cn2"),n("cn3","cn4"),n("cf1","cf2"),n("cf3","cf4"),n("n1","n2"),n("n2","n4"),n("n4","n3"),n("n3","n1"),n("p","n1"),n("p","n2"),n("p","n3"),n("p","n4"),n("f1","f2"),n("f2","f4"),n("f4","f3"),n("f3","f1"),n("n1","f1"),n("n2","f2"),n("n3","f3"),n("n4","f4"),n("c","t"),n("p","c"),{vertices:e,colors:t,pointMap:i}}();t.setPositions(n),t.setColors(r),this.line=new zv(t,i),this.line.frustumCulled=!1,this.add(this.line),this.pointMap=s,this.update(),this.setColors(this._colorFrustum,this._colorCone,this._colorUp,this._colorTarget,this._colorCross)}setColors(e,t,i,n,r){const s=this.line.geometry,a=s.getAttribute("instanceColorStart"),o=s.getAttribute("instanceColorEnd");let l=0;function c(e){a.setXYZ(l,e.r,e.g,e.b),o.setXYZ(l,e.r,e.g,e.b),l++}c(i),c(i),c(i),c(r),c(r),c(r),c(r),c(e),c(e),c(e),c(e),c(t),c(t),c(t),c(t),c(e),c(e),c(e),c(e),c(e),c(e),c(e),c(e),c(n),c(r),a.needsUpdate=!0,o.needsUpdate=!0}update(){if(!this.camera||!this.line)return;const e=this.line.geometry,t=this.pointMap,{_camera:i,_vector:n}=this;this.camera.updateProjectionMatrix(),i.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),IO("c",t,e,i,0,0,-1,n),IO("t",t,e,i,0,0,1,n),IO("n1",t,e,i,-1,-1,-1,n),IO("n2",t,e,i,1,-1,-1,n),IO("n3",t,e,i,-1,1,-1,n),IO("n4",t,e,i,1,1,-1,n),IO("f1",t,e,i,-1,-1,1,n),IO("f2",t,e,i,1,-1,1,n),IO("f3",t,e,i,-1,1,1,n),IO("f4",t,e,i,1,1,1,n),IO("u1",t,e,i,.7,1.1,-1,n),IO("u2",t,e,i,-.7,1.1,-1,n),IO("u3",t,e,i,0,2,-1,n),IO("cf1",t,e,i,-1,0,1,n),IO("cf2",t,e,i,1,0,1,n),IO("cf3",t,e,i,0,-1,1,n),IO("cf4",t,e,i,0,1,1,n),IO("cn1",t,e,i,-1,0,-1,n),IO("cn2",t,e,i,1,0,-1,n),IO("cn3",t,e,i,0,-1,-1,n),IO("cn4",t,e,i,0,1,-1,n),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(t){return new e(t)}};((e,t,i)=>{for(var n,r=void 0,s=e.length-1;s>=0;s--)(n=e[s])&&(r=n(t,i,r)||r);r&&MO(t,i,r)})([Hg(),Vm(EO.prototype.update)],EO.prototype,"showFar");let TO=EO;function IO(e,t,i,n,r,s,a,o){o.set(r,s,a).unproject(n);const l=t[e];if(void 0!==l){const e=i.getAttribute("instanceStart"),t=i.getAttribute("instanceEnd");for(let i=0,n=l.length;i<n;i++){const n=Math.floor(l[i]/2);(l[i]%2==0?e:t).setXYZ(n,o.x,o.y,o.z)}}}var PO=Object.defineProperty,DO=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&PO(t,i,s),s};const RO=class e extends _O{constructor(e,t,i){super(e),this.lineWidth=5,this.size=.5,this._v1=new Xi,this._v2=new Xi,this._v3=new Xi,this.color=i,void 0!==t&&(this.size=t);let n=new RC;this.hMaterial=new MC({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 BC(n,this.hMaterial),this.add(this.lightPlane),n=new RC,n.setPositions([0,0,0,0,0,1]),this.targetLine=new BC(n,this.hMaterial),this.add(this.targetLine),this.update(),this.traverse(e=>{e.userData.__keepShadowDef=!0,e.castShadow=!1,e.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(t){return new e(t)}};DO([Qm(RO.prototype.update)],RO.prototype,"hMaterial"),DO([Qm(RO.prototype.update),Fg(void 0,[.1,20],.01)],RO.prototype,"lineWidth"),DO([Qm(RO.prototype.update),Fg(void 0,[.01,10],.01)],RO.prototype,"size");let BO=RO;var LO=Object.defineProperty,OO=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&LO(t,i,s),s};const UO=class e extends yO{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 ns(1,1,1,2,2,2),dw.upgradeGeometry.call(this._cubeGeometry),this._cubeMaterial=new vr({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 r=this.line.geometry.userData?.generationParams?.curve;if(r){const t=kO(r),i=this._vertexHandles;this._vertexHandles=[];for(let e=t.length;e<i.length;e++)this.remove(i[e]);for(let n=0;n<t.length;n++){const s=t[n],a=i[n]??new ts(this._cubeGeometry,this._cubeMaterial2);a.renderOrder=100;const o=s[0];isFinite(o[0])||(o[0]=0),isFinite(o[1])||(o[1]=0),isFinite(o[2])||(o[2]=0),a.position.fromArray(o),a.scale.setScalar(this.editableHandleSize),a.frustumCulled=!1,a.castShadow=!1,a.receiveShadow=!1,a.userData.__keepShadowDef=!0,a.parent||this.add(a),this._vertexHandles.push(a),a.userData.isWidgetHandle=!0,a.userData.transformControls={mode:"translate",space:"local",showX:!0,showY:!0,showZ:!0,lockProps:["mode"]},a.__handle=s,a.setDirty=t=>{if("transform"!==t.change)return;const i=a.__handle,n=i[0],s=i[1],o=a.position;if(Math.abs(n[0]-o.x)+Math.abs(n[1]-o.y)+Math.abs(n[2]-o.z)<=1e-4)return;n[0]=o.x,n[1]=o.y,n[2]=o.z;let l=r,c=s;if(c.startsWith("curves.")){const e=c.indexOf(".",7),t=parseInt(c.slice(7,e)||"0");c=c.slice(e+1),t>=0&&t<r.curves.length&&(l=r.curves[t])}if(c.startsWith("points.")){const e=parseInt(c.slice(7)||"0",10);l.points?.[e]?.set(n[0],n[1],n[2])}else l[c]?.set(n[0],n[1],n[2]);e.setDirty&&e.setDirty({regenerate:!0})}}if(t.length)return}this._clearVertexCubes();const s=this._vertexHandles;this._vertexHandles=[];for(let e=n;e<s.length;e++)this.remove(s[e]);for(let e=0;e<n;e++){const t=i[3*e],n=i[3*e+1],r=i[3*e+2],a=s[e]??new ts(this._cubeGeometry,this._cubeMaterial);a.position.set(isFinite(t)?t:0,isFinite(n)?n:0,isFinite(r)?r:0),a.scale.setScalar(this.handleSize),a.frustumCulled=!1,a.castShadow=!1,a.receiveShadow=!1,a.userData.__keepShadowDef=!0,a.parent||this.add(a),this._vertexHandles.push(a)}}_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(t){return new e(t)}};OO([Qm(UO.prototype.update),Fg(void 0,[.001,.2],.001)],UO.prototype,"handleSize"),OO([Qm(UO.prototype.update),Fg(void 0,[.001,.5],.001)],UO.prototype,"editableHandleSize"),OO([Qm(UO.prototype.update),Qg()],UO.prototype,"handleColor"),OO([Qm(UO.prototype.update),Qg()],UO.prototype,"editableHandleColor");let FO=UO;function kO(e){const t=[];return e.v0?.toArray&&t.push([e.v0.toArray(),"v0"]),e.v1?.toArray&&t.push([e.v1.toArray(),"v1"]),e.v2?.toArray&&t.push([e.v2.toArray(),"v2"]),e.v3?.toArray&&t.push([e.v3.toArray(),"v3"]),void 0!==e.points&&e.points.forEach((e,i)=>{t.push([e.toArray(),"points."+i])}),void 0!==e.curves&&e.curves.forEach((e,i)=>{const n=kO(e);n.forEach(e=>{e[1]="curves."+i+"."+e[1]}),t.push(...n)}),t}var NO=Object.defineProperty,jO=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&NO(t,i,s),s};const zO=class e extends _O{constructor(e,t,i){super(e),this.lineWidth=5,this.size=.5,this.color=i,void 0!==t&&(this.size=t);const n=new jC(new yd(.5,4,2));this.hMaterial=new MC({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 AB(n,this.hMaterial),this.lightSphere.computeLineDistances(),this.add(this.lightSphere),this.update(),this.traverse(e=>{e.userData.__keepShadowDef=!0,e.castShadow=!1,e.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(t){return new e(t)}};jO([Qm(zO.prototype.update)],zO.prototype,"hMaterial"),jO([Qm(zO.prototype.update),Fg(void 0,[.1,20],.01)],zO.prototype,"lineWidth"),jO([Qm(zO.prototype.update),Fg(void 0,[.01,10],.01)],zO.prototype,"size");let GO=zO;var QO=Object.defineProperty,VO=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&QO(t,i,s),s};const HO=class e extends yO{constructor(e,t,i){super(e),this._vector=new Xi,this._boneMatrix=new Sn,this._matrixWorldInv=new Sn,this.lineWidth=5,this.color1=new mr(0,0,1),this.color2=new mr(0,1,0),this.autoUpdate=!0,t&&this.color1.set(t),i&&this.color2.set(i),this.bones=qO(e);const n=new wv;this.hMaterial=new MC({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 zv(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 e of this.bones)e.parent&&e.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 r=0;for(const e of this.bones)e.parent&&e.parent.isBone&&(this._boneMatrix.multiplyMatrices(this._matrixWorldInv,e.parent.matrixWorld),this._vector.setFromMatrixPosition(this._boneMatrix),i[3*r]=this._vector.x,i[3*r+1]=this._vector.y,i[3*r+2]=this._vector.z,this._boneMatrix.multiplyMatrices(this._matrixWorldInv,e.matrixWorld),this._vector.setFromMatrixPosition(this._boneMatrix),i[3*r+3]=this._vector.x,i[3*r+4]=this._vector.y,i[3*r+5]=this._vector.z,r+=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(e=>{e._hasSkeletonHelper&&(t=!0)}),!t&&qO(e).length>0}static Create(t){const i=new e(t);return t._hasSkeletonHelper=!0,i}};VO([Vm(HO.prototype.update)],HO.prototype,"hMaterial"),VO([Vm(HO.prototype.update),Fg(void 0,[.1,20],.01)],HO.prototype,"lineWidth"),VO([Vm(HO.prototype.update),Qg()],HO.prototype,"color1"),VO([Vm(HO.prototype.update),Qg()],HO.prototype,"color2"),VO([Hg(),Vm(HO.prototype.update)],HO.prototype,"autoUpdate");let WO=HO;function qO(e){const t=[];!0===e.isBone&&t.push(e);for(const i of e.children)t.push(...qO(i));return t}var XO=Object.defineProperty,YO=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&XO(t,i,s),s};const KO=class e extends _O{constructor(e,t,i){super(e),this.lineWidth=5,this._v1=new Xi,this.color=i;const n=new wv,r=[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 e=0,t=1,i=32;e<i;e++,t++){const n=e/i*Math.PI*2,s=t/i*Math.PI*2;r.push(Math.cos(n),Math.sin(n),1,Math.cos(s),Math.sin(s),1)}n.setPositions(r),this.hMaterial=new MC({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 zv(n,this.hMaterial),this.add(this.cone),this.update(),this.traverse(e=>{e.userData.__keepShadowDef=!0,e.castShadow=!1,e.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(t){return new e(t)}};YO([Qm(KO.prototype.update)],KO.prototype,"hMaterial"),YO([Qm(KO.prototype.update),Fg(void 0,[.1,20],.01)],KO.prototype,"lineWidth");let JO=KO;const ZO=class e{constructor(){this._initialMatrix=new Sn,this._chainActive=!1}onSelectionChanged(){this._chainActive=!1}onDuplicated(e){this._initialMatrix.copy(e),this._chainActive=!0}applyOffset(t,i,n="simple"){if(!this._chainActive)return!1;const r=e._iP,s=e._iQ,a=e._iS;this._initialMatrix.decompose(r,s,a);const o=i.position.clone().sub(r),l=s.invert().premultiply(i.quaternion.clone()).normalize(),c=i.scale.clone().divide(a),h=o.lengthSq()>1e-10,d=Math.abs(l.x)>1e-6||Math.abs(l.y)>1e-6||Math.abs(l.z)>1e-6,u=Math.abs(c.x-1)>1e-6||Math.abs(c.y-1)>1e-6||Math.abs(c.z-1)>1e-6;if(!h&&!d&&!u)return!1;const p="compound"===n,m=e._rel;for(const e of t)p?(m.copy(e.position).sub(r),u&&m.multiply(c),d&&m.applyQuaternion(l),e.position.copy(i.position).add(m)):h&&e.position.add(o),d&&e.quaternion.premultiply(l).normalize(),u&&e.scale.multiply(c),e.updateMatrixWorld(!0),e.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}};ZO._iP=new Xi,ZO._iQ=new qi,ZO._iS=new Xi,ZO._rel=new Xi;let $O=ZO;class eU{constructor(){this._state=null}get state(){return this._state}get isEmpty(){return!this._state}copy(e){const t=Xw(e);t.length&&(this._state={objects:t,mode:"copy",sourceParents:this._parentMap(t)})}cut(e){const t=Xw(e);t.length&&(this._state={objects:t,mode:"cut",sourceParents:this._parentMap(t)})}paste(e){return this._state?"copy"===this._state.mode?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 r of t.objects){const t=r.clone(!0);cw(r,t);const s=e??r.parent;s&&(s.add(t),n.set(t,s)),i.push(t)}return{objects:i,undo:()=>{for(const e of i)e.removeFromParent()},redo:()=>{for(const e of i){const t=n.get(e);t&&!e.parent&&t.add(e)}}}}_pasteFromCut(e){const t=this._state;if(!t)return null;const i=t.objects,n=t.sourceParents;for(const t of i){const i=e??n.get(t);i&&t.parent!==i&&(t.removeFromParent(),i.add(t))}return this._state=null,{objects:i,undo:()=>{for(const e of i){const t=n.get(e);t&&e.parent!==t&&(e.removeFromParent(),t.add(e))}this._state=t},redo:()=>{for(const t of i){const i=e??n.get(t);i&&t.parent!==i&&(t.removeFromParent(),i.add(t))}this._state=null}}}_parentMap(e){const t=new Map;for(const i of e)t.set(i,i.parent);return t}}var tU=Object.defineProperty,iU=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&tU(t,i,s),s};function nU(e){for(;e.parent&&"widget"!==e.assetType&&!e.userData.allowPicking;)e=e.parent;return e}const rU=(s=class extends sw{constructor(t=SO,i=!0,n=!1){super(),this.enabled=!0,this._extraWidgets=[],this._clipboard=new eU,this._duplicateTracker=new $O,this.duplicateMode="simple",this.dependencies=[qR],this.selectionMode="object",this.autoFocusHover=!1,this.autoApplyMaterialOnDrop=!0,this.widgetEnabled=!0,this.multiSelectEnabled=!0,this._onKeyDown=e=>{if(this.isDisabled()||"TEXTAREA"===e.target?.tagName||"INPUT"===e.target?.tagName)return;const t=e.ctrlKey||e.metaKey;t&&"KeyA"===e.code?(e.preventDefault(),this.selectAll()):t&&"KeyD"===e.code?(e.preventDefault(),this.duplicateSelected(e.shiftKey?"simple"===this.duplicateMode?"compound":"simple":void 0)):t&&"KeyC"===e.code?(e.preventDefault(),this.copySelected()):t&&"KeyX"===e.code?(e.preventDefault(),this.cutSelected()):t&&"KeyV"===e.code?(e.preventDefault(),this.pasteFromClipboard()):"Escape"===e.code?this.clearSelection():"Delete"===e.code||"Backspace"===e.code?(e.preventDefault(),this.deleteSelected()):"KeyH"!==e.code||t?"KeyF"!==e.code||t?e.altKey&&!t&&("KeyG"===e.code||"KeyR"===e.code||"KeyS"===e.code)&&(e.preventDefault(),this.resetTransform("KeyG"===e.code?"position":"KeyR"===e.code?"rotation":"scale")):(e.preventDefault(),this.focusSelected()):(e.preventDefault(),e.shiftKey?this.unhideAll():this.toggleVisibilitySelected())},this._mainCameraChange=()=>{!this._picker||!this._viewer||(this._picker.camera=this._viewer.scene.mainCamera)},this._addSceneObject=e=>{e.object?.userData?.isWidgetRoot&&e.object.parent===this._viewer?.scene&&this._picker?.extraObjects.push(e.object)},this._sceneUpdate=e=>{if("removedFromParent"===e?.change&&e.object?.userData?.isWidgetRoot&&this._picker){const t=this._picker.extraObjects.indexOf(e.object);t>=0&&this._picker.extraObjects.splice(t,1)}},this._objCompChange=e=>{e.object&&e.object===this.getSelectedObject()&&this.refreshUiChildren(e.object)},this._onObjectSelectEvent=e=>{e.source!==s.PluginType&&(void 0===e.object&&void 0===e.value?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(e.object||e.value,this.autoFocus||e.focusCamera,e.trackUndo??!0))},this._selectedObjectChanged=t=>{if(!this._viewer)return;this._duplicateTracker.onSelectionChanged(),this.dispatchEvent(t);const i=this._picker?.selectedObject||void 0,n=this._viewer.getPlugin(e.FrameFadePlugin);n&&(i?n.disable(this):n.enable(this)),i?this._viewer.scene.disableAutoNearFar("PickingPlugin"):this._viewer.scene.enableAutoNearFar("PickingPlugin"),this.refreshUiChildren(i);const r=this._widget;r&&this.widgetEnabled&&(i?.isObject3D?r.attach(i):r.detach()),this._updateExtraWidgets(),this._viewer.setDirty(),this.autoFocus&&"object"===this.selectionMode&&this.focusObject(i)},this._hoverObjectChanged=e=>{if(!this._viewer)return;this.dispatchEvent(e);const t=this._picker?.hoverObject||void 0,i=this._hoverWidget;i&&this.widgetEnabled&&(t?.isObject3D?i.attach(t):i.detach()),this._viewer?.setDirty(),this.autoFocusHover&&"object"===this.selectionMode&&this.focusObject(t)},this._onObjectHit=e=>{if(!this._viewer)return;if(this.isDisabled())return void(e.intersects.selectedObject=null);let t=e.intersects.selectedObject;if(t){const i=t;t=nU(t),"widget"===t.assetType&&t.object&&(e.intersects.selectedObject=t.object,e.intersects.selectedWidget=t,e.intersects.selectedHandle=i.userData.isWidgetHandle?i:void 0)}this.dispatchEvent(e)},this._selectionModeChanged=e=>{this._viewer&&(this.dispatchEvent(e),!this.isDisabled()&&this.uiConfig?.uiRefresh?.(!0,"postFrame",1))},this._multiSelectChanged=e=>{if(this._viewer&&(this.dispatchEvent(e),!this.multiSelectEnabled&&this._picker&&this._picker.selectedObjects.length>1)){const e=this._picker.selectedObject;this._picker.setSelected(e,!1)}},this._onDrop=async e=>{if(!this._viewer||!this.autoApplyMaterialOnDrop)return;const t=e.assets?.find(e=>e.isMaterial),i=this.getSelectedObject();if(i&&i?.isObject3D&&t&&await this._viewer.dialog.confirm("Applying material: Apply material to the selected object?")){let e=i.material;Array.isArray(e)&&(console.warn("Dropping on material array not yet fully supported."),e=e[0]);let n=Array.from(e?.appliedMeshes??[]);(n.length>1?!await this._viewer.dialog.confirm("Applying material: Apply to all objects using this material?"):n.length<1)&&(n=[i]);for(const e of n)e&&(e.material=t)}},this._pickPromptUi={type:"button",label:"Select an object to see its properties",readOnly:!0,hidden:()=>void 0!==this.getSelectedObject()},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 e=this.getSelectedObject();this.autoFocus&&e&&this.setSelectedObject(e,!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(e=>({label:e,value:e}))}],this.uiConfig={type:"folder",label:"Picker",expanded:!0,children:[...this._uiConfigChildren,this._pickPromptUi]},this.canRemoveMaterial=e=>{if(!e.material)return!1;const t=Array.isArray(e.material)?e.material:e.material?[e.material]:[];return t.length&&(1!==t.length||!t[0].userData?.isPlaceholder)},this.removeMaterial=e=>{if(!e.material)return;const t=e.material;return e.material=this.getPlaceholderMaterial(e),()=>e.material=t},this.materialTypes=[{cls:kw,def:$S.DummyMaterial,name:"Unlit"},{cls:xC,def:$S.DummyLineBasicMaterial,line:!0,name:"Basic Line"},{cls:MC,def:$S.DummyLineMaterial,line:!0,name:"Line"},{cls:yC,name:"Physical"}],this._selectionWidgetClass=t,t&&(this._widget=new t,this._hoverWidget=new t,this._hoverWidget.lineMaterial&&(this._hoverWidget.lineMaterial.linewidth/=2,this._hoverWidget.lineMaterial.color.set("#aa2222"))),this._pickUi=i,this.autoFocus=n,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 e=(this._picker?.selectedObjects||[]).filter((e,t)=>t>0&&e?.isObject3D);for(let t=e.length;t<this._extraWidgets.length;t++)this._extraWidgets[t].detach();for(let t=0;t<e.length;t++){if(!this._extraWidgets[t]){const e=new this._selectionWidgetClass;e.lineMaterial&&(e.lineMaterial.color.set("#ff8844"),e.lineMaterial.opacity=.7),this._extraWidgets.push(e),this._viewer.scene.addObject(e,{addToRoot:!0})}this.widgetEnabled?this._extraWidgets[t].attach(e[t]):this._extraWidgets[t].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?1===t.length?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&&"model"===t.assetType&&!1!==t.userData.userSelectable&&t.material&&e.push(t)}),e.length&&this._picker.setSelected(1===e.length?e[0]:e,!0)}clearSelection(){this._picker&&this._picker.setSelected(null,!0)}_setSelectedFromArray(e){e&&e.length?1===e.length?this._picker?.setSelected(e[0],!1):this._picker?.setSelected(e,!1):this._picker?.setSelected(null,!1)}async deleteSelected(){const e=this.getSelectedObjects().filter(e=>e?.isObject3D);if(!e.length)return;const t=await Yw(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(e=>e?.isObject3D);if(!i.length)return;const{clones:n,undo:r,redo:s}=Kw(i);if(!n.length)return;const a=this._duplicateTracker.saveState(),o=(new Sn).compose(n[0].position,n[0].quaternion,n[0].scale);this._duplicateTracker.applyOffset(n,i[0],t),this._setSelectedFromArray(n),this._duplicateTracker.onDuplicated(o);const l=[...i];this._undoManager?.record({undo:()=>{r(),this._setSelectedFromArray(l),this._duplicateTracker.restoreState(a)},redo:()=>{s(),this._setSelectedFromArray(n),this._duplicateTracker.onDuplicated(o)}})}copySelected(){const e=this.getSelectedObjects().filter(e=>e?.isObject3D);e.length&&this._clipboard.copy(e)}cutSelected(){const e=this.getSelectedObjects().filter(e=>e?.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:r,redo:s}=t;this._undoManager?.record({undo:()=>{r(),this._setSelectedFromArray(i),this._viewer?.setDirty()},redo:()=>{s(),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||"light"===e.assetType||"camera"===e.assetType||"widget"===e.assetType)}toggleVisibilitySelected(){const e=this.getSelectedObjects().filter(e=>e?.isObject3D);if(!e.length)return;const t=!e[0].visible,i=new Map;for(const t of e)i.set(t,t.visible);for(const i of e)i.visible=t,i.setDirty?.();this._viewer?.setDirty(),this._undoManager?.record({undo:()=>{for(const[e,t]of i)e.visible=t,e.setDirty?.();this._viewer?.setDirty()},redo:()=>{for(const i of e)i.visible=t,i.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(e=>e?.isObject3D);e.length&&this.focusObject(1===e.length?e[0]:e)}resetTransform(e){const t=this.getSelectedObjects().filter(e=>e?.isObject3D);if(!t.length)return;const i=t.map(e=>({obj:e,position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()})),n=()=>{for(const i of t)"position"===e?i.position.set(0,0,0):"rotation"===e?i.quaternion.identity():i.scale.set(1,1,1),i.updateMatrixWorld(!0),i.setDirty?.({change:"transform"});this._viewer?.setDirty()};n(),this._undoManager?.record({undo:()=>{for(const e of i)e.obj.position.copy(e.position),e.obj.quaternion.copy(e.quaternion),e.obj.scale.copy(e.scale),e.obj.updateMatrixWorld(!0),e.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 r=this.autoFocus;this.autoFocus=!1,this._picker.setSelected(e||null,i),this.autoFocus=r,!n&&e&&"object"===this.selectionMode&&(r||t)&&this.focusObject(e)}onAdded(e){super.onAdded(e),this.setDirty(),this._picker=new mv(e.scene.modelRoot,e.canvas,e.scene.mainCamera,e=>{if(!e.material&&!e.userData.userSelectable)return!1;let t=e;t=nU(t);let i=!1;for(;t;){if(!t.visible||(("model"===t.assetType||"light"===t.assetType)&&(i=!0),!1===t.userData.userSelectable)||!1===t.userData.bboxVisible)return!1;t=t.parent}return i}),this._picker.extraObjects.push(...e.scene.children.filter(e=>e.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",e=>{e.addEventListener("drop",this._onDrop)},e=>{e.removeEventListener("drop",this._onDrop)}),e.forPlugin("UndoManagerPlugin",e=>{this._picker&&(this._picker.undoManager=e.undoManager,this._undoManager=e.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 e of this._extraWidgets)e.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 i=e;t.children.push(...this.objectSelectionUiConfig(i))}const i=e.uiConfig;"folder"===i?.type&&Tm(i,"expanded",!0,!0),i&&t.children.push(i);const n=e?.isObject3D?e:void 0,r=e?.isMaterial?e:n?.material,s=r?Array.isArray(r)?r:[r]:[],a=e?.isBufferGeometry?e:n?.geometry;if(a?.uiConfig&&a!==e){const e=a.uiConfig;"folder"===e.type&&Tm(e,"expanded",!0,!0),t.children.push(e)}s.forEach(i=>{i?.uiConfig&&i!==e&&t.children?.push(i.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||1===e.materials.length&&e.materials[0]===t.def):()=>!(!e.materials?.length||1===e.materials.length&&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");return(e.isLineSegments2||e.isWireframe?this.materialTypes.find(e=>e.cls===MC)?.def:e.isLine||e.isLineSegments?this.materialTypes.find(e=>e.cls===xC)?.def:null)||t[0]}},s.PluginType="Picking",s.OldPluginType="PickingPlugin",s);iU([qm(),Qm(rU.prototype.setDirty)],rU.prototype,"enabled"),iU([zy({obj:"_picker",key:"selectionMode"})],rU.prototype,"selectionMode"),iU([qm()],rU.prototype,"autoFocus"),iU([Qm(rU.prototype._widgetEnabledChange)],rU.prototype,"widgetEnabled"),iU([zy({obj:"_picker",key:"multiSelectEnabled"})],rU.prototype,"multiSelectEnabled");let sU=rU;class aU{constructor(){this.multiObjects=[],this._dummy=null,this._dummyStart=new Sn,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 Zn,this._dummy.userData.isMultiSelectDummy=!0,t.scene.addObject(this._dummy,{addToRoot:!0}));const i=new Xi;for(const t of e)t.updateWorldMatrix(!0,!1),i.add((new Xi).setFromMatrixPosition(t.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 e=0;e<this.multiObjects.length;e++){const i=this.multiObjects[e],n=t.clone().multiply(this._startWorldMatrices[e]),r=new Sn;i.parent&&r.copy(i.parent.matrixWorld).invert(),r.clone().multiply(n).decompose(i.position,i.quaternion,i.scale),i.updateMatrixWorld(!0),i.setDirty?.({change:"transform",frameFade:!1})}}updateDummyPosition(){if(!this._dummy||!this.multiObjects.length)return;const e=new Xi;for(const t of this.multiObjects)t.updateWorldMatrix(!0,!1),e.add((new Xi).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(e=>({position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()})),n=t.map(e=>({position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()}));let r=!1;for(let e=0;e<t.length;e++)if(!i[e].position.equals(n[e].position)||!i[e].quaternion.equals(n[e].quaternion)||!i[e].scale.equals(n[e].scale)){r=!0;break}r&&e.record({undo:()=>{for(let e=0;e<t.length;e++)t[e].position.copy(i[e].position),t[e].quaternion.copy(i[e].quaternion),t[e].scale.copy(i[e].scale),t[e].updateMatrixWorld(!0),t[e].setDirty?.({change:"transform"});this.updateDummyPosition()},redo:()=>{for(let e=0;e<t.length;e++)t[e].position.copy(n[e].position),t[e].quaternion.copy(n[e].quaternion),t[e].scale.copy(n[e].scale),t[e].updateMatrixWorld(!0),t[e].setDirty?.({change:"transform"});this.updateDummyPosition()}})}}var oU=Object.defineProperty,lU=Object.getOwnPropertyDescriptor,cU=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?lU(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&oU(t,i,s),s};e.TransformControlsPlugin=class extends sw{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.dependencies=[sU],this._isInteracting=!1,this._viewerListeners={postFrame:()=>{!this.transformControls||this._viewer}},this._transformState={obj:null,position:new Xi,rotation:new On,scale:new Xi},this.selectionFilterTest=void 0,this._multi=new aU,this._mainCameraChange=()=>{!this.transformControls||!this._viewer||(this.transformControls.camera=this._viewer.scene.mainCamera)},rA.ObjectConstructors.MeshBasicMaterial=kw,rA.ObjectConstructors.LineBasicMaterial=xC,this.enabled=e}setDirty(){if(!this._viewer)return;const e=this._viewer.getPlugin(sU),t=!this.isDisabled();if(this.transformControls)if(t){const t=e.getSelectedObjects().filter(e=>e?.isObject3D);t.length>1?this.transformControls.attach(this._multi.setup(t,this._viewer)):1===t.length?(this._multi.clear(this._viewer),this.transformControls.attach(t[0])):(this._multi.clear(this._viewer),this.transformControls.detach())}else this.transformControls.detach(),this._multi.clear(this._viewer);this._viewer.setDirty()}onAdded(t){super.onAdded(t),this.setDirty(),this.transformControls=new e.TransformControls2(t.scene.mainCamera,t.canvas),this._mainCameraChange=this._mainCameraChange.bind(this),t.scene.addEventListener("mainCameraChange",this._mainCameraChange),this.transformControls.addEventListener("dragging-changed",t=>{if(!this?._viewer)return;const i=this._viewer.scene.mainCamera.controls;"function"==typeof i?.stopDamping&&i?.enabled&&i.stopDamping(),this._viewer.scene.mainCamera.setInteractions(!t.value,e.TransformControlsPlugin.PluginType)}),this.transformControls.addEventListener("axis-changed",e=>{if(!this?._viewer)return;this._isInteracting=!!e.value;const t=this._viewer.scene.mainCamera.controls;"function"==typeof t?.stopDamping&&t?.enabled&&t.stopDamping(),this._viewer.setDirty()}),t.scene.addObject(this.transformControls,{addToRoot:!0}),t.getPlugin(sU).addEventListener("selectedObjectChanged",e=>{if(!this.transformControls)return;if(this.isDisabled())return this.transformControls.object&&this.transformControls.detach(),void this._multi.clear(this._viewer);const t=(e.objects||[]).filter(e=>e?.isObject3D);if(t.length>1)this.transformControls.attach(this._multi.setup(t,this._viewer));else if(e.object){this._multi.clear(this._viewer);let t=e.intersects?.selectedHandle??e.intersects?.selectedObject??e.object;if(this.selectionFilterTest&&(t=this.selectionFilterTest(t)),!t||!t.isObject3D)return void this.transformControls.detach();this.transformControls.attach(t)}else this._multi.clear(this._viewer),this.transformControls.detach()}),t.forPlugin("UndoManagerPlugin",e=>{this.undoManager=e.undoManager},()=>this.undoManager=void 0,this),this.transformControls.addEventListener("mouseDown",()=>{if(!this.transformControls)return;if(this._multi.hasMultiSelect)return void this._multi.captureStart();const e=this.transformControls.object;e&&(this._transformState.obj=e,this._transformState.position=e.position.clone(),this._transformState.rotation=e.rotation.clone(),this._transformState.scale=e.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)return void(this.undoManager&&this._multi.recordUndo(this.undoManager));const e=this.transformControls.object;if(!e||this._transformState.obj!==e||!this.undoManager)return;const t={translate:"position",rotate:"rotation",scale:"scale"}[this.transformControls.getMode()];if(!t||this._transformState[t].equals(e[t]))return;const i={last:this._transformState[t].clone(),current:e[t].clone(),set:i=>{e[t].copy(i),e.updateMatrixWorld(!0),this.transformControls?.dispatchEvent({type:"change"}),this.transformControls?.dispatchEvent({type:"objectChange"})},undo:()=>i.set(i.last),redo:()=>i.set(i.current)};this.undoManager.record(i)})}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)}},e.TransformControlsPlugin.PluginType="TransformControlsPlugin",cU([Hg(),Qm(e.TransformControlsPlugin.prototype.setDirty)],e.TransformControlsPlugin.prototype,"enabled",2),cU([Lg(void 0,{expanded:!0})],e.TransformControlsPlugin.prototype,"transformControls",2),cU([jg("Center All Meshes")],e.TransformControlsPlugin.prototype,"centerAllMeshes",1),e.TransformControlsPlugin=cU([qg("Transform Controls")],e.TransformControlsPlugin),e.TransformControls2=class extends rA{constructor(e,t){super(e,t),this.isWidget=!0,this.assetType="widget",this.setDirty=qw.setDirty.bind(this),this.refreshUi=qw.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(e=>{e.castShadow=!1,e.receiveShadow=!1,e.userData.__keepShadowDef=!0})}_keyDownListener(e){if(this.enabled&&this.object){if(!EA(e,{toggleSpace:()=>{this.space="local"===this.space?"world":"local"},adjustSize:e=>{this.size=Math.max(this.size+e,.1)},toggleAxis:e=>{0===e?this.showX=!this.showX:1===e?this.showY=!this.showY:this.showZ=!this.showZ},toggleEnabled:()=>{this.enabled=!this.enabled}})){if(e.metaKey||e.ctrlKey||"TEXTAREA"===e.target?.tagName||"INPUT"===e.target?.tagName)return;switch(e.code){case"ShiftLeft":case"ShiftRight":this.translationSnap=.5,this.rotationSnap=gi.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}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 t=["translationSnap","rotationSnap","scaleSnap","space","mode","showX","showY","showZ","lockProps"];for(const i of t)void 0!==e.userData.transformControls[i]&&(this._savedSettings[i]=this[i],this[i]=e.userData.transformControls[i])}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}},cU([Ng("Mode",["translate","rotate","scale"].map(e=>({label:e})))],e.TransformControls2.prototype,"mode",2),cU([Ng("Space",["world","local"].map(e=>({label:e})))],e.TransformControls2.prototype,"space",2),cU([Fg("Size",[.1,10],.01)],e.TransformControls2.prototype,"size",2),cU([Hg("Show X")],e.TransformControls2.prototype,"showX",2),cU([Hg("Show Y")],e.TransformControls2.prototype,"showY",2),cU([Hg("Show Z")],e.TransformControls2.prototype,"showZ",2),e.TransformControls2=cU([qg("Transform Controls")],e.TransformControls2);var hU=Object.defineProperty,dU=Object.getOwnPropertyDescriptor,uU=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?dU(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&hU(t,i,s),s};e.PivotControlsPlugin=class extends sw{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.dependencies=[sU],this._isInteracting=!1,this._viewerListeners={preFrame:()=>{!this.pivotControls||!this._viewer||this.pivotControls.updateGizmoScale()}},this._transformState={obj:null,position:new Xi,rotation:new On,scale:new Xi},this.selectionFilterTest=void 0,this._multi=new aU,this._mainCameraChange=()=>{!this.pivotControls||!this._viewer||(this.pivotControls.camera=this._viewer.scene.mainCamera)},$A.ObjectConstructors.MeshBasicMaterial=kw,$A.ObjectConstructors.LineBasicMaterial=xC,this.enabled=e}setDirty(){if(!this._viewer)return;const e=this._viewer.getPlugin(sU),t=!this.isDisabled();if(this.pivotControls)if(t){const t=e.getSelectedObjects().filter(e=>e?.isObject3D);t.length>1?this.pivotControls.attach(this._multi.setup(t,this._viewer)):1===t.length?(this._multi.clear(this._viewer),this.pivotControls.attach(t[0])):(this._multi.clear(this._viewer),this.pivotControls.detach())}else this.pivotControls.detach(),this._multi.clear(this._viewer);this._viewer.setDirty()}onAdded(t){super.onAdded(t),this.setDirty(),this.pivotControls=new e.PivotControls2(t.scene.mainCamera,t.canvas),this._mainCameraChange=this._mainCameraChange.bind(this),t.scene.addEventListener("mainCameraChange",this._mainCameraChange),this.pivotControls.addEventListener("dragging-changed",t=>{if(!this?._viewer)return;const i=this._viewer.scene.mainCamera.controls;"function"==typeof i?.stopDamping&&i?.enabled&&i.stopDamping(),this._viewer.scene.mainCamera.setInteractions(!t.value,e.PivotControlsPlugin.PluginType)}),this.pivotControls.addEventListener("change",()=>{this?._viewer&&this._viewer.setDirty()}),t.scene.addObject(this.pivotControls,{addToRoot:!0}),t.getPlugin(sU).addEventListener("selectedObjectChanged",e=>{if(!this.pivotControls)return;if(this.isDisabled())return this.pivotControls.object&&this.pivotControls.detach(),void this._multi.clear(this._viewer);const t=(e.objects||[]).filter(e=>e?.isObject3D);if(t.length>1)this.pivotControls.attach(this._multi.setup(t,this._viewer));else if(e.object){this._multi.clear(this._viewer);let t=e.intersects?.selectedHandle??e.intersects?.selectedObject??e.object;if(this.selectionFilterTest&&(t=this.selectionFilterTest(t)),!t||!t.isObject3D)return void this.pivotControls.detach();this.pivotControls.attach(t)}else this._multi.clear(this._viewer),this.pivotControls.detach()}),t.forPlugin("UndoManagerPlugin",e=>{this.undoManager=e.undoManager},()=>this.undoManager=void 0,this),this.pivotControls.addEventListener("mouseDown",()=>{if(!this.pivotControls)return;if(this._multi.hasMultiSelect)return void this._multi.captureStart();const e=this.pivotControls.object;e&&(this._transformState.obj=e,this._transformState.position=e.position.clone(),this._transformState.rotation=e.rotation.clone(),this._transformState.scale=e.scale.clone())}),this.pivotControls.addEventListener("objectChange",()=>{this._multi.hasMultiSelect&&this._multi.applyDelta()}),this.pivotControls.addEventListener("mouseUp",e=>{if(!this.pivotControls)return;if(this._multi.hasMultiSelect&&this._multi.hasStartStates)return void(this.undoManager&&this._multi.recordUndo(this.undoManager));const t=this.pivotControls.object;if(!t||this._transformState.obj!==t||!this.undoManager)return;const i={translate:"position",rotate:"rotation",scale:"scale"}[e.mode];if(!i||this._transformState[i].equals(t[i]))return;const n={last:this._transformState[i].clone(),current:t[i].clone(),set:e=>{t[i].copy(e),t.updateMatrixWorld(!0),this.pivotControls?.dispatchEvent({type:"change"}),this.pivotControls?.dispatchEvent({type:"objectChange"})},undo:()=>n.set(n.last),redo:()=>n.set(n.current)};this.undoManager.record(n)})}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)}},e.PivotControlsPlugin.PluginType="PivotControlsPlugin",uU([Hg(),Qm(e.PivotControlsPlugin.prototype.setDirty)],e.PivotControlsPlugin.prototype,"enabled",2),uU([Lg(void 0,{expanded:!0})],e.PivotControlsPlugin.prototype,"pivotControls",2),e.PivotControlsPlugin=uU([qg("Pivot Controls")],e.PivotControlsPlugin),e.PivotControls2=class extends $A{constructor(e,t){super(e,t),this.isWidget=!0,this.assetType="widget",this.setDirty=qw.setDirty.bind(this),this.refreshUi=qw.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(e=>{e.castShadow=!1,e.receiveShadow=!1,e.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}},uU([Ng("Space",["world","local"].map(e=>({label:e}))),Qm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"space",2),uU([Fg("Gizmo Scale",[.1,10],.01),Qm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"gizmoScale",2),uU([Hg("Fixed Size"),Qm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"fixed",2),uU([Hg("Depth Test"),Qm(e.PivotControls2.prototype._onRebuild)],e.PivotControls2.prototype,"depthTest",2),uU([Hg("Annotations")],e.PivotControls2.prototype,"annotations",2),uU([Fg("Translation Snap",[.01,5],.01)],e.PivotControls2.prototype,"translationSnap",2),uU([Fg("Rotation Snap (deg)",[1,90],1)],e.PivotControls2.prototype,"rotationSnap",2),uU([Fg("Scale Snap",[.01,1],.01)],e.PivotControls2.prototype,"scaleSnap",2),uU([Hg("Uniform Scale (Alt)")],e.PivotControls2.prototype,"uniformScaleEnabled",2),uU([Hg("Disable Axes"),Qm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"disableAxes",2),uU([Hg("Disable Sliders"),Qm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"disableSliders",2),uU([Hg("Disable Rotations"),Qm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"disableRotations",2),uU([Hg("Disable Scaling"),Qm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"disableScaling",2),e.PivotControls2=uU([qg("Pivot Controls")],e.PivotControls2);var pU=Object.defineProperty,mU=Object.getOwnPropertyDescriptor,gU=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?mU(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&pU(t,i,s),s};const fU=new Xi,AU=new Xi;e.PivotEditPlugin=class extends sw{constructor(e=!0){super(),this.dependencies=[sU],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(sU);t.addEventListener("hitObject",e=>{e.intersects?.selectedHandle?.userData.isPivotMarker&&(e.intersects.consumed=!0,this.editPivot=!this.editPivot,this._onEditPivotChange())}),t.addEventListener("selectedObjectChanged",e=>{const t=e.object,i=t!==this._selectedObject;this._selectedObject=t,this._markerWidget&&(this._markerWidget.object=this._selectedObject),this.editPivot&&i&&(this.editPivot=!1,this._onEditPivotChange()),this._updateMarker()}),e.forPlugin("UndoManagerPlugin",e=>{this.undoManager=e.undoManager},()=>this.undoManager=void 0,this),this._onKeyDown=e=>{this.isDisabled()||e.metaKey||e.ctrlKey||"TEXTAREA"===e.target?.tagName||"INPUT"===e.target?.tagName||("KeyP"===e.code?(this.editPivot=!this.editPivot,this._onEditPivotChange()):"Escape"===e.code&&this.editPivot&&(this.editPivot=!1,this._onEditPivotChange()))},window.addEventListener("keydown",this._onKeyDown);const i=new vr({color:this.markerColor,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,opacity:.9});this._pivotMarker=new ts(new yd(1,8,8),i),this._pivotMarker.renderOrder=1e3,this._pivotMarker.userData.isWidgetHandle=!0,this._pivotMarker.userData.isPivotMarker=!0;const n=new PC;n.isWidget=!0,n.assetType="widget",n.object=this._selectedObject,n.attach=e=>(n.object=e,n),n.detach=()=>(n.object=void 0,n),this._markerWidget=n,this._markerWidget.add(this._pivotMarker),this._markerRoot=new PC,this._markerRoot.userData.isWidgetRoot=!0,this._markerRoot.add(this._markerWidget),this._markerRoot.visible=!1,this._markerRoot.traverse(e=>{e.castShadow=!1,e.receiveShadow=!1,e.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 Ly).expandByObject(this._selectedObject,!0,!0),t=e.getCenter(new Xi);this._applyPivot(new Xi(t.x,e.min.y,t.z))}pivotToOrigin(){this._applyPivot(new Xi(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)return void(this._markerRoot.visible=!1);this._selectedObject.updateWorldMatrix(!0,!1),fU.setFromMatrixPosition(this._selectedObject.matrixWorld),this._markerRoot.position.copy(fU),this._markerRoot.visible=!0;const e=this._viewer.scene.mainCamera;let t;e.isOrthographicCamera?t=(e.top-e.bottom)/e.zoom:(AU.setFromMatrixPosition(e.matrixWorld),t=fU.distanceTo(AU)*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||(rA.ObjectConstructors.MeshBasicMaterial=kw,rA.ObjectConstructors.LineBasicMaterial=xC,this._pivotGizmo=new rA(this._viewer.scene.mainCamera,this._viewer.canvas),this._pivotGizmo.setMode("translate"),this._pivotGizmo.userData.bboxVisible=!1,this._pivotGizmo.visible=!1,this._pivotGizmo.traverse(e=>{e.castShadow=!1,e.receiveShadow=!1,e.userData.__keepShadowDef=!0}),this._pivotGizmo.addEventListener("mouseUp",()=>{if(!this._selectedObject?.pivotToPoint||!this._pivotGizmo?.object)return;const e=(new Xi).setFromMatrixPosition(this._pivotGizmo.object.matrixWorld),t=this._selectedObject.pivotToPoint(e,!0);this._recordUndo(t),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;"function"==typeof i?.stopDamping&&i?.enabled&&i.stopDamping(),this._viewer.scene.mainCamera.setInteractions(!t.value,e.PivotEditPlugin.PluginType)}),this._viewer.scene.addObject(this._pivotGizmo,{addToRoot:!0})),this._selectedObject.updateWorldMatrix(!0,!1);const t=(new Xi).setFromMatrixPosition(this._selectedObject.matrixWorld);if(this._pivotGizmo.object)this._pivotGizmo.object.position.copy(t),this._pivotGizmo.object.updateMatrixWorld(!0);else{const e=new Zn;e.position.copy(t),this._viewer.scene.addObject(e,{addToRoot:!0}),this._pivotGizmo.attach(e)}}_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 Xi).setFromMatrixPosition(t.matrixWorld);this.undoManager.record({undo:()=>{e(),this._refreshAfterPivotChange()},redo:()=>{t.pivotToPoint&&(t.pivotToPoint(i,!0),this._refreshAfterPivotChange())}})}},e.PivotEditPlugin.PluginType="PivotEditPlugin",gU([Hg(),Qm(e.PivotEditPlugin.prototype._onEnabledChange)],e.PivotEditPlugin.prototype,"enabled",2),gU([Hg("Edit Pivot"),Qm(e.PivotEditPlugin.prototype._onEditPivotChange)],e.PivotEditPlugin.prototype,"editPivot",2),gU([Hg("Show Pivot Marker"),Qm(e.PivotEditPlugin.prototype._onDirty)],e.PivotEditPlugin.prototype,"showPivotMarker",2),gU([Fg("Marker Scale",[.1,5],.1),Qm(e.PivotEditPlugin.prototype._onDirty)],e.PivotEditPlugin.prototype,"markerScale",2),gU([Qg("Marker Color"),Qm(e.PivotEditPlugin.prototype._onMarkerColorChange)],e.PivotEditPlugin.prototype,"markerColor",2),gU([jg("Pivot to Center")],e.PivotEditPlugin.prototype,"pivotToCenter",1),gU([jg("Pivot to Bottom")],e.PivotEditPlugin.prototype,"pivotToBottom",1),gU([jg("Pivot to Origin")],e.PivotEditPlugin.prototype,"pivotToOrigin",1),e.PivotEditPlugin=gU([qg("Pivot Edit")],e.PivotEditPlugin);var yU=Object.defineProperty,vU=Object.getOwnPropertyDescriptor,_U=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?vU(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&yU(t,i,s),s};e.EditorViewWidgetPlugin=class extends sw{constructor(e="top-left",t=128){super(),this.placement=e,this.size=t,this.enabled=!0,this._needsRender=!1,this._viewerListeners={postRender:e=>{!this._viewer||!this.widget||this.isDisabled()||(this._needsRender=!0)},postFrame:e=>{!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(t){super.onAdded(t),this.widget=new o_(t.scene.mainCamera,t.canvas,this.placement,this.size),this.widget.target=t.scene.mainCamera.target,this.widget.addEventListener("animating-changed",i=>{const n=i.detail.value;t.scene.mainCamera.setInteractions(!n,e.EditorViewWidgetPlugin.PluginType)}),this.widget.addEventListener("update",()=>this._needsRender=!0),t.scene.addEventListener("mainCameraChange",this._mainCameraChange),t.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)}},e.EditorViewWidgetPlugin.PluginType="EditorViewWidgetPlugin",_U([Hg(),Qm(e.EditorViewWidgetPlugin.prototype.setDirty)],e.EditorViewWidgetPlugin.prototype,"enabled",2),e.EditorViewWidgetPlugin=_U([qg("Editor View Widget")],e.EditorViewWidgetPlugin);const bU=class extends CL{constructor(){super(...arguments),this.controlsKey="deviceOrientation",this._controlsCtor=(t,i)=>new e.DeviceOrientationControls2(t)}};bU.PluginType="DeviceOrientationControlsPlugin";let xU=bU;const wU=class extends CL{constructor(){super(...arguments),this.controlsKey="pointerLock",this._controlsCtor=(t,i)=>new e.PointerLockControls2(t,i?.ownerDocument?i:(i||document).documentElement)}};wU.PluginType="PointerLockControlsPlugin";let CU=wU;const SU=class extends CL{constructor(){super(...arguments),this.controlsKey="threeFirstPerson",this._controlsCtor=(t,i)=>new e.FirstPersonControls2(t,i||document.documentElement)}};SU.PluginType="ThreeFirstPersonControlsPlugin";let MU=SU;var EU=Object.defineProperty,TU=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&EU(t,i,s),s};const IU=(a=class extends sw{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]:e=>{const t=()=>{e.onUndoRedo&&e.onUndoRedo(e)};return{undo:()=>{console.log("undo",e.lastVal),e.binding&&(this.setValue(e.binding,e.lastVal,e.props,e.uid,void 0,!1),t())},redo:()=>{e.binding&&(this.setValue(e.binding,e.val,e.props,e.uid,void 0,!1),t())}}},[this.undoCommandTypes.action]:e=>{const t=()=>{e.onUndoRedo&&e.onUndoRedo(e)};return{undo:async()=>{await e.undo.call(e.target,...e.args),t()},redo:async()=>{await e.redo.call(e.target,...e.args),t()}}}},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 tm({bindHotKeys:!0,limit:this.limit,debug:e.debug||null!==dg("debugUndo"),hotKeyRoot:document}),this._refresh()}onRemove(e){this.undoManager?.dispose(),this.undoManager=void 0,super.onRemove(e)}recordUndo(e){return Cg(this.undoManager,e,this.undoCommandTypes.setValue,this.undoEditingWaitTime)}async performAction(e,t,i,n,r){const s=()=>void 0===e?t(...i):t.call(e,...i);let a=await s();const o="function"==typeof a?a:a?.undo?.bind(a),l="function"!=typeof a?a?.action?.bind(a):null,c="function"==typeof a?s:a?.redo?.bind(a)??l;"function"==typeof l&&(a=await l()),"function"==typeof o&&this.recordUndo({type:"UiConfigMethods_action",uid:n,target:e,undo:o,redo:c,args:i,onUndoRedo:r})}setValue(e,t,i,n,r,s=!0,a){return!(!Sg(this.undoManager,e,t,i,n,this.undoCommandTypes.setValue,s,this.undoEditingWaitTime,!0,a).undoable&&!r)}setValues(e,t,i,n,r,s,a=!0,o){const l=DU(e,t);return this.setValue([l,"value"],i,n,r,s,a,o)}},a.PluginType="UndoManagerPlugin",a);TU([Qm(IU.prototype._refresh)],IU.prototype,"enabled"),TU([Qm(IU.prototype._refresh)],IU.prototype,"limit");let PU=IU;function DU(e,t){return{p:new Proxy([],{get(i,n,...r){if("length"===n)return e.length;const s=Number(n);if(isNaN(s)||s<0||s>=e.length)return Reflect.get(Array.prototype,n,...r)||Reflect.get(i,n,...r);const[a,o]=e[s];return a?.[o]??t[s]},set(t,i,n,...r){const s=Number(i);if(isNaN(s)||s<0||s>=e.length)return Reflect.set(t,i,n,...r);const[a,o]=e[s];return!!a&&(a[o]=n,!0)},has(t,i,...n){const r=Number(i);return!(isNaN(r)||r<0||r>=e.length)||(Reflect.has(Array.prototype,i,...n)||Reflect.has(t,i,...n))}}),get value(){return this.p},set value(t){e.length!==t.length&&console.error(`UndoManager - setValues: bindings length (${e.length}) does not match value length (${t.length})`);for(let i=0;i<Math.min(t.length,e.length);i++)this.p[i]=t[i]}}}var RU=Object.defineProperty,BU=Object.getOwnPropertyDescriptor,LU=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?BU(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&RU(t,i,s),s};e.Rhino3dmLoadPlugin=class extends _L{constructor(){super(...arguments),this._importer=new qS(qD,["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(){qD.ImportMaterials=this.importMaterials,qD.ForceLayerMaterials=this.forceLayerMaterials,qD.ReplaceWithInstancedMesh=this.replaceWithInstancedMesh,qD.HideLineMesh=this.hideLineMesh,qD.HidePointMesh=this.hidePointMesh,qD.LoadUserDataStrings=this.loadUserDataStrings,qD.LoadUserDataWarnings=!1}onAdded(e){if(!window.WebAssembly)throw new Error("Rhino3dmLoadPlugin requires WebAssembly support");super.onAdded(e),this._refresh()}},e.Rhino3dmLoadPlugin.PluginType="Rhino3dmLoadPlugin",LU([Qm(e.Rhino3dmLoadPlugin.prototype._refresh),Hg()],e.Rhino3dmLoadPlugin.prototype,"importMaterials",2),LU([Qm(e.Rhino3dmLoadPlugin.prototype._refresh),Hg()],e.Rhino3dmLoadPlugin.prototype,"forceLayerMaterials",2),LU([Qm(e.Rhino3dmLoadPlugin.prototype._refresh),Hg()],e.Rhino3dmLoadPlugin.prototype,"replaceWithInstancedMesh",2),LU([Qm(e.Rhino3dmLoadPlugin.prototype._refresh),Hg()],e.Rhino3dmLoadPlugin.prototype,"hideLineMesh",2),LU([Qm(e.Rhino3dmLoadPlugin.prototype._refresh),Hg()],e.Rhino3dmLoadPlugin.prototype,"hidePointMesh",2),LU([Qm(e.Rhino3dmLoadPlugin.prototype._refresh),Hg()],e.Rhino3dmLoadPlugin.prototype,"loadUserDataStrings",2),e.Rhino3dmLoadPlugin=LU([qg("Rhino 3dm Loader")],e.Rhino3dmLoadPlugin);const OU=class extends _L{constructor(){super(...arguments),this._importer=new qS(class extends tL{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")&&"string"!=typeof e){const t=this.currentUrl.split("/").pop();if(t){const i={};i[t]=new Uint8Array(e),e=ZP(i).buffer}}return super.parse(e)}},["usdz","usda"],["model/vnd.usd+zip","model/vnd.usdz+zip","model/vnd.usda"],!1)}};OU.PluginType="USDZLoadPlugin";let UU=OU;const FU=class extends _L{constructor(){super(...arguments),this._importer=new qS(class extends nL{transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new ts(e,new yC({color:new mr(1,1,1),vertexColors:e.hasAttribute("color")})):void 0}},["ply"],["text/plain+ply"],!1)}};FU.PluginType="PLYLoadPlugin";let kU=FU;const NU=class extends _L{constructor(){super(...arguments),this._importer=new qS(class extends sL{transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new ts(e,new yC({color:new mr(1,1,1),vertexColors:e.hasAttribute("color")})):void 0}},["stl"],["model/stl","model/x.stl-binary","model/x.stl-ascii"],!1)}};NU.PluginType="STLLoadPlugin";let jU=NU;const zU=class extends _L{constructor(){super(...arguments),this._importer=new qS(ZB,["ktx"],["image/ktx"],!1)}};zU.PluginType="KTXLoadPlugin";let GU=zU;const QU=class e extends _L{constructor(){super(...arguments),this._importer=new qS(HU,["ktx2"],["image/ktx2"],!1)}onAdded(t){this._importer.onCtor=i=>i.setTranscoderPath(e.TRANSCODER_LIBRARY_PATH).detectSupport(t.renderManager.renderer),super.onAdded(t),t.assetManager.exporter.getExporter("gltf","glb")?.extensions?.push(qU)}onRemove(e){const t=e.assetManager.exporter.getExporter("gltf","glb"),i=t?.extensions?.indexOf(qU);void 0!==i&&-1!==i&&t?.extensions?.splice(i,1),super.onRemove(e)}};QU.PluginType="KTX2LoadPlugin",QU.TRANSCODER_LIBRARY_PATH="https://cdn.jsdelivr.net/gh/BinomialLLC/basis_universal@1.16.4/webgl/transcoder/build/",QU.SAVE_SOURCE_BLOBS=!1;let VU=QU;class HU extends qB{_initTexture(e){uS.call(e),e.userData.mimeType="image/ktx2",e.toJSON=t=>T_(e,t,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=VU.SAVE_SOURCE_BLOBS?new Uint8Array(e.slice(0)):void 0,n=await super.createTexture(e,t);return VU.SAVE_SOURCE_BLOBS&&i&&(n.source._sourceImgBuffer=i,n.source._canSerialize=!0),this._initTexture(n),n}}const WU="KHR_texture_basisu",qU=e=>({writeTexture:(t,i)=>{if("image/ktx2"!==t.userData.mimeType)return;if(void 0!==i.source&&null!==i.source)return void console.warn("ktx2 export: source already set");const n=t.source._sourceImgBuffer||t.__sourceBuffer;if(!n)return void console.warn("ktx2 export: no source buffer for ktx2");i.extensions=i.extensions||{};const r={},s=new Blob([n],{type:"image/ktx2"});r.source=e.processImageBlob(s,t),i.extensions[WU]=r,e.extensionsUsed[WU]=!0}}),XU=class e extends Jp{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 t=document.createElement("script");t.type="module";const i=Math.random().toString(36).substring(7);t.innerHTML=`\nimport { MeshoptDecoder } from ${JSON.stringify(e.DECODER_URL)};\nwindow.MeshoptDecoder = MeshoptDecoder; // setting it before ready as GLTFLoader supports it.\nMeshoptDecoder.ready.then(() => {\nwindow.dispatchEvent(new CustomEvent('${i}'))\n});\n`,this._initializing=new Promise(e=>{window.addEventListener(i,()=>e(),{once:!0}),this.rootNode.appendChild(t),this._script=t}),await this._initializing,this.dispatchEvent({type:"initialized"})}dispose(){this._script&&(this._script.remove(),delete window.MeshoptDecoder),this._script=void 0}onAdded(){}onRemove(){}};XU.PluginType="GLTFMeshOptDecodePlugin",XU.DECODER_URL="https://unpkg.com/meshoptimizer@0.20.0/meshopt_decoder.module.js";let YU=XU;var KU=Object.defineProperty;const JU=class extends sw{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 t=new Blob([JSON.stringify(this._viewer?.exportConfig(!1),null,2)],{type:"application/json"});t&&await(this._viewer?.exportBlob(t,this.exportOptions.name+"."+e.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)return void this._viewer?.dialog.alert("Export Selected: Nothing selected");const n=i.name||"selected",r=await this._viewer.assetManager.exporter.exportObject(i,e??this.exportOptions);return r&&t&&await(this._viewer?.exportBlob(r,n+"."+r.ext)),r}};JU.PluginType="AssetExporterPlugin";let ZU=JU;((e,t,i)=>{for(var n,r=void 0,s=e.length-1;s>=0;s--)(n=e[s])&&(r=n(t,i,r)||r);r&&KU(t,i,r)})([qm()],ZU.prototype,"exportOptions");var $U=Object.defineProperty,eF=Object.getOwnPropertyDescriptor,tF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?eF(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&$U(t,i,s),s};e.CanvasSnapshotPlugin=class extends sw{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(t,i={}){await(this._viewer?.doOnce("postFrame"));const n=this._viewer,r=this._viewer?.canvas;if(!n||!r)return;n.scene.mainCamera.setInteractions(!1,e.CanvasSnapshotPlugin.PluginType);const s=n.renderManager.renderScale;void 0!==i.displayPixelRatio&&i.displayPixelRatio!==s&&(n.renderManager.renderScale=i.displayPixelRatio),i.timeout&&await Zp(i.timeout);const a=n.getPlugin(e.ProgressivePlugin);let o=i.waitForProgressive??!!a;o&&!a&&(n.console.warn("CanvasSnapshotPlugin: ProgressivePlugin required to wait for progressive rendering"),o=!1),i.progressiveFrames&&!o&&n.console.warn("CanvasSnapshotPlugin: waitForProgressive must be true to use progressiveFrames");const l=a?.maxFrameCount;if(o&&a)for(a.maxFrameCount=Math.max(i.progressiveFrames??64,a.maxFrameCount),n.setDirty(),await n.doOnce("postFrame");!a.isConverged(!0);)await n.doOnce("postFrame");else n.setDirty(),await n.doOnce("postFrame");let c;if(delete i.displayPixelRatio,i.tileRows&&i.tileRows>1||i.tileColumns&&i.tileColumns>1){const e=await jx.GetTiledFiles(r,t,Math.max(1,i.tileRows||1),Math.max(1,i.tileColumns||1),i);if(Array.isArray(e))if(1===e.length)c=e[0];else if(0===e.length)c=void 0;else if(i.getDataUrl)c=e;else{const i={};for(const t of e)i[t.name]=new Uint8Array(await t.arrayBuffer());const n=ZP(i);c=new File([n],t+".zip",{type:"application/zip",lastModified:Date.now()})}else c=e}else c=await jx.GetFile(r,t,i);return i.displayPixelRatio=n.renderManager.renderScale,a&&void 0!==l&&(a.maxFrameCount=l),n.scene.mainCamera.setInteractions(!0,e.CanvasSnapshotPlugin.PluginType,!1),n.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 Zp(100);this._downloading=!0;const i=await this.getFile(e,{...this.defaultOptions,...t}).catch(e=>(this._viewer?.console.error("CanvasSnapshotPlugin: Error exporting file",e),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"})}},e.CanvasSnapshotPlugin.PluginType="CanvasSnapshotPlugin",tF([zg("Filename"),qm()],e.CanvasSnapshotPlugin.prototype,"filename",2),tF([Lg(void 0,{label:"Options"}),qm()],e.CanvasSnapshotPlugin.prototype,"defaultOptions",2),tF([jg("Download .png")],e.CanvasSnapshotPlugin.prototype,"_downloadPng",1),tF([jg("Download .jpeg")],e.CanvasSnapshotPlugin.prototype,"_downloadJpeg",1),tF([jg("Download .webp")],e.CanvasSnapshotPlugin.prototype,"_downloadWebp",1),e.CanvasSnapshotPlugin=tF([qg("Image Export (Canvas Snapshot)")],e.CanvasSnapshotPlugin);const iF=class extends e.CanvasSnapshotPlugin{constructor(){super(),console.warn("CanvasSnipperPlugin is deprecated, use CanvasSnapshotPlugin")}};iF.PluginType="CanvasSnipper";let nF=iF;const rF=class extends sw{constructor(){super(),this.enabled=!0,this.toJSON=void 0,this.defaultActions={exportFile:async(e,t,i)=>{bm(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:e,progress:i})=>{this.dispatchEvent({type:"transferFile",path:t,state:e??"exporting",progress:i})}),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,"done"!==e.state?{state:e.state,progress:e.progress?100*e.progress:void 0}:void 0)}};rF.PluginType="FileTransferPlugin";let sF=rF;var aF=Object.defineProperty,oF=Object.getOwnPropertyDescriptor,lF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?oF(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&aF(t,i,s),s};e.VignettePlugin=class extends sB{constructor(e=!0){super(),this.extraUniforms={power:{value:1},bgcolor:{value:new mr}},this.power=.5,this.color=new mr(0),this.priority=-50,this.parsFragmentSnippet=()=>this.isDisabled()?"":ym`
            uniform float power;
            uniform vec3 bgcolor;
            ${"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);}"}
        `,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}},e.VignettePlugin.PluginType="Vignette",lF([Qm(e.VignettePlugin.prototype.setDirty),Hg("Enable"),qm()],e.VignettePlugin.prototype,"enabled",2),lF([Fg("Power",[.1,4],.01),ky({propKey:"power"}),qm()],e.VignettePlugin.prototype,"power",2),lF([Qg("Color",e=>({onChange:()=>e?.setDirty()})),ky({propKey:"bgcolor"}),qm("bgcolor")],e.VignettePlugin.prototype,"color",2),e.VignettePlugin=lF([qg("Vignette")],e.VignettePlugin);var cF=Object.defineProperty,hF=Object.getOwnPropertyDescriptor,dF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?hF(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&cF(t,i,s),s};e.ChromaticAberrationPlugin=class extends sB{constructor(e=!0){super(),this.extraUniforms={aberrationIntensity:{value:1}},this.intensity=.5,this.priority=-50,this.parsFragmentSnippet=()=>this.isDisabled()?"":ym`
            uniform float aberrationIntensity;
            ${"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;}"}
        `,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}},e.ChromaticAberrationPlugin.PluginType="ChromaticAberration",dF([Qm(e.ChromaticAberrationPlugin.prototype.setDirty),Hg("Enable"),qm()],e.ChromaticAberrationPlugin.prototype,"enabled",2),dF([Fg("Intensity",[0,.3],.001),ky({propKey:"aberrationIntensity"}),qm("aberrationIntensity")],e.ChromaticAberrationPlugin.prototype,"intensity",2),e.ChromaticAberrationPlugin=dF([qg("ChromaticAberration")],e.ChromaticAberrationPlugin);var uF=Object.defineProperty,pF=Object.getOwnPropertyDescriptor,mF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?pF(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&uF(t,i,s),s};e.FilmicGrainPlugin=class extends sB{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()?"":ym`
            uniform float grainIntensity;
            uniform bool grainMultiply;
            ${"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);}"}
        `,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}},e.FilmicGrainPlugin.PluginType="FilmicGrain",mF([Qm(e.FilmicGrainPlugin.prototype.setDirty),Hg("Enable"),qm()],e.FilmicGrainPlugin.prototype,"enabled",2),mF([Fg("Intensity",[0,20],.01),ky({propKey:"grainIntensity"}),qm("grainIntensity")],e.FilmicGrainPlugin.prototype,"intensity",2),mF([Hg("Multiply"),ky({propKey:"grainMultiply"}),qm("grainMultiply")],e.FilmicGrainPlugin.prototype,"multiply",2),e.FilmicGrainPlugin=mF([qg("FilmicGrain")],e.FilmicGrainPlugin);var gF=Object.defineProperty,fF=Object.getOwnPropertyDescriptor,AF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?fF(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&gF(t,i,s),s};const yF=(o=class extends sw{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 em,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||"playing"===this._animationState)&&this.playAnimation())},this._objectRemove=e=>{const t=e.object;if(!this._viewer||!t)return;const i=this._animations.find(e=>e.object===t);i&&(i.mixer.stopAllAction(),this._animations.splice(this._animations.indexOf(i),1),this.dispatchEvent({type:"removeAnimation",animation:i}))},this._sceneUpdate=e=>{this._viewer&&this._refreshAnimations(this._viewer.scene.modelRoot,this._viewer.scene.modelRoot)&&(this._onPropertyChange(!this.autoplayOnLoad),(this.autoplayOnLoad||this.autoplayOnLoadForce||"playing"===this._animationState)&&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:[...Rg(this),()=>this._animations.map(e=>({type:"folder",label:`Animation - ${e.object.name||e.object.uuid}`,children:[...e.actions.map(e=>{const t=e.getClip(),i=e.clipData;return i?{type:"folder",label:`Clip - ${t.name}`,children:[{type:"checkbox",label:"Active",property:[i,"active"]},{type:"input",label:"Name",property:[i,"name"]},{type:"monitor",label:"Duration",getValue:()=>t.duration.toFixed(3)},{type:"number",label:"Start Time",property:[i,"startTime"]},{type:"number",label:"Time Scale",property:[i,"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(){"playing"===this._animationState?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(e=>this._objectAdd({object:e})),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(e=>this._objectRemove({object:e})),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:t})=>{t.forEach(t=>{e.includes(t.getClip().name)&&i.push(t)})}),this.playAnimation(t,i)}async playAnimation(e=!1,t){if(this.isDisabled())return;let i=!1;"playing"===this._animationState&&(this.stopAnimation(!1),i=!0);let n=0;const r=!t;t||(t=[],this._animations.forEach(({actions:e})=>{t.push(...e)})),i?this.resetAnimation():"paused"!==this.animationState&&(t.forEach(e=>{e.reset()}),this._animationTime=0);const s=Ky();this._lastAnimId=s;for(const e of t)e.setLoop(this.loopAnimations?xt:bt,this.loopRepetitions),e.play(),n=Math.max(n,e.getClip().duration/Math.abs(e.timeScale));if(this._animationState="playing",this._viewer?.setDirty(),r){if(!isFinite(this._animationDuration))return;await new Promise(e=>{const t=()=>{this.removeEventListener("checkpointEnd",t),e()};this.addEventListener("checkpointEnd",t)})}else{const e=this.loopAnimations?this.loopRepetitions:1;if(n*=e,!isFinite(n))return;await new Promise(e=>{const t=i=>{i.time>=n&&(this.removeEventListener("animationStep",t),e())};this.addEventListener("animationStep",t)})}s===this._lastAnimId&&this.stopOnCheckpointEnd&&this.stopAnimation(e)}pauseAnimation(){"playing"===this._animationState?(this._animationState="paused",this._viewer?.setDirty()):console.warn("pauseAnimation called when animation was not playing.")}resumeAnimation(){"paused"===this._animationState?(this._animationState="playing",this._viewer?.setDirty()):console.warn("resumeAnimation called when animation was not paused.")}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(){"stopped"===this._animationState||"none"===this._animationState?(this._animations.forEach(({mixer:e})=>{e.stopAllAction(),e.setTime(0)}),this._animationTime=0,this._viewer?.setDirty()):this.stopAnimation(!0)}_postFrame(){if(!this._viewer)return;const e=this.animateOnScroll,t=this.animateOnPageScroll,i=this.animateOnDrag;if(this.isDisabled()||this._animations.length<1||"playing"!==this._animationState)return this._lastFrameTime=0,void(this._fadeDisabled&&(this._viewer.getPlugin("FrameFade")?.enable(this),this._fadeDisabled=!1));const n=this._animationTime;if(this.autoIncrementTime||t||e||i){const n=$p()/1e3;this._lastFrameTime<1&&(this._lastFrameTime=n-1/30);let r=n-this._lastFrameTime;r*=this.animationSpeed,this._lastFrameTime=n,t?r*=this._pageScrollAnimationState:e&&i?r*=lg(this._scrollAnimationState,this._dragAnimationState):e?r*=this._scrollAnimationState:i&&(r*=this._dragAnimationState);const s=this._viewer.getPlugin("Progressive")?.postFrameConvergedRecordingDelta();s&&s>0&&(r=s),0===s&&(r=0);const a=Math.abs(this.timeScale);this._animationTime+=r*(a>0?a:1)}else{const e=$p()/1e3;this._lastFrameTime=e;const t=Math.abs(this.timeScale)*this.animationSpeed;this._animationTime=this._viewer.timeline.time*(t>0?t:1)}const r=this._animationTime-this._lastAnimationTime;if(this._lastAnimationTime=this._animationTime,Math.abs(r)<1e-4)return;n<1e-4&&this.dispatchEvent({type:"checkpointBegin"});const s=this.timeScale<0?(isFinite(this._animationDuration)?this._animationDuration:0)-this._animationTime:this._animationTime;if(this._animations.map(e=>{e.actions.forEach(e=>{const t=e.clipData?.startTime||0,i=e.clipData?.active??!0;void 0!==e.clipData?.timeScale&&(e.timeScale=e.clipData.timeScale),(void 0!==t&&null===e._startTime||e._startTime!==t)&&(e._startTime=t);let n=e.getClip().duration;this.autoIncrementTime&&this.loopAnimations&&(n*=this.loopRepetitions);const r=i&&s>=t&&(!isFinite(n)||s<n/Math.abs(e.timeScale)+t);this.autoUnpauseActions&&e.paused&&r&&(e.paused=!1),this.autoEnableActions&&!e.enabled&&r&&(e.enabled=!0),null!==this.inactiveActionWeight&&!r&&e.weight?e.setEffectiveWeight(this.inactiveActionWeight):null!==this.activeActionWeight&&r&&!e.weight&&e.setEffectiveWeight(this.activeActionWeight)}),e.mixer.setTime(s)}),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:r,time:s}),this._viewer.renderManager.resetShadows(),this._viewer.setDirty(),!this._fadeDisabled){const e=this._viewer.getPlugin("FrameFade");e&&(e.disable(o.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(t=>t.object===e)||{object:e,mixer:new Ap(t),clips:[],actions:[],duration:0};n.clips=i,n.duration=Math.max(...i.map(e=>e.duration)),(t.userData.gltfAnim_SyncMaxDuration??this.syncMaxDuration)&&(i.forEach(e=>e.duration=n.duration),t.userData.gltfAnim_SyncMaxDuration=!0);const r=i.flatMap(t=>{t.userData.clipActions||(t.userData.clipActions={});const i=t.userData.clipActions?.[e.uuid];if(i&&i.length){const e=[];for(const t of i){const i=n.actions.find(e=>e.clipData?.uid===t.uid);i&&e.push(i)}if(e.length)return e}i||(t.userData.clipActions[e.uuid]=[]);const r=n.mixer.clipAction(t);return r.clipData={uid:Ky(),active:!0,name:t.name,startTime:0,timeScale:1},r.setLoop(this.loopAnimations?xt:bt,this.loopRepetitions),t.userData.clipActions[e.uuid].push(r.clipData),r});return n.actions=r,n.actions.forEach(e=>e.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:e})=>e))*(this.loopAnimations?this.loopRepetitions:1),"playing"===this._animationState&&!1!==e&&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="x"===this.dragAxis?e.delta.x*this._viewer.canvas.width/4:e.delta.y*this._viewer.canvas.height/4)}},o.PluginType="GLTFAnimation",o);AF([Vm(yF.prototype._onPropertyChange),Hg("Loop"),qm()],yF.prototype,"loopAnimations",2),AF([Vm(yF.prototype._onPropertyChange),qm()],yF.prototype,"loopRepetitions",2),AF([Fg("Timescale",[-2,2],.01),qm()],yF.prototype,"timeScale",2),AF([Fg("Speed",[.1,4],.1),qm()],yF.prototype,"animationSpeed",2),AF([Hg(),qm()],yF.prototype,"animateOnScroll",2),AF([Fg("Scroll Damping",[0,1]),qm()],yF.prototype,"scrollAnimationDamping",2),AF([Hg(),qm()],yF.prototype,"animateOnPageScroll",2),AF([Fg("Page Scroll Damping",[0,1]),qm()],yF.prototype,"pageScrollAnimationDamping",2),AF([Hg(),qm()],yF.prototype,"animateOnDrag",2),AF([Ng("Drag Axis",[{label:"x"},{label:"y"}]),qm()],yF.prototype,"dragAxis",2),AF([Fg("Drag Damping",[0,1]),qm()],yF.prototype,"dragAnimationDamping",2),AF([Hg(),qm()],yF.prototype,"autoplayOnLoad",2),AF([Hg("syncMaxDuration(dev)"),qm()],yF.prototype,"syncMaxDuration",2),AF([Ug()],yF.prototype,"animationState",1),AF([Ug()],yF.prototype,"animationTime",1),AF([Ug()],yF.prototype,"animationDuration",1),AF([jg("Play/Pause",e=>({label:()=>"playing"===e.animationState?"Pause":"Play"}))],yF.prototype,"playPauseAnimation",1),AF([Qm(yF.prototype.onStateChange)],yF.prototype,"_animationState",2),AF([Hg()],yF.prototype,"autoUnpauseActions",2),AF([Hg()],yF.prototype,"autoEnableActions",2),AF([jg("Stop",{sendArgs:!1})],yF.prototype,"stopAnimation",1),AF([jg("Reset",{sendArgs:!1})],yF.prototype,"resetAnimation",1);let vF=yF;const _F=class e extends sw{constructor(){super(),this.toJSON=void 0,this.enabled=!0,this.dependencies=[NR],this._addSceneObject=t=>{const i=t.object;i?.traverse&&!i.isWidget&&i.traverse(t=>{if(t.isWidget)return;t.userData[e.PluginType]?.transforms?.forEach((e,t)=>{void 0===e.name&&(e.name="Transform "+t)});const i={type:"folder",label:"Transform Animation",children:[{type:"button",label:"Add Current Transform",value:()=>{this.addTransform(t),i?.uiRefresh?.()}},()=>t.userData[e.PluginType]?.transforms.map((e,i)=>({type:"folder",label:e.name||`Transform ${i}`,children:[{type:"input",label:"Name",property:[e,"name"]},{type:"vec3",label:"Position",property:[e,"position"]},{type:"vec3",label:"Quaternion",property:[e,"quaternion"]},{type:"vec3",label:"Scale",property:[e,"scale"]},{type:"button",label:"Set",value:()=>{this.setTransform(t,e)}},{type:"button",label:"Animate",value:()=>{this.animateTransform(t,e)}}]}))]};t.uiConfig?.children?.push(i)})}}onAdded(e){super.onAdded(e),e.scene.addEventListener("addSceneObject",this._addSceneObject)}onRemove(e){return e.scene.removeEventListener("addSceneObject",this._addSceneObject),super.onRemove(e)}addTransform(t,i){t.userData[e.PluginType]||(t.userData[e.PluginType]={transforms:[]});const n={name:i||"Transform "+(t.userData[e.PluginType].transforms.length+1),position:t.position.clone(),quaternion:t.quaternion.clone(),scale:t.scale.clone()};return t.userData[e.PluginType].transforms.push(n),n}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(t,i){return"number"==typeof t?i.userData[e.PluginType]?.transforms[t]:"string"==typeof t?i.userData[e.PluginType]?.transforms.find(e=>e.name===t):t}animateTransform(e,t,i=2e3){const n=this._viewer?.getPlugin(NR);n||this._viewer?.console.error("PopmotionPlugin required for animation");const r=this.getSavedTransform(t,e);if(!r)return;const s=new Xi,a=new qi,o=new Xi,l=e.position.clone(),c=e.quaternion.clone(),h=e.scale.clone(),d=r.position,u=r.quaternion,p=r.scale;return n?.animate({from:0,to:1,duration:i,onUpdate:t=>{s.lerpVectors(l,d,t),a.slerpQuaternions(c,u,t),o.lerpVectors(h,p,t),e.position.copy(s),e.quaternion.copy(a),e.scale.copy(o),this._viewer?.setDirty(),this._viewer?.renderManager.resetShadows()},onStop:()=>{e.position.copy(r.position),e.quaternion.copy(r.quaternion),e.scale.copy(r.scale),e.setDirty?.(),e.uiConfig?.uiRefresh?.()}})}};_F.PluginType="TransformAnimationPlugin";let bF=_F;var xF=Object.defineProperty;const wF=(l=class extends sw{constructor(){super(),this.enabled=!0,this.dependencies=[NR],this.animation=new e.AnimationObject(()=>this._viewer,()=>this._viewer,"Viewer Animation"),this.runtimeAnimation=new e.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(t=>this._refreshTriggerBtn(e.animation,t))}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(t=>this._refreshTriggerBtn(e.target,t))},this._viewerTimelineUpdate=()=>{!this._viewer||!this._triggerButtonsShown||this._visibleBtns.forEach((e,t)=>{e.forEach(e=>this._refreshTriggerBtn(t,e))})},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(NR);this._refTimeline&&e&&(this._refTimeline=!1,this._currentTimeline.forEach(([e,t])=>t.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(e=>this._addAnimationObject(e,t)),this._setupUiConfig(t)))},this._objectRemove=e=>{const t=e.object;t&&(Array.isArray(t.userData.animationObjects)&&t.userData.animationObjects.forEach(e=>this._removeAnimationObject(e)),this._cleanUpUiConfig(t))},this._materialAdd=e=>{const t=e.material;t&&(Array.isArray(t.userData.animationObjects)&&t.userData.animationObjects.forEach(e=>this._addAnimationObject(e,t)),this._setupUiConfig(t))},this._materialRemove=e=>{const t=e.material;t&&(Array.isArray(t.userData.animationObjects)&&t.userData.animationObjects.forEach(e=>this._removeAnimationObject(e)),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||"widget"===t.assetType||!i)return;const n=this._iObservers.get(t)?.filter(e=>(e.key===i||e.key?.endsWith("."+i))&&e.btn?.parentElement);if(n?.length)for(const e of n){const i=SF(t,e.key);if(!i)return;this._refreshTriggerBtn(i,e.btn)}},this.uiConfig={label:"Viewer Animations",type:"folder",children:[Rg(this.animation).filter(e=>{const t=Im(e?.label)??"";return["Animate","Stop","Animate Reverse"].includes(t)})??[],()=>Rg(this.animation.animSet).map(e=>Im(e)).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}),om("\n        .anim-object-uic-trigger{\n            padding: 4px;\n            margin-top: -4px;\n            cursor: pointer;\n            color: var(--tp-label-foreground-color, #777);\n            display: none;\n        }\n        .anim-object-uic-trigger-visible{\n        }\n        .anim-object-uic-trigger-active{\n            color: blue;\n        }\n        .anim-object-uic-trigger-equals{\n            color: red !important;\n        }\n        .aouic-triggers-visible .anim-object-uic-trigger{\n            display: inline-block;\n        }\n        ")}getAllAnimations(){return[...this.animation.animSet,...this.runtimeAnimation.animSet]}_getActiveIndex(e){if(!e.target)return"";const t=(1e3*(this._viewer?.timeline.time||0)-e.delay)/e.duration,i=e.offsets,n=i.reduce((e,n,r)=>Math.abs(n-t)<Math.abs(i[e]-t)?r:e,0);return Math.abs(i[n]-t)*e.duration<50?n.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((e,t)=>{e.forEach(e=>this._refreshTriggerBtn(t,e))})}showTriggers(e=!0){this.triggerButtonsShown=e}rebuildTimeline(){this._refTimeline=!0}getTimeline(){return this._currentTimeline}addAnimation(t,i,n){return n=n||new e.AnimationObject,void 0!==t&&(n.access=t),i?.userData?(i.userData.animationObjects||(i.userData.animationObjects=[]),i.userData.animationObjects.includes(n)||(i.userData.animationObjects.push(n),this._addAnimationObject(n,i),this._setupUiConfig(i))):this.animation.animSet.includes(n)||this.animation.add(n),n}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(e=>"object"==typeof e&&e.tags?.includes(l.PluginType))||(e.uiConfig?.children?.push({type:"folder",label:"Property Animations",tags:["animation",l.PluginType],children:[()=>e.userData.animationObjects?.map(e=>e.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:e,btn:t})=>{e.disconnect(),t.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(e=>"object"==typeof e&&e.tags?.includes(l.PluginType));void 0!==i&&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 e of i)this.cleanupUiConfigButton(e)}setupUiConfigButton(t,i,n){if(i._animTriggerInit)return;const r=Im(i.property);if(!r)return;const[s,a]=r;if(!s||"string"!=typeof a||s!==t&&!n)return;const o=n?n.endsWith(".")?n+a:n:a,l=sm({innerHTML:"◆",classList:["anim-object-uic-trigger"],addToBody:!1});l.parentElement&&l.remove(),l.dataset.isAnimObjectTrigger="1",l.title="Add Animation for "+Im(i.label,a),l.addEventListener("click",()=>{const n=this._viewer?.getPlugin("UndoManagerPlugin");let r=SF(t,o);const s=1e3*(this._viewer?.timeline.time||0);if(r){if(r.values.length>1){const e=r,t=l.dataset.activeIndex||"",i=this._getActiveIndex(r);if(i===t){const t=parseInt(i||"-1"),a=()=>this._refreshTriggerBtn(e,l);n?(t<0?n.performAction(r,r.addKeyframe,[s],"addKeyframe-"+r.access,a):n.performAction(r,r.updateKeyframe,[t],"editKeyframe-"+r.access,a),a()):(t<0?r.addKeyframe(s):r.updateKeyframe(t),a())}else console.error("Active index mismatch",i,t)}}else{r=new e.AnimationObject,r.access=o,r.name=t.name+" "+(Im(i.label,o)||o),r.updateTarget=!0,r.delay=s,r.duration=2e3;const a=r,c={redo:()=>{t.userData.animationObjects||(t.userData.animationObjects=[]),t.userData.animationObjects.push(a),this._addAnimationObject(a,t),this._refreshTriggerBtn(a,l)},undo:()=>{a.removeFromParent(),this._refreshTriggerBtn(a,l)}};c.redo(),n?.undoManager?.record(c)}this._setBtnVisible(r,l,!0)});const c=new IntersectionObserver(e=>{const i=SF(t,o);if(i)for(const t of e)t.target===l&&this._setBtnVisible(i,l,t.isIntersecting)});c.observe(l),this._iObservers.has(t)||this._iObservers.set(t,[]),this._iObservers.get(t)?.push({o:c,btn:l,key:o});const h=SF(t,o);h&&this._refreshTriggerBtn(h,l),i._animTriggerInit=!0,i.domChildren=!i.domChildren||Array.isArray(i.domChildren)?[...i.domChildren||[],l]:i.domChildren}cleanupUiConfigButton(e){e&&(e.domChildren=Array.isArray(e.domChildren)?e.domChildren?.filter(e=>!(e instanceof HTMLElement&&e.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=>"object"==typeof t&&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(e=>this._objectAdd({object:e})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.object3dManager.getMaterials().forEach(e=>this._materialAdd({material:e})),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(e=>this._objectRemove({object:e})),e.object3dManager.removeEventListener("materialAdd",this._materialAdd),e.object3dManager.removeEventListener("materialRemove",this._materialRemove),e.object3dManager.getMaterials().forEach(e=>this._materialRemove({material:e})),delete e._animGetters,super.onRemove(e)}fromJSON(e,t){return super.fromJSON(e,t)?this:null}},l.PluginType="AnimationObjectPlugin",l);((e,t,i)=>{for(var n,r=void 0,s=e.length-1;s>=0;s--)(n=e[s])&&(r=n(t,i,r)||r);r&&xF(t,i,r)})([qm()],wF.prototype,"animation");let CF=wF;const SF=(e,t)=>e?.userData.animationObjects?.find(e=>e.access===t);var MF=Object.defineProperty,EF=Object.getOwnPropertyDescriptor,TF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?EF(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&MF(t,i,s),s};e.ClearcoatTintPlugin=class extends sw{constructor(){super(),this.enabled=!0,this._uniforms={ccTintColor:{value:new mr},ccThickness:{value:0},ccIor:{value:0}},this.materialExtension={parsFragmentSnippet:(e,t)=>!this.isDisabled()&&t?.userData._clearcoatTint?.enableTint&&t.clearcoat>0?ym`
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=R_(e.fragmentShader,"float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );","float dotNVcc = saturate( dot( geometryClearcoatNormal, -refract(geometryViewDir, geometryClearcoatNormal, 1./ccIor) ) );"),e.fragmentShader=R_(e.fragmentShader,"outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;","outgoingLight *= clearcoatTint(dotNVcc, dotNVcc, material.clearcoat);\n",{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,mw({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:t=>{const i=this._viewer;void 0===t.userData._clearcoatTint&&(t.userData._clearcoatTint={});const n=t.userData._clearcoatTint,r={type:"folder",label:"Clearcoat Tint",onChange:e=>{e.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return n.enableTint||!1},set value(s){s!==n.enableTint&&(s?e.ClearcoatTintPlugin.AddClearcoatTint(t)||i.dialog.alert("Cannot add clearcoat tint."):(n.enableTint=!1,t.setDirty&&t.setDirty()),r.uiRefresh?.(!0,"postFrame"))}},{type:"color",label:"Tint color",hidden:()=>!n.enableTint,property:[n,"tintColor"]},{type:"input",label:"Thickness",hidden:()=>!n.enableTint,property:[n,"thickness"]},{type:"slider",bounds:[.8,2.5],label:"IOR",hidden:()=>!n.enableTint,property:[n,"ior"]}]};return r}},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,void 0===n.tintColor&&(n.tintColor="#ffffff"),void 0===n.thickness&&(n.thickness=.1),void 0===n.ior&&(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(PF)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(PF.name),super.onRemove(e)}},e.ClearcoatTintPlugin.PluginType="ClearcoatTintPlugin",e.ClearcoatTintPlugin.CLEARCOAT_TINT_GLTF_EXTENSION="WEBGI_materials_clearcoat_tint",TF([Hg("Enabled",e=>({onChange:e.setDirty})),qm()],e.ClearcoatTintPlugin.prototype,"enabled",2),e.ClearcoatTintPlugin=TF([qg("Clearcoat Tint (MatExt)")],e.ClearcoatTintPlugin);class IF{constructor(e){this.parser=e,this.name=PF.name}async extendMaterialParams(t,i){const n=this.parser.json.materials[t];if(!n.extensions||!n.extensions[this.name])return;const r=n.extensions[this.name];i.userData||(i.userData={}),e.ClearcoatTintPlugin.AddClearcoatTint(i),f_.Deserialize(r,i.userData._clearcoatTint)}}const PF={name:"WEBGI_materials_clearcoat_tint",import:e=>new IF(e),export:e=>({writeMaterial:(t,i)=>{if(!t.isMeshStandardMaterial||!t.userData._clearcoatTint?.enableTint)return;i.extensions=i.extensions||{};const n=f_.Serialize(t.userData._clearcoatTint);i.extensions[PF.name]=n,e.extensionsUsed[PF.name]=!0}}),textures:void 0};var DF=Object.defineProperty,RF=Object.getOwnPropertyDescriptor,BF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?RF(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&DF(t,i,s),s};e.NoiseBumpMaterialPlugin=class extends sw{constructor(){super(),this.enabled=!0,this._uniforms={noiseBumpParams:{value:new fi},noiseBumpScale:{value:.05},noiseBumpFlakeScale:{value:1e3},noiseFlakeClamp:{value:1},noiseFlakeRadius:{value:.5},flakeParams:{value:new Gi(0,1,3,0)},flakeFallOffParams:{value:new Xi(0,1,0)},useColorFlakes:{value:!1}},this.materialExtension={parsFragmentSnippet:(e,t)=>this.isDisabled()||!t?.userData._noiseBumpMat?.hasBump?"":"#include <randomHelpers>\n#include <voronoiNoise>\nuniform 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){\n#ifdef BUMP_MAP_SCALE_LEGACY\nvec3 vSigmaX=(dFdx(surf_pos.xyz));vec3 vSigmaY=(dFdy(surf_pos.xyz));\n#else\nvec3 vSigmaX=normalize(dFdx(surf_pos.xyz));vec3 vSigmaY=normalize(dFdy(surf_pos.xyz));\n#endif\nvec3 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);}",shaderExtender:(e,t)=>{this.isDisabled()||!t?.userData._noiseBumpMat?.hasBump||(e.fragmentShader=R_(e.fragmentShader,"#glMarker beforeAccumulation","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);\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\nvec3 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);}\n#endif\n",{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,mw({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:t=>{const i=this._viewer;void 0===t.userData._noiseBumpMat&&(t.userData._noiseBumpMat={});const n=t.userData._noiseBumpMat,r={type:"folder",label:"SparkleBump (NoiseBump)",onChange:e=>{e.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return n.hasBump||!1},set value(s){s!==n.hasBump&&(s?e.NoiseBumpMaterialPlugin.AddNoiseBumpMaterial(t)||i.dialog.alert("Cannot add NoiseBumpMaterial."):(n.hasBump=!1,t.setDirty&&t.setDirty()),r.uiRefresh?.(!0,"postFrame"))}},{type:"vec4",label:"Bump Noise Params",bounds:[0,1],hidden:()=>!n.hasBump,property:[n,"bumpNoiseParams"]},{type:"slider",label:"Bump Scale",bounds:[0,.001],stepSize:1e-5,hidden:()=>!n.hasBump,property:[n,"bumpScale"]},{type:"slider",label:"Flake Scale",bounds:[100,1e4],stepSize:1e-4,hidden:()=>!n.hasBump,property:[n,"flakeScale"]},{type:"slider",label:"Flake Clamp",bounds:[0,1],stepSize:1,hidden:()=>!n.hasBump,property:[n,"flakeClamp"]},{type:"slider",label:"Flake Radius",bounds:[.01,1],stepSize:.001,hidden:()=>!n.hasBump,property:[n,"flakeRadius"]},{type:"slider",label:"Flake Roughness",bounds:[0,1],stepSize:.01,hidden:()=>!n.hasBump,property:[n.flakeParams,"x"]},{type:"slider",label:"Flake Metalness",bounds:[0,1],stepSize:.01,hidden:()=>!n.hasBump,property:[n.flakeParams,"y"]},{type:"slider",label:"Flake Strength",bounds:[0,100],stepSize:.001,hidden:()=>!n.hasBump,property:[n.flakeParams,"z"]},{type:"slider",label:"Flake Threshold",bounds:[.1,10],stepSize:.001,hidden:()=>!n.hasBump,property:[n.flakeParams,"w"]},{type:"slider",label:"Falloff",stepSize:1,bounds:[0,1],hidden:()=>!n.hasBump,property:[n.flakeFallOffParams,"x"]},{type:"slider",label:"Linear falloff factor",bounds:[0,10],stepSize:.001,hidden:()=>!n.hasBump,property:[n.flakeFallOffParams,"y"]},{type:"slider",label:"Quadratic falloff factor",bounds:[0,10],stepSize:.001,hidden:()=>!n.hasBump,property:[n.flakeFallOffParams,"z"]},{type:"checkbox",label:"Colored Flakes",hidden:()=>!n.hasBump,property:[n,"useColorFlakes"]}]};return r}},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,void 0===n.bumpNoiseParams&&(n.bumpNoiseParams=new fi(.5,.5)),void 0===n.bumpScale&&(n.bumpScale=.05),void 0===n.flakeScale&&(n.flakeScale=.05),void 0===n.flakeClamp&&(n.flakeClamp=1),void 0===n.flakeRadius&&(n.flakeRadius=.3),void 0===n.useColorFlakes&&(n.useColorFlakes=!1),void 0===n.flakeParams&&(n.flakeParams=new Gi(0,1,3,0)),void 0===n.flakeFallOffParams&&(n.flakeFallOffParams=new Xi(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(OF)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(OF.name),super.onRemove(e)}},e.NoiseBumpMaterialPlugin.PluginType="NoiseBumpMaterialPlugin",e.NoiseBumpMaterialPlugin.NOISE_BUMP_MATERIAL_GLTF_EXTENSION="WEBGI_materials_noise_bump",BF([Hg("Enabled",e=>({onChange:e.setDirty})),qm()],e.NoiseBumpMaterialPlugin.prototype,"enabled",2),e.NoiseBumpMaterialPlugin=BF([qg("Noise/Sparkle Bump (MatExt)")],e.NoiseBumpMaterialPlugin);class LF{constructor(e){this.parser=e,this.name=OF.name}async extendMaterialParams(t,i){const n=this.parser.json.materials[t];if(!n.extensions||!n.extensions[this.name])return;const r=n.extensions[this.name];i.userData||(i.userData={}),e.NoiseBumpMaterialPlugin.AddNoiseBumpMaterial(i),f_.Deserialize(r,i.userData._noiseBumpMat)}}const OF={name:"WEBGI_materials_noise_bump",import:e=>new LF(e),export:e=>({writeMaterial:(t,i)=>{if(!t.isMeshStandardMaterial||!t.userData._noiseBumpMat?.hasBump)return;i.extensions=i.extensions||{};const n=f_.Serialize(t.userData._noiseBumpMat);i.extensions[OF.name]=n,e.extensionsUsed[OF.name]=!0}}),textures:void 0};var UF=Object.defineProperty,FF=Object.getOwnPropertyDescriptor,kF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?FF(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&UF(t,i,s),s};e.CustomBumpMapPlugin=class extends sw{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 Ai},customBumpScale:{value:.001},customBumpMap:{value:null}},this.materialExtension={parsFragmentSnippet:(e,t)=>this.isDisabled()||!t?.userData._hasCustomBump?"":"#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0\n#if CUSTOM_BUMP_MAP_BICUBIC > 0\nvec4 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);}\n#endif\nvarying vec2 vCustomBumpUv;uniform sampler2D customBumpMap;uniform float customBumpScale;vec2 dHdxy_fwd_cb(){vec2 dSTdx=dFdx(vCustomBumpUv);vec2 dSTdy=dFdy(vCustomBumpUv);\n#if CUSTOM_BUMP_MAP_BICUBIC > 0\nfloat 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;\n#else\nfloat Hll=customBumpScale*texture2D(customBumpMap,vCustomBumpUv).x;float dBx=customBumpScale*texture2D(customBumpMap,vCustomBumpUv+dSTdx).x-Hll;float dBy=customBumpScale*texture2D(customBumpMap,vCustomBumpUv+dSTdy).x-Hll;\n#endif\nreturn vec2(dBx,dBy);}\n#ifndef USE_BUMPMAP\nvec3 perturbNormalArb(vec3 surf_pos,vec3 surf_norm,vec2 dHdxy,float faceDirection){\n#ifdef BUMP_MAP_SCALE_LEGACY\nvec3 vSigmaX=(dFdx(surf_pos.xyz));vec3 vSigmaY=(dFdy(surf_pos.xyz));\n#else\nvec3 vSigmaX=normalize(dFdx(surf_pos.xyz));vec3 vSigmaY=normalize(dFdy(surf_pos.xyz));\n#endif\nvec3 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);}\n#endif\n#endif\n",shaderExtender:(e,t)=>{this.isDisabled()||!t?.userData._hasCustomBump||!t.userData._customBumpMap||(e.fragmentShader=R_(e.fragmentShader,"#glMarker beforeAccumulation","\n#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0\n    normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd_cb(), faceDirection );\n#endif\n                ",{prepend:!0}),e.vertexShader=R_(e.vertexShader,"#include <uv_pars_vertex>","\n#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0\n    varying vec2 vCustomBumpUv;\n    uniform mat3 customBumpUvTransform;\n#endif\n                ",{prepend:!0}),e.vertexShader=R_(e.vertexShader,"#include <uv_vertex>","\n#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0\n    vCustomBumpUv = ( customBumpUvTransform * vec3( uv, 1 ) ).xy;\n#endif\n                ",{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)),mw({...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,r={type:"folder",label:"CustomBumpMap",onChange:e=>{e.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return n._hasCustomBump||!1},set value(s){s!==n._hasCustomBump&&(s?i(e)||t.dialog.alert("CustomBumpMapPlugin - Cannot add CustomBumpMap."):(n._hasCustomBump=!1,e.setDirty&&e.setDirty()),r.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()}},bw(n,"_customBumpMap","Sampler",()=>!n._hasCustomBump,()=>e.setDirty&&e.setDirty())]};return r}},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(void 0===n._hasCustomBump){const t=e.appliedMeshes;let i=!0;if(t)for(const{geometry:e}of t)e&&(!e.attributes.position||!e.attributes.normal||!e.attributes.uv)&&(i=!1);if(!i)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(jF)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(jF.name),super.onRemove(e)}},e.CustomBumpMapPlugin.PluginType="CustomBumpMapPlugin",e.CustomBumpMapPlugin.CUSTOM_BUMP_MAP_GLTF_EXTENSION="WEBGI_materials_custom_bump_map",kF([Hg("Enabled",e=>({onChange:e.setDirty})),qm()],e.CustomBumpMapPlugin.prototype,"enabled",2),kF([Hg("Bicubic",e=>({onChange:e.setDirty})),Ny("CUSTOM_BUMP_MAP_BICUBIC",void 0,!0,e.CustomBumpMapPlugin.prototype.setDirty),qm()],e.CustomBumpMapPlugin.prototype,"bicubicFiltering",2),e.CustomBumpMapPlugin=kF([qg("Custom BumpMap (MatExt)")],e.CustomBumpMapPlugin);class NF{constructor(e,t){this._viewer=t,this.parser=e,this.name=jF.name}async extendMaterialParams(e,t){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return;const r=n.extensions[this.name];t.userData||(t.userData={}),t.userData._hasCustomBump=!0,t.userData._customBumpScale=r.customBumpScale??0;const s=r.resources?await(this._viewer?.loadConfigResources(r.resources)):void 0,a=[],o=r.customBumpMap;return o&&(o&&o.resource&&"string"==typeof o.resource?t.userData._customBumpMap=f_.Deserialize(o,null,s,!1):o&&void 0!==o.index?a.push(i.assignTexture(t.userData,"_customBumpMap",o).then(e=>{e.colorSpace=Ot})):(console.warn("CustomBumpMapPlugin: Invalid Texture Map in extension",o,n.name),t.userData._customBumpMap=null)),Promise.all(a)}}const jF={name:"WEBGI_materials_custom_bump_map",import:(e,t)=>new NF(e,t),export:e=>({writeMaterial:(t,i)=>{if(!t.isMeshStandardMaterial||!t.userData._hasCustomBump||(t.userData._customBumpScale||0)<.001)return;i.extensions=i.extensions||{};const n={images:{},textures:{}},r={};r.customBumpScale=t.userData._customBumpScale||1;const s=t.userData._customBumpMap?.userData.rootPath;if(s&&Eg(s)&&(r.customBumpMap=f_.Serialize(t.userData._customBumpMap,n,!1)),e.checkEmptyMap(t.userData._customBumpMap)&&void 0===r.customBumpMap){const i={index:e.processTexture(t.userData._customBumpMap)};e.applyTextureTransform(i,t.userData._customBumpMap),r.customBumpMap=i}(Object.keys(n.textures).length||Object.keys(n.images).length)&&(r.resources=n),i.extensions[jF.name]=r,e.extensionsUsed[jF.name]=!0}}),textures:{customBumpMap:"RGB"}};var zF=Object.defineProperty,GF=Object.getOwnPropertyDescriptor,QF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?GF(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&zF(t,i,s),s};e.ParallaxMappingPlugin=class extends sw{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:(e,t,i)=>{if(t.bumpMap&&!this.isDisabled()){e.fragmentShader=e.fragmentShader.replace("#include <normal_fragment_begin>",""),e.fragmentShader=e.fragmentShader.replace("#include <normal_fragment_maps>",""),e.fragmentShader=e.fragmentShader.replace("#include <map_fragment>","#include <normal_fragment_begin>\n#include <normal_fragment_maps>\n#include <map_fragment>");for(const t of["map_fragment","alphamap_fragment","roughnessmap_fragment","metalnessmap_fragment","emissivemap_fragment","transmission_fragment"])e.fragmentShader=R_(e.fragmentShader,`#include <${t}>`,Ts[t].replace(/\bv\w+Uv\b/g,"parallaxUv.xy",{replaceAll:!0}));(this.debugNormals||this.debugHitHeight)&&(e.fragmentShader=R_(e.fragmentShader,"texture2D( map, parallaxUv.xy )",this.debugNormals?"vec4(normal, 1.); normal = nonPerturbedNormal":"vec4(parallaxUv.z,0., 0., 1.)")),e.fragmentShader=R_(e.fragmentShader,"#include <normal_fragment_maps>",R_(R_(Ts.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()?"":"\n#ifdef USE_BUMPMAP\nmat3 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){\n#if defined( TANGENTSPACE_NORMALMAP ) && 0\nvec3 mapN=texture2D(normalMap,texCoords).xyz;mapN.xy*=normalScale;return normalize(mapN);\n#else\nvec2 texOffs=1.0/bumpMapSize;\n#if PARALLAX_NORMAL_MAP_QUALITY > 0\nfloat 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]);\n#else\nfloat 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);\n#endif\nreturn normalize(vec3(deltaH/texOffs,1.0));\n#endif\n}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;\n#pragma unroll_loop_start\nfor(int i=0;i<PARALLAX_MAP_STEPS;i++){if(mapHeight<bestBumpHeight){bestBumpHeight-=bumpHeightStep;mapHeight=back_face+surf_sign*CalculateHeight(texC.xy-bestBumpHeight*texStep.xy);}}\n#pragma unroll_loop_end\nbestBumpHeight+=bumpHeightStep;\n#pragma unroll_loop_start\nfor(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;}\n#pragma unroll_loop_end\nbestBumpHeight-=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);\n#ifdef FLIP_SIDED\nnormal=-normal;\n#endif\nreturn parallaxUv;}\n#endif\n\n".replaceAll("PARALLAX_MAP_STEPS",this.stepCount.toString()).replaceAll("PARALLAX_MAP_B_STEPS",this.binaryStepCount.toString()),isCompatible:e=>e.isPhysicalMaterial,computeCacheKey:e=>""+!this.isDisabled()+e.bumpMap?.uuid+this.debugNormals+this.debugHitHeight+this.stepCount.toString()+this.binaryStepCount.toString(),onObjectRender:(e,t,i)=>{this.isDisabled()||mw({...this._defines},t)}},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)}},e.ParallaxMappingPlugin.PluginType="ReliefParallaxMapping",QF([Qm(e.ParallaxMappingPlugin.prototype._updateExtension),qm(),Hg("Enabled")],e.ParallaxMappingPlugin.prototype,"enabled",2),QF([Fg("Step count",[1,32],1),Qm(e.ParallaxMappingPlugin.prototype._updateExtension),qm()],e.ParallaxMappingPlugin.prototype,"stepCount",2),QF([Fg("Binary search steps",[1,8],1),Qm(e.ParallaxMappingPlugin.prototype._updateExtension),qm()],e.ParallaxMappingPlugin.prototype,"binaryStepCount",2),QF([Qm(e.ParallaxMappingPlugin.prototype._updateExtension),Hg("Debug Normals")],e.ParallaxMappingPlugin.prototype,"debugNormals",2),QF([Qm(e.ParallaxMappingPlugin.prototype._updateExtension),Hg("Debug Hit Height")],e.ParallaxMappingPlugin.prototype,"debugHitHeight",2),e.ParallaxMappingPlugin=QF([qg("Parallax Bump Mapping (MatExt)")],e.ParallaxMappingPlugin);var VF=Object.defineProperty,HF=Object.getOwnPropertyDescriptor,WF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?HF(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&VF(t,i,s),s};e.FragmentClippingExtensionPlugin=class extends sw{constructor(){super(),this.enabled=!0,this._defines={FRAG_CLIPPING_DEBUG:0},this._uniforms={fragClippingPosition:{value:new Gi},fragClippingParams:{value:new Gi},fragClippingCamAspect:{value:1}},this._plane=new bs,this._viewNormalMatrix=new Ai,this._v4=new Gi,this.materialExtension={parsFragmentSnippet:(e,t)=>this.enabled&&t?.userData._fragmentClippingExt?.clipEnabled?Object.entries(qF).map(e=>["FragmentClippingMode."+e[0],""+e[1]]).reduce((e,t)=>e.replace(t[0],t[1]),"#include <simpleCameraHelpers>\nuniform vec4 fragClippingPosition;uniform vec4 fragClippingParams;uniform float fragClippingCamAspect;\n#if FRAG_CLIPPING_MODE == FragmentClippingMode.Circle\nfloat 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;}\n#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Ellipse\nfloat 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;}\n#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Rectangle\nfloat 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));}\n#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Plane\nfloat fragClippingPlane(){vec3 pos=vViewPosition.xyz;vec3 normal=fragClippingParams.xyz;float d=dot(pos,normal)-fragClippingParams.w;return d;}\n#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Sphere\nfloat fragClippingSphere(){vec3 pos=vViewPosition.xyz;vec3 center=fragClippingPosition.xyz;float radius=fragClippingParams.x;pos.y/=fragClippingCamAspect;center.y/=fragClippingCamAspect;return length(pos-center)-radius;}\n#endif\n"):"",shaderExtender:(e,t)=>{!this.enabled||!t?.userData._fragmentClippingExt?.clipEnabled||(e.fragmentShader=R_(e.fragmentShader,"#glMarker mainStart",Object.entries(qF).map(e=>["FragmentClippingMode."+e[0],""+e[1]]).reduce((e,t)=>e.replace(t[0],t[1]),"\nfloat fragClippingDist=0.0;\n#if FRAG_CLIPPING_MODE == FragmentClippingMode.Circle\nfragClippingDist=fragClippingCircle();\n#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Ellipse\nfragClippingDist=fragClippingEllipse();\n#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Rectangle\nfragClippingDist=fragClippingRectangle();\n#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Plane\nfragClippingDist=fragClippingPlane();\n#elif FRAG_CLIPPING_MODE == FragmentClippingMode.Sphere\nfragClippingDist=fragClippingSphere();\n#endif\n#if FRAG_CLIPPING_DEBUG\ngl_FragColor=vec4(max(fragClippingDist,0.0),0.0,0.0,1.0);\n#include <colorspace_fragment>\nreturn;\n#endif\n#if FRAG_CLIPPING_INVERSE == 1\nif(fragClippingDist>0.0)discard;\n#else\nif(fragClippingDist<0.0)discard;\n#endif\n"),{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),3===i.clipMode&&i.clipParams){const e=Array.isArray(i.clipParams)?this._v4.fromArray(i.clipParams):this._v4.copy(i.clipParams),t=this._viewer.scene.mainCamera.matrixWorldInverse;this._plane.normal.set(e.x,e.y,e.z),this._plane.constant=e.w,this._viewNormalMatrix.getNormalMatrix(t),this._plane.applyMatrix4(t,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,mw({...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:t=>{const i=this._viewer;void 0===t.userData._fragmentClippingExt&&(t.userData._fragmentClippingExt={});const n=t.userData._fragmentClippingExt,r={type:"folder",label:"Fragment Clipping",onChange:e=>{e.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return n.clipEnabled||!1},set value(s){s!==n.clipEnabled&&(s?e.FragmentClippingExtensionPlugin.AddFragmentClipping(t)||i.dialog.alert("Cannot add FragmentClippingExtension."):(n.clipEnabled=!1,t.setDirty&&t.setDirty()),r.uiRefresh?.(!0,"postFrame"))}},{type:"dropdown",label:"Mode",children:Object.entries(qF).map(e=>({label:e[0],value:e[1]})),hidden:()=>!n.clipEnabled,property:[n,"clipMode"]},{type:"vec4",label:"Position",bounds:[-1,1],hidden:()=>!n.clipEnabled,property:[n,"clipPosition"]},{type:"vec4",label:"Params",bounds:[0,1],hidden:()=>!n.clipEnabled,property:[n,"clipParams"]},{type:"toggle",label:"Invert",hidden:()=>!n.clipEnabled,property:[n,"clipInvert"]}]};return r}},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,void 0===n.clipPosition&&(n.clipPosition=[0,0,0,0]),void 0===n.clipParams&&(n.clipParams=[0,0,0,0]),void 0===n.clipMode!==void 0&&(n.clipMode=0),void 0===n.clipInvert!==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(YF)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(YF.name),super.onRemove(e)}},e.FragmentClippingExtensionPlugin.PluginType="FragmentClippingExtensionPlugin1",e.FragmentClippingExtensionPlugin.FRAGMENT_CLIPPING_EXTENSION_GLTF_EXTENSION="WEBGI_materials_fragment_clipping_extension",WF([Hg("Enabled",e=>({onChange:e.setDirty})),qm()],e.FragmentClippingExtensionPlugin.prototype,"enabled",2),e.FragmentClippingExtensionPlugin=WF([qg("Fragment Clipping (MatExt)")],e.FragmentClippingExtensionPlugin);var qF=(e=>(e[e.Circle=0]="Circle",e[e.Ellipse=1]="Ellipse",e[e.Rectangle=2]="Rectangle",e[e.Plane=3]="Plane",e[e.Sphere=4]="Sphere",e))(qF||{});class XF{constructor(e){this.parser=e,this.name=YF.name}async extendMaterialParams(t,i){const n=this.parser.json.materials[t];if(!n.extensions||!n.extensions[this.name])return;const r=n.extensions[this.name];i.userData||(i.userData={}),e.FragmentClippingExtensionPlugin.AddFragmentClipping(i),f_.Deserialize(r,i.userData._fragmentClippingExt)}}const YF={name:"WEBGI_materials_fragment_clipping",import:e=>new XF(e),export:e=>({writeMaterial:(t,i)=>{if(!t.isMeshStandardMaterial||!t.userData._fragmentClippingExt?.clipEnabled)return;i.extensions=i.extensions||{};const n=f_.Serialize(t.userData._fragmentClippingExt);i.extensions[YF.name]=n,e.extensionsUsed[YF.name]=!0}}),textures:void 0};var KF=Object.defineProperty,JF=Object.getOwnPropertyDescriptor,ZF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?JF(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&KF(t,i,s),s};e.VirtualCamerasPlugin=class extends sw{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.cameras=[],this._viewerListeners={preRender:()=>{if(this.isDisabled()||!this._viewer)return;const e=this._viewer;for(const t of this.cameras){if(!t.enabled)continue;const i=t.camera;try{this.dispatchEvent({type:"preRenderCamera",camera:t}),e.scene.renderCamera=i,e.renderManager.render(e.scene,!1);const n=e.renderManager.composer.readBuffer.texture;this.dispatchEvent({type:"preBlitCamera",camera:t,readBuffer:n}),e.renderManager.blit(t.target,{source:n}),this.dispatchEvent({type:"postRenderCamera",camera:t})}catch(i){if(e.console.error(i),t.enabled=!1,e.debug)throw i}}}},this._objectExtension={uuid:"VirtualCameraPluginExt",isCompatible:e=>e.isCamera,getUiConfig:e=>{if(e.isCamera)return[{type:"button",label:"Add Virtual Camera",hidden:()=>!!this.cameras.find(t=>t.camera===e),onClick:()=>{if(this._viewer)return this.addCamera(e,void 0,!0),e.setDirty&&e.setDirty(),()=>{this.removeCamera(e),e.setDirty&&e.setDirty()}}},{type:"button",label:"Virtual Camera Enabled",hidden:()=>!this.cameras.find(t=>t.camera===e),getValue:()=>{const t=this.cameras.find(t=>t.camera===e);return!!t&&t.enabled},setValue:()=>{const t=this.cameras.find(t=>t.camera===e);return!!t&&(t.enabled=!t.enabled,t.enabled)}},{type:"button",label:"Remove Virtual Camera",hidden:()=>!this.cameras.find(t=>t.camera===e),onClick:()=>{if(this._viewer)return this.removeCamera(e),e.setDirty&&e.setDirty(),()=>{this.addCamera(e,void 0,!0),e.setDirty&&e.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)).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(t=>t.camera===e);if(t>=0){const e=this.cameras[t];return this.cameras.splice(t,1),this._viewer.getPlugin("RenderTargetPreviewPlugin")?.removeTarget(e.target),e.target.dispose(),!0}return!1}},e.VirtualCamerasPlugin.PluginType="VirtualCamerasPlugin",ZF([Hg()],e.VirtualCamerasPlugin.prototype,"enabled",2),e.VirtualCamerasPlugin=ZF([qg("Virtual Cameras")],e.VirtualCamerasPlugin);var $F=Object.defineProperty,ek=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&$F(t,i,s),s};const tk={cascades:3,shadowMapSize:2048,shadowBias:void 0,lightNear:void 0,lightFar:void 0,lightMargin:200},ik=(c=class extends sw{constructor(e=!0){super(),this.enabled=!0,this.parent=new ll,this.maxFar=1e5,this.mode="practical",this.attachToFirstLight=!0,this.frustums=[],this.breaks=[],this.extendedBreaks=[],this.lights=[],this._lightRef=void 0,this._lightUpdate=e=>{e?.object===this.light&&this.refreshLights(e)},this._refreshingLights=!1,this.refreshLights=e=>{if(!this._refreshingLights){this._refreshingLights=!0;try{this._refreshLightsInner(e)}finally{this._refreshingLights=!1}}},this._refreshLightsInner=e=>{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 t=this.light.userData[c.PluginType];t||(t={},this.light.userData[c.PluginType]=t);const i={...tk,...t};for(let e=0;e<i.cascades;e++){if(!this.lights[e]){const t=new Eu(16777215,1);t.name="CSM Light "+e,this.lights.push(t),this.parent.add(t),this.parent.add(t.target)}const t=this.lights[e];t.intensity=this.light.intensity,t.color.set(this.light.color),t.castShadow=!0,t.shadow.mapSize.width=i.shadowMapSize,t.shadow.mapSize.height=i.shadowMapSize,t.shadow.camera.near=i.lightNear??this.light.shadow.camera.near,t.shadow.camera.far=i.lightFar??this.light.shadow.camera.far,t.shadow.bias=i.shadowBias??this.light.shadow.bias,t.shadow.normalBias=this.light.shadow.normalBias,t.shadow.radius=this.light.shadow.radius}if(this.lights.length>i.cascades){const e=this.lights.splice(i.cascades,this.lights.length-i.cascades);for(const t of e)this.parent.remove(t.target),this.parent.remove(t)}const n=e?.change??e?.key;!n&&!["intensity","castShadow","mapSize","bias","radius","shadow","deserialize"].includes(n)&&this.cameraNeedsUpdate()},this._mainCameraChange=e=>{this.camera=e.camera,this.cameraNeedsUpdate()},this._cameraUpdated=!1,this._mainCameraUpdate=e=>{!1!==e.projectionUpdated?this.cameraNeedsUpdate():this.setDirty()},this.cameraNeedsUpdate=()=>{this._cameraUpdated=!0,this._viewer?.setDirty()},this._needsUpdate=!1,this.setDirty=()=>{const e=!this.isDisabled();e!==this._lastEnabled&&(this._lastEnabled=e,this.refreshLights(),e||(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())),e&&(this._needsUpdate=!0,this._viewer?.setDirty())},this._viewerListeners={preRender:()=>{if(this.isDisabled()||!this.light)return;let e=!1;this._cameraUpdated&&(this._updateFrustums(),e=!0),this._needsUpdate&&!this.update()&&(e=!0),e&&this._viewer?.renderManager.resetShadows()}},this._lastCenters=[],this._lightAutoAttached=!1,this.refreshAttachedLight=()=>{if(this.light&&this._lightAutoAttached)return void(this.light.parent||(this.light=void 0,this._lightAutoAttached=!1));if(!this.attachToFirstLight)return;const e=this._viewer?.object3dManager.getLights()||[];for(const t of e)if(t.isDirectionalLight&&t.castShadow){if(t===this.light)return;return this._lightAutoAttached=!0,void(this.light=t)}},this._sversion=0,this._updateFrustums=()=>{if(!this.light)return;const{cascades:e=tk.cascades}=this.light.userData[c.PluginType]||{},t=this._getBreaks(e);this._initCascades(t),this._updateShadowBounds(),this.extendedBreaks.length=0;for(let e=0;e<t.length;e++){const i=t[e];this.extendedBreaks.push(new fi(t[e-1]||0,i))}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:(e,t)=>{if(this.isDisabled()||!this.light)return t.extraUniformsToUpload.CSM_cascades&&(t.extraUniformsToUpload.CSM_cascades.needsUpdate=!1),t.extraUniformsToUpload.cameraNear&&(t.extraUniformsToUpload.cameraNear.needsUpdate=!1),void(t.extraUniformsToUpload.shadowFar&&(t.extraUniformsToUpload.shadowFar.needsUpdate=!1));t.extraUniformsToUpload||(t.extraUniformsToUpload={}),t.extraUniformsToUpload.CSM_cascades||(t.extraUniformsToUpload.CSM_cascades={value:[]}),t.extraUniformsToUpload.cameraNear||(t.extraUniformsToUpload.cameraNear={value:0}),t.extraUniformsToUpload.shadowFar||(t.extraUniformsToUpload.shadowFar={value:0}),t.__csmVersion||(t.__csmVersion=0),t.extraUniformsToUpload.cameraNear.needsUpdate=!0,t.extraUniformsToUpload.shadowFar.needsUpdate=!0,t.extraUniformsToUpload.CSM_cascades.needsUpdate=!0,t.__csmVersion!==this._sversion&&(t.__csmVersion=this._sversion,t.extraUniformsToUpload.cameraNear.value=this.camera?.near??.01,t.extraUniformsToUpload.shadowFar.value=Math.min(this.camera?.far??1e3,this.maxFar),t.extraUniformsToUpload.CSM_cascades.value=this.extendedBreaks)},isCompatible:e=>e.isMeshStandardMaterial||e.isMeshPhysicalMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial},this.uiConfig={type:"folder",label:"Cascaded Shadows (CSM)",children:[...Rg(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 Xi,this._cameraToLightMatrix=new Sn,this._lightSpaceFrustum=new rk,this._center=new Xi,this._bbox=new Ji,this._uniformArray=[],this._logArray=[],this._lightOrientationMatrix=new Sn,this._lightOrientationMatrixInverse=new Sn,this._up=new Xi(0,1,0),this.injectInclude(),this._lastEnabled=e,this.enabled=e,this.mainFrustum=new rk}setLightParams(e,t){if(!(t=t||this.light))return void this._viewer?.console.warn("CascadedShadowsPlugin: No light attached to CascadedShadowsPlugin");let i=t.userData[c.PluginType];i||(i={},t.userData[c.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 e of this.lights)this.parent.remove(e.target),this.parent.remove(e);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 t=this.lights[e].shadow.camera,i=this.frustums[e],n=i.vertices.near,r=i.vertices.far,s=r[0];let a;a=s.distanceTo(r[2])>s.distanceTo(n[2])?r[2]:n[2];let o=s.distanceTo(a);if(this.fade&&this.camera){const e=this.camera,t=Math.max(e.far,this.maxFar),n=i.vertices.far[0].z/(t-e.near);o+=.25*Math.pow(n,2)*(t-e.near)}t.left=-o/2,t.right=o/2,t.top=o/2,t.bottom=-o/2,t.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("custom"===n&&void 0===this.customSplitsCallback&&(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)}return this.breaks}_uniformSplit(e,t,i,n){for(let r=1;r<e;r++)n.push((t+(i-t)*r/e)/i);n.push(1)}_logarithmicSplit(e,t,i,n){for(let r=1;r<e;r++)n.push(t*(i/t)**(r/e)/i);n.push(1)}_practicalSplit(e,t,i,n,r){this._uniformArray.length=0,this._logArray.length=0,this._logarithmicSplit(e,t,i,this._logArray),this._uniformSplit(e,t,i,this._uniformArray);for(let t=1;t<e;t++)r.push(gi.lerp(this._uniformArray[t-1],this._logArray[t-1],n));r.push(1)}update(){this._needsUpdate=!1;const e=this.camera;if(!e||!this.light)return!0;const t=this.frustums,{shadowMapSize:i=tk.shadowMapSize,lightMargin:n=tk.lightMargin}=this.light.userData[c.PluginType]||{};{this.light.updateMatrixWorld();const e=this.light.getWorldPosition(this._center);this.light.target.updateMatrixWorld(),this.light.target.getWorldPosition(this._lightDirection),this._lightOrientationMatrix.lookAt(e,this._lightDirection,this._up),this._lightOrientationMatrixInverse.copy(this._lightOrientationMatrix).invert(),this._lightDirection.sub(e).normalize()}const r=[];for(let s=0;s<t.length;s++){const a=this.lights[s],o=a.shadow.camera,l=(o.right-o.left)/i,c=(o.top-o.bottom)/i;this._cameraToLightMatrix.multiplyMatrices(this._lightOrientationMatrixInverse,e.matrixWorld),t[s].toSpace(this._cameraToLightMatrix,this._lightSpaceFrustum);const h=this._lightSpaceFrustum.vertices.near,d=this._lightSpaceFrustum.vertices.far;this._bbox.makeEmpty();for(let e=0;e<4;e++)this._bbox.expandByPoint(h[e]),this._bbox.expandByPoint(d[e]);this._bbox.getCenter(this._center),this._center.z=this._bbox.max.z+n,this._center.x=Math.floor(this._center.x/l)*l,this._center.y=Math.floor(this._center.y/c)*c,this._center.applyMatrix4(this._lightOrientationMatrix),r.push(this._center.clone()),a.position.copy(this._center),a.target.position.copy(this._center).add(this._lightDirection)}let s=!0;if(r.length===this._lastCenters.length){for(let e=0;e<r.length;e++)if(Math.abs(r[e].x-this._lastCenters[e].x)+Math.abs(r[e].y-this._lastCenters[e].y)+Math.abs(r[e].z-this._lastCenters[e].z)>.001){s=!1;break}}else s=!1;return this._lastCenters=r,s}get cascades(){return this.isDisabled()||!this.light?0:this.frustums.length}injectInclude(){Ts.lights_fragment_begin.includes("defined( USE_CSM ) && defined( CSM_CASCADES )")||(Ts.lights_fragment_begin=R_(Ts.lights_fragment_begin,"#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n","\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES )\n\n\tDirectionalLight directionalLight;\n\tfloat linearDepth = (vViewPosition.z) / (shadowFar - cameraNear);\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\n\t#if defined( USE_SHADOWMAP ) && defined( CSM_FADE )\n\t\tvec2 cascade;\n\t\tfloat cascadeCenter;\n\t\tfloat closestEdge;\n\t\tfloat margin;\n\t\tfloat csmx;\n\t\tfloat csmy;\n\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\t\tdirectionalLight = directionalLights[ i ];\n\t\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\n\t\t\t#if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\t\t\n            #if ( UNROLLED_LOOP_INDEX < CSM_CASCADES )\n\n\t\t\t\t// NOTE: Depth gets larger away from the camera.\n\t\t\t\t// cascade.x is closer, cascade.y is further\n\t\t\t\tcascade = CSM_cascades[ UNROLLED_LOOP_INDEX ];\n\t\t\t\tcascadeCenter = ( cascade.x + cascade.y ) / 2.0;\n\t\t\t\tclosestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y;\n\t\t\t\tmargin = 0.25 * pow( closestEdge, 2.0 );\n\t\t\t\tcsmx = cascade.x - margin / 2.0;\n\t\t\t\tcsmy = cascade.y + margin / 2.0;\n\t\t\t\tif( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) {\n\n\t\t\t\t\tfloat dist = min( linearDepth - csmx, csmy - linearDepth );\n\t\t\t\t\tfloat ratio = clamp( dist / margin, 0.0, 1.0 );\n\n\t\t\t\t\tvec3 prevColor = directLight.color;\n\t\t\t\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\t\t\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\n\t\t\t\t\tbool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter;\n\t\t\t\t\tdirectLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 );\n\n\t\t\t\t\tReflectedLight prevLight = reflectedLight;\n\t\t\t\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\n\t\t\t\t\tbool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter;\n\t\t\t\t\tfloat blendRatio = shouldBlend ? ratio : 1.0;\n\n\t\t\t\t\treflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio );\n\t\t\t\t\treflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio );\n\t\t\t\t\treflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio );\n\t\t\t\t\treflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio );\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n            #else \n            \n                directionalLightShadow = directionalLightShadows[ i ];\n                directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n    \n                RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\n\t\t\t#endif\n\t\t\t\n\t\t\t#endif\n\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#elif defined (USE_SHADOWMAP)\n\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\t\tdirectionalLight = directionalLights[ i ];\n\t\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\n\t\t\t#if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\n                directionalLightShadow = directionalLightShadows[ i ];\n\t\t\t\t\n\t\t\t\t#if ( UNROLLED_LOOP_INDEX < CSM_CASCADES )\n\n\t\t\t\t\tif(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;\n\n\t\t\t\t\tif(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 );\n\n\t\t\t\t#else\n\n\t\t\t\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\n\t\t\t\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\n\t\t\t\t#endif\n\t\t\t\t\n\t\t\t#endif\n\n\t\t}\n\t\t#pragma unroll_loop_end\n\n\t#elif ( NUM_DIR_LIGHT_SHADOWS > 0 )\n\t\t// note: no loop here - all CSM lights are in fact one light only\n\t\tgetDirectionalLightInfo( directionalLights[0], directLight );\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\n\t#endif\n\n\t#if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS)\n\t\t// compute the lights not casting shadows (if any)\n\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) {\n\n\t\t\tdirectionalLight = directionalLights[ i ];\n\n\t\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\n\t\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\n\t\t}\n\t\t#pragma unroll_loop_end\n\n\t#endif\n\n#endif\n\n\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !( defined( USE_CSM ) && defined( CSM_CASCADES ) )\n"),Ts.lights_pars_begin="\n#if defined( USE_CSM ) && defined( CSM_CASCADES )\nuniform vec2 CSM_cascades[CSM_CASCADES];\nuniform float cameraNear;\nuniform float shadowFar;\n#endif\n\t"+Ts.lights_pars_begin)}},c.PluginType="CascadedShadowsPlugin",c);ek([Hg(),qm(),Qm("setDirty")],ik.prototype,"enabled"),ek([Qm("cameraNeedsUpdate"),qm(),zg()],ik.prototype,"maxFar"),ek([Qm("cameraNeedsUpdate"),qm(),Ng(void 0,["uniform","logarithmic","practical"])],ik.prototype,"mode"),ek([Hg(),qm()],ik.prototype,"attachToFirstLight"),ek([Qm("cameraNeedsUpdate"),qm(),Hg()],ik.prototype,"fade"),ek([Qm("refreshLights")],ik.prototype,"light"),ek([Qm("cameraNeedsUpdate")],ik.prototype,"customSplitsCallback"),ek([jg()],ik.prototype,"refreshAttachedLight");let nk=ik;class rk{constructor(e={}){this._inverseProjectionMatrix=new Sn,this.vertices={near:[new Xi,new Xi,new Xi,new Xi],far:[new Xi,new Xi,new Xi,new Xi]},void 0!==e.projectionMatrix&&this.setFromProjectionMatrix(e.projectionMatrix,e.maxFar||1e4)}setFromProjectionMatrix(e,t){const i=0===e.elements[11];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(e=>{e.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(e=>{e.applyMatrix4(this._inverseProjectionMatrix);const n=Math.abs(e.z);i?e.z*=Math.min(t/n,1):e.multiplyScalar(Math.min(t/n,1))}),this.vertices}split(e,t){for(;e.length>t.length;)t.push(new rk);t.length=e.length;for(let i=0;i<e.length;i++){const n=t[i];if(0===i)for(let e=0;e<4;e++)n.vertices.near[e].copy(this.vertices.near[e]);else for(let t=0;t<4;t++)n.vertices.near[t].lerpVectors(this.vertices.near[t],this.vertices.far[t],e[i-1]);if(i===e.length-1)for(let e=0;e<4;e++)n.vertices.far[e].copy(this.vertices.far[e]);else for(let t=0;t<4;t++)n.vertices.far[t].lerpVectors(this.vertices.near[t],this.vertices.far[t],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 sk=Object.defineProperty,ak=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&sk(t,i,s),s};const ok=(h=class extends sw{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(sU,e=>{this._picking=e,this._picking?.addEventListener("selectedObjectChanged",this._refreshUiConfig)},()=>{this._picking?.removeEventListener("selectedObjectChanged",this._refreshUiConfig),this._picking=void 0},this),this._previewGenerator=new _v,e.addEventListener("preFrame",this._refreshUi),e.addEventListener("preFrame",this._preFrame)}reapplyAll(){this.variations.forEach(async e=>{void 0!==e.selectedIndex&&this.applyVariation(e,e.selectedIndex)})}fromJSON(e,t){return this.variations=[],super.fromJSON(e,t)?((this.applyOnLoadForce&&!1!==e.applyOnLoad||void 0!==e.applyOnLoad&&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??1?null!==e.match("string"==typeof t.uuid?"^"+t.uuid+"$":t.uuid):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&&void 0===t.regex&&(t.regex=!0),t}applyVariation(e,t,i,n){const r=this._viewer?.materialManager;if(!r)return!1;const s=this.findMaterialVariation(t,e);if(!s)return!1;i&&(e.selectedIndex=e.materials.indexOf(s));const a=void 0!==n?.from?this.findMaterialVariation(n.from,e):void 0;return r.applyMaterial(s,e.uuid,e.regex??!0,void 0!==n?.from?{...n,from:a}:n)}findMaterialVariation(e,t){return"string"==typeof e?t.materials.find(t=>t.uuid===e):t.materials[e]}async applyVariationAnimate(t,i,n=500){t._animation&&t._animation.stop();const r=this._viewer?.getPlugin(NR);if(!r)throw new Error("MaterialConfiguratorBasePlugin - PopmotionPlugin is required for animation, please add it to the viewer.");this._viewer?.getPlugin(e.FrameFadePlugin)?.disable(h.PluginType);const s=r.animateNumber({duration:n,onUpdate:(e,n)=>{this.applyVariation(t,i,!0,{t:e,dt:n})},onComplete:()=>{this.applyVariation(t,i,!0,{t:1,dt:0})},onEnd:()=>{t._animation===s&&(t._animation=void 0)}});t._animation=s,await(t._animation?.promise),this._viewer?.getPlugin(e.FrameFadePlugin)?.enable(h.PluginType)}getPreview(e,t,i=!0){if(!this._viewer)return"";const n=e;if(!n)return"";let r="";if(t.startsWith("generate:"))r=this._previewGenerator.generate(n,this._viewer.renderManager.renderer,this._viewer.scene.environment,t.split(":")[1]);else{const e=n[t]||"#ff00ff";r=e.image?Zm(e.image,100):"",r.length||(r=ig(e.isColor?e.getHexString():e))}return i&&this._viewer.setDirty(),r}refreshUi(){this.isDisabled()||!this._viewer||Im(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)&&(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 r of this.variations){if(!r.timeline?.length)continue;const s=r.selectedIndex,a=r.timeline.sort((e,t)=>-e.time+t.time),o=a.find(t=>t.time<=e),l=o?a.indexOf(o):-1,c=l<a.length-1&&l>=0?a[l+1]:i&&l>0?a[0]:void 0,h=!this._viewer?.timeline.running;if(o){const i=typeof s>"u"||o.index!==s&&("number"!=typeof s||o.index!==r.materials[s]?.uuid);if(h||i){const i=o.time,s=o.duration??.5;let a=s<1e-6?1:(e-i)/s,l=s<1e-6?0:t/s;a>1&&(a=1),l<1e-6&&(l=1/60),this.applyVariation(r,o.index,a>=.99999,{t:a,dt:l,from:h?c?.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(yC.MaterialProperties).filter(e=>e.endsWith("Map"))].map(e=>({label:e,value:e}))},{type:"checkbox",label:"regex mapping",property:()=>[e,"regex"],onChange:async()=>this.refreshUi()},...e.materials.map(e=>e.uiConfig?Object.assign(e.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 i=this.findVariation(t??e.uuid);!i&&!t&&e.name.length>0&&(i=this.findVariation(e.name)),i||(i=this.createVariation(e,t)),i.materials.push(n),this.refreshUi()}}createVariation(e,t){return this.variations.push({uuid:t??e.name.length>0?gm(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]}},h.PluginType="MaterialConfiguratorPlugin",h);ak([qm()],ok.prototype,"applyOnLoad"),ak([qm()],ok.prototype,"variations");let lk=ok;var ck=Object.defineProperty,hk=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&ck(t,i,s),s};const dk=class extends sw{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(e=>e.name);let i;return e.traverseAncestors(e=>{i||e.name&&t.includes(e.name)&&(i=e)}),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(sU,e=>{this._picking=e,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 r="number"==typeof t?n.children[t]:n.children.find(e=>e.name===t||e.uuid===t);if(!r)return this._viewer?.console.warn("SwitchNodePlugin: child not found",t),!1;e.selected=r.name||r.uuid;let s=!1;for(const t of n.children){const i=t.visible;t.visible=(t.name||t.uuid)===e.selected,s=s||i!==t.visible}return s&&i&&this._viewer.scene.setDirty({refreshScene:this.refreshScene,frameFade:!0}),s}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)?(void 0===e.applyOnLoad&&(this.applyOnLoad=!0),this.applyOnLoad&&this.reapplyAll(),this):null}refreshUi(){this.enabled&&(this._uiNeedRefresh=!0)}_refreshUi(){return!(!this.enabled||!this._viewer)&&(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,r=new Xi((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 s=vv(this._viewer.renderManager.renderer,t,this._viewer?.scene,7,r.multiplyScalar(2*e.camDistance));return i&&this._viewer.setDirty(),s}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){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 t=this.getPreview(e,i,!1);t&&(i.userData.__icon=t)}}else console.warn("no object found for variation, skipping",e)}}};dk.PluginType="SwitchNodePlugin";let uk=dk;function pk(e,t,i,n,r){const s=e.getAttribute(t),a=Array.isArray(n)?n.length/i:n.count;return s&&s.count===a?(s.set(Array.isArray(n)?n:n.array),s.needsUpdate=!0):e.setAttribute(t,Array.isArray(n)?new Ir(n,i):n),s}function mk(e,t){const i=e.uiConfig;if(!i)return;let n=i.children?.find(e=>"object"==typeof e&&e.tags?.includes("generatedGeometry"));if(!n){n={type:"folder",label:"Generation Params",expanded:!0,tags:["generatedGeometry"],children:[]};const e=i.children?.findIndex(e=>"object"==typeof e&&("divider"===e.type||"separator"===e.type))??-1;e>=0?i.children?.splice(e,0,n):i.children?.push(n)}e.userData.__generationParamsUiType!==e.userData.generationParams.type&&(n.children=t(),e.userData.__generationParamsUiType=e.userData.generationParams.type,n.uiRefresh?.(!0,"postFrame"))}hk([qm()],uk.prototype,"refreshScene"),hk([qm()],uk.prototype,"variations");class gk{constructor(e){this.type=e,this.defaultMeshClass=()=>DC,this.defaultMaterialClass=()=>yC,this.defaultGeometryClass=()=>UC}createUiConfig(e){if(!e.userData.generationParams)return[];const t=Rg(e.userData.generationParams)?.flatMap(e=>Im(e)).filter(e=>"type"!==Im(e.property)?.[1])||[];return t.forEach(t=>{t.onChange=()=>this.generate(e)}),t}generate(e,t={}){const i=e??new UC;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:r,vertices:s,normals:a,uvs:o,groups:l,positions:c}=this._generateData(n);if(void 0!==c&&i.setPositions?i.setPositions(c):(r&&function(e,t){const i=e.index;i&&i.count===(Array.isArray(t)?t.length:t.count)?(i.set(Array.isArray(t)?t:t.array),i.needsUpdate=!0):e.setIndex(t)}(i,r),s&&pk(i,"position",3,s),a&&pk(i,"normal",3,a),o&&pk(i,"uv",2,o)),l){i.clearGroups();for(const e of l)i.addGroup(e.start,e.count,e.materialIndex)}return i.computeBoundingBox&&i.computeBoundingBox(),i.computeBoundingSphere&&i.computeBoundingSphere(),Object.assign(i.userData.generationParams,n),mk(i,()=>this.createUiConfig(i)),i.setDirty(),i}setDefaultParams(e){return Object.assign(this.defaultParams,e),this}}class fk extends gk{constructor(e="torus",t){super(e),this.defaultParams={radius:1,tube:.4,radialSegments:12,tubularSegments:48,arc:2*Math.PI},t&&Object.assign(this.defaultParams,t)}_generateData(e){const{radius:t,tube:i,arc:n}=e;let{radialSegments:r,tubularSegments:s}=e;r=Math.floor(r),s=Math.floor(s);const a=[],o=[],l=[],c=[],h=new Xi,d=new Xi,u=new Xi;for(let e=0;e<=r;e++)for(let a=0;a<=s;a++){const p=a/s*n,m=e/r*Math.PI*2;d.x=(t+i*Math.cos(m))*Math.cos(p),d.y=(t+i*Math.cos(m))*Math.sin(p),d.z=i*Math.sin(m),o.push(d.x,d.y,d.z),h.x=t*Math.cos(p),h.y=t*Math.sin(p),u.subVectors(d,h).normalize(),l.push(u.x,u.y,u.z),c.push(a/s),c.push(e/r)}for(let e=1;e<=r;e++)for(let t=1;t<=s;t++){const i=(s+1)*e+t-1,n=(s+1)*(e-1)+t-1,r=(s+1)*(e-1)+t,o=(s+1)*e+t;a.push(i,n,o),a.push(n,r,o)}return{indices:a,vertices:o,normals:l,uvs:c}}}class Ak extends gk{constructor(e="circle",t){super(e),this.defaultParams={radius:1,segments:32,thetaStart:0,thetaLength:2*Math.PI},t&&Object.assign(this.defaultParams,t)}_generateData(e){const{radius:t,thetaStart:i,thetaLength:n}=e,r=Math.max(3,e.segments),s=[],a=[],o=[],l=[],c=new Xi,h=new fi;a.push(0,0,0),o.push(0,0,1),l.push(.5,.5);for(let e=0,s=3;e<=r;e++,s+=3){const d=i+e/r*n;c.x=t*Math.cos(d),c.y=t*Math.sin(d),a.push(c.x,c.y,c.z),o.push(0,0,1),h.x=(a[s]/t+1)/2,h.y=(a[s+1]/t+1)/2,l.push(h.x,h.y)}for(let e=1;e<=r;e++)s.push(e,e+1,0);return{indices:s,vertices:a,normals:o,uvs:l}}}class yk extends gk{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,r,s,a,o,l,c,h,d){const{indices:u,vertices:p,normals:m,uvs:g,numberOfVertices:f,groupStart:A,groups:y}=e,v=a/c,_=o/h,b=a/2,x=o/2,w=l/2,C=c+1,S=h+1;let M=0,E=0;const T=new Xi;for(let e=0;e<S;e++){const a=e*_-x;for(let o=0;o<C;o++){const d=o*v-b;T[t]=d*r,T[i]=a*s,T[n]=w,p.push(T.x,T.y,T.z),T[t]=0,T[i]=0,T[n]=l>0?1:-1,m.push(T.x,T.y,T.z),g.push(o/c),g.push(1-e/h),M+=1}}for(let e=0;e<h;e++)for(let t=0;t<c;t++){const i=f+t+C*e,n=f+t+C*(e+1),r=f+(t+1)+C*(e+1),s=f+(t+1)+C*e;u.push(i,n,s),u.push(n,r,s),E+=6}y.push({start:A,count:E,materialIndex:d}),e.groupStart+=E,e.numberOfVertices+=M}_generateData(e){const{width:t,height:i,depth:n}=e;let{widthSegments:r,heightSegments:s,depthSegments:a}=e;r=Math.floor(r),s=Math.floor(s),a=Math.floor(a);const o={indices:[],vertices:[],normals:[],uvs:[],numberOfVertices:0,groupStart:0,groups:[]};return this._buildPlane(o,"z","y","x",-1,-1,n,i,t,a,s,0),this._buildPlane(o,"z","y","x",1,-1,n,i,-t,a,s,1),this._buildPlane(o,"x","z","y",1,1,t,n,i,r,a,2),this._buildPlane(o,"x","z","y",1,-1,t,n,-i,r,a,3),this._buildPlane(o,"x","y","z",1,-1,t,i,n,r,s,4),this._buildPlane(o,"x","y","z",-1,-1,t,i,-n,r,s,5),o}}class vk extends gk{constructor(e="sphere",t){super(e),this.defaultParams={radius:1,widthSegments:32,heightSegments:16,phiStart:0,phiLength:2*Math.PI,thetaStart:0,thetaLength:Math.PI},t&&Object.assign(this.defaultParams,t)}_generateData(e){const{radius:t,phiStart:i,phiLength:n,thetaStart:r,thetaLength:s}=e;let{widthSegments:a,heightSegments:o}=e;a=Math.max(3,Math.floor(a)),o=Math.max(2,Math.floor(o));const l=Math.min(r+s,Math.PI);let c=0;const h=[],d=new Xi,u=new Xi,p=[],m=[],g=[],f=[];for(let e=0;e<=o;e++){const p=[],A=e/o;let y=0;0===e&&0===r?y=.5/a:e===o&&l===Math.PI&&(y=-.5/a);for(let e=0;e<=a;e++){const o=e/a;d.x=-t*Math.cos(i+o*n)*Math.sin(r+A*s),d.y=t*Math.cos(r+A*s),d.z=t*Math.sin(i+o*n)*Math.sin(r+A*s),m.push(d.x,d.y,d.z),u.copy(d).normalize(),g.push(u.x,u.y,u.z),f.push(o+y,1-A),p.push(c++)}h.push(p)}for(let e=0;e<o;e++)for(let t=0;t<a;t++){const i=h[e][t+1],n=h[e][t],s=h[e+1][t],a=h[e+1][t+1];(0!==e||r>0)&&p.push(i,n,a),(e!==o-1||l<Math.PI)&&p.push(n,s,a)}return{indices:p,vertices:m,normals:g,uvs:f}}}class _k extends gk{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),r=Math.floor(e.heightSegments),s=n+1,a=r+1,o=e.width/n,l=e.height/r,c=[],h=[],d=[],u=[];for(let e=0;e<a;e++){const a=e*l-i;for(let i=0;i<s;i++){const s=i*o-t;h.push(s,-a,0),d.push(0,0,1),u.push(i/n),u.push(1-e/r)}}for(let e=0;e<r;e++)for(let t=0;t<n;t++){const i=t+s*e,n=t+s*(e+1),r=t+1+s*(e+1),a=t+1+s*e;c.push(i,n,a),c.push(n,r,a)}return{indices:c,vertices:h,normals:d,uvs:u}}}class bk extends gk{constructor(e="cylinder",t){super(e),this.defaultParams={radiusTop:1,radiusBottom:1,height:1,radialSegments:32,heightSegments:1,openEnded:!1,thetaStart:0,thetaLength:2*Math.PI},t&&Object.assign(this.defaultParams,t)}_generateTorso(e){const{radiusTop:t,radiusBottom:i,height:n,radialSegments:r,heightSegments:s,thetaStart:a,thetaLength:o,indexArray:l,indices:c,groups:h,vertices:d,normals:u,uvs:p,groupStart:m,halfHeight:g}=e,f=new Xi,A=new Xi;let y=0;const v=(i-t)/n;for(let c=0;c<=s;c++){const h=[],m=c/s,y=m*(i-t)+t;for(let t=0;t<=r;t++){const i=t/r,s=i*o+a,l=Math.sin(s),c=Math.cos(s);A.x=y*l,A.y=-m*n+g,A.z=y*c,d.push(A.x,A.y,A.z),f.set(l,v,c).normalize(),u.push(f.x,f.y,f.z),p.push(i,1-m),h.push(e.index++)}l.push(h)}for(let e=0;e<r;e++)for(let t=0;t<s;t++){const i=l[t][e],n=l[t+1][e],r=l[t+1][e+1],s=l[t][e+1];c.push(i,n,s),c.push(n,r,s),y+=6}h.push({start:m,count:y,materialIndex:0}),e.groupStart+=y}_generateCap(e,t){const{radiusTop:i,radiusBottom:n,radialSegments:r,thetaStart:s,thetaLength:a,indices:o,groups:l,vertices:c,normals:h,uvs:d,groupStart:u,halfHeight:p}=e,m=e.index,g=new fi,f=new Xi;let A=0;const y=!0===t?i:n,v=!0===t?1:-1;for(let t=1;t<=r;t++)c.push(0,p*v,0),h.push(0,v,0),d.push(.5,.5),e.index++;const _=e.index;for(let t=0;t<=r;t++){const i=t/r*a+s,n=Math.cos(i),o=Math.sin(i);f.x=y*o,f.y=p*v,f.z=y*n,c.push(f.x,f.y,f.z),h.push(0,v,0),g.x=.5*n+.5,g.y=.5*o*v+.5,d.push(g.x,g.y),e.index++}for(let e=0;e<r;e++){const i=m+e,n=_+e;!0===t?o.push(n,n+1,i):o.push(n+1,n,i),A+=3}l.push({start:u,count:A,materialIndex:!0===t?1:2}),e.groupStart+=A}_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),!1===e.openEnded&&(e.radiusTop>0&&this._generateCap(n,!0),e.radiusBottom>0&&this._generateCap(n,!1)),n}}const xk={};function wk(e,t,i=xk){return{type:"dropdown",label:"Curve Type",children:Object.keys(i).map(e=>({label:e.replace(/([A-Z])/g," $1").trim(),value:e})),getValue:()=>e&&e.type||"LineCurve3",setValue:n=>{const r=e.type?i[e.type]:null,s=i[n];if(!e||!s||e.type===n)return!0;const a=s.ctor;if(!a)return!1;const o=new a;if(Array.isArray(o.points)&&0===o.points.length){const e=o.type.endsWith("3")?new Xi:new fi,t=o.type.endsWith("3")?new Xi(1,1,1):new fi(1,1);o.points.push(e,t)}if(Array.isArray(o.curves)&&0===o.curves.length){const e=o.type.endsWith("3")?new yh(new Xi(0,0,0),new Xi(1,1,0)):new Ah(new fi(0,0),new fi(1,1));o.curves.push(e)}if(r){const t=Object.entries(r.vals).map(([t,i])=>[t,e[i],s.vals[t]]).filter(([e,t,i])=>null!=t&&!!i);for(const[,e,i]of t){const t=o[i];void 0!==t&&("object"==typeof t&&"function"==typeof t.copy?o[i].copy(e):Array.isArray(t)&&Array.isArray(e)?o[i]=[...e]:o[i]="object"==typeof t&&"object"==typeof e&&null!==e?{...e}:e)}}return t(o),!0}}}function Ck(e,t=xk){const i=e.type,n=t[i];if(!n)return[];const r={type:"folder",label:i.replace(/([A-Z])/g," $1").trim(),children:n.getUiConfig(e)||[]};return e.uiConfig=r,[r]}xk.LineCurve={ctor:Ah,vals:{start:"v1",end:"v2"},getUiConfig:e=>[Dg(e,"v1","Start Point"),Dg(e,"v2","End Point")]},xk.CubicBezierCurve={ctor:gh,vals:{start:"v0",end:"v3",control1:"v1",control2:"v2"},getUiConfig:e=>[Dg(e,"v0","Start Point"),Dg(e,"v1","Control Point 1"),Dg(e,"v2","Control Point 2"),Dg(e,"v3","End Point")]},xk.QuadraticBezierCurve={ctor:vh,vals:{start:"v0",end:"v2",control1:"v1"},getUiConfig:e=>[Dg(e,"v0","Start Point"),Dg(e,"v1","Control Point"),Dg(e,"v2","End Point")]},xk.EllipseCurve={ctor:rh,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise",rotation:"aRotation"},getUiConfig:e=>[Dg(e,"aX","X Center"),Dg(e,"aY","Y Center"),Dg(e,"xRadius","X Radius"),Dg(e,"yRadius","Y Radius"),Dg(e,"aStartAngle","Start Angle"),Dg(e,"aEndAngle","End Angle"),Dg(e,"aClockwise","Clockwise"),Dg(e,"aRotation","Rotation")]},xk.ArcCurve={ctor:sh,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise"},getUiConfig:e=>{const t=Dg(e,"xRadius","Radius");if(t){const i=t.onChange;t.onChange=(...t)=>{e.yRadius=e.xRadius,i?.(...t)}}return[Dg(e,"aX","X Center"),Dg(e,"aY","Y Center"),t,Dg(e,"aStartAngle","Start Angle"),Dg(e,"aEndAngle","End Angle"),Dg(e,"aClockwise","Clockwise")]}},xk.SplineCurve={ctor:bh,vals:{points:"points"},getUiConfig:e=>[()=>e.points.map((t,i)=>Dg(e.points,i.toString(),`Point ${i}`)),{type:"button",label:"Add Point",value:()=>{const t=e.points,i=t[t.length-1]||new fi(0,0),n=t[t.length-2]||new fi(1,1);t.push(i.clone().add(i.clone().sub(n))),e.points=t,e.updateArcLengths(),e.uiConfig?.uiRefresh?.(!0,"postFrame")}}]},xk.LineCurve3={...xk.LineCurve,ctor:yh},xk.CubicBezierCurve3={...xk.CubicBezierCurve,ctor:fh},xk.QuadraticBezierCurve3={...xk.QuadraticBezierCurve,ctor:_h},xk.CatmullRomCurve3={ctor:dh,vals:{points:"points",closed:"closed",curveType:"curveType",tension:"tension"},getUiConfig:e=>[()=>e.points.map((t,i)=>Dg(e.points,i.toString(),`Point ${i}`)),{type:"button",label:"Add Point",value:()=>{const t=e.points,i=t[t.length-1]||new Xi(0,0,0),n=t[t.length-2]||new Xi(1,1,0);t.push(i.clone().add(i.clone().sub(n))),e.points=t,e.updateArcLengths(),e.uiConfig?.uiRefresh?.(!0,"postFrame")}},Dg(e,"closed","Closed Loop"),{type:"dropdown",property:[e,"curveType"],label:"Curve Type",children:["centripetal","chordal","catmullrom"].map(e=>({label:e,value:e}))},Dg(e,"tension","Tension")]},xk.EllipseCurve3D={ctor:QC,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise",rotation:"aRotation"},getUiConfig:xk.EllipseCurve.getUiConfig},xk.CurvePath={ctor:wh,vals:{},getUiConfig:e=>[()=>e.curves.map((t,i)=>{if(t.uiConfig)return t.uiConfig;const n=t.type,r=xk[n];if(r){const s=r.getUiConfig(t)||[],a={type:"folder",label:n.replace(/([A-Z])/g," $1").trim(),children:[wk(t,t=>{e.curves[i]=t,e.updateArcLengths(),e.uiConfig?.uiRefresh?.(!0,"postFrame")}),...s,{type:"button",label:"Remove Curve",value:()=>(e.curves.splice(i,1),e.updateArcLengths(),e.uiConfig?.uiRefresh?.(!0,"postFrame"),!0)}]};return t.uiConfig=a,a}}),{type:"button",label:"Add Curve",value:()=>{const t=e.type.endsWith("3")?new yh(new Xi(0,0,0),new Xi(1,1,0)):new Ah(new fi(0,0),new fi(1,1));return e.add(t),e.updateArcLengths(),e.uiConfig?.uiRefresh?.(!0,"postFrame"),!0}}]},xk.CurvePath3={...xk.CurvePath,ctor:u_};class Sk extends gk{constructor(e="tube",t){super(e),this.defaultParams={path:new QC(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 xd(e.path,e.tubularSegments,e.radius,e.radialSegments,e.closed),i=t.getAttribute("position"),n=t.getAttribute("normal"),r=t.getAttribute("uv"),s={indices:t.index?Array.from(t.index.array):[],vertices:i,normals:n,uvs:r};return t.dispose(),s}createUiConfig(e){const t=e.userData.generationParams;if(!t)return[];const i=super.createUiConfig(e).filter(e=>"path"!==e.label);return[wk(t.path,i=>{t.path=i,e.userData.__generationParamsUiType="",this.generate(e)}),...Ck(t.path),...i]}}function Mk(e,t){const i=new Fh;switch(e){case"rectangle":{const e=(t.width??1)/2,n=(t.height??1)/2;return i.moveTo(-e,-n),i.lineTo(e,-n),i.lineTo(e,n),i.lineTo(-e,n),i.closePath(),i}case"circle":{const e=t.circleRadius??1,n=t.circleSegments??32;for(let t=0;t<n;t++){const r=t/n*Math.PI*2,s=e*Math.cos(r),a=e*Math.sin(r);0===t?i.moveTo(s,a):i.lineTo(s,a)}return i.closePath(),i}case"polygon":{const e=Math.max(3,t.sides??6),n=t.polygonRadius??1;for(let t=0;t<e;t++){const r=t/e*Math.PI*2-Math.PI/2,s=n*Math.cos(r),a=n*Math.sin(r);0===t?i.moveTo(s,a):i.lineTo(s,a)}return i.closePath(),i}default:throw new Error("Unknown shape preset type: "+e)}}function Ek(e){const t=e.getPoints();return t.reverse(),new Fh(t)}class Tk extends gk{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=Mk(e.shapeType,e),i=new Ad(t,e.curveSegments);i.computeVertexNormals();const n=i.getAttribute("position"),r=i.getAttribute("normal"),s=i.getAttribute("uv"),a={indices:i.index?Array.from(i.index.array):[],vertices:n,normals:r,uvs:s};return i.dispose(),a}createUiConfig(e){const t=e.userData.generationParams;if(!t)return[];const i=super.createUiConfig(e);for(const e of i){const i=e.label;"width"===i||"height"===i?e.hidden=()=>"rectangle"!==t.shapeType:"circleRadius"===i||"circleSegments"===i?e.hidden=()=>"circle"!==t.shapeType:("sides"===i||"polygonRadius"===i)&&(e.hidden=()=>"polygon"!==t.shapeType)}return i}}class Ik extends gk{constructor(e="tubeShape",t){super(e),this.defaultParams={path:new QC(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=Ek("custom"===e.shapeType&&e.shape?e.shape:Mk(e.shapeType,e)),i=new zC(t,e.path,e.shapeSegments,e.tubularSegments,e.closed,new fi(e.shapeScaleX,e.shapeScaleY),e.primary);if(e.materialSplits){const t=e.materialSplits.split(",").map(e=>parseFloat(e.trim())).filter(e=>!isNaN(e));t.length>0&&i.createSplits(t)}const n=i.getAttribute("position"),r=i.getAttribute("normal"),s=i.getAttribute("uv"),a={indices:i.index?Array.from(i.index.array):[],vertices:n,normals:r,uvs:s};return i.groups.length>0&&(a.groups=i.groups.map(e=>({start:e.start,count:e.count,materialIndex:e.materialIndex}))),i.dispose(),a}createUiConfig(e){const t=e.userData.generationParams;if(!t)return[];const i=super.createUiConfig(e).filter(e=>{const t=e.label;return"path"!==t&&"shape"!==t});for(const e of i){const i=e.label;"width"===i||"height"===i?e.hidden=()=>"rectangle"!==t.shapeType:"circleRadius"===i||"circleSegments"===i?e.hidden=()=>"circle"!==t.shapeType:("sides"===i||"polygonRadius"===i)&&(e.hidden=()=>"polygon"!==t.shapeType)}return[wk(t.path,i=>{t.path=i,e.userData.__generationParamsUiType="",this.generate(e)}),...Ck(t.path),...i]}}const Pk=class e extends gk{constructor(t="line",i){super(t),this.defaultParams={curve:new yh(new Xi(0,0,0),new Xi(1,1,0)),segments:50,closePath:!1},this.defaultMeshClass=()=>e.UseMeshLines?LC:Nc,this.defaultMaterialClass=()=>e.UseMeshLines?MC:xC,this.defaultGeometryClass=()=>e.UseMeshLines?FC:UC,i&&Object.assign(this.defaultParams,i)}_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),r=e.closePath||!1;i.updateArcLengths();const s=i.getSpacedPoints(n-1);s.length!==n&&console.error(`LineGeometryGenerator: Curve points length (${s.length}) does not match segments (${n}).`);for(const e of s)"z"in e?t.push(e.x,e.y,e.z):t.push(e.x,e.y,0);if(r&&s.length>0){const e=s[0];"z"in e?t.push(e.x,e.y,e.z):t.push(e.x,e.y,0)}return{vertices:t,normals:[],uvs:[],positions:t}}createUiConfig(e){const t=super.createUiConfig(e),i=t.find(e=>"curve"===e.label&&"folder"===e.type),n=e.userData.generationParams?.curve;if(!n)return[];if(n?.uiConfig){const e=i?t.indexOf(i):-1;e>=0?t.splice(e,1,n.uiConfig):t.push(n.uiConfig)}else if(i){const e=Ck(n);if(e.length>0){const n=t.indexOf(i);t.splice(n,1,...e)}}return[wk(n,t=>{e.userData.generationParams.curve=t,e.userData.__generationParamsUiType="",this.generate(e)}),...t]}};Pk.UseMeshLines=!0;let Dk=Pk;const Rk=class extends sw{constructor(){super(...arguments),this.enabled=!0,this.toJSON=void 0,this.generators={plane:new _k("plane"),sphere:new vk("sphere"),box:new yk("box"),circle:new Ak("circle"),torus:new fk("torus"),cylinder:new bk("cylinder"),tube:new Sk("tube"),shape:new Tk("shape"),tubeShape:new Ik("tubeShape"),line:new Dk("line")},this.defaultMeshClass=DC,this.defaultMaterialClass=yC,this.defaultGeometryClass=UC,this._objectAdd=e=>{const t=e.object,i=t?.geometry?.userData?.generationParams?.type;i&&mk(t.geometry,()=>{const e=t.geometry;if(!e)return[];const n=this.generators[i];return n?.createUiConfig?n.createUiConfig(e)??[]:[]})},this._objectRemove=e=>{const t=e.object?.geometry;t?.userData?.generationParams?.type&&function(e){const t=e.uiConfig;if(!t)return;const i=t.children?.findIndex(e=>"object"==typeof e&&e.tags?.includes("generatedGeometry"))??-1;i>=0&&(t.children?.splice(i,1),t.uiRefresh?.(!0,"postFrame"))}(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,...r}={}){const s=this.generators[e];if(!s)throw new Error("Unknown generator type: "+e);let a=t;const o=a?.geometry||i||(s.defaultGeometryClass?new(s.defaultGeometryClass()):new this.defaultGeometryClass),l=a?.material||n||(s.defaultMaterialClass?new(s.defaultMaterialClass()):new this.defaultMaterialClass);return a=a||(s.defaultMeshClass?new(s.defaultMeshClass())(o,l):new this.defaultMeshClass(o,l)),a&&(a.geometry!==o&&(a.geometry=o),a.material!==l&&(a.material=l),s.generate(a.geometry,r),a.name=e,o.name||(o.name="Generated "+pm(e)),l.name||(l.name="Material for "+o.name),a)}generateGeometry(e,t,i){const n=this.generators[e];if(!n)throw new Error("Unknown generator type: "+e);const r=n.generate(i,t);return r.name="Generated "+e,r}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(e=>this._objectAdd({object:e})),e.object3dManager.addEventListener("objectAdd",this._objectAdd),e.object3dManager.addEventListener("objectRemove",this._objectRemove),e.forPlugin("Object3DGeneratorPlugin",e=>{e.addObject3DGenerators("geometry-",Object.fromEntries(Object.keys(this.generators).map(e=>[e,t=>{const i=this.generateObject(e,t);return i.name=e,i}])))},e=>{e.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(e=>this._objectRemove({object:e})),super.onRemove(e)}};Rk.PluginType="GeometryGeneratorPlugin";let Bk=Rk;var Lk=Object.defineProperty,Ok=Object.getOwnPropertyDescriptor,Uk=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?Ok(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&Lk(t,i,s),s};e.ShapeTubeExtrudePlugin=class extends sw{constructor(){super(...arguments),this.dependencies=[sU,Bk],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 e=this._viewer?.getPlugin(sU)?.getSelectedObject();if(!e||!e.geometry)return;const t=new QC(0,0,1,1,0,2*Math.PI,!1,0);this.extrudeObject(e,t)}}extrudeObject(t,i,n=this.shapeSegments,r=this.tubularSegments,s=this.shapeScaleX,a=this.shapeScaleY,o=this.materialSplits,l=this.horizontalSplits){if(!this._viewer)return;if(t.userData._extrudeSource){const e=t.userData._extrudeSource,i=t.parent?.children.find(t=>e===t.uuid);if(!i)return void console.warn("Could not find extrude source with uuid",e);t=i}if(t.userData.extrudedObject){const e=t.userData.extrudedObject,i=t.parent?.children.find(t=>e===t.uuid);i&&i.dispose?.(!0),delete t.userData.extrudedObject}const c=t.geometry;if(!c)return void console.warn("ShapeTubeExtrudePlugin: No geometry to extrude");let h;try{h=e.ShapeTubeExtrudePlugin.ConvertGeometryToFlatShape(c)}catch(e){return void console.warn("ShapeTubeExtrudePlugin:","string"==typeof e?e:e?.message)}const d=this._viewer.getPlugin(Bk);if(!d)return;const u=o?o.split(",").map(e=>parseFloat(e.trim())).filter(e=>!isNaN(e)).join(", "):"",p=d.generateObject("tubeShape",{path:i,shapeType:"custom",shape:h,shapeSegments:n,tubularSegments:r,closed:!0,shapeScaleX:s,shapeScaleY:a,primary:l?"shape":"path",materialSplits:u});p.userData._extrudeSource=t.uuid,p.userData.isExtrudedTube=!0,p.name=t.name+"_extruded",t.visible=!1,t.userData.extrudedObject=p.uuid,t.parent?t.parent.add(p):this._viewer.scene.addObject(p)}static ExtrudeShape(e,t,i,n=32,r=64,s=1,a=1,o="",l=!0){const c=e.getPlugin(Bk);if(c)return c.generateObject("tubeShape",{path:i,shapeType:"custom",shape:t,shapeSegments:n,tubularSegments:r,closed:!0,shapeScaleX:s,shapeScaleY:a,primary:l?"shape":"path",materialSplits:o})}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 Xi),r=n.x<.001?"x":n.y<.001?"y":n.z<.001?"z":null;if(!r)throw new Error("Geometry is not axis-aligned planar");let s=[];for(let e=0;e<i.count;e++){const t=new fi;"x"===r?t.set(i.getY(e),i.getZ(e)):"y"===r?t.set(i.getX(e),i.getZ(e)):t.set(i.getX(e),i.getY(e)),s.push(t)}if(t){let e=0;for(let t=0;t<s.length;t++)(s[t].x<s[e].x||s[t].x===s[e].x&&s[t].y<s[e].y)&&(e=t);0!==e&&(s=s.slice(e).concat(s.slice(0,e)))}const a=new Fh(s);return e.userData.__planarShape=a,a}},e.ShapeTubeExtrudePlugin.PluginType="ShapeTubeExtrudePlugin",Uk([Fg("Shape Segments",[1,100],1)],e.ShapeTubeExtrudePlugin.prototype,"shapeSegments",2),Uk([Fg("Tube Segments",[1,100],1)],e.ShapeTubeExtrudePlugin.prototype,"tubularSegments",2),Uk([Fg("Shape Scale X",[.01,10],.01)],e.ShapeTubeExtrudePlugin.prototype,"shapeScaleX",2),Uk([Fg("Shape Scale Y",[.01,10],.01)],e.ShapeTubeExtrudePlugin.prototype,"shapeScaleY",2),Uk([zg("Material Splits")],e.ShapeTubeExtrudePlugin.prototype,"materialSplits",2),Uk([Hg("Horizontal Splits")],e.ShapeTubeExtrudePlugin.prototype,"horizontalSplits",2),Uk([jg("Extrude Circle Tube")],e.ShapeTubeExtrudePlugin.prototype,"extrudeCircleTube",2),e.ShapeTubeExtrudePlugin=Uk([qg("Extrude Tube Shapes")],e.ShapeTubeExtrudePlugin);var Fk=Object.defineProperty,kk=Object.getOwnPropertyDescriptor,Nk=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?kk(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&Fk(t,i,s),s};e.HDRiGroundPlugin=class extends sw{constructor(e=!1,t=!0){super(),this.enabled=!1,this.worldRadius=100,this.tripodHeight=10,this.originPosition=new Xi(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&&"environment"!==e&&(e&&e.isDataTexture?e.mapping=ue:!this.promptOnBackgroundMismatch||this._viewer.dialog.confirmSync("Background must be same as environment, do you want to change it?")?this._viewer.scene.background="environment":this.enabled=!1);const t=this._viewer.renderManager.renderer.background.getBoxMesh2()?.material,i=t?.uniforms??Ps.backgroundCube.uniforms;i.tripodHeight||(i.tripodHeight={value:1}),i.worldRadius||(i.worldRadius={value:1}),i.originPosition||(i.originPosition={value:new Xi}),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"),!Ps.backgroundCube.fragmentShader.includes("#ifdef HDRi_GROUND_PROJ")){const t="void main() {",i=Ps.backgroundCube.fragmentShader.split(t);2!==i.length?e.console.error("HDRi Ground Plugin: Could not parse backgroundCube shader"):Ps.backgroundCube.fragmentShader=i[0]+`\n\n#ifdef HDRi_GROUND_PROJ\nfloat 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);}\n#define PI_HALF 1.5707963267948966\nuniform 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;}\n#endif\n\n${t}\nvec3 worldDirection = \n#ifdef HDRi_GROUND_PROJ\nhdriProject()\n#else\nvWorldDirection\n#endif\n;\n${R_(i[1],"vWorldDirection","worldDirection",{replaceAll:!0})}\n`}e.scene.addEventListener("environmentChanged",this.setDirty)}},e.HDRiGroundPlugin.PluginType="HDRiGroundPlugin",Nk([qm(),Qm(e.HDRiGroundPlugin.prototype.setDirty),Hg("Enabled")],e.HDRiGroundPlugin.prototype,"enabled",2),Nk([qm(),Qm(e.HDRiGroundPlugin.prototype.setDirty),Fg("World Radius",[1,1e3],.01)],e.HDRiGroundPlugin.prototype,"worldRadius",2),Nk([qm(),Qm(e.HDRiGroundPlugin.prototype.setDirty),Fg("Tripod height",[0,50],.01)],e.HDRiGroundPlugin.prototype,"tripodHeight",2),Nk([qm(),Qm(e.HDRiGroundPlugin.prototype.setDirty),kg("Origin Position",void 0,.001,e=>({onChange:e.setDirty}))],e.HDRiGroundPlugin.prototype,"originPosition",2),Nk([qm(),Qm(e.HDRiGroundPlugin.prototype.setDirty)],e.HDRiGroundPlugin.prototype,"promptOnBackgroundMismatch",2),e.HDRiGroundPlugin=Nk([qg("HDRi Ground")],e.HDRiGroundPlugin);var jk=Object.defineProperty;const zk=(d=class extends sw{constructor(e=!0,t=!1){super(),this.enabled=!0,this.helpers=[BO,JO,GO,TO,FO,WO],this.toJSON=null,this.inSceneRoot=!1,this._widgetRoot=new PC,this.refreshObject=e=>{this._createWidget(e)||this._removeWidget(e)},this._viewerListeners={preRender:()=>{this.widgets.forEach(e=>e.preRender&&e.preRender())}},this.widgets=[],this._widgetDisposed=e=>this._unregisterWidget(e.target),this._objectAdd=e=>{const t=e.object;this._createWidget(t)},this._objectRemove=e=>{const t=e.object;this._removeWidget(t)},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(e=>this._objectAdd({object:e})),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(e=>this._objectRemove({object:e})),this.widgets.forEach(e=>e.dispose&&e.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||"widget"===e.assetType||e===this._widgetRoot||e.isWidget||e.userData.disableWidgets)return!1;let t=!1,i=!1;if(e.traverseAncestors(e=>{t=t||e===this._widgetRoot||!!e.isWidget||"widget"===e.assetType||!!e.userData.disableWidgets,i=i||e===this._modelRoot}),t||!i)return!1;const n=this.widgets.find(t=>t.object===e);if(n)return n.update&&n.update(),!0;const r=this.helpers.filter(t=>t.Check(e));for(const t of r){const i=t.Create(e);i.visible=!this.isDisabled(),this._widgetRoot.add(i),this._registerWidget(i)}return!0}_removeWidget(e){if(!e)return;const t=this.widgets.filter(t=>t.object===e);for(const e of t)e.dispose&&e.dispose(!0),e.parent&&e.removeFromParent(),this._unregisterWidget(e)}},d.PluginType="Object3DWidgetsPlugin",d);((e,t,i)=>{for(var n,r=void 0,s=e.length-1;s>=0;s--)(n=e[s])&&(r=n(t,i,r)||r);r&&jk(t,i,r)})([Qm(zk.prototype.setDirty)],zk.prototype,"enabled");let Gk=zk;var Qk=Object.defineProperty,Vk=Object.getOwnPropertyDescriptor,Hk=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?Vk(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&Qk(t,i,s),s};e.Object3DGeneratorPlugin=class extends sw{constructor(){super(),this.enabled=!0,this.toJSON=void 0,this._selectedType="",this.generators={"object-empty":(e={})=>{const t=new IC;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 PC;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 lC(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 mC(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 JC(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 Xi(0,0,0)),t.name="Directional Light",t},"light-ambient":(e={})=>{const t=new qC(e.color??16777215,e.intensity??1);return t.name="Ambient Light",t},"light-point":(e={})=>{const t=new rS(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 dS(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 Xi(0,0,0)),t.name="Spot Light",t},"light-hemisphere":(e={})=>{const t=new eS(e.color??11184895,5592131,e.intensity??1);return t.name="Hemisphere Light",t},"light-rect-area":(e={})=>{const t=new oS(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 Xi(0,0,0)),t.name="Rect Area Light",t}},this._selectedType=Object.keys(this.generators)[0]}generate(e,t,i=!0,n=!0,r=!0){if(!this._viewer)throw new Error("No viewer");const s=this.generators[e??this._selectedType]?.(t);if(i&&s){const e={redo:()=>this._viewer?.scene.addObject(s),undo:()=>s.dispose?s.dispose(!0):s.removeFromParent()};r&&this._viewer?.getPlugin("UndoManagerPlugin")?.undoManager?.record(e),e.redo(),n&&s.dispatchEvent({type:"select",value:s,object:s,ui:!0,bubbleToParent:!0,trackUndo:!1})}return s||void 0}removeObject3DGenerators(e,t=!0){return this.generators=Object.fromEntries(Object.entries(this.generators).filter(([t,i])=>!t.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(([t,i])=>{this.generators[e+t]=i}),i&&this.uiConfig?.uiRefresh?.(!0)}addObject3DGenerator(e,t,i=!0){this.removeObject3DGenerator(e,!1),this.generators[e]=t,i&&this.uiConfig?.uiRefresh?.(!0)}},e.Object3DGeneratorPlugin.PluginType="Object3DGeneratorPlugin",Hk([Ng("Type",void 0,e=>({children:[()=>Object.keys(e.generators).map(e=>({label:e}))]}))],e.Object3DGeneratorPlugin.prototype,"_selectedType",2),Hk([jg("Generate",{sendArgs:!1})],e.Object3DGeneratorPlugin.prototype,"generate",1),e.Object3DGeneratorPlugin=Hk([Wg("Generate Scene Objects")],e.Object3DGeneratorPlugin);var Wk=Object.defineProperty,qk=Object.getOwnPropertyDescriptor,Xk=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?qk(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&Wk(t,i,s),s};e.ContactShadowGroundPlugin=class extends e.BaseGroundPlugin{constructor(){super(),this.contactShadows=!0,this.shadowScale=1,this.shadowHeight=5,this.blurAmount=1,this.mapMode="aoMap",this.shadowCamera=new zs(-1,1,1,-1,.001,this.shadowHeight),this._depthTex=null,this._refreshShadowCameraFrustum=this._refreshShadowCameraFrustum.bind(this),this.refresh=this.refresh.bind(this)}onAdded(t){const i=t.renderManager.createTarget({type:Ce,format:Ue,colorSpace:Lt,size:{width:512,height:512},generateMipmaps:!1,depthBuffer:!0,minFilter:be,magFilter:be});i.texture.name="groundContactDepthTexture";const n=new el({depthPacking:Pt,transparent:!1,blending:w});n.opacity=-1,n.onBeforeCompile=e=>{e.fragmentShader=R_(e.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 e.GBufferRenderPass("contactShadowGround",i,n,new mr(1,1,1),1),this._blurHelper=new yv(t),super.onAdded(t)}onRemove(e){const t=Im(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=Im(this._depthPass.target);if(!e)return;const t=this._viewer.renderManager.getTempTarget({type:Ce,format:Ue,colorSpace:Lt,size:{width:1024,height:1024},generateMipmaps:!1,depthBuffer:!1,minFilter:be,magFilter:be});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)&&(this.shadowCamera.position.copy(this._mesh.getWorldPosition(new Xi)),this.shadowCamera.setRotationFromEuler(new On(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=Im(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="aoMap"===this.mapMode,this._material.userData.ssreflDisabled="alphaMap"===this.mapMode,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("aoMap"===this.mapMode?new mr(1,1,1):new mr(0,0,0)),this._depthPass.clearAlpha="aoMap"===this.mapMode?1:0,this._depthPass.overrideMaterial.opacity="aoMap"===this.mapMode?-1:1)),e}},e.ContactShadowGroundPlugin.PluginType="ContactShadowGroundPlugin",Xk([Hg("Contact Shadows"),Qm(e.ContactShadowGroundPlugin.prototype.refresh),qm()],e.ContactShadowGroundPlugin.prototype,"contactShadows",2),Xk([Fg("Shadow Scale",[0,2]),qm(),Qm(e.ContactShadowGroundPlugin.prototype._refreshShadowCameraFrustum)],e.ContactShadowGroundPlugin.prototype,"shadowScale",2),Xk([Fg("Shadow Height",[0,20]),qm(),Qm(e.ContactShadowGroundPlugin.prototype._refreshShadowCameraFrustum)],e.ContactShadowGroundPlugin.prototype,"shadowHeight",2),Xk([Fg("Blur Amount",[0,10]),qm(),Qm(e.ContactShadowGroundPlugin.prototype._setDirty)],e.ContactShadowGroundPlugin.prototype,"blurAmount",2),Xk([Qm(e.ContactShadowGroundPlugin.prototype._refreshMaterial),Ng("Map Mode",["aoMap","map","alphaMap"]),qm()],e.ContactShadowGroundPlugin.prototype,"mapMode",2),e.ContactShadowGroundPlugin=Xk([Wg("Ground Plane (Contact Shadows)")],e.ContactShadowGroundPlugin);var Yk=Object.defineProperty,Kk=Object.getOwnPropertyDescriptor,Jk=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?Kk(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&Yk(t,i,s),s};const Zk=class extends sw{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(sU)}simplifyGeometries(e,t){if(!e){const t=this._pickingPlugin?.getSelectedObject();if(!t?.isObject3D)return;const i=[];if(t?.traverse(e=>{e.geometry&&!i.includes(e.geometry)&&i.push(e.geometry)}),!(e=i)||!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:r=!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 s=this._simplify(e,i);s.computeBoundingBox(),s.computeBoundingSphere(),s.computeVertexNormals();const a=s.boundingBox,o=a.getSize(new Xi);if(!isFinite(o.x)||!isFinite(o.y)||!isFinite(o.z))return this._viewer?.console.error("SimplifyModifierPlugin: Unable to simplify",e,s,o),e;const l=e.boundingBox,c=l.getSize(new Xi),h=o.clone().sub(c),d=h.clone().divide(c);if(d.lengthSq()>.001&&console.warn("Simplify",e,s,a,l,o,c,h,d),!n)return s;const u=e.appliedMeshes;if(!u)return console.error("No meshes found for geometry, cannot replace",e),s;for(const e of u)e.geometry=s;return r&&e.dispose(!0),s}async simplifyAll(e,t){if(!e&&this._viewer&&(e=this._viewer.scene.modelRoot),!e)return void console.error("SimplifyModifierPlugin: No root found");if(!this.initialized&&(await this.initialize(),!this.initialized))return void this._viewer?.console.error("SimplifyModifierPlugin cannot be initialized");const i=[];if(e.traverse(e=>{e.geometry&&!i.includes(e.geometry)&&i.push(e.geometry)}),i.length)return this.simplifyGeometries(i,t);console.error("SimplifyModifierPlugin: No geometries found")}async simplifySelected(){if(!this._viewer)return;if(!this.initialized&&(await this.initialize(),!this.initialized))return void await this._viewer.dialog.alert("Simplify: SimplifyModifierPlugin cannot be initialized");const e=this._pickingPlugin?.getSelectedObject();if(!e?.isObject3D)return void await this._viewer.dialog.alert("Simplify: No Object Selected");let t=!1;e.geometry?0===e.children.length&&(t=!0):t=!0,t||await this._viewer.dialog.confirm("Simplify: Simplify all in hierarchy?")&&(t=!0),t?this.simplifyGeometries():this.simplifyGeometry(e.geometry)}};Zk.PluginType="SimplifyModifierPlugin";let $k=Zk;Jk([Fg("Simplify Factor",[0,1])],$k.prototype,"simplifyFactor",2),Jk([jg("Simplify All",{sendArgs:!1})],$k.prototype,"simplifyAll",1),Jk([jg("Simplify Selected")],$k.prototype,"simplifySelected",1);var eN=Object.defineProperty,tN=Object.getOwnPropertyDescriptor,iN=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?tN(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&eN(t,i,s),s};e.MeshOptSimplifyModifierPlugin=class extends $k{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 t=document.createElement("script");t.type="module";const i=Math.random().toString(36).substring(7);return t.innerHTML=`\nimport { MeshoptSimplifier } from ${JSON.stringify(e.MeshOptSimplifyModifierPlugin.SIMPLIFIER_URL)};\nMeshoptSimplifier.ready.then(() => {\nwindow.MeshoptSimplifier = MeshoptSimplifier;\nwindow.dispatchEvent(new CustomEvent('${i}'))\n});\n`,this._initializing=new Promise(e=>{window.addEventListener(i,()=>e(),{once:!0}),this.rootNode.appendChild(t),this._script=t}),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");const i=(e=e.index?e.clone():Yy(e)).index.array,n=e.attributes.position.array,r=t/e.attributes.position.count,s=3*Math.floor(r*i.length/3),[a,o]=window.MeshoptSimplifier.simplify(i,n,3,s,this.errorThreshold,this.lockBorder?["LockBorder"]:[]);return console.log("srcCount",i.length/3,"destCount",a.length/3),o&&console.warn("Simplify error",o),e.setIndex(new Mr(new Uint32Array(a),1)),dw.upgradeGeometry.call(e.toNonIndexed())}},e.MeshOptSimplifyModifierPlugin.PluginType="MeshOptSimplifyModifierPlugin",e.MeshOptSimplifyModifierPlugin.SIMPLIFIER_URL="https://unpkg.com/meshoptimizer@0.20.0/meshopt_simplifier.module.js",iN([Gg()],e.MeshOptSimplifyModifierPlugin.prototype,"errorThreshold",2),iN([Hg()],e.MeshOptSimplifyModifierPlugin.prototype,"lockBorder",2),e.MeshOptSimplifyModifierPlugin=iN([qg("Simplify Modifier (meshopt)")],e.MeshOptSimplifyModifierPlugin);const nN=(e,t)=>{const i={};for(const n of e.mappings)for(const e of n.variants)i[t[e]]={material:null,gltfMaterialIndex:n.material};return i},rN="KHR_materials_variants";class sN{constructor(e){this.parser=e,this.name=rN}async afterRoot(e){const t=this.parser,i=t.json;if(!i.extensions||!i.extensions[this.name])return;const n=(e=>{const t=[],i=new Set;for(const n of e){let e=n,r=0;for(;i.has(e);)e=n+"."+ ++r;i.add(e),t.push(e)}return t})((i.extensions[this.name].variants||[]).map(e=>e.name));for(const r of e.scenes)r.traverse(e=>{const r=t.associations.get(e);if(!r||void 0===r.meshes||void 0===r.primitives)return;const s=i.meshes[r.meshes].primitives[r.primitives].extensions;!s||!s[this.name]||(e.userData._variantMaterials=nN(s[this.name],n))});await Promise.all(e.scenes.map(async e=>{const i=[];return e.traverse(e=>(e=>void 0!==e.material&&e.userData&&e.userData._variantMaterials)(e)&&i.push((async e=>{const i=e.material,n=e.userData._variantMaterials,r=[];for(const i in n){const s=n[i];if(s.material)continue;const a=s.gltfMaterialIndex;r.push(t.getDependency("material",a).then(r=>{e.material=r,t.assignFinalMaterial(e),n[i].material=e.material}))}return Promise.all(r).then(()=>{e.material=i})})(e))),e.userData.__importData||(e.userData.__importData={}),e.userData.__importData[rN]={names:n},Promise.all(i)}))}}const aN=e=>void 0!==e.material&&e.userData&&e.userData._variantMaterials&&!!Object.values(e.userData._variantMaterials).filter(e=>oN(e?.material)),oN=e=>e&&e.isMaterial&&!Array.isArray(e);class lN{constructor(e){this.writer=e,this.name=rN,this.variantNames=[]}beforeParse(e){const t=new Set;for(const i of e)i.traverse(e=>{if(!aN(e))return;const i=e.userData._variantMaterials;for(const e in i){const n=i[e];oN(n.material)&&t.add(e)}});t.forEach(e=>this.variantNames.push(e))}writeMesh(e,t){if(!aN(e))return;const i=e.userData,n=i._variantMaterials,r={};for(const e in n){const t=n[e].material;if(!oN(t))continue;const i=this.variantNames.indexOf(e),s=this.writer.processMaterial(t);r[s]||(r[s]={material:s,variants:[]}),r[s].variants.push(i)}const s=Object.values(r).map(e=>e.variants.sort((e,t)=>e-t)&&e).sort((e,t)=>e.material-t.material);if(0===s.length)return;const a=oN(i._originalMaterial)?this.writer.processMaterial(i._originalMaterial)??-1:-1;for(const e of t.primitives)a>=0&&(e.material=a),e.extensions=e.extensions||{},e.extensions[this.name]={mappings:s}}afterParse(e){if(0===this.variantNames.length)return;const t=this.writer.json;t.extensions=t.extensions||{};const i=this.variantNames.map(e=>({name:e}));t.extensions[this.name]={variants:i},this.writer.extensionsUsed[this.name]=!0}}var cN=Object.defineProperty,hN=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&cN(t,i,s),s};const dN=(u=class extends sw{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(e=>{if(e.userData._variantMaterials)for(const t of Object.values(e.userData._variantMaterials))t?.material&&(t.material=this._viewer?.materialManager.convertToIMaterial(t.material,{})||t.material);const t=e.userData?.__importData?.[rN];if(!t)return;const i=t.names||[];for(const t of i)this.variants[t]||(this.variants[t]=[]),this.variants[t].push(e);delete e.userData.__importData[rN]}),!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(pN)}onRemove(e){return e.scene.removeEventListener("addSceneObject",this._objectAdded),e.assetManager.unregisterGltfExtension(pN.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 r=i?Array.isArray(i)?i:[i]:e?this.variants[e]||[]:Object.values(this.variants).flat();for(const t of r){const i=new Set,r=t=>{if(!t.userData._variantMaterials||i.has(t))return;const n=e?t.userData._variantMaterials[e]?.material:t.userData._originalMaterial;n&&(t.userData._originalMaterial||(t.userData._originalMaterial=t.material),t.material=n),i.add(t)};n?t.traverse(r):r(t)}}},u.PluginType="GLTFKHRMaterialVariantsPlugin",u);hN([Qm(dN.prototype._variantChanged),qm()],dN.prototype,"selectedVariant"),hN([qm()],dN.prototype,"applyFirstVariantOnLoad");let uN=dN;const pN={name:rN,import:e=>new sN(e),export:function(e){return new lN(e)}};var mN=Object.getOwnPropertyDescriptor;e.TailwindCSSCDNPlugin=class extends sw{constructor(){super(...arguments),this.enabled=!0,this._tailwindScript=null,this.toJSON=null}async onAdded(t){super.onAdded(t),this._tailwindScript=document.createElement("script"),this._tailwindScript.src=e.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)}},e.TailwindCSSCDNPlugin.PluginType="TailwindCDNPlugin",e.TailwindCSSCDNPlugin.CDN_URL="https://cdn.tailwindcss.com",e.TailwindCSSCDNPlugin=((e,t,i,n)=>{for(var r,s=n>1?void 0:n?mN(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(s)||s);return s})([qg("Tailwind CSS")],e.TailwindCSSCDNPlugin);const gN=class extends sw{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.");"object"==typeof e&&"function"==typeof e.then&&(e=await e);const i="string"==typeof e?e:e.__tpPluginPath||"";if(i?.length&&this.plugins.has(i))throw new Error("Plugin already loaded: "+i);const n="object"==typeof e?e:"string"==typeof i&&i?await import(i+"?t="+Date.now()):null;if(!n)throw new Error("Could not find/load module: "+i);const r=n.default||Object.values(n)[0];if(!r)throw new Error("No plugin found in module: "+i);if("function"!=typeof r)throw new Error("Plugin is not a class or function in module: "+e);if(!(r.prototype&&r.prototype instanceof rw))throw new Error("Plugin is not a subclass of AViewerPlugin in module: "+e);const s=r.PluginType;if(console.log(s),console.log(n),t.getPlugin(s))throw new Error("Plugin of type "+s+" already added to viewer");return i?.length&&this.plugins.set(i,r),await t.addPlugin(r)}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)}};gN.PluginType="DynamicImportPlugin";let fN=gN;const AN={handleHotUpdate({server:e,modules:t,timestamp:i}){const n=new Set,r=[];for(const s of t)console.log(s.id,s.url),s.url.endsWith(".plugin.ts")?(e.moduleGraph.invalidateModule(s,n,i,!0),e.ws.send({type:"custom",event:"custom-tp-plugin-update",data:{url:s.url,id:s.id}})):r.push(s);return r},transform(e,t){if(t.endsWith(".plugin.ts")){return e+`\nexport const __tpPluginPath = "${t}";\n`}}},yN={copy_position:{defaultProps:{axis:["x","y","z"],invert:[]},update:(e,t,i,n)=>{if(!t)return{changed:!1};const{axis:r=["x","y","z"],invert:s=[]}=i,a=t.getWorldPosition(new Xi);let o=!1,l=!0;return r.forEach(t=>{s.includes(t)&&(a[t]*=-1);const i=e.position[t];e.position[t]=a[t]*n+i*(1-n),o=o||Math.abs(e.position[t]-i)>1e-5,l=l&&Math.abs(e.position[t]-i)<1e-5}),{changed:o,end:l,change:"position"}},setDirty(e,t){const i=e.change||e.key;return!i||"position"===i||"transform"===i}},copy_rotation:{defaultProps:{axis:["x","y","z"],invert:[],order:void 0},update:(e,t,i,n)=>{if(!t)return{changed:!1};const{axis:r=["x","y","z"],invert:s=[]}=i;let a=i.order;const o=(new On).copy(e.rotation);a||(a=o.order),o.order=a;const l=new qi;t.getWorldQuaternion(l);const c=(new On).setFromQuaternion(l,a);let h=!1,d=!0;return r.forEach(t=>{let i=c[t];s.includes(t)&&(i*=-1);const r=e.rotation[t],a=i*n+r*(1-n);o[t]=a,h=h||Math.abs(a-r)>1e-5,d=d&&Math.abs(a-r)<1e-5}),e.rotation.copy(o),{changed:h,end:d,change:"rotation"}},setDirty(e,t){const i=e.change||e.key;return!i||"rotation"===i||"quaternion"===i||"transform"===i}},copy_scale:{defaultProps:{axis:["x","y","z"]},update:(e,t,i,n)=>{if(!t)return{changed:!1};const{axis:r=["x","y","z"],uniform:s=!1}=i,a=new Xi;t.getWorldScale(a);const o=e.scale.clone();let l=0;if(r.forEach(t=>{const i=a[t]*n+o[t]*(1-n);e.scale[t]=i,l+=i}),s){const t=l/r.length;e.scale.set(t,t,t)}return{changed:!o.equals(e.scale),end:o.distanceTo(e.scale)<1e-5,change:"scale"}},setDirty(e,t){const i=e.change||e.key;return!i||"scale"===i||"transform"===i}},copy_transforms:{defaultProps:{},update:(e,t,i,n)=>{if(!t)return{changed:!1};const r=new Sn;t.updateMatrixWorld(),r.copy(t.matrixWorld);const s=(new Xi).copy(e.position),a=(new qi).copy(e.quaternion),o=(new Xi).copy(e.scale),l=new Xi,c=new qi,h=new Xi;r.decompose(l,c,h),e.position.lerpVectors(s,l,n),e.quaternion.slerpQuaternions(a,c,n),e.scale.lerpVectors(o,h,n);return{changed:!s.equals(e.position)||!a.equals(e.quaternion)||!o.equals(e.scale),end:s.distanceTo(e.position)<1e-5&&a.angleTo(e.quaternion)<1e-5&&o.distanceTo(e.scale)<1e-5,change:"transform"}},setDirty(e,t){const i=e.change||e.key;return!i||"position"===i||"rotation"===i||"quaternion"===i||"scale"===i||"transform"===i}},follow_path:{defaultProps:{offset:0,followCurve:!1},update:(e,t,i,n)=>{if(!t)return{changed:!1};const{offset:r=0,followCurve:s=!1}=i;if(!t.geometry)return{changed:!1};const a=t.geometry,o=function(e,t){if(!e)return null;const i=e.length/3;if(i<2)return null;const n=[];let r=0;for(let t=0;t<i-1;t++){const i=e[3*t],s=e[3*t+1],a=e[3*t+2],o=e[3*(t+1)],l=e[3*(t+1)+1],c=e[3*(t+1)+2],h=Math.sqrt((o-i)**2+(l-s)**2+(c-a)**2);n.push(h),r+=h}if(0===r)return null;const s=Math.max(0,Math.min(1,t))*r;let a=0,o=0,l=0;for(let e=0;e<n.length;e++){if(a+n[e]>=s){o=e,l=(s-a)/n[e];break}a+=n[e]}const c=3*o,h=3*(o+1),d=e[c],u=e[c+1],p=e[c+2],m=e[h],g=e[h+1],f=e[h+2],A=new Xi(d+(m-d)*l,u+(g-u)*l,p+(f-p)*l),y=new Xi(m-d,g-u,f-p);return y.normalize(),{targetPos:A,direction:y}}(a.getPositions?a.getPositions():a.attributes?.position?.array,r);if(!o)return{changed:!1};const{targetPos:l,direction:c}=o,h=t.localToWorld(l.clone()),d=c?.lengthSq()>0?t.localToWorld(c.clone().add(l)).sub(h).normalize():null,u=(new Xi).copy(e.position),p=(new qi).copy(e.quaternion);e.position.copy(h);let m=!1;if(s&&d){const t=h.clone().add(d);if(e.lookAt(t),1!==n){const t=e.quaternion.clone();e.quaternion.slerpQuaternions(p,t,n)}m=!p.equals(e.quaternion)}1!==n&&e.position.lerpVectors(u,h,n);return{changed:!u.equals(e.position)||m,end:u.distanceTo(e.position)<1e-5&&(!m||p.angleTo(e.quaternion)<1e-5),change:m?"transform":"position"}},setDirty(e,t){const i=e.change||e.key;return!i||"position"===i||"transform"===i||"geometry"===i}},look_at:{defaultProps:{upAxis:"y"},update:(e,t,i,n)=>{if(!t)return{changed:!1};const{upAxis:r="y"}=i,s=t.getWorldPosition(new Xi).clone().sub(e.position).normalize(),a=new Xi(0,1,0);"x"===r?a.set(1,0,0):"-x"===r?a.set(-1,0,0):"y"===r?a.set(0,1,0):"-y"===r?a.set(0,-1,0):"z"===r?a.set(0,0,1):"-z"===r&&a.set(0,0,-1);const o=(new Xi).crossVectors(a,s).normalize();a.crossVectors(s,o).normalize();const l=new Sn;l.makeBasis(o,a,s);const c=(new qi).setFromRotationMatrix(l);e.quaternion.slerp(c,n);return{changed:!e.quaternion.equals(c),end:e.quaternion.angleTo(c)<1e-5,change:"rotation"}},setDirty(e,t){const i=e.change||e.key;return!i||"position"===i||"rotation"===i||"quaternion"===i||"scale"===i||"transform"===i}}};var vN=Object.defineProperty,_N=Object.getOwnPropertyDescriptor,bN=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?_N(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=(n?r(t,i,s):r(s))||s);return n&&s&&vN(t,i,s),s};e.ObjectConstraintsPlugin=class extends sw{constructor(e=!0){super(),this.enabled=!0,this.dependencies=[],this._objectAdd=e=>{const t=e.object;t&&(t.isWidget||(Array.isArray(t.userData.constraints)&&t.userData.constraints.forEach(e=>this._registerConstraint(e,t)),this._setupUiConfig(t),Array.from(this._constraints.keys()).forEach(e=>{e?.target===t.uuid&&this._refreshConstraint(e,t)})))},this._objectRemove=e=>{const t=e.object;t&&(Array.isArray(t.userData.constraints)&&t.userData.constraints.forEach(e=>this._unregisterConstraint(e,t)),this._cleanUpUiConfig(t),this._constraintTargets.get(t)?.forEach(e=>this._refreshConstraint(e,null)))},this._constraints=new Map,this._constraintTargets=new Map,this._constraintObjects=new Map,this._objectUpdate=e=>{this._constraintTargets.get(e.object)?.forEach(t=>{t.setDirty(e,!0)}),this._constraintObjects.get(e.object)?.forEach(t=>{t.setDirty(e,!1)})},this._viewerListeners={preFrame:()=>{this.isDisabled()||this._viewer?.timeline.running&&0===this._viewer.timeline.delta||Array.from(this._constraints.keys()).filter(e=>e.needsUpdate).forEach(e=>{const t=this._constraints.get(e);t&&e.update(t)})}},this.enabled=e}addConstraint(t,i,n){const r="string"==typeof i?new e.ObjectConstraint(i):i||new e.ObjectConstraint;return t.userData.constraints||(t.userData.constraints=[]),n&&(r.target="string"==typeof n?n:n.uuid),t.userData.constraints.includes(r)||(t.userData.constraints.push(r),this._registerConstraint(r,t),t.setDirty&&t.setDirty({change:"userData.constraints",source:"ObjectConstraintsPlugin.addConstraint"})),r}removeConstraint(e,t){if(!e.userData.constraints)return;const i=e.userData.constraints.indexOf(t);-1!==i&&(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=void 0!==t?t??void 0:this._viewer?.object3dManager.findObject(e.target),r=i.target;n!==r&&(this._removeTarget(r,e),this._addTarget(n,e)),i.target=n}_registerConstraint(e,t){if(this._constraints.has(e))return void this._refreshConstraint(e);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 i=this._viewer?.getPlugin("AnimationObjectPlugin");if(i){const r=this._animatableComponents(e);r.length&&r.forEach(e=>i.setupUiConfigButton(t,e,"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),0===n.size&&this._constraintObjects.delete(t)),this._constraints.delete(e),e.refresh=void 0,e.uiConfig){const t=this._viewer?.getPlugin("AnimationObjectPlugin");t&&this._animatableComponents(e).forEach(e=>t.cleanupUiConfigButton(e))}}}_animatableComponents(e){return e?.uiConfig?.children?.flatMap(e=>Im(e)).filter(t=>"object"==typeof t&&"number"===t.type&&"offset"===t.property[1]&&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()),0===i.size&&this._constraintTargets.delete(e))}_setupUiConfig(t){!t.isObject3D&&!t.isMaterial||!t.uiConfig||t.uiConfig?.children?.find(t=>"object"==typeof t&&t.tags?.includes(e.ObjectConstraintsPlugin.PluginType))||t.uiConfig?.children?.push({type:"folder",label:"Constraints",tags:["constraints",e.ObjectConstraintsPlugin.PluginType],children:[()=>t.userData.constraints?.map(e=>e.uiConfig),{type:"button",label:"Add Constraint",icon:"plus",tags:["context-menu","header-action"],onClick:()=>{const e=this.addConstraint(t);return()=>this.removeConstraint(t,e)}}]})}_cleanUpUiConfig(t){if(!t.uiConfig)return;const i=t.uiConfig?.children?.findIndex(t=>"object"==typeof t&&t.tags?.includes(e.ObjectConstraintsPlugin.PluginType));void 0!==i&&i>=0&&t.uiConfig.children?.splice(i,1)}onAdded(e){super.onAdded(e),e.object3dManager.getObjects().forEach(e=>this._objectAdd({object:e})),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(e=>this._objectRemove({object:e})),super.onRemove(e)}},e.ObjectConstraintsPlugin.PluginType="ObjectConstraintsPlugin",e.ObjectConstraintsPlugin.ConstraintTypes=yN,bN([Hg(),qm()],e.ObjectConstraintsPlugin.prototype,"enabled",2),e.ObjectConstraintsPlugin=bN([qg("Object Constraints")],e.ObjectConstraintsPlugin),e.ObjectConstraint=class{constructor(t){this.uuid=Ky(),this.enabled=!0,this.target="",this.influence=1,this.props={},this.needsUpdate=!1,this.setDirty=(e,t)=>{if(!this.needsUpdate&&e?.source!==this.uuid){if("object"!=typeof e&&(e=void 0),e){const i=yN[this.type];if(e.key&&/.props\..+$/.test(e.key))this._propsUi.forEach(e=>e?.uiRefresh?.());else if(i?.setDirty&&!i.setDirty(e,t))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",e.ObjectConstraintsPlugin.PluginType],onChange:this.setDirty,children:[...Rg(this),()=>{if(this._propsUi.length)return this._propsUi.forEach(e=>e.uiRefresh?.(!0)),this._propsUi;const e=Rg(this.props).map(e=>Im(e));return this._propsUi=e,e},{type:"button",tags:["context-menu"],label:"Remove Constraint",icon:"cross",property:[this,"remove"]}]},this.type=t??"copy_position",this.props=yN[this.type]?.defaultProps||{},this.props||(this.props={})}update(e){const t=yN[this.type]?.update(e.obj,e.target,this.props,this.influence);return t?.changed&&t.change&&e.obj.setDirty&&e.obj.setDirty({change:t.change,source:this.uuid}),this.needsUpdate=!(t.end??1),t?.changed||!1}typeChanged(){const e=this.props;this.props=yN[this.type]?.defaultProps||{};for(const t of Object.keys(this.props))if(void 0!==e[t]){const i=typeof this.props[t],n=typeof e[t];i===n&&("object"!=typeof i||i?.type&&i.type===n?.type)&&(this.props[t]=e[t])}this._propsUi=[],this.setDirty(),this.uiConfig?.uiRefresh?.(!0,"postFrame",1)}},bN([qm(),Hg()],e.ObjectConstraint.prototype,"enabled",2),bN([qm(),Qm("typeChanged"),Ng(void 0,Object.keys(yN).map(e=>({label:e})))],e.ObjectConstraint.prototype,"type",2),bN([qm(),Qm("refresh2"),zg()],e.ObjectConstraint.prototype,"target",2),bN([qm(),Fg(void 0,[0,1],.01)],e.ObjectConstraint.prototype,"influence",2),bN([qm()],e.ObjectConstraint.prototype,"props",2),e.ObjectConstraint=bN([Xm("ObjectConstraint")],e.ObjectConstraint);const xN=class{static AddClass(e){const t=e.ctor.prototype.serializableClassId;t?(t!==e.key&&console.warn(`TypeSystem: class serializableClassId "${t}" does not match registered className "${e.key}"`),this.Classes.set(e.key,e)):console.error("Non Serializable class cannot be added to TypeSystem",e)}static GetClass(e){const t="string"==typeof e?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(void 0===e)return!1;if(null===e)return"null";if("function"==typeof e)return!1;if("number"==typeof e)return`${e}`;if("string"==typeof e)return`${JSON.stringify(e)}`;if("boolean"==typeof e)return`${e}`;if(Array.isArray(e)){const t=new Set;for(const i of e){const e=this.GetType(i);if(!e)return!1;t.add(e)}return{arrayOf:1===t.size?t.values().next().value:{oneOf:t,type:"Union"},type:"Array"}}if("object"==typeof e){const i=e.constructor;if(i&&i!==Object){const n=this.GetClassType(i);if(n)return n;if(t){if(e.type&&jm.SerializableClasses.has(e.type))return e.type;if(e.serializableClassId&&jm.SerializableClasses.has(e.serializableClassId))return e.serializableClassId;const t=jm.GetSerializer(e);return!(!t||"string"!=typeof t.type||t.type.startsWith("_"))&&t.type}}const n=new Map;for(const t in e){const i=e[t];if("function"==typeof i)continue;const r=this.GetType(i);if(!r)return!1;n.set(t,r)}return{recordOf:n,type:"Object"}}return!1}static NonLiteral(e){return"string"!=typeof e?e:/^"(?:[^"\\]|\\.)*"$/.test(e)?"string":/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)?"number":"true"===e||"false"===e?"boolean":"Infinity"===e||"-Infinity"===e||"NaN"===e?"number":e}static TypeToString(e){return"string"==typeof e?e:"oneOf"in e?`(${Array.from(e.oneOf).map(e=>this.TypeToString(e)).join("|")})`:"arrayOf"in e?`Array<${this.TypeToString(e.arrayOf)}>`:"recordOf"in e?`{ ${Array.from(e.recordOf.entries()).map(([e,t])=>`${e}: ${this.TypeToString(t)}`).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("string"==typeof t){if("string"==typeof e)return this.NonLiteral(e)===t;if("oneOf"in e){const i=e.oneOf;for(const e of i)if(!this.CanAssign(e,t))return!1;return!0}return!1}if("oneOf"in t){const i=t.oneOf;for(const t of i)if(this.CanAssign(e,t))return!0;return!1}if("arrayOf"in t)return"string"!=typeof e&&"arrayOf"in e&&this.CanAssign(e.arrayOf,t.arrayOf);if("recordOf"in t){if("string"!=typeof e&&"recordOf"in e){for(const[i,n]of t.recordOf){const t=e.recordOf.get(i);if(!t||!this.CanAssign(t,n))return!1}return!0}return!1}return!1}};xN.Classes=new Map;let wN=xN;class CN{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=MN.Get(this);t&&(t.__rootPath?e.typed[this.id]={external:!0,rootPath:t.__rootPath,rootPathOptions:t.__rootPathOptions}:e.typed[this.id]=f_.Serialize(t,e))}return{id:this.id}}fromJSON(e,t){if(e&&"string"==typeof e.id&&(this.id=e.id,t?.typed)){const e=t.typed[this.id],i=t.__isLoadedResources,n=i&&e?e:f_.Deserialize(e,t);n?.external&&n.rootPath?console.warn("ReferenceManager - External resources is expected to be loaded already in ImportMeta phase:",n):(this._itemObject=n,i&&(t.typed[this.id]=n))}return this}}const SN=class e{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 r=n.refs.get(i);r||(r=new Set,n.refs.set(i,r));const s=new CN(e);return r.add(s),s}static Remove(e,t,i){const n=this.Objects.get(e);if(n){const r=n.refs.get(t);r&&r.has(i)&&(r.delete(i),0===r.size&&(n.refs.delete(t),0===n.refs.size&&this.Objects.delete(e)))}}static Delete(e){if(e)for(const[t,i]of[...this.Objects])i.refs.delete(e),0===i.refs.size&&this.Objects.delete(t),i.object===e&&this.Objects.delete(t)}static RemoveOp(t,i){if(void 0!==t&&t.isItemRef){const n=t;e.Remove(n.id,i,n)}}static GetOp(t,i=!0){if(t.isItemRef){return e.Get(t)||(i&&console.error("Object3DComponent: Reference not found",t),null)}}static GetCached(e){if(e&&e.isItemRef&&e._itemObject){const t=e._itemObject;return e._itemObject=void 0,t}}};f_.MakeSerializable(CN,"ItemRef"),SN.Objects=new Map;let MN=SN;function EN(e){const t=new Set;let i=e;for(;i&&i!==ON&&i!==Function.prototype;)i.ComponentType&&t.add(i.ComponentType),i=Object.getPrototypeOf(i);return t}function TN(e,t){if(!e.isObject3DComponent)throw new Error("EntityComponentPlugin: invalid component instance");e.ctx=t;const i=function(e){const t=PN.TypeProperties.get(e);if(t)return t;const i=new Map;let n=e,r=0;for(;n&&n!==Function.prototype;){if(n.StateProperties)for(const e of n.StateProperties){const t="string"==typeof e?e:e.key,s=i.get(t);if(s){const e=s[1];e===n?console.error("Object3DComponent: duplicate state property in class",{key:t,base:n}):console.warn("Object3DComponent: state property overridden in derived class",{key:t,base:n,constructor:e});continue}i.set(t,["string"==typeof e?{key:e}:e,n,r]),r+=.001}if(n===ON)break;n=Object.getPrototypeOf(n),r-=1}return Array.from(i.values()).sort((e,t)=>e[2]-t[2]).map(e=>e[0])}(e.constructor),n=e.uiConfig??{type:"folder",label:()=>e._sType?`Missing (${e._sType})`:e.constructor.ComponentType,expanded:!1,children:Rg(e)},r=n.children,s=[];i.forEach(t=>{const i=t.key;if(!Om(e,i))return void console.error("Object3DComponent: state property not found on component",t,e);const n=t.default??e[i];if(void 0===n)return void console.error("Object3DComponent: state property default value must be set",t,e);const a=wN.GetType(n);if(!a)return void console.error("Object3DComponent: unsupported type for state property",t,n);const o=t.type??wN.NonLiteral(a);if(!wN.CanAssign(a,o))return void console.error("Object3DComponent: default value type is not compatible with state property type",t,n,a,o);delete e[i],Object.defineProperty(e,i,{get:()=>DN(e,i,n),set:t=>{RN(t,e,i,o,n)},enumerable:!0,configurable:!0}),BN(a,n,n,e,i);const l={config:t,propType:o,defaultValue:n,defaultValueType:a,propKey:i};if(s.push(l),r){const t=function(e,t){const{config:i,propType:n,defaultValue:r,propKey:s}=t,a="string"==typeof n?[n]:"oneOf"in n?Array.from(n.oneOf):["unknown"],o=a.includes("null"),l=a.map(e=>wN.GetClass(e)).filter(e=>void 0!==e),c=[];if(l.length===a.length&&!o||l.length===a.length-1&&o){const t={type:"reference",label:i.label??s+"",property:[e,s],classTypes:l,allowNull:o,defaultValue:r};c.push(t)}const h=a.map(e=>"string"==typeof e?e.startsWith('"')&&e.endsWith('"')?JSON.parse(e):isNaN(Number(e))?"true"===e||"false"!==e&&("number"==typeof e||"boolean"==typeof e?e:void 0):Number(e):void 0).filter(e=>void 0!==e),d=()=>{const n=Dg(e,s,i.label,void 0,!1);if(n)return"object"==typeof n&&(n.uuid=s,n.dispatchMode="immediate"),h.length>0&&h.length===a.length&&("input"===n.type||"number"===n.type||"string"===n.type)&&(n.type="dropdown",n.children=h.map(e=>({label:"string"==typeof e?e:"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e+"",value:e}))),t.config.uiConfig&&Object.assign(n,t.config.uiConfig),n};return c.push(d),c}(e,l);t?.length&&r.push(...t)}}),PN.InstanceProperties.set(e,s),r?.push({type:"button",label:"Reset to Default",uuid:"reset_to_default",tags:["context-menu"],value:()=>{const t={};return s.forEach(({propKey:i,defaultValue:n})=>{e[i]=n,t[i]=e[i]}),()=>{s.forEach(({propKey:i})=>{e[i]=t[i]})}}},{type:"button",label:"Remove Component",uuid:"remove_component",tags:["context-menu"],value:()=>t.ecp.removeComponent(e.object,e.uuid)}),e.uiConfig=n}const IN=class{};IN.TypeProperties=new Map,IN.InstanceProperties=new Map;let PN=IN;function DN(e,t,i,n,r=!0){if(void 0===(n=n??e.stateRef[t]))return i;const s=MN.GetOp(n,r);return void 0!==s?s:n}function RN(e,t,i,n,r,s){if(void 0===e)return void console.error("Object3DComponent: state property cannot be set to undefined",i,e);const a=void 0!==s?DN(t,i,r,s):t[i];if(a===e)return;const o=wN.GetType(e);o?wN.CanAssign(o,n)?(void 0===s&&(s=t.stateRef[i]),MN.RemoveOp(s,t),BN(o,e,r,t,i),void 0!==a&&a!==e&&t.stateChangeHandlers[i]?.forEach(t=>t(e,a,i))):console.error("Object3DComponent: assigned value type is not compatible with state property type",i,e,o,n):console.error("Object3DComponent: unsupported type for state property",i,e)}function BN(e,t,i,n,r){let s;const a=wN.GetClass(e);if(a){const e=a.getId(t);if(!e)return void console.error("Object3DComponent: cannot get reference id for value of state property",r,t);s=MN.Add(e,t,n)}else s=t===i?void 0:t;void 0===s?delete n.stateRef[r]:n.stateRef[r]=s}const LN=class{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){this._state=e&&"object"==typeof e?e:{};for(const e in t)e in this._state||(this._state[e]=t[e]);return function(e,t){if(!e.isObject3DComponent)throw new Error("EntityComponentPlugin: invalid component instance");const i=PN.InstanceProperties.get(e);if(i)for(const{propKey:n,defaultValue:r,propType:s}of i){const i=t?t[n]:void 0,a=e.stateRef[n];let o;const l=MN.GetCached(a);o=void 0!==l?l:DN(e,n,r,a,!1),RN(o,e,n,s,r,i)}}(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?zN.GetComponent(i,e):zN.GetComponentInParent(i,e)||this.ctx.ecp.getComponentOfType(e):t?null:this.ctx.ecp.getComponentOfType(e)}};LN.StateProperties=[],LN.ComponentType="Object3DComponent";let ON=LN;var UN=Object.defineProperty,FN=(e,t,i,n)=>{for(var r,s=void 0,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(t,i,s)||s);return s&&UN(t,i,s),s};const kN=class extends ON{constructor(){super(...arguments),this.running=!0,this.mass=1,this.damping=.98,this.velocity=new Xi,this.acceleration=new Xi,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 Zp(32)},this.PushBackward=async()=>{for(let e=0;e<200;e++)this.addForce({z:-10}),await Zp(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)&&(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){void 0!==e.x&&(this.acceleration.x+=e.x/this.mass),void 0!==e.y&&(this.acceleration.y+=e.y/this.mass),void 0!==e.z&&(this.acceleration.z+=e.z/this.mass)}applyImpulse(e){void 0!==e.x&&(this.velocity.x+=e.x/this.mass),void 0!==e.y&&(this.velocity.y+=e.y/this.mass),void 0!==e.z&&(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)}};kN.StateProperties=["running","mass","damping"],kN.ComponentType="SampleBodyComponent";let NN=kN;FN([jg()],NN.prototype,"MoveLeft"),FN([jg()],NN.prototype,"MoveRight"),FN([jg()],NN.prototype,"PushForward"),FN([jg()],NN.prototype,"PushBackward");const jN=class e extends sw{constructor(t=!0){super(),this.enabled=!0,this._components=new Map,this._typeToComponents=new Map,this.componentTypes=new Map,this._onRemove=[],this._preFrame=e=>{if(this.isDisabled()||!this._viewer?.renderEnabled||e.deltaTime<=0)return;const t=[e];let i=!1,n=this.componentsDispatch("preFrame",...t);!i&&n.find(e=>!!e[1])&&(i=!0),this._running&&e.timeline.delta>0&&(n=this.componentsDispatch("update",...t),!i&&n.find(e=>!!e[1])&&(i=!0)),i&&this._viewer?.setDirty(this)},this._objectAdd=t=>{const i=t.object;if(!i||i.isWidget)return;if(i.getComponent||(i.getComponent=(t,n=!1)=>n?e.GetComponent(i,t):e.GetComponentInParent(i,t)||this.getComponentOfType(t)),!i._compUiInit&&i.uiConfig?.children&&e.AddObjectUiConfig){i._compUiInit=!0;const t={type:"dropdown",label:"Add Component",value:"",children:[{label:"Select component type",value:""},()=>[...this.componentTypes.values()].map(e=>({label:e.ComponentType,value:e.ComponentType}))]};i.uiConfig.children.push({type:"folder",label:"Components",tags:[e.PluginType],children:[t,{type:"button",label:"Add Component",onClick:()=>{if(t.value)return this.addComponent(i,t.value)}},()=>{const t=e.GetObjectData(i);return t?Object.keys(t).map(e=>this._components.get(i.uuid+e)?.uiConfig).filter(e=>!!e):[]}]})}const n=e.GetObjectData(i);n&&Object.entries(n).forEach(([e,r])=>{if(t.componentType&&r.type!==t.componentType)return;const s=this.registerComponent(i,r,e);s&&(n[e].state=s.stateRef)})},this._objectRemove=t=>{const i=t.object;if(!i)return;const n=e.GetObjectData(i);i.getComponent&&delete i.getComponent,i._compUiInit&&i.uiConfig?.children&&(i._compUiInit=!1,i.uiConfig.children=i.uiConfig.children.filter(t=>{if("object"==typeof t&&t.tags&&Array.isArray(t.tags)&&t.tags.includes(e.PluginType))return!1})),n&&Object.entries(n).forEach(([e,n])=>{if(t.componentType&&n.type!==t.componentType)return;const r=this._components.get(i.uuid+e);if(r){if(r.object!==i)return void console.warn(`EntityComponentPlugin: component with id ${e} exists on a different object`);const t=this.unregisterComponent(r);t&&(n.state=t)}})},this._objectUpdate=e=>{if("deserialize"===e.change){if(!e.object)return;this._objectAdd(e)}},this.componentTypes.set(ON.ComponentType,ON),this._running=t}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(t,...i){return e.ComponentsDispatch([...this._components.values()],t,i)}static ObjectDispatch(t,i,...n){const r=e.ObjectToComponents.get(t);return r?e.ComponentsDispatch(r,i,n):[]}static ComponentsDispatch(e,t,i){const n=[];for(const r of e){const e=r[t];if("function"==typeof e)try{n.push([r,e.apply(r,i)])}catch(e){console.error(`EntityComponentPlugin: Error in component ${r.constructor.ComponentType} handling ${t}`,r,e)}}return n}addComponentType(e){if(!e||"function"!=typeof e)throw new Error("EntityComponentPlugin: invalid component type");if(!e.ComponentType||"string"!=typeof e.ComponentType)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||"function"!=typeof e)throw new Error("EntityComponentPlugin: invalid component type");if(!e.ComponentType||"string"!=typeof e.ComponentType)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="string"==typeof e?e:e.ComponentType;return this.componentTypes.has(t)}onAdded(e){super.onAdded(e),e.object3dManager.getObjects().forEach(e=>this._objectAdd({object:e})),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(e=>this._objectRemove({object:e})),e.scene.removeEventListener("objectUpdate",this._objectUpdate),this._onRemove.forEach(e=>e()),super.onRemove(e)}static GetObjectData(t){let i=t.userData[e.UserDataKey];return i&&"object"!=typeof i&&(console.warn(`EntityComponentPlugin: userData.${e.UserDataKey} is not an object`,t),i={},t.userData[e.UserDataKey]=i),i||null}addComponent(t,i,n){if(!this._viewer)throw new Error("EntityComponentPlugin: no viewer");const r=i?"string"==typeof i?{type:i,state:{}}:i.ComponentType?{type:i.ComponentType,state:{}}:i&&"string"==typeof i.type&&i.state?i:{type:"Object3DComponent",state:{}}:{type:"Object3DComponent",state:{}};i.ComponentType&&(this.hasComponentType(i)||this.addComponentType(i));const s=this.registerComponent(t,r,n);if(!s)throw new Error("EntityComponentPlugin: cannot create component of type "+r.type);let a=e.GetObjectData(t);a||(a={},t.userData[e.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},t.setDirty&&t.setDirty({change:`userData.${e.UserDataKey}`,source:"EntityComponentPlugin.addComponent",refreshUi:!0});const o={undo:()=>{const e=this.removeComponent(t,o.component.uuid);e&&(o.redo=e.undo)},redo:()=>{this.addComponent(t,i)},component:s};return o}removeComponent(t,i){if(!this._viewer)return;const n=this._components.get(t.uuid+i);if(!n)return;const r=n.constructor.ComponentType,s=this.unregisterComponent(n),a=e.GetObjectData(t);a&&(delete a[i],0===Object.keys(a).length&&delete t.userData[e.UserDataKey],t.setDirty&&t.setDirty({change:`userData.${e.UserDataKey}`,source:"EntityComponentPlugin.removeComponent",refreshUi:!0}));const o={state:s,undo:()=>{o.state&&this.addComponent(t,{type:r,state:o.state},i)},redo:()=>{this.removeComponent(t,i)}};return o}static GetComponentData(t,i){if(!t)return null;const n=e.GetObjectData(t);if(!n)return null;const r="string"==typeof i?[i]:[...EN(i)];for(const[e,t]of Object.entries(n))for(const i of r)if(t.type===i)return{id:e,...t};const s=e.GetComponent(t,i);return s?{id:s.uuid,type:s.constructor.ComponentType,state:s.stateRef}:null}static GetComponents(t,i){if(!t)return[];const n=e.ObjectToComponents.get(t)||[];if(!i)return n;const r="string"==typeof i?[i]:[...EN(i)];return n.filter(e=>{const t=EN(e.constructor);return r.some(e=>t.has(e))})}static GetComponent(t,i){if(!t)return null;const n=e.ObjectToComponents.get(t)||[],r="string"==typeof i?[i]:[...EN(i)];for(const e of n){const t=EN(e.constructor);for(const i of r)if(t.has(i))return e}return null}static GetComponentInParent(t,i){if(!t)return null;let n=t,r=null;for(;!r&&n;)r=e.GetComponent(n,i),n=n.parent;return r}static GetComponentsInParent(t,i){if(!t)return[];let n=t;const r=[];for(;n;)r.push(...e.GetComponents(n,i)),n=n.parent;return r}getComponentsOfType(e){const t="string"==typeof e?e:e.ComponentType,i=this._typeToComponents.get(t);return i?[...i]:[]}getComponentOfType(e){const t="string"==typeof e?e:e.ComponentType,i=this._typeToComponents.get(t);return i&&0!==i.size?i.values().next().value:null}registerComponent(t,i,n){if(!this._viewer)throw new Error("EntityComponentPlugin: no viewer");if(!t)throw new Error("EntityComponentPlugin: no object");if((!i||"object"!=typeof i)&&(console.warn("EntityComponentPlugin: invalid component state",i,t),i={type:"Object3DComponent",state:{}}),n){const e=this._components.get(t.uuid+n);if(e)return e.object!==t&&(console.error(`EntityComponentPlugin: component with id ${n} already exists on a different object`),e.object=t),e.constructor.ComponentType!==i.type?(console.warn(`EntityComponentPlugin: component with id ${n} type mismatch (${e.constructor.ComponentType} != ${i.type}), removing previous component and creating new one`),this.unregisterComponent(e)):e.setState(i.state),e}const r=this.componentTypes.get(i.type),s={viewer:this._viewer,ecp:this,plugin:e=>{const t=s.viewer?.getPlugin(e);if(!t)throw new Error(`EntityComponentPlugin: cannot find plugin ${"string"==typeof e?e:e.name}`);return t}};let a;try{a=r?new r:new ON,r||(console.error("EntityComponentPlugin: unknown component type "+i.type,t),a._sType=i.type),n&&(a.uuid=n),TN(a,s)}catch(e){return console.error("EntityComponentPlugin: Error creating component of type "+i.type),console.error(e),null}this._components.set(t.uuid+a.uuid,a),e.ObjectToComponents.set(t,[...e.ObjectToComponents.get(t)||[],a]);const o=this._typeToComponents.get(a.constructor.ComponentType)||new Set;o.add(a),this._typeToComponents.set(a.constructor.ComponentType,o);try{a.init(t,i.state)}catch(e){console.error("EntityComponentPlugin: Error initializing component",a),console.error(e)}this.dispatchEvent({type:"registerComponent",component:a,object:t});try{this.running&&a.start()}catch(e){console.error("EntityComponentPlugin: Error starting component",a),console.error(e)}return a}unregisterComponent(t){if(!t)return;const i=t.object;let n=null;if(i){try{this.running&&t.stop()}catch(e){console.error("EntityComponentPlugin: Error stopping component",t),console.error(e)}try{n=t.destroy()}catch(e){console.error("EntityComponentPlugin: Error destroying component",t),console.error(e)}}else console.warn("EntityComponentPlugin: component already destroyed",t);this._components.delete(i.uuid+t.uuid);const r=this._typeToComponents.get(t.constructor.ComponentType);r&&(r.delete(t),0===r.size&&this._typeToComponents.delete(t.constructor.ComponentType)),function(e){if(!e.isObject3DComponent)throw new Error("EntityComponentPlugin: invalid component instance");MN.Delete(e),PN.InstanceProperties.delete(e)}(t);const s=e.ObjectToComponents.get(i)||[],a=s.indexOf(t);return-1!==a&&(s.splice(a,1),0===s.length&&e.ObjectToComponents.delete(i)),i&&this.dispatchEvent({type:"unregisterComponent",component:t,object:i}),n}};jN.PluginType="EntityComponentPlugin",jN.ObjectToComponents=new Map,jN.UserDataKey=jN.PluginType,jN.AddObjectUiConfig=!0;let zN=jN;const GN=zN;e.AAssetManagerProcessStatePlugin=EL,e.ACESFilmicToneMapping=4,e.ACameraControlsPlugin=CL,e.ACameraHelperWidget=vO,e.AGeometryGenerator=gk,e.AHelperWidget=yO,e.ALightHelperWidget=_O,e.AScreenPassExtensionPlugin=sB,e.AViewerPlugin=rw,e.AViewerPluginAsync=class extends rw{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}},e.AViewerPluginSync=sw,e.AddEquation=100,e.AddOperation=2,e.AdditiveAnimationBlendMode=2501,e.AdditiveBlending=2,e.AgXToneMapping=6,e.AlphaFormat=1021,e.AlwaysCompare=519,e.AlwaysDepth=1,e.AlwaysStencilFunc=519,e.AmbientLight=Tu,e.AmbientLight2=qC,e.AnimationAction=gp,e.AnimationClip=eu,e.AnimationLoader=class extends su{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new lu(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(i){try{t(r.parse(JSON.parse(i)))}catch(t){n?n(t):console.error(t),r.manager.itemError(e)}},i,n)}parse(e){const t=[];for(let i=0;i<e.length;i++){const n=eu.parse(e[i]);t.push(n)}return t}},e.AnimationMixer=Ap,e.AnimationObjectGroup=class{constructor(){this.isAnimationObjectGroup=!0,this.uuid=ci(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;const e={};this._indicesByUUID=e;for(let t=0,i=arguments.length;t!==i;++t)e[arguments[t].uuid]=t;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,r=this._bindings,s=r.length;let a,o=e.length,l=this.nCachedObjects_;for(let c=0,h=arguments.length;c!==h;++c){const h=arguments[c],d=h.uuid;let u=t[d];if(void 0===u){u=o++,t[d]=u,e.push(h);for(let e=0,t=s;e!==t;++e)r[e].push(new mp(h,i[e],n[e]))}else if(u<l){a=e[u];const o=--l,c=e[o];t[c.uuid]=u,e[u]=c,t[d]=o,e[o]=h;for(let e=0,t=s;e!==t;++e){const t=r[e],s=t[o];let a=t[u];t[u]=s,void 0===a&&(a=new mp(h,i[e],n[e])),t[o]=a}}else e[u]!==a&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=l}remove(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,n=i.length;let r=this.nCachedObjects_;for(let s=0,a=arguments.length;s!==a;++s){const a=arguments[s],o=a.uuid,l=t[o];if(void 0!==l&&l>=r){const s=r++,c=e[s];t[c.uuid]=l,e[l]=c,t[o]=s,e[s]=a;for(let e=0,t=n;e!==t;++e){const t=i[e],n=t[s],r=t[l];t[l]=n,t[s]=r}}}this.nCachedObjects_=r}uncache(){const e=this._objects,t=this._indicesByUUID,i=this._bindings,n=i.length;let r=this.nCachedObjects_,s=e.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,l=t[o];if(void 0!==l)if(delete t[o],l<r){const a=--r,o=e[a],c=--s,h=e[c];t[o.uuid]=l,e[l]=o,t[h.uuid]=a,e[a]=h,e.pop();for(let e=0,t=n;e!==t;++e){const t=i[e],n=t[a],r=t[c];t[l]=n,t[a]=r,t.pop()}}else{const r=--s,a=e[r];r>0&&(t[a.uuid]=l),e[l]=a,e.pop();for(let e=0,t=n;e!==t;++e){const t=i[e];t[l]=t[r],t.pop()}}}this.nCachedObjects_=r}subscribe_(e,t){const i=this._bindingsIndicesByPath;let n=i[e];const r=this._bindings;if(void 0!==n)return r[n];const s=this._paths,a=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,h=new Array(l);n=r.length,i[e]=n,s.push(e),a.push(t),r.push(h);for(let i=c,n=o.length;i!==n;++i){const n=o[i];h[i]=new mp(n,e,t)}return h}unsubscribe_(e){const t=this._bindingsIndicesByPath,i=t[e];if(void 0!==i){const n=this._paths,r=this._parsedPaths,s=this._bindings,a=s.length-1,o=s[a];t[e[a]]=i,s[i]=o,s.pop(),r[i]=r[a],r.pop(),n[i]=n[a],n.pop()}}},e.AnimationObjectPlugin=CF,e.AnimationUtils=zd,e.ArcCurve=sh,e.ArrayCamera=ol,e.ArrowHelper=class extends Zn{constructor(e=new Xi(0,0,1),t=new Xi(0,0,0),i=1,n=16776960,r=.2*i,s=.2*r){super(),this.type="ArrowHelper",void 0===Xp&&(Xp=new Fr,Xp.setAttribute("position",new Ir([0,0,0,0,1,0],3)),Yp=new Th(0,.5,1,5,1),Yp.translate(0,-.5,0)),this.position.copy(t),this.line=new Nc(Xp,new Dc({color:n,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new ts(Yp,new vr({color:n,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(e),this.setLength(i,r,s)}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{qp.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(qp,t)}}setLength(e,t=.2*e,i=.2*t){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()}},e.AssetExporter=xR,e.AssetExporterPlugin=ZU,e.AssetImporter=$S,e.AssetManager=TR,e.AsyncCompress=fP,e.AsyncDecompress=DP,e.AsyncDeflate=lP,e.AsyncGunzip=_P,e.AsyncGzip=fP,e.AsyncInflate=uP,e.AsyncUnzipInflate=tD,e.AsyncUnzlib=EP,e.AsyncZipDeflate=KP,e.AsyncZlib=CP,e.AttachedBindMode="attached",e.Audio=Zu,e.AudioAnalyser=class{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}},e.AudioContext=Gu,e.AudioListener=class extends Zn{constructor(){super(),this.type="AudioListener",this.context=Gu.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Wu}getInput(){return this.gain}removeFilter(){return null!==this.filter&&(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 null!==this.filter?(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(Xu,Yu,Ku),Ju.set(0,0,-1).applyQuaternion(Yu),t.positionX){const e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Xu.x,e),t.positionY.linearRampToValueAtTime(Xu.y,e),t.positionZ.linearRampToValueAtTime(Xu.z,e),t.forwardX.linearRampToValueAtTime(Ju.x,e),t.forwardY.linearRampToValueAtTime(Ju.y,e),t.forwardZ.linearRampToValueAtTime(Ju.z,e),t.upX.linearRampToValueAtTime(i.x,e),t.upY.linearRampToValueAtTime(i.y,e),t.upZ.linearRampToValueAtTime(i.z,e)}else t.setPosition(Xu.x,Xu.y,Xu.z),t.setOrientation(Ju.x,Ju.y,Ju.z,i.x,i.y,i.z)}},e.AudioLoader=class extends su{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new lu(this.manager);function a(t){n?n(t):console.error(t),r.manager.itemError(e)}s.setResponseType("arraybuffer"),s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(e){try{const i=e.slice(0);Gu.getContext().decodeAudioData(i,function(e){t(e)}).catch(a)}catch(e){a(e)}},i,n)}},e.AxesHelper=class extends Qc{constructor(e=1){const t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],i=new Fr;i.setAttribute("position",new Ir(t,3)),i.setAttribute("color",new Ir([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(i,new Dc({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(e,t,i){const n=new mr,r=this.geometry.attributes.color.array;return n.set(e),n.toArray(r,0),n.toArray(r,3),n.set(t),n.toArray(r,6),n.toArray(r,9),n.set(i),n.toArray(r,12),n.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}},e.BackSide=1,e.BaseImporterPlugin=_L,e.BasicDepthPacking=3200,e.BasicShadowMap=0,e.BatchedMesh=Pc,e.Bone=$l,e.BoneHelper=CO,e.BooleanKeyframeTrack=qd,e.Box2=Tp,e.Box3=Ji,e.Box3B=Ly,e.Box3Helper=class extends Qc{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 Fr;n.setIndex(new Mr(i,1)),n.setAttribute("position",new Ir([1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3)),super(n,new Dc({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()}},e.BoxGeometry=ns,e.BoxGeometryGenerator=yk,e.BoxHelper=class extends Qc{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),r=new Fr;r.setIndex(new Mr(i,1)),r.setAttribute("position",new Mr(n,3)),super(r,new Dc({color:t,toneMapped:!1})),this.object=e,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(e){if(void 0!==e&&console.warn("THREE.BoxHelper: .update() has no longer arguments."),void 0!==this.object&&Wp.setFromObject(this.object),Wp.isEmpty())return;const t=Wp.min,i=Wp.max,n=this.geometry.attributes.position,r=n.array;r[0]=i.x,r[1]=i.y,r[2]=i.z,r[3]=t.x,r[4]=i.y,r[5]=i.z,r[6]=t.x,r[7]=t.y,r[8]=i.z,r[9]=i.x,r[10]=t.y,r[11]=i.z,r[12]=i.x,r[13]=i.y,r[14]=t.z,r[15]=t.x,r[16]=i.y,r[17]=t.z,r[18]=t.x,r[19]=t.y,r[20]=t.z,r[21]=i.x,r[22]=t.y,r[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()}},e.BoxSelectionWidget=SO,e.BufferAttribute=Mr,e.BufferGeometry=Fr,e.BufferGeometry2=UC,e.BufferGeometryLoader=Ou,e.ByteType=1010,e.CSMFrustum=rk,e.Cache=iu,e.Camera=cs,e.CameraHelper=class extends Qc{constructor(e){const t=new Fr,i=new Dc({color:16777215,vertexColors:!0,toneMapped:!1}),n=[],r=[],s={};function a(e,t){o(e),o(t)}function o(e){n.push(0,0,0),r.push(0,0,0),void 0===s[e]&&(s[e]=[]),s[e].push(n.length/3-1)}a("n1","n2"),a("n2","n4"),a("n4","n3"),a("n3","n1"),a("f1","f2"),a("f2","f4"),a("f4","f3"),a("f3","f1"),a("n1","f1"),a("n2","f2"),a("n3","f3"),a("n4","f4"),a("p","n1"),a("p","n2"),a("p","n3"),a("p","n4"),a("u1","u2"),a("u2","u3"),a("u3","u1"),a("c","t"),a("p","c"),a("cn1","cn2"),a("cn3","cn4"),a("cf1","cf2"),a("cf3","cf4"),t.setAttribute("position",new Ir(n,3)),t.setAttribute("color",new Ir(r,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=s,this.update();const l=new mr(16755200),c=new mr(16711680),h=new mr(43775),d=new mr(16777215),u=new mr(3355443);this.setColors(l,c,h,d,u)}setColors(e,t,i,n,r){const s=this.geometry.getAttribute("color");s.setXYZ(0,e.r,e.g,e.b),s.setXYZ(1,e.r,e.g,e.b),s.setXYZ(2,e.r,e.g,e.b),s.setXYZ(3,e.r,e.g,e.b),s.setXYZ(4,e.r,e.g,e.b),s.setXYZ(5,e.r,e.g,e.b),s.setXYZ(6,e.r,e.g,e.b),s.setXYZ(7,e.r,e.g,e.b),s.setXYZ(8,e.r,e.g,e.b),s.setXYZ(9,e.r,e.g,e.b),s.setXYZ(10,e.r,e.g,e.b),s.setXYZ(11,e.r,e.g,e.b),s.setXYZ(12,e.r,e.g,e.b),s.setXYZ(13,e.r,e.g,e.b),s.setXYZ(14,e.r,e.g,e.b),s.setXYZ(15,e.r,e.g,e.b),s.setXYZ(16,e.r,e.g,e.b),s.setXYZ(17,e.r,e.g,e.b),s.setXYZ(18,e.r,e.g,e.b),s.setXYZ(19,e.r,e.g,e.b),s.setXYZ(20,e.r,e.g,e.b),s.setXYZ(21,e.r,e.g,e.b),s.setXYZ(22,e.r,e.g,e.b),s.setXYZ(23,e.r,e.g,e.b),s.setXYZ(24,t.r,t.g,t.b),s.setXYZ(25,t.r,t.g,t.b),s.setXYZ(26,t.r,t.g,t.b),s.setXYZ(27,t.r,t.g,t.b),s.setXYZ(28,t.r,t.g,t.b),s.setXYZ(29,t.r,t.g,t.b),s.setXYZ(30,t.r,t.g,t.b),s.setXYZ(31,t.r,t.g,t.b),s.setXYZ(32,i.r,i.g,i.b),s.setXYZ(33,i.r,i.g,i.b),s.setXYZ(34,i.r,i.g,i.b),s.setXYZ(35,i.r,i.g,i.b),s.setXYZ(36,i.r,i.g,i.b),s.setXYZ(37,i.r,i.g,i.b),s.setXYZ(38,n.r,n.g,n.b),s.setXYZ(39,n.r,n.g,n.b),s.setXYZ(40,r.r,r.g,r.b),s.setXYZ(41,r.r,r.g,r.b),s.setXYZ(42,r.r,r.g,r.b),s.setXYZ(43,r.r,r.g,r.b),s.setXYZ(44,r.r,r.g,r.b),s.setXYZ(45,r.r,r.g,r.b),s.setXYZ(46,r.r,r.g,r.b),s.setXYZ(47,r.r,r.g,r.b),s.setXYZ(48,r.r,r.g,r.b),s.setXYZ(49,r.r,r.g,r.b),s.needsUpdate=!0}update(){const e=this.geometry,t=this.pointMap;Vp.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),Hp("c",t,e,Vp,0,0,-1),Hp("t",t,e,Vp,0,0,1),Hp("n1",t,e,Vp,-1,-1,-1),Hp("n2",t,e,Vp,1,-1,-1),Hp("n3",t,e,Vp,-1,1,-1),Hp("n4",t,e,Vp,1,1,-1),Hp("f1",t,e,Vp,-1,-1,1),Hp("f2",t,e,Vp,1,-1,1),Hp("f3",t,e,Vp,-1,1,1),Hp("f4",t,e,Vp,1,1,1),Hp("u1",t,e,Vp,.7,1.1,-1),Hp("u2",t,e,Vp,-.7,1.1,-1),Hp("u3",t,e,Vp,0,2,-1),Hp("cf1",t,e,Vp,-1,0,1),Hp("cf2",t,e,Vp,1,0,1),Hp("cf3",t,e,Vp,0,-1,1),Hp("cf4",t,e,Vp,0,1,1),Hp("cn1",t,e,Vp,-1,0,-1),Hp("cn2",t,e,Vp,1,0,-1),Hp("cn3",t,e,Vp,0,-1,-1),Hp("cn4",t,e,Vp,0,1,-1),e.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}},e.CameraHelper2=TO,e.CameraViewPlugin=qR,e.CanvasSnapshot=jx,e.CanvasSnipperPlugin=nF,e.CanvasTexture=ih,e.CapsuleGeometry=Mh,e.CascadedShadowsPlugin=nk,e.CatmullRomCurve3=dh,e.CineonToneMapping=3,e.CircleGeometry=Eh,e.CircleGeometryGenerator=Ak,e.ClampToEdgeWrapping=1001,e.Clock=Wu,e.Color=mr,e.ColorKeyframeTrack=Xd,e.ColorManagement=Pi,e.Compress=gP,e.CompressedArrayTexture=eh,e.CompressedCubeTexture=th,e.CompressedTexture=$c,e.CompressedTextureLoader=cu,e.ConeGeometry=Ih,e.ConstantAlphaFactor=213,e.ConstantColorFactor=211,e.ConvexHull=class{constructor(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new vL,this.unassigned=new vL,this.vertices=[]}setFromPoints(e){if(e.length>=4){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.vertices.push(new yL(e[t]));this.compute()}return this}setFromObject(e){const t=[];return e.updateMatrixWorld(!0),e.traverse(function(e){const i=e.geometry;if(void 0!==i){const n=i.attributes.position;if(void 0!==n)for(let i=0,r=n.count;i<r;i++){const r=new Xi;r.fromBufferAttribute(n,i).applyMatrix4(e.matrixWorld),t.push(r)}}}),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,r=1/0;for(let t=0,s=i.length;t<s;t++){const s=i[t],a=s.distanceToPoint(e.origin),o=s.normal.dot(e.direction);if(a>0&&o>=0)return null;const l=0!==o?-a/o:0;if(!(l<=0)&&(o>0?r=Math.min(l,r):n=Math.max(l,n),n>r))return null}return n!==-1/0?e.at(n,t):e.at(r,t),t}intersectsRay(e){return null!==this.intersectRay(e,dL)}makeEmpty(){return this.faces=[],this.vertices=[],this}addVertexToFace(e,t){return e.face=t,null===t.outside?this.assigned.append(e):this.assigned.insertBefore(t.outside,e),t.outside=e,this}removeVertexFromFace(e,t){return e===t.outside&&(null!==e.next&&e.next.face===t?t.outside=e.next:t.outside=null),this.assigned.remove(e),this}removeAllVerticesFromFace(e){if(null!==e.outside){const t=e.outside;let i=e.outside;for(;null!==i.next&&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(void 0!==i)if(void 0===t)this.unassigned.appendChain(i);else{let e=i;do{const i=e.next;t.distanceToPoint(e.point)>this.tolerance?this.addVertexToFace(e,t):this.unassigned.append(e),e=i}while(null!==e)}return this}resolveUnassignedPoints(e){if(!1===this.unassigned.isEmpty()){let t=this.unassigned.first();do{const i=t.next;let n=this.tolerance,r=null;for(let i=0;i<e.length;i++){const s=e[i];if(0===s.mark){const e=s.distanceToPoint(t.point);if(e>n&&(n=e,r=s),n>1e3*this.tolerance)break}}null!==r&&this.addVertexToFace(t,r),t=i}while(null!==t)}return this}computeExtremes(){const e=new Xi,t=new Xi,i=[],n=[];for(let e=0;e<3;e++)i[e]=n[e]=this.vertices[0];e.copy(this.vertices[0].point),t.copy(this.vertices[0].point);for(let r=0,s=this.vertices.length;r<s;r++){const s=this.vertices[r],a=s.point;for(let t=0;t<3;t++)a.getComponent(t)<e.getComponent(t)&&(e.setComponent(t,a.getComponent(t)),i[t]=s);for(let e=0;e<3;e++)a.getComponent(e)>t.getComponent(e)&&(t.setComponent(e,a.getComponent(e)),n[e]=s)}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 r=0,s=0;for(let e=0;e<3;e++){const t=n[e].point.getComponent(e)-i[e].point.getComponent(e);t>r&&(r=t,s=e)}const a=i[s],o=n[s];let l,c;r=0,uL.set(a.point,o.point);for(let t=0,i=this.vertices.length;t<i;t++){const i=e[t];if(i!==a&&i!==o){uL.closestPointToPoint(i.point,!0,mL);const e=mL.distanceToSquared(i.point);e>r&&(r=e,l=i)}}r=-1,pL.setFromCoplanarPoints(a.point,o.point,l.point);for(let t=0,i=this.vertices.length;t<i;t++){const i=e[t];if(i!==a&&i!==o&&i!==l){const e=Math.abs(pL.distanceToPoint(i.point));e>r&&(r=e,c=i)}}const h=[];if(pL.distanceToPoint(c.point)<0){h.push(fL.create(a,o,l),fL.create(c,o,a),fL.create(c,l,o),fL.create(c,a,l));for(let e=0;e<3;e++){const t=(e+1)%3;h[e+1].getEdge(2).setTwin(h[0].getEdge(t)),h[e+1].getEdge(1).setTwin(h[t+1].getEdge(0))}}else{h.push(fL.create(a,l,o),fL.create(c,a,o),fL.create(c,o,l),fL.create(c,l,a));for(let e=0;e<3;e++){const t=(e+1)%3;h[e+1].getEdge(2).setTwin(h[0].getEdge((3-e)%3)),h[e+1].getEdge(0).setTwin(h[t+1].getEdge(1))}}for(let e=0;e<4;e++)this.faces.push(h[e]);for(let t=0,i=e.length;t<i;t++){const i=e[t];if(i!==a&&i!==o&&i!==l&&i!==c){r=this.tolerance;let e=null;for(let t=0;t<4;t++){const n=this.faces[t].distanceToPoint(i.point);n>r&&(r=n,e=this.faces[t])}null!==e&&this.addVertexToFace(i,e)}}return this}reindexFaces(){const e=[];for(let t=0;t<this.faces.length;t++){const i=this.faces[t];0===i.mark&&e.push(i)}return this.faces=e,this}nextVertexToAdd(){if(!1===this.assigned.isEmpty()){let e,t=0;const i=this.assigned.first().face;let n=i.outside;do{const r=i.distanceToPoint(n.point);r>t&&(t=r,e=n),n=n.next}while(null!==n&&n.face===i);return e}}computeHorizon(e,t,i,n){let r;this.deleteFaceVertices(i),i.mark=1,r=null===t?t=i.getEdge(0):t.next;do{const t=r.twin,i=t.face;0===i.mark&&(i.distanceToPoint(e)>this.tolerance?this.computeHorizon(e,t,i,n):n.push(r)),r=r.next}while(r!==t);return this}addAdjoiningFace(e,t){const i=fL.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 r=0;r<t.length;r++){const s=t[r],a=this.addAdjoiningFace(e,s);null===i?i=a:a.next.setTwin(n),this.newFaces.push(a.face),n=a}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();void 0!==(e=this.nextVertexToAdd());)this.addVertexToHull(e);return this.reindexFaces(),this.cleanup(),this}},e.CopyShader=CS,e.CubeCamera=gs,e.CubeReflectionMapping=301,e.CubeRefractionMapping=302,e.CubeTexture=fs,e.CubeTextureLoader=class extends su{constructor(e){super(e)}load(e,t,i,n){const r=new fs;r.colorSpace=Ot;const s=new hu(this.manager);s.setCrossOrigin(this.crossOrigin),s.setPath(this.path);let a=0;function o(i){s.load(e[i],function(e){r.images[i]=e,a++,6===a&&(r.needsUpdate=!0,t&&t(r))},void 0,n)}for(let t=0;t<e.length;++t)o(t);return r}},e.CubeUVReflectionMapping=306,e.CubicBezierCurve=gh,e.CubicBezierCurve3=fh,e.CubicInterpolant=Qd,e.CullFaceBack=1,e.CullFaceFront=2,e.CullFaceFrontBack=3,e.CullFaceNone=0,e.Curve=nh,e.CurvePath=wh,e.CurvePath3=u_,e.CustomBlending=5,e.CustomContextMenu=df,e.CustomToneMapping=5,e.CylinderGeometry=Th,e.CylinderGeometryGenerator=bk,e.Cylindrical=class{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)}},e.DRACOLoader=kD,e.DRACOLoader2=zD,e.Damper=nm,e.Data3DTexture=Wi,e.DataArrayTexture=Hi,e.DataTexture=ec,e.DataTextureLoader=du,e.DataUtils=wr,e.DecodeUTF8=FP,e.Decompress=PP,e.DecrementStencilOp=7683,e.DecrementWrapStencilOp=34056,e.DefaultLoadingManager=ru,e.Deflate=oP,e.DepthFormat=1026,e.DepthNormalMaterial=class extends Ww{constructor(e,t){super(e,t),console.warn("DepthNormalMaterial is deprecated, use GBufferMaterial instead")}},e.DepthStencilFormat=1027,e.DepthTexture=ua,e.DetachedBindMode="detached",e.DeviceOrientationControlsPlugin=xU,e.DirectionalLight=Eu,e.DirectionalLight2=JC,e.DirectionalLightHelper=class extends Zn{constructor(e,t,i){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=i,this.type="DirectionalLightHelper",void 0===t&&(t=1);let n=new Fr;n.setAttribute("position",new Ir([-t,t,0,t,t,0,t,-t,0,-t,-t,0,-t,t,0],3));const r=new Dc({fog:!1,toneMapped:!1});this.lightPlane=new Nc(n,r),this.add(this.lightPlane),n=new Fr,n.setAttribute("position",new Ir([0,0,0,0,0,1],3)),this.targetLine=new Nc(n,r),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),jp.setFromMatrixPosition(this.light.matrixWorld),zp.setFromMatrixPosition(this.light.target.matrixWorld),Gp.subVectors(zp,jp),this.lightPlane.lookAt(zp),void 0!==this.color?(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(zp),this.targetLine.scale.z=Gp.length()}},e.DirectionalLightHelper2=BO,e.DiscreteInterpolant=Hd,e.DisplayP3ColorSpace="display-p3",e.DodecahedronGeometry=Dh,e.DoubleSide=2,e.Dropzone=pf,e.DstAlphaFactor=206,e.DstColorFactor=208,e.DuplicateTracker=$O,e.DynamicCopyUsage=35050,e.DynamicDrawUsage=35048,e.DynamicImportPlugin=fN,e.DynamicReadUsage=35049,e.ECS=GN,e.EXRExporter=nR,e.EXRExporter2=yR,e.EXRLoader=GD,e.EasingFunctions=xx,e.EdgesGeometry=Uh,e.EffectComposer=QS,e.EffectComposer2=VS,e.EllipseCurve=rh,e.EllipseCurve3D=QC,e.EncodeUTF8=kP,e.EntityComponentPlugin=zN,e.EqualCompare=514,e.EqualDepth=4,e.EqualStencilFunc=514,e.EquirectangularReflectionMapping=303,e.EquirectangularRefractionMapping=304,e.Euler=On,e.EventDispatcher=ri,e.ExtendedCopyPass=RS,e.ExtendedRenderPass=DS,e.ExtendedShaderMaterial=fC,e.ExtendedShaderPass=TS,e.ExtrudeGeometry=ud,e.FBXLoader=uD,e.FBXLoader2=PD,e.Face=fL,e.FileLoader=lu,e.FileTransferPlugin=sF,e.FlateErrorCode={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},e.Float16BufferAttribute=class extends Mr{constructor(e,t,i){super(new Uint16Array(e),t,i),this.isFloat16BufferAttribute=!0}getX(e){let t=xr(this.array[e*this.itemSize]);return this.normalized&&(t=pi(t,this.array)),t}setX(e,t){return this.normalized&&(t=mi(t,this.array)),this.array[e*this.itemSize]=br(t),this}getY(e){let t=xr(this.array[e*this.itemSize+1]);return this.normalized&&(t=pi(t,this.array)),t}setY(e,t){return this.normalized&&(t=mi(t,this.array)),this.array[e*this.itemSize+1]=br(t),this}getZ(e){let t=xr(this.array[e*this.itemSize+2]);return this.normalized&&(t=pi(t,this.array)),t}setZ(e,t){return this.normalized&&(t=mi(t,this.array)),this.array[e*this.itemSize+2]=br(t),this}getW(e){let t=xr(this.array[e*this.itemSize+3]);return this.normalized&&(t=pi(t,this.array)),t}setW(e,t){return this.normalized&&(t=mi(t,this.array)),this.array[e*this.itemSize+3]=br(t),this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=mi(t,this.array),i=mi(i,this.array)),this.array[e+0]=br(t),this.array[e+1]=br(i),this}setXYZ(e,t,i,n){return e*=this.itemSize,this.normalized&&(t=mi(t,this.array),i=mi(i,this.array),n=mi(n,this.array)),this.array[e+0]=br(t),this.array[e+1]=br(i),this.array[e+2]=br(n),this}setXYZW(e,t,i,n,r){return e*=this.itemSize,this.normalized&&(t=mi(t,this.array),i=mi(i,this.array),n=mi(n,this.array),r=mi(r,this.array)),this.array[e+0]=br(t),this.array[e+1]=br(i),this.array[e+2]=br(n),this.array[e+3]=br(r),this}},e.Float32BufferAttribute=Ir,e.FloatType=1015,e.FnCaller=Gm,e.Fog=vl,e.FogExp2=yl,e.FragmentClippingMode=qF,e.FrameFadeBlendPass=qL,e.FramebufferTexture=class extends Ni{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=ye,this.minFilter=ye,this.generateMipmaps=!1,this.needsUpdate=!0}},e.FrontSide=0,e.Frustum=Cs,e.FullScreenQuad=xS,e.GBufferMaterial=Ww,e.GLBufferAttribute=class{constructor(e,t,i,n,r){this.isGLBufferAttribute=!0,this.name="",this.buffer=e,this.type=t,this.itemSize=i,this.elementSize=n,this.count=r,this.version=0}set needsUpdate(e){!0===e&&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}},e.GLSL1="100",e.GLSL3="300 es",e.GLStatsJS=cf,e.GLTFAnimationPlugin=vF,e.GLTFBinaryExtension=qE,e.GLTFExporter=iM,e.GLTFExporter2=$D,e.GLTFKHRMaterialVariantsPlugin=uN,e.GLTFLightExtrasExtension=ZM,e.GLTFLoader=wE,e.GLTFLoader2=LD,e.GLTFMaterialExtrasExtension=eE,e.GLTFMaterialsAlphaMapExtension=iE,e.GLTFMaterialsBumpMapExtension=aE,e.GLTFMaterialsDisplacementMapExtension=hE,e.GLTFMaterialsLightMapExtension=mE,e.GLTFMeshOptDecodePlugin=YU,e.GLTFObject3DExtrasExtension=yE,e.GLTFParser=vT,e.GLTFViewerConfigExtension=xE,e.GLTFWriter2=KM,e.GPUComputationRenderer=class{constructor(e,t,i){this.variables=[],this.currentTextureIndex=0;let n=Pe;const r={passThruTexture:{value:null}},s=l("uniform sampler2D passThruTexture;\n\nvoid main() {\n\n\tvec2 uv = gl_FragCoord.xy / resolution.xy;\n\n\tgl_FragColor = texture2D( passThruTexture, uv );\n\n}\n",r),a=new xS(s);function o(i){i.defines.resolution="vec2( "+e.toFixed(1)+", "+t.toFixed(1)+" )"}function l(e,t){const i=new ls({name:"GPUComputationShader",uniforms:t=t||{},vertexShader:"void main()\t{\n\n\tgl_Position = vec4( position, 1.0 );\n\n}\n",fragmentShader:e});return o(i),i}this.setDataType=function(e){return n=e,this},this.addVariable=function(e,t,i){const n={name:e,initialValueTexture:i,material:this.createShaderMaterial(t),dependencies:null,renderTargets:[],wrapS:null,wrapT:null,minFilter:ye,magFilter:ye};return this.variables.push(n),n},this.setVariableDependencies=function(e,t){e.dependencies=t},this.init=function(){if(0===i.capabilities.maxVertexTextures)return"No support for vertex shader textures.";for(let i=0;i<this.variables.length;i++){const n=this.variables[i];n.renderTargets[0]=this.createRenderTarget(e,t,n.wrapS,n.wrapT,n.minFilter,n.magFilter),n.renderTargets[1]=this.createRenderTarget(e,t,n.wrapS,n.wrapT,n.minFilter,n.magFilter),this.renderTexture(n.initialValueTexture,n.renderTargets[0]),this.renderTexture(n.initialValueTexture,n.renderTargets[1]);const r=n.material,s=r.uniforms;if(null!==n.dependencies)for(let e=0;e<n.dependencies.length;e++){const t=n.dependencies[e];if(t.name!==n.name){let e=!1;for(let i=0;i<this.variables.length;i++)if(t.name===this.variables[i].name){e=!0;break}if(!e)return"Variable dependency not found. Variable="+n.name+", dependency="+t.name}s[t.name]={value:null},r.fragmentShader="\nuniform sampler2D "+t.name+";\n"+r.fragmentShader}}return this.currentTextureIndex=0,null},this.compute=function(){const e=this.currentTextureIndex,t=0===this.currentTextureIndex?1:0;for(let i=0,n=this.variables.length;i<n;i++){const n=this.variables[i];if(null!==n.dependencies){const t=n.material.uniforms;for(let i=0,r=n.dependencies.length;i<r;i++){const r=n.dependencies[i];t[r.name].value=r.renderTargets[e].texture}}this.doRenderTarget(n.material,n.renderTargets[t])}this.currentTextureIndex=t},this.getCurrentRenderTarget=function(e){return e.renderTargets[this.currentTextureIndex]},this.getAlternateRenderTarget=function(e){return e.renderTargets[0===this.currentTextureIndex?1:0]},this.dispose=function(){a.dispose();const e=this.variables;for(let t=0;t<e.length;t++){const i=e[t];i.initialValueTexture&&i.initialValueTexture.dispose();const n=i.renderTargets;for(let e=0;e<n.length;e++)n[e].dispose()}},this.addResolutionDefine=o,this.createShaderMaterial=l,this.createRenderTarget=function(i,r,s,a,o,l){return new Vi(i=i||e,r=r||t,{wrapS:s=s||fe,wrapT:a=a||fe,minFilter:o=o||ye,magFilter:l=l||ye,format:Ue,type:n,depthBuffer:!1})},this.createTexture=function(){const i=new Float32Array(e*t*4),n=new ec(i,e,t,Ue,Pe);return n.needsUpdate=!0,n},this.renderTexture=function(e,t){r.passThruTexture.value=e,this.doRenderTarget(s,t),r.passThruTexture.value=null},this.doRenderTarget=function(e,t){const n=i.getRenderTarget(),r=i.xr.enabled,o=i.shadowMap.autoUpdate;i.xr.enabled=!1,i.shadowMap.autoUpdate=!1,a.material=e,i.setRenderTarget(t),a.render(i),a.material=s,i.xr.enabled=r,i.shadowMap.autoUpdate=o,i.setRenderTarget(n)}}},e.GenericBlendTexturePass=IS,e.GeometryGeneratorPlugin=Bk,e.GreaterCompare=516,e.GreaterDepth=6,e.GreaterEqualCompare=518,e.GreaterEqualDepth=5,e.GreaterEqualStencilFunc=518,e.GreaterStencilFunc=516,e.GridHelper=class extends Qc{constructor(e=10,t=10,i=4473924,n=8947848){i=new mr(i),n=new mr(n);const r=t/2,s=e/t,a=e/2,o=[],l=[];for(let e=0,c=0,h=-a;e<=t;e++,h+=s){o.push(-a,0,h,a,0,h),o.push(h,0,-a,h,0,a);const t=e===r?i:n;t.toArray(l,c),c+=3,t.toArray(l,c),c+=3,t.toArray(l,c),c+=3,t.toArray(l,c),c+=3}const c=new Fr;c.setAttribute("position",new Ir(o,3)),c.setAttribute("color",new Ir(l,3));super(c,new Dc({vertexColors:!0,toneMapped:!1})),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}},e.Group=ll,e.Group2=PC,e.Gunzip=vP,e.Gzip=gP,e.HVBlurHelper=yv,e.HalfEdge=AL,e.HalfFloatType=1016,e.HemisphereLight=mu,e.HemisphereLight2=eS,e.HemisphereLightHelper=class extends Zn{constructor(e,t,i){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=i,this.type="HemisphereLightHelper";const n=new gd(t);n.rotateY(.5*Math.PI),this.material=new vr({wireframe:!0,fog:!1,toneMapped:!1}),void 0===this.color&&(this.material.vertexColors=!0);const r=n.getAttribute("position"),s=new Float32Array(3*r.count);n.setAttribute("color",new Mr(s,3)),this.add(new ts(n,this.material)),this.update()}dispose(){this.children[0].geometry.dispose(),this.children[0].material.dispose()}update(){const e=this.children[0];if(void 0!==this.color)this.material.color.set(this.color);else{const t=e.geometry.getAttribute("color");kp.copy(this.light.color),Np.copy(this.light.groundColor);for(let e=0,i=t.count;e<i;e++){const n=e<i/2?kp:Np;t.setXYZ(e,n.r,n.g,n.b)}t.needsUpdate=!0}this.light.updateWorldMatrix(!0,!1),e.lookAt(Fp.setFromMatrixPosition(this.light.matrixWorld).negate())}},e.HorizontalBlurShader=fv,e.IcosahedronGeometry=md,e.ImageBitmapLoader=ju,e.ImageLoader=hu,e.ImageUtils=Li,e.Importer=qS,e.IncrementStencilOp=7682,e.IncrementWrapStencilOp=34055,e.Inflate=dP,e.InstancedBufferAttribute=rc,e.InstancedBufferGeometry=Lu,e.InstancedInterleavedBuffer=_p,e.InstancedMesh=uc,e.InstancedMesh2=class extends uc{constructor(e,t,i=1){super(e,t,i),this.assetType="model",this.setDirty=qw.setDirty,this.refreshUi=qw.refreshUi,qw.upgradeObject3D.call(this)}get modelObject(){return this}},e.Int16BufferAttribute=class extends Mr{constructor(e,t,i){super(new Int16Array(e),t,i)}},e.Int32BufferAttribute=class extends Mr{constructor(e,t,i){super(new Int32Array(e),t,i)}},e.Int8BufferAttribute=class extends Mr{constructor(e,t,i){super(new Int8Array(e),t,i)}},e.IntType=1013,e.InterleavedBuffer=bl,e.InterleavedBufferAttribute=wl,e.Interpolant=Gd,e.InterpolateDiscrete=2300,e.InterpolateLinear=2301,e.InterpolateSmooth=2302,e.InvertStencilOp=5386,e.JSONMaterialLoader=MT,e.JSUndoManager=tm,e.KHR_TEXTURE_BASISU=WU,e.KTX2LoadPlugin=VU,e.KTX2Loader=qB,e.KTX2Loader2=HU,e.KTXLoadPlugin=GU,e.KTXLoader=ZB,e.KeepStencilOp=7680,e.KeyframeTrack=Wd,e.LOD=Gl,e.LatheGeometry=Sh,e.Layers=Un,e.LegacyPhongMaterial=TC,e.LessCompare=513,e.LessDepth=2,e.LessEqualCompare=515,e.LessEqualDepth=3,e.LessEqualStencilFunc=515,e.LessStencilFunc=513,e.Light=pu,e.LightProbe=Du,e.Line=Nc,e.Line2=BC,e.Line3=Dp,e.LineBasicMaterial=Dc,e.LineBasicMaterial2=class extends xC{constructor(e){super(e),console.error("LineBasicMaterial2 is deprecated, use UnlitLineMaterial instead")}},e.LineCurve=Ah,e.LineCurve3=yh,e.LineDashedMaterial=Od,e.LineGeometry=RC,e.LineGeometry2=FC,e.LineGeometryGenerator=Dk,e.LineHelper=FO,e.LineLoop=Vc,e.LineMaterial=Cv,e.LineMaterial2=MC,e.LineSegments=Qc,e.LineSegments2=zv,e.LineSegmentsGeometry=wv,e.LineSegmentsGeometry2=NC,e.LinearDisplayP3ColorSpace="display-p3-linear",e.LinearEncoding=3e3,e.LinearFilter=1006,e.LinearInterpolant=Vd,e.LinearMipMapLinearFilter=1008,e.LinearMipMapNearestFilter=1007,e.LinearMipmapLinearFilter=1008,e.LinearMipmapNearestFilter=1007,e.LinearSRGBColorSpace="srgb-linear",e.LinearToSRGB=Sm,e.LinearToneMapping=1,e.LinearTransfer="linear",e.Loader=su,e.LoaderUtils=Bu,e.LoadingManager=nu,e.LoopOnce=2200,e.LoopPingPong=2202,e.LoopRepeat=2201,e.LuminanceAlphaFormat=1025,e.LuminanceFormat=1024,e.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},e.MTLLoader2=ET,e.Material=Ar,e.MaterialConfiguratorBasePlugin=lk,e.MaterialExtender=pw,e.MaterialLoader=Ru,e.MaterialManager=CR,e.MaterialPreviewGenerator=_v,e.MathUtils=gi,e.Matrix2=Mp,e.Matrix3=Ai,e.Matrix4=Sn,e.MaxEquation=104,e.Mesh=ts,e.Mesh2=DC,e.MeshBasicMaterial=vr,e.MeshBasicMaterial2=class extends kw{constructor(e){super(e),console.error("MeshBasicMaterial2 is deprecated, use UnlitMaterial instead")}},e.MeshDepthMaterial=el,e.MeshDepthMaterialOverride=NL,e.MeshDistanceMaterial=tl,e.MeshLambertMaterial=Bd,e.MeshLine=LC,e.MeshLineMaterial=class extends MC{},e.MeshLineSegments=OC,e.MeshMatcapMaterial=Ld,e.MeshNormalMaterial=Rd,e.MeshNormalMaterialOverride=QL,e.MeshPhongMaterial=Pd,e.MeshPhysicalMaterial=Id,e.MeshStandardMaterial=Td,e.MeshStandardMaterial2=class extends yC{constructor(e){super(e),console.error("MeshStandardMaterial2 is deprecated, use UnlitMaterial instead")}},e.MeshSurfaceSampler=class{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,r=new Float32Array(n);for(let s=0;s<n;s++){let n=1,a=3*s,o=3*s+1,l=3*s+2;e&&(a=e.getX(a),o=e.getX(o),l=e.getX(l)),i&&(n=i.getX(a)+i.getX(o)+i.getX(l)),aL.a.fromBufferAttribute(t,a),aL.b.fromBufferAttribute(t,o),aL.c.fromBufferAttribute(t,l),n*=aL.getArea(),r[s]=n}const s=new Float32Array(n);let a=0;for(let e=0;e<n;e++)a+=r[e],s[e]=a;return this.distribution=s,this}setRandomGenerator(e){return this.randomFunction=e,this}sample(e,t,i,n){const r=this.sampleFaceIndex();return this.sampleFace(r,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,r=-1;for(;i<=n;){const s=Math.ceil((i+n)/2);if(0===s||t[s-1]<=e&&t[s]>e){r=s;break}e<t[s]?n=s-1:i=s+1}return r}sampleFace(e,t,i,n,r){let s=this.randomFunction(),a=this.randomFunction();s+a>1&&(s=1-s,a=1-a);const o=this.indexAttribute;let l=3*e,c=3*e+1,h=3*e+2;return o&&(l=o.getX(l),c=o.getX(c),h=o.getX(h)),aL.a.fromBufferAttribute(this.positionAttribute,l),aL.b.fromBufferAttribute(this.positionAttribute,c),aL.c.fromBufferAttribute(this.positionAttribute,h),t.set(0,0,0).addScaledVector(aL.a,s).addScaledVector(aL.b,a).addScaledVector(aL.c,1-(s+a)),void 0!==i&&(void 0!==this.normalAttribute?(aL.a.fromBufferAttribute(this.normalAttribute,l),aL.b.fromBufferAttribute(this.normalAttribute,c),aL.c.fromBufferAttribute(this.normalAttribute,h),i.set(0,0,0).addScaledVector(aL.a,s).addScaledVector(aL.b,a).addScaledVector(aL.c,1-(s+a)).normalize()):aL.getNormal(i)),void 0!==n&&void 0!==this.colorAttribute&&(aL.a.fromBufferAttribute(this.colorAttribute,l),aL.b.fromBufferAttribute(this.colorAttribute,c),aL.c.fromBufferAttribute(this.colorAttribute,h),oL.set(0,0,0).addScaledVector(aL.a,s).addScaledVector(aL.b,a).addScaledVector(aL.c,1-(s+a)),n.r=oL.x,n.g=oL.y,n.b=oL.z),void 0!==r&&void 0!==this.uvAttribute&&(lL.fromBufferAttribute(this.uvAttribute,l),cL.fromBufferAttribute(this.uvAttribute,c),hL.fromBufferAttribute(this.uvAttribute,h),r.set(0,0).addScaledVector(lL,s).addScaledVector(cL,a).addScaledVector(hL,1-(s+a))),this}},e.MeshToonMaterial=Dd,e.MetaImporter=C_,e.MinEquation=103,e.MirroredRepeatWrapping=1002,e.MixOperation=1,e.MultiplyBlending=4,e.MultiplyOperation=0,e.NearestFilter=1003,e.NearestMipMapLinearFilter=1005,e.NearestMipMapNearestFilter=1004,e.NearestMipmapLinearFilter=1005,e.NearestMipmapNearestFilter=1004,e.NeutralToneMapping=7,e.NeverCompare=512,e.NeverDepth=0,e.NeverStencilFunc=512,e.NoBlending=0,e.NoColorSpace="",e.NoToneMapping=0,e.NormalAnimationBlendMode=2500,e.NormalBlending=1,e.NotEqualCompare=517,e.NotEqualDepth=7,e.NotEqualStencilFunc=517,e.NumberKeyframeTrack=Yd,e.OBJLoader2=zT,e.Object3D=Zn,e.Object3D2=IC,e.Object3DComponent=ON,e.Object3DManager=DR,e.Object3DWidgetsPlugin=Gk,e.ObjectClipboard=eU,e.ObjectLoader=Uu,e.ObjectPicker=mv,e.ObjectShaderMaterial=_C,e.ObjectSpaceNormalMap=1,e.OctahedronGeometry=gd,e.OneFactor=201,e.OneMinusConstantAlphaFactor=214,e.OneMinusConstantColorFactor=212,e.OneMinusDstAlphaFactor=207,e.OneMinusDstColorFactor=209,e.OneMinusSrcAlphaFactor=205,e.OneMinusSrcColorFactor=203,e.OrbitControls=Bf,e.OrbitControls2=class extends Bf{constructor(e,t){super(e,t),this.throttleUpdate=60,this.targetOffset=new Xi(0,0,0);const i=this.update;this.update=()=>this._update(i)}_update(e){this.target.add(this.targetOffset),Sy.copy(this.object.position).sub(this.target),Dy=Sy.length(),Py.copy(this.target);const t=e();return Py.sub(this.target),Sy.copy(this.object.position).sub(this.target),Dy/=Sy.length(),this.target.add(Py),this.object.position.copy(this.target).add(Sy),Sy.normalize(),My.crossVectors(Ry,Sy).normalize(),Ey.crossVectors(Sy,My).normalize(),Ty.crossVectors(My,Ey).normalize().negate(),My.length()>.1&&this.object.up.crossVectors(Sy.clone().normalize(),My),this.enablePan&&(Iy.set(0,0,0).addScaledVector(My,Py.x).addScaledVector(Ey,Py.y).addScaledVector(Ty,Py.z),this.targetOffset.add(Iy),this.targetOffset.multiplyScalar(1/Dy)),Iy.set(0,0,0).addScaledVector(My,-this.targetOffset.x).addScaledVector(Ey,-this.targetOffset.y).addScaledVector(Ty,-this.targetOffset.z),this.object.lookAt(Iy.add(this.target)),this.object.updateMatrixWorld(),this.object.isCamera&&this.object.updateProjectionMatrix(),this.target.sub(this.targetOffset),t}},e.OrthographicCamera=zs,e.OrthographicCamera0=gC,e.OrthographicCamera2=mC,e.P3Primaries="p3",e.PCFShadowMap=1,e.PCFSoftShadowMap=2,e.PLYLoadPlugin=kU,e.PLYLoader=nL,e.PMREMGenerator=$s,e.Pass=vS,e.Path=Ch,e.PerspectiveCamera=ps,e.PerspectiveCamera0=cC,e.PerspectiveCamera2=lC,e.PhysicalMaterial=yC,e.PickingPlugin=sU,e.PipelinePassPlugin=eB,e.PivotControls=$A,e.Plane=bs,e.PlaneGeometry=Es,e.PlaneGeometryGenerator=_k,e.PlaneHelper=class extends Nc{constructor(e,t=1,i=16776960){const n=i,r=new Fr;r.setAttribute("position",new Ir([1,-1,0,-1,1,0,-1,-1,0,1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],3)),r.computeBoundingSphere(),super(r,new Dc({color:n,toneMapped:!1})),this.type="PlaneHelper",this.plane=e,this.size=t;const s=new Fr;s.setAttribute("position",new Ir([1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],3)),s.computeBoundingSphere(),this.add(new ts(s,new vr({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()}},e.PointLight=Su,e.PointLight2=rS,e.PointLightHelper=class extends ts{constructor(e,t,i){super(new yd(t,4,2),new vr({wireframe:!0,fog:!1,toneMapped:!1})),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),void 0!==this.color?this.material.color.set(this.color):this.material.color.copy(this.light.color)}},e.PointLightHelper2=GO,e.PointerDragHelper=em,e.PointerLockControlsPlugin=CU,e.Points=Kc,e.PointsMaterial=Hc,e.PolarGridHelper=class extends Qc{constructor(e=10,t=16,i=8,n=64,r=4473924,s=8947848){r=new mr(r),s=new mr(s);const a=[],o=[];if(t>1)for(let i=0;i<t;i++){const n=i/t*(2*Math.PI),l=Math.sin(n)*e,c=Math.cos(n)*e;a.push(0,0,0),a.push(l,0,c);const h=1&i?r:s;o.push(h.r,h.g,h.b),o.push(h.r,h.g,h.b)}for(let t=0;t<i;t++){const l=1&t?r:s,c=e-e/i*t;for(let e=0;e<n;e++){let t=e/n*(2*Math.PI),i=Math.sin(t)*c,r=Math.cos(t)*c;a.push(i,0,r),o.push(l.r,l.g,l.b),t=(e+1)/n*(2*Math.PI),i=Math.sin(t)*c,r=Math.cos(t)*c,a.push(i,0,r),o.push(l.r,l.g,l.b)}}const l=new Fr;l.setAttribute("position",new Ir(a,3)),l.setAttribute("color",new Ir(o,3));super(l,new Dc({vertexColors:!0,toneMapped:!1})),this.type="PolarGridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}},e.PolyhedronGeometry=Ph,e.PopmotionPlugin=NR,e.PositionalAudio=class extends Zu{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),!0===this.hasPlaybackControl&&!1===this.isPlaying)return;this.matrixWorld.decompose($u,ep,tp),ip.set(0,0,1).applyQuaternion(ep);const t=this.panner;if(t.positionX){const e=this.context.currentTime+this.listener.timeDelta;t.positionX.linearRampToValueAtTime($u.x,e),t.positionY.linearRampToValueAtTime($u.y,e),t.positionZ.linearRampToValueAtTime($u.z,e),t.orientationX.linearRampToValueAtTime(ip.x,e),t.orientationY.linearRampToValueAtTime(ip.y,e),t.orientationZ.linearRampToValueAtTime(ip.z,e)}else t.setPosition($u.x,$u.y,$u.z),t.setOrientation(ip.x,ip.y,ip.z)}},e.ProgressiveBlendPass=OL,e.PropertyBinding=mp,e.PropertyMixer=np,e.QuadraticBezierCurve=vh,e.QuadraticBezierCurve3=_h,e.Quaternion=qi,e.QuaternionKeyframeTrack=Jd,e.QuaternionLinearInterpolant=Kd,e.RED_GREEN_RGTC2_Format=36285,e.RED_RGTC1_Format=36283,e.REVISION="168",e.RGBADepthPacking=3201,e.RGBAFormat=1023,e.RGBAIntegerFormat=1033,e.RGBA_ASTC_10x10_Format=37819,e.RGBA_ASTC_10x5_Format=37816,e.RGBA_ASTC_10x6_Format=37817,e.RGBA_ASTC_10x8_Format=37818,e.RGBA_ASTC_12x10_Format=37820,e.RGBA_ASTC_12x12_Format=37821,e.RGBA_ASTC_4x4_Format=37808,e.RGBA_ASTC_5x4_Format=37809,e.RGBA_ASTC_5x5_Format=37810,e.RGBA_ASTC_6x5_Format=37811,e.RGBA_ASTC_6x6_Format=37812,e.RGBA_ASTC_8x5_Format=37813,e.RGBA_ASTC_8x6_Format=37814,e.RGBA_ASTC_8x8_Format=37815,e.RGBA_BPTC_Format=36492,e.RGBA_ETC2_EAC_Format=37496,e.RGBA_PVRTC_2BPPV1_Format=35843,e.RGBA_PVRTC_4BPPV1_Format=35842,e.RGBA_S3TC_DXT1_Format=33777,e.RGBA_S3TC_DXT3_Format=33778,e.RGBA_S3TC_DXT5_Format=33779,e.RGBDepthPacking=3202,e.RGBELoader=SR,e.RGBEPNGLoader=vE,e.RGBFormat=1022,e.RGBIntegerFormat=1032,e.RGBM16ColorSpace="rgbm-16",e.RGB_BPTC_SIGNED_Format=36494,e.RGB_BPTC_UNSIGNED_Format=36495,e.RGB_ETC1_Format=36196,e.RGB_ETC2_Format=37492,e.RGB_PVRTC_2BPPV1_Format=35841,e.RGB_PVRTC_4BPPV1_Format=35840,e.RGB_S3TC_DXT1_Format=33776,e.RGDepthPacking=3203,e.RGFormat=1030,e.RGIntegerFormat=1031,e.RawShaderMaterial=Ed,e.Ray=Cn,e.Raycaster=xp,e.Rec709Primaries="rec709",e.RectAreaLight=Iu,e.RectAreaLight2=oS,e.RedFormat=1028,e.RedIntegerFormat=1029,e.ReferenceManager=MN,e.ReinhardToneMapping=2,e.RenderPass=wS,e.RenderTarget=Qi,e.RenderTargetManager=WS,e.RepeatWrapping=1e3,e.ReplaceStencilOp=7681,e.ReverseSubtractEquation=102,e.Rhino3dmLoader=VD,e.Rhino3dmLoader2=qD,e.RingGeometry=fd,e.SIGNED_RED_GREEN_RGTC2_Format=36286,e.SIGNED_RED_RGTC1_Format=36284,e.SRGBColorSpace="srgb",e.SRGBToLinear=function(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)},e.SRGBTransfer="srgb",e.STLLoadPlugin=jU,e.STLLoader=sL,e.SVGTextureLoader=YD,e.SampleBodyComponent=NN,e.Scene=_l,e.SceneUiConfigPlugin=lO,e.SelectionWidget=gO,e.Serialization=jm,e.ShaderChunk=Ts,e.ShaderLib=Ps,e.ShaderMaterial=ls,e.ShaderMaterial2=Hw,e.ShaderPass=SS,e.ShadowMaterial=Md,e.Shape=Fh,e.ShapeGeometry=Ad,e.ShapeGeometryGenerator=Tk,e.ShapePath=class{constructor(){this.type="ShapePath",this.color=new mr,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Ch,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,r,s){return this.currentPath.bezierCurveTo(e,t,i,n,r,s),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(e,t){const i=t.length;let n=!1;for(let r=i-1,s=0;s<i;r=s++){let i=t[r],a=t[s],o=a.x-i.x,l=a.y-i.y;if(Math.abs(l)>Number.EPSILON){if(l<0&&(i=t[s],o=-o,a=t[r],l=-l),e.y<i.y||e.y>a.y)continue;if(e.y===i.y){if(e.x===i.x)return!0}else{const t=l*(e.x-i.x)-o*(e.y-i.y);if(0===t)return!0;if(t<0)continue;n=!n}}else{if(e.y!==i.y)continue;if(a.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=a.x)return!0}}return n}const i=cd.isClockWise,n=this.subPaths;if(0===n.length)return[];let r,s,a;const o=[];if(1===n.length)return s=n[0],a=new Fh,a.curves=s.curves,o.push(a),o;let l=!i(n[0].getPoints());l=e?!l:l;const c=[],h=[];let d,u,p=[],m=0;h[m]=void 0,p[m]=[];for(let t=0,a=n.length;t<a;t++)s=n[t],d=s.getPoints(),r=i(d),r=e?!r:r,r?(!l&&h[m]&&m++,h[m]={s:new Fh,p:d},h[m].s.curves=s.curves,l&&m++,p[m]=[]):p[m].push({h:s,p:d[0]});if(!h[0])return function(e){const t=[];for(let i=0,n=e.length;i<n;i++){const n=e[i],r=new Fh;r.curves=n.curves,t.push(r)}return t}(n);if(h.length>1){let e=!1,i=0;for(let e=0,t=h.length;e<t;e++)c[e]=[];for(let n=0,r=h.length;n<r;n++){const r=p[n];for(let s=0;s<r.length;s++){const a=r[s];let o=!0;for(let r=0;r<h.length;r++)t(a.p,h[r].p)&&(n!==r&&i++,o?(o=!1,c[r].push(a)):e=!0);o&&c[n].push(a)}}i>0&&!1===e&&(p=c)}for(let e=0,t=h.length;e<t;e++){a=h[e].s,o.push(a),u=p[e];for(let e=0,t=u.length;e<t;e++)a.holes.push(u[e].h)}return o}},e.ShapeUtils=cd,e.ShortType=1011,e.SimpleEventDispatcher=Jp,e.SimpleJSONExporter=eR,e.SimpleJSONLoader=CT,e.SimpleTextExporter=tR,e.SimplifyModifierPlugin=$k,e.Skeleton=nc,e.SkeletonHelper=class extends Qc{constructor(e){const t=Up(e),i=new Fr,n=[],r=[],s=new mr(0,0,1),a=new mr(0,1,0);for(let e=0;e<t.length;e++){const i=t[e];i.parent&&i.parent.isBone&&(n.push(0,0,0),n.push(0,0,0),r.push(s.r,s.g,s.b),r.push(a.r,a.g,a.b))}i.setAttribute("position",new Ir(n,3)),i.setAttribute("color",new Ir(r,3));super(i,new Dc({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0})),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");Op.copy(this.root.matrixWorld).invert();for(let e=0,i=0;e<t.length;e++){const r=t[e];r.parent&&r.parent.isBone&&(Lp.multiplyMatrices(Op,r.matrixWorld),Bp.setFromMatrixPosition(Lp),n.setXYZ(i,Bp.x,Bp.y,Bp.z),Lp.multiplyMatrices(Op,r.parent.matrixWorld),Bp.setFromMatrixPosition(Lp),n.setXYZ(i+1,Bp.x,Bp.y,Bp.z),i+=2)}i.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose()}},e.SkeletonHelper2=WO,e.SkinnedMesh=Zl,e.Source=Ui,e.Sphere=fn,e.SphereGeometry=yd,e.SphereGeometryGenerator=vk,e.Spherical=Sp,e.SphericalHarmonics3=Pu,e.SplineCurve=bh,e.SpotLight=_u,e.SpotLight2=dS,e.SpotLightHelper=class extends Zn{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new Fr,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 e=0,t=1,i=32;e<i;e++,t++){const r=e/i*Math.PI*2,s=t/i*Math.PI*2;n.push(Math.cos(r),Math.sin(r),1,Math.cos(s),Math.sin(s),1)}i.setAttribute("position",new Ir(n,3));const r=new Dc({fog:!1,toneMapped:!1});this.cone=new Qc(i,r),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),Rp.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(Rp),void 0!==this.color?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}},e.SpotLightHelper2=JO,e.Sprite=kl,e.SpriteMaterial=Cl,e.SrcAlphaFactor=204,e.SrcAlphaSaturateFactor=210,e.SrcColorFactor=202,e.StaticCopyUsage=35046,e.StaticDrawUsage=35044,e.StaticReadUsage=35045,e.StereoCamera=class{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new ps,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new ps,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,Hu.copy(e.projectionMatrix);const i=t.eyeSep/2,n=i*t.near/t.focus,r=t.near*Math.tan(oi*t.fov*.5)/t.zoom;let s,a;Vu.elements[12]=-i,Qu.elements[12]=i,s=-r*t.aspect+n,a=r*t.aspect+n,Hu.elements[0]=2*t.near/(a-s),Hu.elements[8]=(a+s)/(a-s),this.cameraL.projectionMatrix.copy(Hu),s=-r*t.aspect-n,a=r*t.aspect-n,Hu.elements[0]=2*t.near/(a-s),Hu.elements[8]=(a+s)/(a-s),this.cameraR.projectionMatrix.copy(Hu)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(Vu),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(Qu)}},e.StreamCopyUsage=35042,e.StreamDrawUsage=35040,e.StreamReadUsage=35041,e.StringKeyframeTrack=Zd,e.SubtractEquation=101,e.SubtractiveBlending=3,e.SwitchNodeBasePlugin=uk,e.TOUCH={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},e.TYPED_ARRAYS=dm,e.TangentSpaceNormalMap=0,e.TetrahedronGeometry=vd,e.Texture=Ni,e.TextureLoader=uu,e.ThreeFirstPersonControlsPlugin=MU,e.ThreeSerialization=f_,e.TorusGeometry=_d,e.TorusGeometryGenerator=fk,e.TorusKnotGeometry=bd,e.TransformAnimationPlugin=bF,e.TransformControls=rA,e.TransformControlsGizmo=SA,e.TransformControlsPlane=MA,e.Triangle=cr,e.TriangleFanDrawMode=2,e.TriangleStripDrawMode=1,e.TrianglesDrawMode=0,e.TubeGeometry=xd,e.TubeGeometryGenerator=Sk,e.TubeShapeGeometry=zC,e.TubeShapeGeometryGenerator=Ik,e.TypeSystem=wN,e.USDZLoadPlugin=UU,e.USDZLoader=tL,e.UVMapping=300,e.UVsDebug=yB,e.UiConfigMethods=Jg,e.UiConfigRenderer=class extends Zg{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);-1!==t&&(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 sm({id:"uiConfigContainer",addToBody:!1})}},e.UiConfigRendererBase=Zg,e.UiConfigTypeMap=Pg,e.Uint16BufferAttribute=Er,e.Uint32BufferAttribute=Tr,e.Uint8BufferAttribute=class extends Mr{constructor(e,t,i){super(new Uint8Array(e),t,i)}},e.Uint8ClampedBufferAttribute=class extends Mr{constructor(e,t,i){super(new Uint8ClampedArray(e),t,i)}},e.UndoManagerPlugin=PU,e.Uniform=yp,e.UniformsGroup=class extends ri{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:vp++}),this.name="",this.usage=$t,this.uniforms=[]}add(e){return this.uniforms.push(e),this}remove(e){const t=this.uniforms.indexOf(e);return-1!==t&&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 e=0,i=t.length;e<i;e++){const i=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0;e<i.length;e++)this.uniforms.push(i[e].clone())}return this}clone(){return(new this.constructor).copy(this)}},e.UniformsLib=Is,e.UniformsUtils=os,e.UnlitLineMaterial=xC,e.UnlitMaterial=kw,e.UnsignedByteType=1009,e.UnsignedInt248Type=1020,e.UnsignedInt5999Type=35902,e.UnsignedIntType=1014,e.UnsignedShort4444Type=1017,e.UnsignedShort5551Type=1018,e.UnsignedShortType=1012,e.Unzip=iD,e.UnzipInflate=eD,e.UnzipPassThrough=$P,e.Unzlib=MP,e.VSMShadowMap=3,e.Vector2=fi,e.Vector3=Xi,e.Vector4=Gi,e.VectorKeyframeTrack=$d,e.VertexList=vL,e.VertexNode=yL,e.VerticalBlurShader=Av,e.VideoLoader=KD,e.VideoTexture=Zc,e.VideoTextureLoader=JD,e.ViewHelper2=o_,e.ViewerUiConfigPlugin=sO,e.WebGL3DRenderTarget=class extends Vi{constructor(e=1,t=1,i=1,n={}){super(e,t,n),this.isWebGL3DRenderTarget=!0,this.depth=i,this.texture=new Wi(null,e,t,i),this.texture.isRenderTargetTexture=!0}},e.WebGLArrayRenderTarget=class extends Vi{constructor(e=1,t=1,i=1,n={}){super(e,t,n),this.isWebGLArrayRenderTarget=!0,this.depth=i,this.texture=new Hi(null,e,t,i),this.texture.isRenderTargetTexture=!0}},e.WebGLCoordinateSystem=2e3,e.WebGLCubeRenderTarget=As,e.WebGLRenderTarget=Vi,e.WebGLRenderer=Al,e.WebGLUtils=al,e.WebGPUCoordinateSystem=2001,e.Wireframe=AB,e.WireframeGeometry=wd,e.WireframeGeometry2=jC,e.WireframeGeometry3=class extends jC{constructor(e){super(e),this.center2=dw.center2,this.setDirty=dw.setDirty,this.refreshUi=dw.refreshUi,this.appliedMeshes=new Set,dw.upgradeGeometry.call(this)}},e.WrapAroundEnding=2402,e.ZeroCurvatureEnding=2400,e.ZeroFactor=200,e.ZeroSlopeEnding=2401,e.ZeroStencilOp=0,e.Zip=JP,e.ZipDeflate=YP,e.ZipLoader=DD,e.ZipPassThrough=XP,e.Zlib=wP,e._testFinish=function(){window.dispatchEvent(new Event("threepipe-test-finished")),document.body.classList.add("_testFinish")},e._testStart=function(){window.dispatchEvent(new Event("threepipe-test-started")),document.body.classList.add("_testStarted")},e.absMax=lg,e.addModelProcess=qx,e.aesGcmDecrypt=Km,e.aesGcmEncrypt=Ym,e.animate=bx,e.animateAsync=Cx,e.animateCameraToViewLinear=Px,e.animateCameraToViewSpherical=Ix,e.animateTarget=async function(e,t,i,n,r=!1){t in e||console.error("invalid key",t,e);const s=wx(e,t),a=r||void 0===i.from?e[t]:i.from,o=e=>{s(e),i.onUpdate&&i.onUpdate(e)};if("boolean"==typeof a){const{duration:e}=i;return Zp(e??0).then(()=>o(i.to))}return"function"==typeof i.to&&(i={...i,to:i.to(a,e)}),Cx({...i,from:a,onUpdate:o},n)},e.arrayBufferToBase64=cm,e.assetExportHook=vR,e.autoCenterObject3D=function(e){return qw.autoCenter.call(e)},e.autoGPUInstanceMeshes=gv,e.autoScaleObject3D=function(e,t,i,n){return qw.autoScale.call(e,t,i,n)},e.base64ToArrayBuffer=hm,e.basicObjectConstraints=yN,e.bindToValue=zy,e.blobToDataURL=xm,e.blobToImage=function(e){return new Promise((t,i)=>{const n=new Image,r=URL.createObjectURL(e);n.onload=()=>{URL.revokeObjectURL(r),t(n)},n.onerror=e=>{URL.revokeObjectURL(r),i(e)},n.src=r})},e.buildTextSvg=tw,e.cLinearToRGBM=function(e,t){return Fx(new Gi(e.r,e.g,e.b,1),t)},e.cRGBMToLinear=function(e,t){return Ux(e,t),new mr(e.x,e.y,e.z)},e.canvasFlipY=tg,e.centerAllGeometries=Xx,e.checkTexMapReference=Zy,e.clearBit=function(e,t){return e&~(1<<t)},e.clearCoatTintGLTFExtension=PF,e.clonePrimitive=bg,e.cloneScriptTag=lm,e.colorToDataUrl=function(e,t=1,i=1){const n=document.createElement("canvas");n.width=t,n.height=i;const r=n.getContext("2d");r.fillStyle="#"+e,r.fillRect(0,0,t,i);const s=n.toDataURL();return n.remove(),s},e.compress=AP,e.compressSync=yP,e.computeMikkTSpaceTangents=function(e,t,i=!0){if(!t||!t.isReady)throw new Error("BufferGeometryUtils: Initialized MikkTSpace library required.");if(!e.hasAttribute("position")||!e.hasAttribute("normal")||!e.hasAttribute("uv"))throw new Error('BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.');function n(e){if(e.normalized||e.isInterleavedBufferAttribute){const t=new Float32Array(e.count*e.itemSize);for(let i=0,n=0;i<e.count;i++)t[n++]=e.getX(i),t[n++]=e.getY(i),e.itemSize>2&&(t[n++]=e.getZ(i));return t}return e.array instanceof Float32Array?e.array:new Float32Array(e.array)}const r=e.index?e.toNonIndexed():e,s=t.generateTangents(n(r.attributes.position),n(r.attributes.normal),n(r.attributes.uv));if(i)for(let e=3;e<s.length;e+=4)s[e]*=-1;return r.setAttribute("tangent",new Mr(s,4)),e!==r&&e.copy(r),e},e.computeMorphedAttributes=function(e){const t=new Xi,i=new Xi,n=new Xi,r=new Xi,s=new Xi,a=new Xi,o=new Xi,l=new Xi,c=new Xi;function h(e,h,d,u,p,m,g,f){t.fromBufferAttribute(h,p),i.fromBufferAttribute(h,m),n.fromBufferAttribute(h,g);const A=e.morphTargetInfluences;if(d&&A){o.set(0,0,0),l.set(0,0,0),c.set(0,0,0);for(let e=0,h=d.length;e<h;e++){const h=A[e],f=d[e];0!==h&&(r.fromBufferAttribute(f,p),s.fromBufferAttribute(f,m),a.fromBufferAttribute(f,g),u?(o.addScaledVector(r,h),l.addScaledVector(s,h),c.addScaledVector(a,h)):(o.addScaledVector(r.sub(t),h),l.addScaledVector(s.sub(i),h),c.addScaledVector(a.sub(n),h)))}t.add(o),i.add(l),n.add(c)}e.isSkinnedMesh&&(e.applyBoneTransform(p,t),e.applyBoneTransform(m,i),e.applyBoneTransform(g,n)),f[3*p+0]=t.x,f[3*p+1]=t.y,f[3*p+2]=t.z,f[3*m+0]=i.x,f[3*m+1]=i.y,f[3*m+2]=i.z,f[3*g+0]=n.x,f[3*g+1]=n.y,f[3*g+2]=n.z}const d=e.geometry,u=e.material;let p,m,g;const f=d.index,A=d.attributes.position,y=d.morphAttributes.position,v=d.morphTargetsRelative,_=d.attributes.normal,b=d.morphAttributes.position,x=d.groups,w=d.drawRange;let C,S,M,E,T,I,P;const D=new Float32Array(A.count*A.itemSize),R=new Float32Array(_.count*_.itemSize);if(null!==f)if(Array.isArray(u))for(C=0,M=x.length;C<M;C++)for(T=x[C],I=Math.max(T.start,w.start),P=Math.min(T.start+T.count,w.start+w.count),S=I,E=P;S<E;S+=3)p=f.getX(S),m=f.getX(S+1),g=f.getX(S+2),h(e,A,y,v,p,m,g,D),h(e,_,b,v,p,m,g,R);else for(I=Math.max(0,w.start),P=Math.min(f.count,w.start+w.count),C=I,M=P;C<M;C+=3)p=f.getX(C),m=f.getX(C+1),g=f.getX(C+2),h(e,A,y,v,p,m,g,D),h(e,_,b,v,p,m,g,R);else if(Array.isArray(u))for(C=0,M=x.length;C<M;C++)for(T=x[C],I=Math.max(T.start,w.start),P=Math.min(T.start+T.count,w.start+w.count),S=I,E=P;S<E;S+=3)p=S,m=S+1,g=S+2,h(e,A,y,v,p,m,g,D),h(e,_,b,v,p,m,g,R);else for(I=Math.max(0,w.start),P=Math.min(A.count,w.start+w.count),C=I,M=P;C<M;C+=3)p=C,m=C+1,g=C+2,h(e,A,y,v,p,m,g,D),h(e,_,b,v,p,m,g,R);return{positionAttribute:A,normalAttribute:_,morphedPositionAttribute:new Ir(D,3),morphedNormalAttribute:new Ir(R,3)}},e.computeScreenSpaceBoundingBox=function e(t,i){let n,r;if(Array.isArray(t))for(const s of t){const t=e(s,i);void 0===n||void 0===r?(n=t.min.clone(),r=t.max.clone()):(n.min(t.min),r.max(t.max))}const s=t;if(void 0!==s.geometry){const e=s.geometry.vertices;if(void 0===e&&void 0!==s.geometry.attributes&&"position"in s.geometry.attributes){const e=new Xi,a=s.geometry.attributes.position;for(let s=0;s<a.count*a.itemSize;s+=a.itemSize){e.set(a.array[s],a.array[s+1],a.array[3]);const o=e.applyMatrix4(t.matrixWorld).project(i),l=new fi(o.x,o.y);void 0===n||void 0===r?(n=l.clone(),r=l.clone()):(n.min(l),r.max(l))}}else for(const s of e){const e=s.clone().applyMatrix4(t.matrixWorld).project(i),a=new fi(e.x,e.y);void 0===n||void 0===r?(n=a.clone(),r=a.clone()):(n.min(a),r.max(a))}}if(void 0!==t.children)for(const s of t.children){const t=e(s,i);void 0===n||void 0===r?(n=t.min.clone(),r=t.max.clone()):(n.min(t.min),r.max(t.max))}return new Tp(n,r)},e.convertArrayBufferToStringsInMeta=b_,e.convertStringsToArrayBuffersInMeta=x_,e.copyMaterialUserData=v_,e.copyObject3DUserData=__,e.copyPrimitive=wg,e.copyProps=Pm,e.copyTextureUserData=y_,e.copyUserData=A_,e.createBindingsProxy=DU,e.createCameraPath=iC,e.createCanvasElement=rm,e.createCurvePropertyUi=Ck,e.createCurveTypeDropdown=wk,e.createDiv=sm,e.createImage=am,e.createRenderTargetKey=HS,e.createScriptFromURL=async function(e,t=document.head){return new Promise((i,n)=>{const r=document.createElement("script");r.setAttribute("src",e),r.addEventListener("load",()=>i(r)),r.addEventListener("error",n),t.appendChild(r)})},e.createShapeFromPreset=Mk,e.createStyles=om,e.css=vm,e.curveUiConfigs=xk,e.customBumpMapGLTFExtension=jF,e.dataTextureFromColor=function(e){const t=new ec(new Uint8Array([Math.floor(255*e.r),Math.floor(255*e.g),Math.floor(255*e.b),255]),1,1,Ue,Ce);return t.needsUpdate=!0,t.colorSpace=Ut,t},e.dataTextureFromVec4=function(e){const t=new ec(new Uint8Array([Math.floor(255*e.x),Math.floor(255*e.y),Math.floor(255*e.z),Math.floor(255*e.w)]),1,1,Ue,Ce);return t.needsUpdate=!0,t.colorSpace=Ut,t},e.decompress=function(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&yI(7),31==e[0]&&139==e[1]&&8==e[2]?bP(e,t,i):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?pP(e,t,i):TP(e,t,i)},e.decompressSync=function(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?xP(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?mP(e,t):IP(e,t)},e.deepAccessObject=Lm,e.deepCloneAttribute=function(e){return e.isInstancedInterleavedBufferAttribute||e.isInterleavedBufferAttribute?Wy(e):e.isInstancedBufferAttribute?(new rc).copy(e):(new Mr).copy(e)},e.defaultObjectProcessor=Wx,e.deflate=cP,e.deflateSync=hP,e.deinterleaveAttribute=Wy,e.deinterleaveGeometry=function(e){const t=e.attributes,i=e.morphTargets,n=new Map;for(const e in t){const i=t[e];i.isInterleavedBufferAttribute&&(n.has(i)||n.set(i,Wy(i)),t[e]=n.get(i))}for(const e in i){const t=i[e];t.isInterleavedBufferAttribute&&(n.has(t)||n.set(t,Wy(t)),i[e]=n.get(t))}},e.deleteObjects=Yw,e.downloadBlob=bm,e.downloadFile=wm,e.duplicateObjects=Kw,e.embedUrlRefs=ag,e.equalsPrimitive=xg,e.escapeRegExp=gm,e.estimateBytesUsed=function(e){let t=0;for(const i in e.attributes){const n=e.getAttribute(i);t+=n.count*n.itemSize*n.array.BYTES_PER_ELEMENT}const i=e.getIndex();return t+=i?i.count*i.itemSize*i.array.BYTES_PER_ELEMENT:0,t},e.extractAnimationKey=Hx,e.filterTopmostAncestors=Xw,e.findLastIndex=Rm,e.fontFormatExtensionMap=ew,e.fragmentClippingGLTFExtension=YF,e.generateUUID=Ky,e.generateUiConfig=Rg,e.generateUiFolder=Bg,e.generateValueConfig=Dg,e.getComponentTypes=EN,e.getEmptyMeta=w_,e.getFileHandle=async function(){return"showOpenFilePicker"in window?window.showOpenFilePicker().then(e=>e[0]):window.chooseFileSystemEntries()},e.getFilenameFromPath=function(e){return e.substring(e.lastIndexOf("/")+1)},e.getFittingDistance=p_,e.getKeyByValue=function(e,t){return Object.keys(e).find(i=>e[i]===t)},e.getNewFileHandle=function(){if("showSaveFilePicker"in window){const e={types:[{description:"Text file",accept:{"text/plain":[".txt"]}}]};return window.showSaveFilePicker(e)}return window.chooseFileSystemEntries({type:"save-file",accepts:[{description:"Text file",extensions:["txt"],mimeTypes:["text/plain"]}]})},e.getOrCall=Im,e.getPartialProps=I_,e.getPropDesc=Mg,e.getPropertyDescriptor=Mm,e.getTexelDecoding=Qy,e.getTexelDecodingFunction=Gy,e.getTextureDataType=$y,e.getTypedArray=um,e.getUrlQueryParam=dg,e.glbEncryptionPreparser=xT,e.glbEncryptionProcessor=bT,e.glsl=ym,e.gunzip=bP,e.gunzipSync=xP,e.gzip=AP,e.gzipSync=yP,e.halfFloatToRgbe=Fy,e.html=(e,...t)=>String.raw({raw:e},...t),e.htmlDialogWrapper=_g,e.htmlToCanvas=async function(e,t,i){const n=og(e,t,i);return await ng(n,i)},e.htmlToPng=async function(e,t,i){const n=og(e,t,i);return await rg(n,i)},e.htmlToSvg=og,e.iCameraCommons=nC,e.iGeometryCommons=dw,e.iLightCommons=VC,e.iMaterialCommons=Nw,e.iObjectCommons=qw,e.imageBitmapToBase64=Zm,e.imageBitmapToBlob=async function(e,t=8192,i=!1,n="image/png"){if(!e.width&&!e.videoWidth||!e.height&&!e.videoHeight)return Promise.reject("Invalid bitmap");const r=Jm(e,t,!1);return new Promise((t,s)=>{r.toBlob(n=>{n?t(n):s("Could not get blob"),r.remove(),i&&e instanceof ImageBitmap&&e.close()},n)})},e.imageBitmapToCanvas=Jm,e.imageDataToCanvas=function(e){const t=document.createElement("canvas");return t.width=e.width,t.height=e.height,t.getContext("2d").putImageData(e,0,0),t},e.imageToCanvas=eg,e.imageUrlToImageData=$m,e.includesAll=Dm,e.incrementObjectCloneName=cw,e.inflate=pP,e.inflateSync=mP,e.interleaveAttributes=function(e){let t,i=0,n=0;for(let r=0,s=e.length;r<s;++r){const s=e[r];if(void 0===t&&(t=s.array.constructor),t!==s.array.constructor)return console.error("AttributeBuffers of different types cannot be interleaved"),null;i+=s.array.length,n+=s.itemSize}const r=new bl(new t(i),n);let s=0;const a=[],o=["getX","getY","getZ","getW"],l=["setX","setY","setZ","setW"];for(let t=0,i=e.length;t<i;t++){const i=e[t],n=i.itemSize,c=i.count,h=new wl(r,n,s,i.normalized);a.push(h),s+=n;for(let e=0;e<c;e++)for(let t=0;t<n;t++)h[l[t]](e,i[o[t]](e))}return a},e.isInScene=function e(...t){if(t.length>1)return t.some(t=>e(t));const i=t[0];if(i.isTexture)return Array.from(i.appliedObjects||[]).some(t=>e(t))??!1;const n=i.isObject3D?[i]:i.appliedMeshes;for(const e of n){let t=!1;if(e.traverseAncestors(e=>e.isScene&&(t=!0)),t)return!0}return!1},e.isNonRelativeUrl=Eg,e.isPropertyWritable=Em,e.isWebpExportSupported=function(){const e=document.createElement("canvas");return!(!e.getContext||!e.getContext("2d"))&&e.toDataURL("image/webp").startsWith("data:image/webp")},e.jsonToBlob=E_,e.lerp=Mx,e.lerpAngle=Sx,e.lerpNumber=Rx,e.lerpParams=Ox,e.lerpTexture=Lx,e.lerpVal=Dx,e.lerpVector=Bx,e.literalStrings=function(e){return{oneOf:e.map(e=>"number"==typeof e||"boolean"==typeof e?`${e}`:`"${e}"`),type:"Union"}},e.localToWorldQuaternion=function(e,t,i=new qi){return t.premultiply(e.getWorldQuaternion(i))},e.longestCommonPrefix=function(e){return e.sort(),e[0].split("").map((t,i)=>e[e.length-1][i]===t?t:"\0").join("").split("\0").at(0)||""},e.makeColorSvg=e=>`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${e}'/%3E%3C/svg%3E%0A`,e.makeColorSvgCircle=ig,e.makeGLBFile=L_,e.makeICameraCommonUiConfig=aw,e.makeIObject3DUiConfig=ow,e.makeSamplerUi=bw,e.makeSetterFor=wx,e.makeTextSvg=e=>`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${e}%3C/text%3E%3C/svg%3E%0A`,e.makeTextSvgAdvanced=async function(e,t){const i=e.fontFamily||"Arial";let n=e.fontPath||iw[i]||"",r=e.style||"";if(n.length>0){!Eg(n)&&!n.startsWith("blob:")&&!n.startsWith("ftp:")&&globalThis.window&&(n=new URL(n,window.location.href).href);const e=mm(n)||"woff";r+="\n"+(n.length>0?`\n            @font-face {\n                font-family: ${JSON.stringify(i)};\n                src: url(${n}) format(${ew[e]||e});\n            }`:"")}let s=tw({...e,fontFamily:i,style:r});s=await ag(s,async e=>async function(e,t){if(e.startsWith("http://www.w3.org"))return e;if(!t)throw new Error("no importer");const i={fileHandler:new Yx(t.loadingManager),processRaw:!1};try{return await t.importSingle(e,i)}catch(e){return console.error(e),""}}(e,t)),s=_m(s);const a=await t.importSingle(s);return a?(a.generateMipmaps=!1,a.minFilter=be,a.flipY=!0,a.needsUpdate=!0,a):null},e.matDefine=Ny,e.matDefineBool=jy,e.mergeAttributes=Hy,e.mergeBufferAttributes=function(e){return console.warn("THREE.BufferGeometryUtils: mergeBufferAttributes() has been renamed to mergeAttributes()."),Hy(e)},e.mergeBufferGeometries=function(e,t=!1){return console.warn("THREE.BufferGeometryUtils: mergeBufferGeometries() has been renamed to mergeGeometries()."),Vy(e,t)},e.mergeGeometries=Vy,e.mergeGroups=function(e){if(0===e.groups.length)return console.warn("THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge."),e;let t=e.groups;if(t=t.sort((e,t)=>e.materialIndex!==t.materialIndex?e.materialIndex-t.materialIndex:e.start-t.start),null===e.getIndex()){const t=e.getAttribute("position"),i=[];for(let e=0;e<t.count;e+=3)i.push(e,e+1,e+2);e.setIndex(i)}const i=e.getIndex(),n=[];for(let e=0;e<t.length;e++){const r=t[e],s=r.start,a=s+r.count;for(let e=s;e<a;e++)n.push(i.getX(e))}e.dispose(),e.setIndex(n);let r=0;for(let e=0;e<t.length;e++){const i=t[e];i.start=r,r+=i.count}let s=t[0];e.groups=[s];for(let i=1;i<t.length;i++){const n=t[i];s.materialIndex===n.materialIndex?s.count+=n.count:(s=n,e.groups.push(s))}return e},e.mergeResources=function(e,t){for(const i of Object.keys(t))"object"!==i&&(e[i]||(e[i]={}),Object.assign(e[i],t[i]));return e},e.mergeVertices=qy,e.metaFromResources=M_,e.metaToResources=S_,e.mobileAndTabletCheck=function(){let e=!1;return t=navigator.userAgent||navigator.vendor||window.opera,(/(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(t)||/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(t.substr(0,4)))&&(e=!0),e;var t},e.noiseBumpMaterialGLTFExtension=OF,e.now=$p,e.objectActionsUiConfig=hw,e.objectExtensionsUiConfig=lw,e.objectHasOwn=Om,e.objectMap=Um,e.objectMap2=Fm,e.onChange=Qm,e.onChange2=Vm,e.onChange3=Hm,e.onChangeDispatchEvent=Wm,e.overrideThreeCache=Uy,e.parseFileExtension=mm,e.pathJoin=function(e,t="/"){return e.join(t)},e.prettyScrollbar=function(e=document.head){return om(vm`
      ::-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);}
    `,e)},e.readFile=function(e){return e.text?e.text():function(e){return new Promise(t=>{const i=new FileReader;i.addEventListener("loadend",e=>{const i=(e.srcElement||e.target).result;t(i)}),i.readAsText(e)})}(e)},e.recordUndoCommand=Cg,e.remoteWorkerURL=function(e,t){const i=(t?`var Module = { locateFile: function(s) { return "${t}"; } }; \n`:"")+`importScripts( "${e}" );`;return URL.createObjectURL(new Blob([i],{type:"text/javascript"}))},e.replaceAll=fm,e.reverseShapeWinding=Ek,e.sRGBEncoding=3001,e.safeReplaceString=function(e,t,i,{replaceAll:n=!1,prepend:r=!1,append:s=!1,notFoundCallback:a=()=>{}}={}){if(a&&!e.includes(t))return a(),e;let o=i;return r?o=i+t:s&&(o=t+i),n?e.replaceAll(t,o):e.replace(t,o)},e.safeSetProperty=Tm,e.sampleThreepipeViteHmrPlugin=AN,e.serializable=Xm,e.serialize=qm,e.serializeTextureInExtras=T_,e.setInnerHTMLWithScripts=async function(e,t){var i;e.innerHTML=t;const n=e.getElementsByTagName("script");for(let e=0;e<n.length;e++){const t=n[e],r=lm(t);let s=!1;await new Promise(e=>{r.onload=e,r.onerror=()=>{s=!0,e(void 0)}}),!s&&(null==(i=t.parentNode)||i.replaceChild(r,t))}},e.setPartialProps=P_,e.setThreeRendererMode=gS,e.setUrlQueryParam=function(e,t,i=!1){var n;if(null==(n=window?.location)||!n.href)return;const r=new URLSearchParams(window.location.search);null==t?r.has(e)&&r.delete(e):r.set(e,t),i?window.location.search=r.toString():window.history.replaceState({},"","?"+r.toString())},e.setValueUndoCommand=Sg,e.setupComponent=TN,e.shaderReplaceString=R_,e.shaderUtils=Tg,e.snapObject=vv,e.sortPasses=jS,e.sphericalFromCameraView=Tx,e.strFromU8=jP,e.strToU8=NP,e.svgToCanvas=ng,e.svgToPng=rg,e.svgUrl=_m,e.texImageToCanvas=iv,e.textureDataToImageData=ev,e.textureToBlob=async function(e,t,i,n,r){const s=tv(e,t,i);return new Promise((e,t)=>{s.toBlob(i=>{i?e(i):t(new Error("Failed to create blob"))},n,r)})},e.textureToCanvas=tv,e.textureToDataUrl=function(e,t,i,n,r){return tv(e,t,i).toDataURL(n,r)},e.threeConstMappings=lv,e.threeMaterialInterpolateProps=Uw,e.threeMaterialPropList=Ow,e.timeout=Zp,e.toCamelCase=function(e){return e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace("-","").replace("_",""))},e.toCreasedNormals=function(e,t=Math.PI/3){const i=Math.cos(t),n=100*(1+1e-10),r=[new Xi,new Xi,new Xi],s=new Xi,a=new Xi,o=new Xi,l=new Xi;function c(e){return`${~~(e.x*n)},${~~(e.y*n)},${~~(e.z*n)}`}const h=e.index?e.toNonIndexed():e,d=h.attributes.position,u={};for(let e=0,t=d.count/3;e<t;e++){const t=3*e,i=r[0].fromBufferAttribute(d,t+0),n=r[1].fromBufferAttribute(d,t+1),o=r[2].fromBufferAttribute(d,t+2);s.subVectors(o,n),a.subVectors(i,n);const l=(new Xi).crossVectors(s,a).normalize();for(let e=0;e<3;e++){const t=c(r[e]);t in u||(u[t]=[]),u[t].push(l)}}const p=new Float32Array(3*d.count),m=new Mr(p,3,!1);for(let e=0,t=d.count/3;e<t;e++){const t=3*e,n=r[0].fromBufferAttribute(d,t+0),h=r[1].fromBufferAttribute(d,t+1),p=r[2].fromBufferAttribute(d,t+2);s.subVectors(p,h),a.subVectors(n,h),o.crossVectors(s,a).normalize();for(let e=0;e<3;e++){const n=u[c(r[e])];l.set(0,0,0);for(let e=0,t=n.length;e<t;e++){const t=n[e];o.dot(t)>i&&l.add(t)}l.normalize(),m.setXYZ(t+e,l.x,l.y,l.z)}}return h.setAttribute("normal",m),h},e.toIndexedGeometry=Yy,e.toTitleCase=pm,e.toTrianglesDrawMode=Xy,e.uiButton=jg,e.uiColor=Qg,e.uiConfig=Lg,e.uiConfigMaterialExtension=_w,e.uiContainer=Og,e.uiDropdown=Ng,e.uiFolderContainer=qg,e.uiImage=Vg,e.uiInput=zg,e.uiMonitor=Ug,e.uiNumber=Gg,e.uiPanelContainer=Wg,e.uiSlider=Fg,e.uiToggle=Hg,e.uiVector=kg,e.uniform=ky,e.unzip=function(e,t,i){i||(i=t,t={}),"function"!=typeof i&&yI(7);var n=[],r=function(){for(var e=0;e<n.length;++e)n[e]()},s={},a=function(e,t){nD(function(){i(e,t)})};nD(function(){a=i});for(var o=e.length-22;101010256!=JI(e,o);--o)if(!o||e.length-o>65558)return a(yI(13,0,1),null),r;var l=KI(e,o+8);if(l){var c=l,h=JI(e,o+16),d=4294967295==h||65535==c;if(d){var u=JI(e,o-12);(d=101075792==JI(e,u))&&(c=l=JI(e,u+32),h=JI(e,u+48))}for(var p=t&&t.filter,m=function(t){var i=QP(e,h,d),o=i[0],c=i[1],u=i[2],m=i[3],g=i[4],f=i[5],A=GP(e,f);h=g;var y=function(e,t){e?(r(),a(e,null)):(t&&(s[m]=t),--l||a(null,s))};if(!p||p({name:m,size:c,originalSize:u,compression:o}))if(o)if(8==o){var v=e.subarray(A,A+c);if(u<524288||c>.8*u)try{y(null,mP(v,{out:new QT(u)}))}catch(e){y(e,null)}else n.push(pP(v,{size:u},y))}else y(yI(14,"unknown compression type "+o,1),null);else y(null,fI(e,A,A+c));else y(null,null)},g=0;g<c;++g)m()}else a(null,{});return r},e.unzipSync=rD,e.unzlib=TP,e.unzlibSync=IP,e.updateBit=cg,e.updateMaterialDefines=mw,e.updateUi=mk,e.upgradeTexture=uS,e.upgradeWebGLRenderer=pS,e.uploadFile=Cm,e.uuidV4=hg,e.vLinearToRGBM=Fx,e.vRGBMToLinear=Ux,e.verifyPermission=async function(e,t){const i={};return t&&(i.writable=!0,i.mode="readwrite"),"granted"===await e.queryPermission(i)||"granted"===await e.requestPermission(i)},e.whiteImageData=cv,e.whiteTexture=hv,e.windowDialogWrapper=ug,e.worldToLocalQuaternion=Jy,e.wrapThisFunction=function(e,t){return function(...i){return e(),t&&t.call(this,...i)}},e.wrapThisFunction2=Bm,e.writeFile=async function(e,t){if(e.createWriter){const i=await e.createWriter();return await i.write(0,t),void await i.close()}const i=await e.createWritable();await i.write(t),await i.close()},e.zip=function(e,t,i){i||(i=t,t={}),"function"!=typeof i&&yI(7);var n={};RP(e,"",n,t);var r=Object.keys(n),s=r.length,a=0,o=0,l=s,c=new Array(s),h=[],d=function(){for(var e=0;e<h.length;++e)h[e]()},u=function(e,t){nD(function(){i(e,t)})};nD(function(){u=i});var p=function(){var e=new QT(o+22),t=a,i=o-a;o=0;for(var n=0;n<l;++n){var r=c[n];try{var s=r.c.length;WP(e,o,r,r.f,r.u,s);var h=30+r.f.length+HP(r.extra),d=o+h;e.set(r.c,d),WP(e,a,r,r.f,r.u,s,o,r.m),a+=16+h+(r.m?r.m.length:0),o=d+s}catch(e){return u(e,null)}}qP(e,a,c.length,i,t),u(null,e)};s||p();for(var m=function(e){var t=r[e],i=n[t],l=i[0],m=i[1],g=RI(),f=l.length;g.p(l);var A=NP(t),y=A.length,v=m.comment,_=v&&NP(v),b=_&&_.length,x=HP(m.extra),w=0==m.level?0:8,C=function(i,n){if(i)d(),u(i,null);else{var r=n.length;c[e]=OI(m,{size:f,crc:g.d(),c:n,f:A,m:_,u:y!=t.length||_&&v.length!=b,compression:w}),a+=30+y+x+r,o+=76+2*(y+x)+(b||0)+r,--s||p()}};if(y>65535&&C(yI(11,0,1),null),w)if(f<16e4)try{C(null,hP(l,m))}catch(e){C(e,null)}else h.push(cP(l,m,C));else C(null,l)},g=0;g<l;++g)m(g);return d},e.zipSync=ZP,e.zlib=function(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&yI(7),qI(e,t,[jI,QI,function(){return[SP]}],function(e){return HI(SP(e.data[0],e.data[1]))},4,i)},e.zlibSync=SP,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
//# sourceMappingURL=/sm/2dc319dc1bedd38fbf08079463a11fe9a818c56cf9d5cf8fe62fded8dd35f2e4.map