/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/threepipe@0.5.1/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";
/**
 * @license
 * threepipe v0.5.1
 * Copyright 2022-2026 repalash <palash@shaders.app>
 * Apache-2.0 License
 * See ./dependencies.txt for bundled third-party dependencies and licenses.
 */
/**
 * @license
 * Copyright 2010-2023 Three.js Authors
 * SPDX-License-Identifier: MIT
 */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,N=204,k=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=1012,Me=1013,Ee=1014,Te=1015,Ie=1016,Pe=1017,De=1018,Re=1020,Be=1023,Le=1026,Oe=1027,Ue=1028,Fe=1030,Ne=33776,ke=33777,je=33778,ze=33779,Ge=35840,Qe=35842,Ve=36196,He=37492,We=37496,qe=37808,Xe=37812,Ye=36492,Ke=2200,Je=2201,Ze=2300,$e=2301,et=2302,tt=2400,it=2401,nt=2402,rt=2500,st=3200,at=3201,ot=0,lt=1,ct="",ht="srgb",dt="srgb-linear",ut="display-p3",pt="display-p3-linear",mt="rgbm-16",gt="linear",ft="srgb",At="rec709",yt="p3",vt=7680,_t=512,bt=513,xt=514,wt=515,Ct=516,St=517,Mt=518,Et=519,Tt=35044,It="300 es",Pt=2e3,Dt=2001,Rt=3001;class Bt{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 Lt=["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 Ot=1234567;const Ut=Math.PI/180,Ft=180/Math.PI;function Nt(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,n=4294967295*Math.random()|0;return(Lt[255&e]+Lt[e>>8&255]+Lt[e>>16&255]+Lt[e>>24&255]+"-"+Lt[255&t]+Lt[t>>8&255]+"-"+Lt[t>>16&15|64]+Lt[t>>24&255]+"-"+Lt[63&i|128]+Lt[i>>8&255]+"-"+Lt[i>>16&255]+Lt[i>>24&255]+Lt[255&n]+Lt[n>>8&255]+Lt[n>>16&255]+Lt[n>>24&255]).toLowerCase()}function kt(e,t,i){return Math.max(t,Math.min(i,e))}function jt(e,t){return(e%t+t)%t}function zt(e,t,i){return(1-i)*e+i*t}function Gt(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 Qt(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 Vt={DEG2RAD:Ut,RAD2DEG:Ft,generateUUID:Nt,clamp:kt,euclideanModulo:jt,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:zt,damp:function(e,t,i,n){return zt(e,t,1-Math.exp(-i*n))},pingpong:function(e,t=1){return t-Math.abs(jt(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&&(Ot=e);let t=Ot+=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*Ut},radToDeg:function(e){return e*Ft},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:Qt,denormalize:Gt};class Ht{constructor(e=0,t=0){Ht.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(kt(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 Wt{constructor(e,t,i,n,r,s,a,o,l){Wt.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(qt.makeScale(e,t)),this}rotate(e){return this.premultiply(qt.makeRotation(-e)),this}translate(e,t){return this.premultiply(qt.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 qt=new Wt;function Xt(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}const Yt={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function Kt(e,t){return new Yt[e](t)}function Jt(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function Zt(){const e=Jt("canvas");return e.style.display="block",e}const $t={};function ei(e){e in $t||($t[e]=!0,console.warn(e))}const ti=(new Wt).set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),ii=(new Wt).set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),ni={[dt]:{transfer:gt,primaries:At,toReference:e=>e,fromReference:e=>e},[ht]:{transfer:ft,primaries:At,toReference:e=>e.convertSRGBToLinear(),fromReference:e=>e.convertLinearToSRGB()},[pt]:{transfer:gt,primaries:yt,toReference:e=>e.applyMatrix3(ii),fromReference:e=>e.applyMatrix3(ti)},[ut]:{transfer:ft,primaries:yt,toReference:e=>e.convertSRGBToLinear().applyMatrix3(ii),fromReference:e=>e.applyMatrix3(ti).convertLinearToSRGB()}},ri=new Set([dt,pt]),si={enabled:!0,_workingColorSpace:dt,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(e){if(!ri.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=ni[t].toReference;return(0,ni[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 ni[e].primaries},getTransfer:function(e){return e===ct||e===mt?gt:ni[e].transfer}};function ai(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function oi(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let li;class ci{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===li&&(li=Jt("canvas")),li.width=e.width,li.height=e.height;const t=li.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),i=li}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=Jt("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*ai(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*ai(t[e]/255)):t[e]=ai(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 hi=0;class di{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:hi++}),this.uuid=Nt(),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(ui(n[t].image)):e.push(ui(n[t]))}else e=ui(n);i.url=e}return t||(e.images[this.uuid]=i),i}}function ui(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap)return ci.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 pi=0;class mi extends Bt{constructor(e=mi.DEFAULT_IMAGE,t=mi.DEFAULT_MAPPING,i=fe,n=fe,r=be,s=we,a=Be,o=Ce,l=mi.DEFAULT_ANISOTROPY,c=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:pi++}),this.uuid=Nt(),this.name="",this.source=new di(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 Ht(0,0),this.repeat=new Ht(1,1),this.center=new Ht(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Wt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,"string"==typeof c?this.colorSpace=c:(ei("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=c===Rt?ht:ct),this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.pmremVersion=0,e instanceof ImageData&&e!==mi.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=fi(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===ht?Rt: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=fi({},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 ei("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace===ht?Rt:3e3}set encoding(e){ei("THREE.Texture: Property .encoding has been replaced by .colorSpace."),this.colorSpace=e===Rt?ht:ct}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}mi.DEFAULT_IMAGE=null,mi.DEFAULT_MAPPING=ce,mi.DEFAULT_ANISOTROPY=1;const gi=["appliedMaterials","uuid"];function fi(e,t){if(t)for(const i of Object.keys(t))gi.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 Ai{constructor(e=0,t=0,i=0,n=1){Ai.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}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 yi extends Bt{constructor(e=1,t=1,i={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new Ai(0,0,e,t),this.scissorTest=!1,this.viewport=new Ai(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,depthTexture:null,samples:0,count:1},i);const r=new mi(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.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 di(t),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,e.depthTexture&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class vi extends yi{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}}class _i extends mi{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}}class bi extends mi{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 xi{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(kt(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 wi{constructor(e=0,t=0,i=0){wi.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(Si.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Si.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 Ci.copy(this).projectOnVector(e),this.sub(Ci)}reflect(e){return this.sub(Ci.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(kt(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 Ci=new wi,Si=new xi;class Mi{constructor(e=new wi(1/0,1/0,1/0),t=new wi(-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(Ti.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint(Ti.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=Ti.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,Ti):Ti.fromBufferAttribute(n,t),Ti.applyMatrix4(e.matrixWorld),this.expandByPoint(Ti);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),Ii.copy(e.boundingBox)):(null===i.boundingBox&&i.computeBoundingBox(),Ii.copy(i.boundingBox)),Ii.applyMatrix4(e.matrixWorld),this.union(Ii)}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,Ti),Ti.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(Ui),Fi.subVectors(this.max,Ui),Pi.subVectors(e.a,Ui),Di.subVectors(e.b,Ui),Ri.subVectors(e.c,Ui),Bi.subVectors(Di,Pi),Li.subVectors(Ri,Di),Oi.subVectors(Pi,Ri);let t=[0,-Bi.z,Bi.y,0,-Li.z,Li.y,0,-Oi.z,Oi.y,Bi.z,0,-Bi.x,Li.z,0,-Li.x,Oi.z,0,-Oi.x,-Bi.y,Bi.x,0,-Li.y,Li.x,0,-Oi.y,Oi.x,0];return!(!ji(t,Pi,Di,Ri,Fi)||(t=[1,0,0,0,1,0,0,0,1],!ji(t,Pi,Di,Ri,Fi)))&&(Ni.crossVectors(Bi,Li),t=[Ni.x,Ni.y,Ni.z],ji(t,Pi,Di,Ri,Fi))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ti).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Ti).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()||(Ei[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ei[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ei[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ei[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ei[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ei[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ei[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ei[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ei)),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 Ei=[new wi,new wi,new wi,new wi,new wi,new wi,new wi,new wi],Ti=new wi,Ii=new Mi,Pi=new wi,Di=new wi,Ri=new wi,Bi=new wi,Li=new wi,Oi=new wi,Ui=new wi,Fi=new wi,Ni=new wi,ki=new wi;function ji(e,t,i,n,r){for(let s=0,a=e.length-3;s<=a;s+=3){ki.fromArray(e,s);const a=r.x*Math.abs(ki.x)+r.y*Math.abs(ki.y)+r.z*Math.abs(ki.z),o=t.dot(ki),l=i.dot(ki),c=n.dot(ki);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const zi=new Mi,Gi=new wi,Qi=new wi;class Vi{constructor(e=new wi,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):zi.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;Gi.subVectors(e,this.center);const t=Gi.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),i=.5*(e-this.radius);this.center.addScaledVector(Gi,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):(Qi.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Gi.copy(e.center).add(Qi)),this.expandByPoint(Gi.copy(e.center).sub(Qi))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Hi=new wi,Wi=new wi,qi=new wi,Xi=new wi,Yi=new wi,Ki=new wi,Ji=new wi;class Zi{constructor(e=new wi,t=new wi(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,Hi)),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=Hi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Hi.copy(this.origin).addScaledVector(this.direction,t),Hi.distanceToSquared(e))}distanceSqToSegment(e,t,i,n){Wi.copy(e).add(t).multiplyScalar(.5),qi.copy(t).sub(e).normalize(),Xi.copy(this.origin).sub(Wi);const r=.5*e.distanceTo(t),s=-this.direction.dot(qi),a=Xi.dot(this.direction),o=-Xi.dot(qi),l=Xi.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(Wi).addScaledVector(qi,d),u}intersectSphere(e,t){Hi.subVectors(e.center,this.origin);const i=Hi.dot(this.direction),n=Hi.dot(Hi)-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,Hi)}intersectTriangle(e,t,i,n,r){Yi.subVectors(t,e),Ki.subVectors(i,e),Ji.crossVectors(Yi,Ki);let s,a=this.direction.dot(Ji);if(a>0){if(n)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}Xi.subVectors(this.origin,e);const o=s*this.direction.dot(Ki.crossVectors(Xi,Ki));if(o<0)return null;const l=s*this.direction.dot(Yi.cross(Xi));if(l<0||o+l>a)return null;const c=-s*Xi.dot(Ji);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 $i{constructor(e,t,i,n,r,s,a,o,l,c,h,d,u,p,m,g){$i.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 $i).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/en.setFromMatrixColumn(e,0).length(),r=1/en.setFromMatrixColumn(e,1).length(),s=1/en.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(nn,e,rn)}lookAt(e,t,i){const n=this.elements;return on.subVectors(e,t),0===on.lengthSq()&&(on.z=1),on.normalize(),sn.crossVectors(i,on),0===sn.lengthSq()&&(1===Math.abs(i.z)?on.x+=1e-4:on.z+=1e-4,on.normalize(),sn.crossVectors(i,on)),sn.normalize(),an.crossVectors(on,sn),n[0]=sn.x,n[4]=an.x,n[8]=on.x,n[1]=sn.y,n[5]=an.y,n[9]=on.y,n[2]=sn.z,n[6]=an.z,n[10]=on.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=en.set(n[0],n[1],n[2]).length();const s=en.set(n[4],n[5],n[6]).length(),a=en.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],tn.copy(this);const o=1/r,l=1/s,c=1/a;return tn.elements[0]*=o,tn.elements[1]*=o,tn.elements[2]*=o,tn.elements[4]*=l,tn.elements[5]*=l,tn.elements[6]*=l,tn.elements[8]*=c,tn.elements[9]*=c,tn.elements[10]*=c,t.setFromRotationMatrix(tn),i.x=r,i.y=s,i.z=a,this}makePerspective(e,t,i,n,r,s,a=Pt){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===Pt)u=-(s+r)/(s-r),p=-2*s*r/(s-r);else{if(a!==Dt)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=Pt){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===Pt)p=(s+r)*h,m=-2*h;else{if(a!==Dt)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 en=new wi,tn=new $i,nn=new wi(0,0,0),rn=new wi(1,1,1),sn=new wi,an=new wi,on=new wi,ln=new $i,cn=new xi;class hn{constructor(e=0,t=0,i=0,n=hn.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(kt(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(-kt(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(kt(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(-kt(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(kt(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(-kt(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 ln.makeRotationFromQuaternion(e),this.setFromRotationMatrix(ln,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return cn.setFromEuler(this),this.setFromQuaternion(cn,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}}hn.DEFAULT_ORDER="XYZ";class dn{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!!(this.mask&e.mask)}isEnabled(e){return!!(this.mask&1<<e)}}let un=0;const pn=new wi,mn=new xi,gn=new $i,fn=new wi,An=new wi,yn=new wi,vn=new xi,_n=new wi(1,0,0),bn=new wi(0,1,0),xn=new wi(0,0,1),wn={type:"added"},Cn={type:"removed"},Sn={type:"childadded",child:null},Mn={type:"childremoved",child:null};class En extends Bt{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:un++}),this.uuid=Nt(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=En.DEFAULT_UP.clone();const e=new wi,t=new hn,i=new xi,n=new wi(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 $i},normalMatrix:{value:new Wt}}),this.matrix=new $i,this.matrixWorld=new $i,this.matrixAutoUpdate=En.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=En.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new dn,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 mn.setFromAxisAngle(e,t),this.quaternion.multiply(mn),this}rotateOnWorldAxis(e,t){return mn.setFromAxisAngle(e,t),this.quaternion.premultiply(mn),this}rotateX(e){return this.rotateOnAxis(_n,e)}rotateY(e){return this.rotateOnAxis(bn,e)}rotateZ(e){return this.rotateOnAxis(xn,e)}translateOnAxis(e,t){return pn.copy(e).applyQuaternion(this.quaternion),this.position.add(pn.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(_n,e)}translateY(e){return this.translateOnAxis(bn,e)}translateZ(e){return this.translateOnAxis(xn,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(gn.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?fn.copy(e):fn.set(e,t,i);const n=this.parent;this.updateWorldMatrix(!0,!1),An.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?gn.lookAt(An,fn,this.up):gn.lookAt(fn,An,this.up),this.quaternion.setFromRotationMatrix(gn),n&&(gn.extractRotation(n.matrixWorld),mn.setFromRotationMatrix(gn),this.quaternion.premultiply(mn.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(wn),Sn.child=e,this.dispatchEvent(Sn),Sn.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(Cn),Mn.child=e,this.dispatchEvent(Mn),Mn.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),gn.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),gn.multiply(e.parent.matrixWorld)),e.applyMatrix4(gn),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(wn),Sn.child=e,this.dispatchEvent(Sn),Sn.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(An,e,yn),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(An,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)&&(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++){const n=t[i];(!0===n.matrixWorldAutoUpdate||!0===e)&&n.updateMatrixWorld(e)}}updateWorldMatrix(e,t){const i=this.parent;if(!0===e&&null!==i&&!0===i.matrixWorldAutoUpdate&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),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++){const i=e[t];!0===i.matrixWorldAutoUpdate&&i.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.maxGeometryCount=this._maxGeometryCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.geometryCount=this._geometryCount,n.matricesTexture=this._matricesTexture.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}}En.DEFAULT_UP=new wi(0,1,0),En.DEFAULT_MATRIX_AUTO_UPDATE=!0,En.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Tn=new wi,In=new wi,Pn=new wi,Dn=new wi,Rn=new wi,Bn=new wi,Ln=new wi,On=new wi,Un=new wi,Fn=new wi;class Nn{constructor(e=new wi,t=new wi,i=new wi){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,n){n.subVectors(i,t),Tn.subVectors(e,t),n.cross(Tn);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){Tn.subVectors(n,t),In.subVectors(i,t),Pn.subVectors(e,t);const s=Tn.dot(Tn),a=Tn.dot(In),o=Tn.dot(Pn),l=In.dot(In),c=In.dot(Pn),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,Dn)&&(Dn.x>=0&&Dn.y>=0&&Dn.x+Dn.y<=1)}static getInterpolation(e,t,i,n,r,s,a,o){return null===this.getBarycoord(e,t,i,n,Dn)?(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,Dn.x),o.addScaledVector(s,Dn.y),o.addScaledVector(a,Dn.z),o)}static isFrontFacing(e,t,i,n){return Tn.subVectors(i,t),In.subVectors(e,t),Tn.cross(In).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 Tn.subVectors(this.c,this.b),In.subVectors(this.a,this.b),.5*Tn.cross(In).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Nn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Nn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,n,r){return Nn.getInterpolation(e,this.a,this.b,this.c,t,i,n,r)}containsPoint(e){return Nn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Nn.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;Rn.subVectors(n,i),Bn.subVectors(r,i),On.subVectors(e,i);const o=Rn.dot(On),l=Bn.dot(On);if(o<=0&&l<=0)return t.copy(i);Un.subVectors(e,n);const c=Rn.dot(Un),h=Bn.dot(Un);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(Rn,s);Fn.subVectors(e,r);const u=Rn.dot(Fn),p=Bn.dot(Fn);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(Bn,a);const g=c*p-u*h;if(g<=0&&h-c>=0&&u-p>=0)return Ln.subVectors(r,n),a=(h-c)/(h-c+(u-p)),t.copy(n).addScaledVector(Ln,a);const f=1/(g+m+d);return s=m*f,a=d*f,t.copy(i).addScaledVector(Rn,s).addScaledVector(Bn,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const kn={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},jn={h:0,s:0,l:0},zn={h:0,s:0,l:0};function Gn(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 Qn{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=ht){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,si.toWorkingColorSpace(this,t),this}setRGB(e,t,i,n=si.workingColorSpace){return this.r=e,this.g=t,this.b=i,si.toWorkingColorSpace(this,n),this}setHSL(e,t,i,n=si.workingColorSpace){if(e=jt(e,1),t=kt(t,0,1),i=kt(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=Gn(r,n,e+1/3),this.g=Gn(r,n,e),this.b=Gn(r,n,e-1/3)}return si.toWorkingColorSpace(this,n),this}setStyle(e,t=ht){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=ht){const i=kn[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=ai(e.r),this.g=ai(e.g),this.b=ai(e.b),this}copyLinearToSRGB(e){return this.r=oi(e.r),this.g=oi(e.g),this.b=oi(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=ht){return si.fromWorkingColorSpace(Vn.copy(this),e),65536*Math.round(kt(255*Vn.r,0,255))+256*Math.round(kt(255*Vn.g,0,255))+Math.round(kt(255*Vn.b,0,255))}getHexString(e=ht){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=si.workingColorSpace){si.fromWorkingColorSpace(Vn.copy(this),t);const i=Vn.r,n=Vn.g,r=Vn.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=si.workingColorSpace){return si.fromWorkingColorSpace(Vn.copy(this),t),e.r=Vn.r,e.g=Vn.g,e.b=Vn.b,e}getStyle(e=ht){si.fromWorkingColorSpace(Vn.copy(this),e);const t=Vn.r,i=Vn.g,n=Vn.b;return e!==ht?`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(jn),this.setHSL(jn.h+e,jn.s+t,jn.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(jn),e.getHSL(zn);const i=zt(jn.h,zn.h,t),n=zt(jn.s,zn.s,t),r=zt(jn.l,zn.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 Vn=new Qn;Qn.NAMES=kn;let Hn=0;class Wn extends Bt{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Hn++}),this.uuid=Nt(),this.name="",this.type="Material",this.blending=C,this.side=_,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=N,this.blendDst=k,this.blendEquation=I,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Qn(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}onBuild(){}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.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!==N&&(i.blendSrc=this.blendSrc),this.blendDst!==k&&(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=qn({},e.userData),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}function qn(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]=qn(Array.isArray(t[i])?[]:{},t[i]):e[i]=t[i].clone()}return e}class Xn extends Wn{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Qn(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 hn,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 Yn=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 Kn(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=kt(e,-65504,65504),Yn.floatView[0]=e;const t=Yn.uint32View[0],i=t>>23&511;return Yn.baseTable[i]+((8388607&t)>>Yn.shiftTable[i])}function Jn(e){const t=e>>10;return Yn.uint32View[0]=Yn.mantissaTable[Yn.offsetTable[t]+(1023&e)]+Yn.exponentTable[t],Yn.floatView[0]}const Zn={toHalfFloat:Kn,fromHalfFloat:Jn},$n=new wi,er=new Ht;class tr{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=Tt,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=Te,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}get updateRange(){return ei("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++)er.fromBufferAttribute(this,t),er.applyMatrix3(e),this.setXY(t,er.x,er.y);else if(3===this.itemSize)for(let t=0,i=this.count;t<i;t++)$n.fromBufferAttribute(this,t),$n.applyMatrix3(e),this.setXYZ(t,$n.x,$n.y,$n.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)$n.fromBufferAttribute(this,t),$n.applyMatrix4(e),this.setXYZ(t,$n.x,$n.y,$n.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)$n.fromBufferAttribute(this,t),$n.applyNormalMatrix(e),this.setXYZ(t,$n.x,$n.y,$n.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)$n.fromBufferAttribute(this,t),$n.transformDirection(e),this.setXYZ(t,$n.x,$n.y,$n.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=Gt(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=Qt(i,this.array)),this.array[e*this.itemSize+t]=i,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Gt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Qt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Gt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Qt(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=Gt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Qt(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=Gt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Qt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=Qt(t,this.array),i=Qt(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=Qt(t,this.array),i=Qt(i,this.array),n=Qt(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=Qt(t,this.array),i=Qt(i,this.array),n=Qt(n,this.array),r=Qt(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!==Tt&&(e.usage=this.usage),e}}class ir extends tr{constructor(e,t,i){super(new Uint16Array(e),t,i)}}class nr extends tr{constructor(e,t,i){super(new Uint32Array(e),t,i)}}class rr extends tr{constructor(e,t,i){super(new Float32Array(e),t,i)}}let sr=0;const ar=new $i,or=new En,lr=new wi,cr=new Mi,hr=new Mi,dr=new wi;class ur extends Bt{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:sr++}),this.uuid=Nt(),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(Xt(e)?nr:ir)(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 Wt).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 ar.makeRotationFromQuaternion(e),this.applyMatrix4(ar),this}rotateX(e){return ar.makeRotationX(e),this.applyMatrix4(ar),this}rotateY(e){return ar.makeRotationY(e),this.applyMatrix4(ar),this}rotateZ(e){return ar.makeRotationZ(e),this.applyMatrix4(ar),this}translate(e,t,i){return ar.makeTranslation(e,t,i),this.applyMatrix4(ar),this}scale(e,t,i){return ar.makeScale(e,t,i),this.applyMatrix4(ar),this}lookAt(e){return or.lookAt(e),or.updateMatrix(),this.applyMatrix4(or.matrix),this}center(e=void 0){return this.computeBoundingBox(),this.boundingBox.getCenter(lr).negate(),this.translate(lr.x,lr.y,lr.z),e&&e.copy(lr),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 rr(t,3)),this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Mi);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 wi(-1/0,-1/0,-1/0),new wi(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];cr.setFromBufferAttribute(i),this.morphTargetsRelative?(dr.addVectors(this.boundingBox.min,cr.min),this.boundingBox.expandByPoint(dr),dr.addVectors(this.boundingBox.max,cr.max),this.boundingBox.expandByPoint(dr)):(this.boundingBox.expandByPoint(cr.min),this.boundingBox.expandByPoint(cr.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 Vi);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 wi,1/0);if(e){const i=this.boundingSphere.center;if(cr.setFromBufferAttribute(e),t)for(let e=0,i=t.length;e<i;e++){const i=t[e];hr.setFromBufferAttribute(i),this.morphTargetsRelative?(dr.addVectors(cr.min,hr.min),cr.expandByPoint(dr),dr.addVectors(cr.max,hr.max),cr.expandByPoint(dr)):(cr.expandByPoint(hr.min),cr.expandByPoint(hr.max))}cr.getCenter(i);let n=0;for(let t=0,r=e.count;t<r;t++)dr.fromBufferAttribute(e,t),n=Math.max(n,i.distanceToSquared(dr));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++)dr.fromBufferAttribute(s,t),a&&(lr.fromBufferAttribute(e,t),dr.add(lr)),n=Math.max(n,i.distanceToSquared(dr))}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 tr(new Float32Array(4*i.count),4));const s=this.getAttribute("tangent"),a=[],o=[];for(let e=0;e<i.count;e++)a[e]=new wi,o[e]=new wi;const l=new wi,c=new wi,h=new wi,d=new Ht,u=new Ht,p=new Ht,m=new wi,g=new wi;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 wi,v=new wi,_=new wi,b=new wi;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 tr(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 wi,r=new wi,s=new wi,a=new wi,o=new wi,l=new wi,c=new wi,h=new wi;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++)dr.fromBufferAttribute(e,t),dr.normalize(),e.setXYZ(t,dr.x,dr.y,dr.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 tr(s,n,r)}if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new ur,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 pr=new $i,mr=new Zi,gr=new Vi,fr=new wi,Ar=new wi,yr=new wi,vr=new wi,_r=new wi,br=new wi,xr=new Ht,wr=new Ht,Cr=new Ht,Sr=new wi,Mr=new wi,Er=new wi,Tr=new wi,Ir=new wi;class Pr extends En{constructor(e=new ur,t=new Xn){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){br.set(0,0,0);for(let i=0,n=r.length;i<n;i++){const n=a[i],o=r[i];0!==n&&(_r.fromBufferAttribute(o,e),s?br.addScaledVector(_r,n):br.addScaledVector(_r.sub(t),n))}t.add(br)}return t}raycast(e,t){const i=this.geometry,n=this.material,r=this.matrixWorld;void 0!==n&&(null===i.boundingSphere&&i.computeBoundingSphere(),gr.copy(i.boundingSphere),gr.applyMatrix4(r),mr.copy(e.ray).recast(e.near),(!1!==gr.containsPoint(mr.origin)||!(null===mr.intersectSphere(gr,fr)||mr.origin.distanceToSquared(fr)>(e.far-e.near)**2))&&(pr.copy(r).invert(),mr.copy(e.ray).applyMatrix4(pr),(null===i.boundingBox||!1!==mr.intersectsBox(i.boundingBox))&&this._computeIntersections(e,t,mr)))}_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=Dr(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=Dr(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=Dr(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=Dr(this,s,e,i,l,c,h,r,r+1,r+2),n&&(n.faceIndex=Math.floor(r/3),t.push(n))}}}}function Dr(e,t,i,n,r,s,a,o,l,c){e.getVertexPosition(o,Ar),e.getVertexPosition(l,yr),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;Ir.copy(o),Ir.applyMatrix4(e.matrixWorld);const c=i.ray.origin.distanceTo(Ir);return c<i.near||c>i.far?null:{distance:c,point:Ir.clone(),object:e}}(e,t,i,n,Ar,yr,vr,Tr);if(h){r&&(xr.fromBufferAttribute(r,o),wr.fromBufferAttribute(r,l),Cr.fromBufferAttribute(r,c),h.uv=Nn.getInterpolation(Tr,Ar,yr,vr,xr,wr,Cr,new Ht)),s&&(xr.fromBufferAttribute(s,o),wr.fromBufferAttribute(s,l),Cr.fromBufferAttribute(s,c),h.uv1=Nn.getInterpolation(Tr,Ar,yr,vr,xr,wr,Cr,new Ht)),a&&(Sr.fromBufferAttribute(a,o),Mr.fromBufferAttribute(a,l),Er.fromBufferAttribute(a,c),h.normal=Nn.getInterpolation(Tr,Ar,yr,vr,Sr,Mr,Er,new wi),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));const e={a:o,b:l,c:c,normal:new wi,materialIndex:0};Nn.getNormal(Ar,yr,vr,e.normal),h.face=e}return h}class Rr extends ur{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 wi;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 rr(l,3)),this.setAttribute("normal",new rr(c,3)),this.setAttribute("uv",new rr(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Rr(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function Br(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 Lr(e){const t={};for(let i=0;i<e.length;i++){const n=Br(e[i]);for(const e in n)t[e]=n[e]}return t}function Or(e){const t=e.getRenderTarget();return null===t?e.outputColorSpace:!0===t.isXRRenderTarget?t.texture.colorSpace:si.workingColorSpace}const Ur={clone:Br,merge:Lr};class Fr extends Wn{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=Br(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 Nr extends En{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new $i,this.projectionMatrix=new $i,this.projectionMatrixInverse=new $i,this.coordinateSystem=Pt}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 kr=new wi,jr=new Ht,zr=new Ht;class Gr extends Nr{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*Ft*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*Ut*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*Ft*Math.atan(Math.tan(.5*Ut*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){kr.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(kr.x,kr.y).multiplyScalar(-e/kr.z),kr.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(kr.x,kr.y).multiplyScalar(-e/kr.z)}getViewSize(e,t){return this.getViewBounds(e,jr,zr),t.subVectors(zr,jr)}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*Ut*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 Qr=-90;class Vr extends En{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const n=new Gr(Qr,1,e,t);n.layers=this.layers,this.add(n);const r=new Gr(Qr,1,e,t);r.layers=this.layers,this.add(r);const s=new Gr(Qr,1,e,t);s.layers=this.layers,this.add(s);const a=new Gr(Qr,1,e,t);a.layers=this.layers,this.add(a);const o=new Gr(Qr,1,e,t);o.layers=this.layers,this.add(o);const l=new Gr(Qr,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===Pt)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!==Dt)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 Hr extends mi{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 Wr 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 Hr(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 Rr(5,5,5),r=new Fr({name:"CubemapFromEquirect",uniforms:Br(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:b,blending:w});r.uniforms.tEquirect.value=t;const s=new Pr(n,r),a=t.minFilter;return t.minFilter===we&&(t.minFilter=be),new Vr(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 qr=new wi,Xr=new wi,Yr=new Wt;class Kr{constructor(e=new wi(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=qr.subVectors(i,t).cross(Xr.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(qr),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||Yr.getNormalMatrix(e),n=this.coplanarPoint(qr).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 Jr=new Vi,Zr=new wi;class $r{constructor(e=new Kr,t=new Kr,i=new Kr,n=new Kr,r=new Kr,s=new Kr){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=Pt){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===Pt)i[5].setComponents(o+a,d+h,g+m,v+y).normalize();else{if(t!==Dt)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(),Jr.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Jr.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Jr)}intersectsSprite(e){return Jr.center.set(0,0,0),Jr.radius=.7071067811865476,Jr.applyMatrix4(e.matrixWorld),this.intersectsSphere(Jr)}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(Zr.x=n.normal.x>0?e.max.x:e.min.x,Zr.y=n.normal.y>0?e.max.y:e.min.y,Zr.z=n.normal.z>0?e.max.z:e.min.z,n.distanceToPoint(Zr)<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 es(){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 ts(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.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}))}i.isInterleavedBufferAttribute&&(i=i.data);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 is extends ur{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 rr(p,3)),this.setAttribute("normal",new rr(m,3)),this.setAttribute("uv",new rr(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new is(e.width,e.height,e.widthSegments,e.heightSegments)}}const ns={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\tattribute float batchId;\n\tuniform highp sampler2D batchingTexture;\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#endif",batching_vertex:"#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( batchId );\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 )\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 )\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",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}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\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_fragment:"#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif",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\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\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_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\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.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.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.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 ) && defined( MORPHTARGETS_TEXTURE )\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\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t#endif\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\t#ifndef USE_INSTANCING_MORPH\n\t\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\t#endif\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\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.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( 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( 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 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 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 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 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 shadow;\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 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 shadow;\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 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 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 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.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.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.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 OptimizedCineonToneMapping( 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\tfloat startCompression = 0.8 - 0.04;\n\tfloat 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, newPeak * vec3(1, 1, 1), 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.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 ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\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#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_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}"},rs={common:{diffuse:{value:new Qn(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Wt},alphaMap:{value:null},alphaMapTransform:{value:new Wt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Wt}},envmap:{envMap:{value:null},envMapRotation:{value:new Wt},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Wt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Wt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Wt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Wt},normalScale:{value:new Ht(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Wt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Wt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Wt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Wt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Qn(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{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 Qn(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Wt},alphaTest:{value:0},uvTransform:{value:new Wt}},sprite:{diffuse:{value:new Qn(16777215)},opacity:{value:1},center:{value:new Ht(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Wt},alphaMap:{value:null},alphaMapTransform:{value:new Wt},alphaTest:{value:0}}},ss={basic:{uniforms:Lr([rs.common,rs.specularmap,rs.envmap,rs.aomap,rs.lightmap,rs.fog]),vertexShader:ns.meshbasic_vert,fragmentShader:ns.meshbasic_frag},lambert:{uniforms:Lr([rs.common,rs.specularmap,rs.envmap,rs.aomap,rs.lightmap,rs.emissivemap,rs.bumpmap,rs.normalmap,rs.displacementmap,rs.fog,rs.lights,{emissive:{value:new Qn(0)}}]),vertexShader:ns.meshlambert_vert,fragmentShader:ns.meshlambert_frag},phong:{uniforms:Lr([rs.common,rs.specularmap,rs.envmap,rs.aomap,rs.lightmap,rs.emissivemap,rs.bumpmap,rs.normalmap,rs.displacementmap,rs.fog,rs.lights,{emissive:{value:new Qn(0)},specular:{value:new Qn(1118481)},shininess:{value:30}}]),vertexShader:ns.meshphong_vert,fragmentShader:ns.meshphong_frag},standard:{uniforms:Lr([rs.common,rs.envmap,rs.aomap,rs.lightmap,rs.emissivemap,rs.bumpmap,rs.normalmap,rs.displacementmap,rs.roughnessmap,rs.metalnessmap,rs.fog,rs.lights,{emissive:{value:new Qn(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ns.meshphysical_vert,fragmentShader:ns.meshphysical_frag},toon:{uniforms:Lr([rs.common,rs.aomap,rs.lightmap,rs.emissivemap,rs.bumpmap,rs.normalmap,rs.displacementmap,rs.gradientmap,rs.fog,rs.lights,{emissive:{value:new Qn(0)}}]),vertexShader:ns.meshtoon_vert,fragmentShader:ns.meshtoon_frag},matcap:{uniforms:Lr([rs.common,rs.bumpmap,rs.normalmap,rs.displacementmap,rs.fog,{matcap:{value:null}}]),vertexShader:ns.meshmatcap_vert,fragmentShader:ns.meshmatcap_frag},points:{uniforms:Lr([rs.points,rs.fog]),vertexShader:ns.points_vert,fragmentShader:ns.points_frag},dashed:{uniforms:Lr([rs.common,rs.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ns.linedashed_vert,fragmentShader:ns.linedashed_frag},depth:{uniforms:Lr([rs.common,rs.displacementmap]),vertexShader:ns.depth_vert,fragmentShader:ns.depth_frag},normal:{uniforms:Lr([rs.common,rs.bumpmap,rs.normalmap,rs.displacementmap,{opacity:{value:1}}]),vertexShader:ns.meshnormal_vert,fragmentShader:ns.meshnormal_frag},sprite:{uniforms:Lr([rs.sprite,rs.fog]),vertexShader:ns.sprite_vert,fragmentShader:ns.sprite_frag},background:{uniforms:{uvTransform:{value:new Wt},t2D:{value:null},backgroundIntensity:{value:1},backgroundColor:{value:new Qn(16777215)},flipX:{value:!1},flipY:{value:!1}},vertexShader:ns.background_vert,fragmentShader:ns.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 Wt}},vertexShader:ns.backgroundCube_vert,fragmentShader:ns.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ns.cube_vert,fragmentShader:ns.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ns.equirect_vert,fragmentShader:ns.equirect_frag},distanceRGBA:{uniforms:Lr([rs.common,rs.displacementmap,{referencePosition:{value:new wi},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ns.distanceRGBA_vert,fragmentShader:ns.distanceRGBA_frag},shadow:{uniforms:Lr([rs.lights,rs.fog,{color:{value:new Qn(0)},opacity:{value:1}}]),vertexShader:ns.shadow_vert,fragmentShader:ns.shadow_frag}};ss.physical={uniforms:Lr([ss.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Wt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Wt},clearcoatNormalScale:{value:new Ht(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Wt},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Wt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Wt},sheen:{value:0},sheenColor:{value:new Qn(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Wt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Wt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Wt},transmissionSamplerSize:{value:new Ht},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Wt},attenuationDistance:{value:0},attenuationColor:{value:new Qn(0)},specularColor:{value:new Qn(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Wt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Wt},anisotropyVector:{value:new Ht},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Wt}}]),vertexShader:ns.meshphysical_vert,fragmentShader:ns.meshphysical_frag};const as={r:0,b:0,g:0},os=new hn,ls=new $i,cs=new Wt;function hs(e,t,i,n,r,s,a){const o=new Qn(0);let l,c,h=!0===s?0:1,d=null,u=0,p=null;function m(t,i){t.getRGB(as,Or(e)),n.buffers.color.setClear(as.r,as.g,as.b,i,a)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),h=t,m(o,h)},getClearAlpha:function(){return h},setClearAlpha:function(e){h=e,m(o,h)},getPlaneMesh:function(){return l},getBoxMesh:function(){return c},getBoxMesh2:function(){return void 0===c&&(c=new Pr(new Rr(1,1,1),new Fr({name:"BackgroundCubeMaterial",uniforms:Br(ss.backgroundCube.uniforms),vertexShader:ss.backgroundCube.vertexShader,fragmentShader:ss.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(s,g){let f=!1,A=!0===g.isScene?g.background:null;const y=g.isScene&&void 0!==g.backgroundColor?g.backgroundColor:null;"environment"===A&&(A=g.environment);const v=A&&A===g.environment;A&&A.isTexture&&(A=(g.backgroundBlurriness>0?i:t).get(A)),null===A?m(o,h):A&&A.isColor&&(m(A,1),f=!0);const x=e.xr.getEnvironmentBlendMode();if("additive"===x?n.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===x&&n.buffers.color.setClear(0,0,0,0,a),(e.autoClear||f)&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),A&&(A.isCubeTexture||A.mapping===me))void 0===c&&(c=new Pr(new Rr(1,1,1),new Fr({name:"BackgroundCubeMaterial",uniforms:Br(ss.backgroundCube.uniforms),vertexShader:ss.backgroundCube.vertexShader,fragmentShader:ss.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)),os.copy(g.backgroundRotation),os.x*=-1,os.y*=-1,os.z*=-1,A.isCubeTexture&&!1===A.isRenderTargetTexture&&(os.y*=-1,os.z*=-1),c.material.uniforms.envMap.value=A,c.material.uniforms.flipEnvMap.value=A.isCubeTexture&&!1===A.isRenderTargetTexture?-1:1,c.material.uniforms.backgroundBlurriness.value=g.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(ls.makeRotationFromEuler(os)),c.material.toneMapped=si.getTransfer(A.colorSpace)!==ft,v&&(c.material.uniforms.backgroundIntensity.value*=g.environmentIntensity,os.copy(g.environmentRotation),os.x*=-1,os.y*=-1,os.z*=-1,A.isCubeTexture&&!1===A.isRenderTargetTexture&&(os.y*=-1,os.z*=-1),c.material.uniforms.backgroundRotation.value.premultiply(cs.setFromMatrix4(ls.makeRotationFromEuler(os)))),(d!==A||u!==A.version||p!==e.toneMapping)&&(c.material.needsUpdate=!0,d=A,u=A.version,p=e.toneMapping),c.layers.enableAll(),s.unshift(c,c.geometry,c.material,0,0,null);else if(A&&A.isTexture||!A&&y){void 0===l&&(l=new Pr(new is(2,2),new Fr({name:"BackgroundMaterial",uniforms:Br(ss.background.uniforms),vertexShader:ss.background.vertexShader,fragmentShader:ss.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(y||16777215),l.material.uniforms.t2D.value=A,l.material.uniforms.backgroundIntensity.value=g.backgroundIntensity,A?(l.material.toneMapped=si.getTransfer(A.colorSpace)!==ft,l.material.uniforms.flipX.value=A.userData.flipX||!1,l.material.uniforms.flipY.value=A.userData.flipY||!1,!0===A.matrixAutoUpdate&&A.updateMatrix(),l.material.uniforms.uvTransform.value.copy(A.matrix),l.material.defines.HAS_TEXTURE="1"):l.material.defines.HAS_TEXTURE&&delete l.material.defines.HAS_TEXTURE;const t=A?A.version:-1;(d!==A||u!==t||p!==e.toneMapping)&&(l.material.needsUpdate=!0,d=A,u=t,p=e.toneMapping),l.layers.enableAll(),s.unshift(l,l.geometry,l.material,0,0,null)}}}}function ds(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===Me;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 us(e,t,i){let n;this.setMode=function(e){n=e},this.render=function(t,r){e.drawArrays(n,t,r),i.update(r,n,1)},this.renderInstances=function(t,r,s){0!==s&&(e.drawArraysInstanced(n,t,r,s),i.update(r,n,s))},this.renderMultiDraw=function(e,r,s){if(0===s)return;const a=t.get("WEBGL_multi_draw");if(null===a)for(let t=0;t<s;t++)this.render(e[t],r[t]);else{a.multiDrawArraysWEBGL(n,e,0,r,0,s);let t=0;for(let e=0;e<s;e++)t+=r[e];i.update(t,n,1)}}}function ps(e,t,i){let n;function r(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 s=void 0!==i.precision?i.precision:"highp";const a=r(s);a!==s&&(console.warn("THREE.WebGLRenderer:",s,"not supported, using",a,"instead."),s=a);const o=!0===i.logarithmicDepthBuffer,l=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),c=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==n)return n;if(!0===t.has("EXT_texture_filter_anisotropic")){const i=t.get("EXT_texture_filter_anisotropic");n=e.getParameter(i.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else n=0;return n},getMaxPrecision:r,precision:s,logarithmicDepthBuffer:o,maxTextures:l,maxVertexTextures:c,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:c>0,maxSamples:e.getParameter(e.MAX_SAMPLES)}}function ms(e){const t=this;let i=null,n=0,r=!1,s=!1;const a=new Kr,o=new Wt,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 gs(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 Wr(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 fs extends Nr{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 As=[.125,.215,.35,.446,.526,.582],ys=20,vs=new fs,_s=new Qn;let bs=null,xs=0,ws=0,Cs=!1;const Ss=(1+Math.sqrt(5))/2,Ms=1/Ss,Es=[new wi(1,1,1),new wi(-1,1,1),new wi(1,1,-1),new wi(-1,1,-1),new wi(0,Ss,Ms),new wi(0,Ss,-Ms),new wi(Ms,0,Ss),new wi(-Ms,0,Ss),new wi(Ss,Ms,0),new wi(-Ss,Ms,0)];class Ts{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){bs=this._renderer.getRenderTarget(),xs=this._renderer.getActiveCubeFace(),ws=this._renderer.getActiveMipmapLevel(),Cs=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=Rs(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Ds(),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(bs,xs,ws),this._renderer.xr.enabled=Cs,e.scissorTest=!1,Ps(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),bs=this._renderer.getRenderTarget(),xs=this._renderer.getActiveCubeFace(),ws=this._renderer.getActiveMipmapLevel(),Cs=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:Ie,format:Be,colorSpace:dt,depthBuffer:!1},n=Is(e,t,i);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=Is(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+As.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=As[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 ur;_.setAttribute("position",new tr(A,m)),_.setAttribute("uv",new tr(y,g)),_.setAttribute("faceIndex",new tr(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(ys),r=new wi(0,1,0);return new Fr({name:"SphericalGaussianBlur",defines:{n:ys,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:Bs(),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 Pr(this._lodPlanes[0],e);this._renderer.compile(t,vs)}_sceneToCubeUV(e,t,i,n){const r=new Gr(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(_s),o.toneMapping=0,o.autoClear=!1;const h=new Xn({name:"PMREM.Background",side:b,depthWrite:!1,depthTest:!1}),d=new Pr(new Rr,h);let u=!1;const p=e.background;p?p.isColor&&(h.color.copy(p),e.background=null,u=!0):(h.color.copy(_s),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;Ps(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=Rs()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Ds());const r=n?this._cubemapMaterial:this._equirectMaterial,s=new Pr(this._lodPlanes[0],r);r.uniforms.envMap.value=e;const a=this._cubeSize;Ps(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;for(let t=1;t<this._lodPlanes.length;t++){const i=Math.sqrt(this._sigmas[t]*this._sigmas[t]-this._sigmas[t-1]*this._sigmas[t-1]),n=Es[(t-1)%Es.length];this._blur(e,t-1,t,i,n)}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 Pr(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):ys;m>ys&&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<ys;++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];Ps(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 Is(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 Ps(e,t,i,n,r){e.viewport.set(t,i,n,r),e.scissor.set(t,i,n,r)}function Ds(){return new Fr({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Bs(),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 Rs(){return new Fr({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Bs(),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 Bs(){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 Ls(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 Ts(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 Ts(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 Os(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&&console.warn("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function Us(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(Xt(i)?nr:ir)(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 Fs(e,t,i){let n,r,s;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=function(t,a,o){0!==o&&(e.drawElementsInstanced(n,a,r,t*s,o),i.update(a,n,o))},this.renderMultiDraw=function(e,a,o){if(0===o)return;const l=t.get("WEBGL_multi_draw");if(null===l)for(let t=0;t<o;t++)this.render(e[t]/s,a[t]);else{l.multiDrawElementsWEBGL(n,a,0,r,e,0,o);let t=0;for(let e=0;e<o;e++)t+=a[e];i.update(t,n,1)}}}function Ns(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 ks(e,t,i){const n=new WeakMap,r=new Ai;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 _i(f,m,g,h);A.type=Te,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 Ht(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 js(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 zs extends mi{constructor(e,t,i,n,r,s,a,o,l,c){if((c=void 0!==c?c:Le)!==Le&&c!==Oe)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===i&&c===Le&&(i=Ee),void 0===i&&c===Oe&&(i=Re),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 Gs=new mi,Qs=new zs(1,1);Qs.compareFunction=515;const Vs=new _i,Hs=new bi,Ws=new Hr,qs=[],Xs=[],Ys=new Float32Array(16),Ks=new Float32Array(9),Js=new Float32Array(4);function Zs(e,t,i){const n=e[0];if(n<=0||n>0)return e;const r=t*i;let s=qs[r];if(void 0===s&&(s=new Float32Array(r),qs[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 $s(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 ea(e,t){for(let i=0,n=t.length;i<n;i++)e[i]=t[i]}function ta(e,t){let i=Xs[t];void 0===i&&(i=new Int32Array(t),Xs[t]=i);for(let n=0;n!==t;++n)i[n]=e.allocateTextureUnit();return i}function ia(e,t){const i=this.cache;i[0]!==t&&(e.uniform1f(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.uniform2f(this.addr,t.x,t.y),i[0]=t.x,i[1]=t.y);else{if($s(i,t))return;e.uniform2fv(this.addr,t),ea(i,t)}}function ra(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($s(i,t))return;e.uniform3fv(this.addr,t),ea(i,t)}}function sa(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($s(i,t))return;e.uniform4fv(this.addr,t),ea(i,t)}}function aa(e,t){const i=this.cache,n=t.elements;if(void 0===n){if($s(i,t))return;e.uniformMatrix2fv(this.addr,!1,t),ea(i,t)}else{if($s(i,n))return;Js.set(n),e.uniformMatrix2fv(this.addr,!1,Js),ea(i,n)}}function oa(e,t){const i=this.cache,n=t.elements;if(void 0===n){if($s(i,t))return;e.uniformMatrix3fv(this.addr,!1,t),ea(i,t)}else{if($s(i,n))return;Ks.set(n),e.uniformMatrix3fv(this.addr,!1,Ks),ea(i,n)}}function la(e,t){const i=this.cache,n=t.elements;if(void 0===n){if($s(i,t))return;e.uniformMatrix4fv(this.addr,!1,t),ea(i,t)}else{if($s(i,n))return;Ys.set(n),e.uniformMatrix4fv(this.addr,!1,Ys),ea(i,n)}}function ca(e,t){const i=this.cache;i[0]!==t&&(e.uniform1i(this.addr,t),i[0]=t)}function ha(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($s(i,t))return;e.uniform2iv(this.addr,t),ea(i,t)}}function da(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($s(i,t))return;e.uniform3iv(this.addr,t),ea(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||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($s(i,t))return;e.uniform4iv(this.addr,t),ea(i,t)}}function pa(e,t){const i=this.cache;i[0]!==t&&(e.uniform1ui(this.addr,t),i[0]=t)}function ma(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($s(i,t))return;e.uniform2uiv(this.addr,t),ea(i,t)}}function ga(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($s(i,t))return;e.uniform3uiv(this.addr,t),ea(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.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($s(i,t))return;e.uniform4uiv(this.addr,t),ea(i,t)}}function Aa(e,t,i){const n=this.cache,r=i.allocateTextureUnit();n[0]!==r&&(e.uniform1i(this.addr,r),n[0]=r);const s=this.type===e.SAMPLER_2D_SHADOW?Qs:Gs;i.setTexture2D(t||s,r)}function ya(e,t,i){const n=this.cache,r=i.allocateTextureUnit();n[0]!==r&&(e.uniform1i(this.addr,r),n[0]=r),i.setTexture3D(t||Hs,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||Ws,r)}function _a(e,t,i){const n=this.cache,r=i.allocateTextureUnit();n[0]!==r&&(e.uniform1i(this.addr,r),n[0]=r),i.setTexture2DArray(t||Vs,r)}function ba(e,t){e.uniform1fv(this.addr,t)}function xa(e,t){const i=Zs(t,this.size,2);e.uniform2fv(this.addr,i)}function wa(e,t){const i=Zs(t,this.size,3);e.uniform3fv(this.addr,i)}function Ca(e,t){const i=Zs(t,this.size,4);e.uniform4fv(this.addr,i)}function Sa(e,t){const i=Zs(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,i)}function Ma(e,t){const i=Zs(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,i)}function Ea(e,t){const i=Zs(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,i)}function Ta(e,t){e.uniform1iv(this.addr,t)}function Ia(e,t){e.uniform2iv(this.addr,t)}function Pa(e,t){e.uniform3iv(this.addr,t)}function Da(e,t){e.uniform4iv(this.addr,t)}function Ra(e,t){e.uniform1uiv(this.addr,t)}function Ba(e,t){e.uniform2uiv(this.addr,t)}function La(e,t){e.uniform3uiv(this.addr,t)}function Oa(e,t){e.uniform4uiv(this.addr,t)}function Ua(e,t,i){const n=this.cache,r=t.length,s=ta(i,r);$s(n,s)||(e.uniform1iv(this.addr,s),ea(n,s));for(let e=0;e!==r;++e)i.setTexture2D(t[e]||Gs,s[e])}function Fa(e,t,i){const n=this.cache,r=t.length,s=ta(i,r);$s(n,s)||(e.uniform1iv(this.addr,s),ea(n,s));for(let e=0;e!==r;++e)i.setTexture3D(t[e]||Hs,s[e])}function Na(e,t,i){const n=this.cache,r=t.length,s=ta(i,r);$s(n,s)||(e.uniform1iv(this.addr,s),ea(n,s));for(let e=0;e!==r;++e)i.setTextureCube(t[e]||Ws,s[e])}function ka(e,t,i){const n=this.cache,r=t.length,s=ta(i,r);$s(n,s)||(e.uniform1iv(this.addr,s),ea(n,s));for(let e=0;e!==r;++e)i.setTexture2DArray(t[e]||Vs,s[e])}class ja{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 ia;case 35664:return na;case 35665:return ra;case 35666:return sa;case 35674:return aa;case 35675:return oa;case 35676:return la;case 5124:case 35670:return ca;case 35667:case 35671:return ha;case 35668:case 35672:return da;case 35669:case 35673:return ua;case 5125:return pa;case 36294:return ma;case 36295:return ga;case 36296:return fa;case 35678:case 36198:case 36298:case 36306:case 35682:return Aa;case 35679:case 36299:case 36307:return ya;case 35680:case 36300:case 36308:case 36293:return va;case 36289:case 36303:case 36311:case 36292:return _a}}(t.type)}}class za{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 ba;case 35664:return xa;case 35665:return wa;case 35666:return Ca;case 35674:return Sa;case 35675:return Ma;case 35676:return Ea;case 5124:case 35670:return Ta;case 35667:case 35671:return Ia;case 35668:case 35672:return Pa;case 35669:case 35673:return Da;case 5125:return Ra;case 36294:return Ba;case 36295:return La;case 36296:return Oa;case 35678:case 36198:case 36298:case 36306:case 35682:return Ua;case 35679:case 36299:case 36307:return Fa;case 35680:case 36300:case 36308:case 36293:return Na;case 36289:case 36303:case 36311:case 36292:return ka}}(t.type)}}class Ga{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 Qa=/(\w+)(\])?(\[|\.)?/g;function Va(e,t){e.seq.push(t),e.map[t.id]=t}function Ha(e,t,i){const n=e.name,r=n.length;for(Qa.lastIndex=0;;){const s=Qa.exec(n),a=Qa.lastIndex;let o=s[1];const l="]"===s[2],c=s[3];if(l&&(o|=0),void 0===c||"["===c&&a+2===r){Va(i,void 0===c?new ja(o,e,t):new za(o,e,t));break}{let e=i.map[o];void 0===e&&(e=new Ga(o),Va(i,e)),i=e}}}class Wa{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);Ha(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 qa(e,t,i){const n=e.createShader(t);return e.shaderSource(n,i),e.compileShader(n),n}let Xa=0;function Ya(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 Ka(e,t){let i;switch(t){case dt:i="";break;case ht:i="sRGBToLinear";break;case mt:i="RGBM16ToLinear";break;default:console.warn("THREE.WebGLProgram: Unsupported color space:",t),i=""}return`vec4 ${e}( vec4 value ) { return ${i} ( value ); }`}function Ja(e,t){const i=function(e){const t=si.getPrimaries(si.workingColorSpace),i=e===ct||e===mt?null:si.getPrimaries(e);let n;switch(t!==i&&i?t===yt&&i===At?n="LinearDisplayP3ToLinearSRGB":t===At&&i===yt&&(n="LinearSRGBToLinearDisplayP3"):n="",e){case ct:return["",""];case dt:case pt:return[n,"LinearTransferOETF"];case ht:case ut:return[n,"sRGBTransferOETF"];case mt: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 Za(e,t){let i;switch(t){case ne:i="Linear";break;case re:i="Reinhard";break;case se:i="OptimizedCineon";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 ); }"}function $a(e){return""!==e}function eo(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 to(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const io=/^[ \t]*#include +<([\w\d./]+)>/gm;function no(e){return e.replace(io,so)}const ro=new Map([["encodings_fragment","colorspace_fragment"],["encodings_pars_fragment","colorspace_pars_fragment"],["output_fragment","opaque_fragment"]]);function so(e,t){let i=ns[t];if(void 0===i){const e=ro.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");i=ns[e],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return no(i)}const ao=/#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(ao,lo)}function lo(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 co(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 ho(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";e.envMap&&e.envMapMode===de&&(t="ENVMAP_MODE_REFRACTION");return 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($a).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($a).join("\n"),f.length>0&&(f+="\n"),A=["#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,m].filter($a).join("\n"),A.length>0&&(A+="\n")):(f=[co(i),"#define SHADER_TYPE "+i.shaderType,"#define SHADER_NAME "+i.shaderName,m,i.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",i.batching?"#define USE_BATCHING":"",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":"",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.useLegacyLights?"#define LEGACY_LIGHTS":"",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","#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter($a).join("\n"),A=[co(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.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?"#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.useLegacyLights?"#define LEGACY_LIGHTS":"",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?ns.tonemapping_pars_fragment:"",0!==i.toneMapping?Za("toneMapping",i.toneMapping):"",i.dithering?"#define DITHERING":"",i.opaque?"#define OPAQUE":"",ns.colorspace_pars_fragment,Ja("linearToOutputTexel",i.outputColorSpace),i.transmissionSamplerMapEncoding?Ka("transmissionSamplerMapTexelToLinear",i.transmissionSamplerMapEncoding):"",i.useDepthPacking?"#define DEPTH_PACKING "+i.depthPacking:"","\n"].filter($a).join("\n")),a=no(a),a=eo(a,i),a=to(a,i),o=no(o),o=eo(o,i),o=to(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===It?"":"layout(location = 0) out highp vec4 pc_fragColor;",i.glslVersion===It?"":"#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=qa(r,r.VERTEX_SHADER,v),x=qa(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=Ya(r,b,"vertex"),n=Ya(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 Wa(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=Xa++,this.cacheKey=t,this.usedTimes=1,this.program=g,this.vertexShader=b,this.fragmentShader=x,this}let uo=0;class po{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 mo(e),t.set(e,i)),i}}class mo{constructor(e){this.id=uo++,this.code=e,this.usedTimes=0}}function go(e,t,i,n,r,s,a){const o=new dn,l=new po,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=ss[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,N=!!s.map,k=!!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.iridescence>0,Z=s.sheen>0,$=s.transmission>0,ee=Y&&!!s.anisotropyMap,te=K&&!!s.clearcoatMap,ie=K&&!!s.clearcoatNormalMap,ne=K&&!!s.clearcoatRoughnessMap,re=J&&!!s.iridescenceMap,se=J&&!!s.iridescenceThicknessMap,ae=Z&&!!s.sheenColorMap,oe=Z&&!!s.sheenRoughnessMap,le=!!s.specularMap,ce=!!s.specularColorMap,he=!!s.specularIntensityMap,de=$&&!!s.transmissionMap,ue=$&&!!s.thicknessMap,pe=!!s.gradientMap,ge=!!s.alphaMap,fe=s.alphaTest>0,Ae=!!s.alphaHash,ye=!!s.extensions;let ve=0;s.toneMapped&&(null===L||!0===L.isXRRenderTarget)&&(ve=e.toneMapping);const _e={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,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!==ht?L.texture.colorSpace:dt,alphaToCoverage:!!s.alphaToCoverage,map:N,matcap:k,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===lt,normalMapTangentSpace:V&&s.normalMapType===ot,metalnessMap:q,roughnessMap:X,anisotropy:Y,anisotropyMap:ee,clearcoat:K,clearcoatMap:te,clearcoatNormalMap:ie,clearcoatRoughnessMap:ne,iridescence:J,iridescenceMap:re,iridescenceThicknessMap:se,sheen:Z,sheenColorMap:ae,sheenRoughnessMap:oe,specularMap:le,specularColorMap:ce,specularIntensityMap:he,transmission:$,transmissionMap:de,thicknessMap:ue,transmissionSamplerMapEncoding:O&&O.texture.colorSpace||dt,gradientMap:pe,opaque:!1===s.transparent&&s.blending===C&&!1===s.alphaToCoverage&&!(s.transmission>0),alphaMap:ge,alphaTest:fe,alphaHash:Ae,combine:s.combine,mapUv:N&&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:ee&&g(s.anisotropyMap.channel),clearcoatMapUv:te&&g(s.clearcoatMap.channel),clearcoatNormalMapUv:ie&&g(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ne&&g(s.clearcoatRoughnessMap.channel),iridescenceMapUv:re&&g(s.iridescenceMap.channel),iridescenceThicknessMapUv:se&&g(s.iridescenceThicknessMap.channel),sheenColorMapUv:ae&&g(s.sheenColorMap.channel),sheenRoughnessMapUv:oe&&g(s.sheenRoughnessMap.channel),specularMapUv:le&&g(s.specularMap.channel),specularColorMapUv:ce&&g(s.specularColorMap.channel),specularIntensityMapUv:he&&g(s.specularIntensityMap.channel),transmissionMapUv:de&&g(s.transmissionMap.channel),thicknessMapUv:ue&&g(s.thicknessMap.channel),alphaMapUv:ge&&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&&(N||ge),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:ve,useLegacyLights:e._useLegacyLights,decodeVideoTexture:N&&!0===s.map.isVideoTexture&&si.getTransfer(s.map.colorSpace)===ft,premultipliedAlpha:s.premultipliedAlpha,doubleSided:s.side===x,flipSided:s.side===b,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionClipCullDistance:ye&&!0===s.extensions.clipCullDistance&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:ye&&!0===s.extensions.multiDraw&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return _e.vertexUv1s=c.has(1),_e.vertexUv2s=c.has(2),_e.vertexUv3s=c.has(3),c.clear(),_e},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),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.useLegacyLights&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.alphaToCoverage&&o.enable(20),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=ss[t];i=Ur.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 ho(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 fo(){let e=new WeakMap;return{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 Ao(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 yo(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 vo(){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||Ao),n.length>1&&n.sort(t||yo),r.length>1&&r.sort(t||yo)}}}function _o(){let e=new WeakMap;return{get:function(t,i){const n=e.get(t);let r;return void 0===n?(r=new vo,e.set(t,[r])):i>=n.length?(r=new vo,n.push(r)):r=n[i],r},dispose:function(){e=new WeakMap}}}function bo(){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 wi,color:new Qn};break;case"SpotLight":i={position:new wi,direction:new wi,color:new Qn,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":i={position:new wi,color:new Qn,distance:0,decay:0};break;case"HemisphereLight":i={direction:new wi,skyColor:new Qn,groundColor:new Qn};break;case"RectAreaLight":i={color:new Qn,position:new wi,halfWidth:new wi,halfHeight:new wi}}return e[t.id]=i,i}}}let xo=0;function wo(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Co(e){const t=new bo,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={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ht};break;case"PointLight":i={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ht,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 wi);const r=new wi,s=new $i,a=new $i;return{setup:function(r,s){let a=0,o=0,l=0;for(let e=0;e<9;e++)n.probe[e].set(0,0,0);let c=0,h=0,d=0,u=0,p=0,m=0,g=0,f=0,A=0,y=0,v=0;r.sort(wo);const _=!0===s?Math.PI:1;for(let e=0,s=r.length;e<s;e++){const s=r[e],b=s.color,x=s.intensity,w=s.distance,C=s.shadow&&s.shadow.map?s.shadow.map.texture:null;if(s.isAmbientLight)a+=b.r*x*_,o+=b.g*x*_,l+=b.b*x*_;else if(s.isLightProbe){for(let e=0;e<9;e++)n.probe[e].addScaledVector(s.sh.coefficients[e],x);v++}else if(s.isDirectionalLight){const e=t.get(s);if(e.color.copy(s.color).multiplyScalar(s.intensity*_),s.castShadow){const e=s.shadow,t=i.get(s);t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,n.directionalShadow[c]=t,n.directionalShadowMap[c]=C,n.directionalShadowMatrix[c]=s.shadow.matrix,m++}n.directional[c]=e,c++}else if(s.isSpotLight){const e=t.get(s);e.position.setFromMatrixPosition(s.matrixWorld),e.color.copy(b).multiplyScalar(x*_),e.distance=w,e.coneCos=Math.cos(s.angle),e.penumbraCos=Math.cos(s.angle*(1-s.penumbra)),e.decay=s.decay,n.spot[d]=e;const r=s.shadow;if(s.map&&(n.spotLightMap[A]=s.map,A++,r.updateMatrices(s),s.castShadow&&y++),n.spotLightMatrix[d]=r.matrix,s.castShadow){const e=i.get(s);e.shadowBias=r.bias,e.shadowNormalBias=r.normalBias,e.shadowRadius=r.radius,e.shadowMapSize=r.mapSize,n.spotShadow[d]=e,n.spotShadowMap[d]=C,f++}d++}else if(s.isRectAreaLight){const e=t.get(s);e.color.copy(b).multiplyScalar(x),e.halfWidth.set(.5*s.width,0,0),e.halfHeight.set(0,.5*s.height,0),n.rectArea[u]=e,u++}else if(s.isPointLight){const e=t.get(s);if(e.color.copy(s.color).multiplyScalar(s.intensity*_),e.distance=s.distance,e.decay=s.decay,s.castShadow){const e=s.shadow,t=i.get(s);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[h]=t,n.pointShadowMap[h]=C,n.pointShadowMatrix[h]=s.shadow.matrix,g++}n.point[h]=e,h++}else if(s.isHemisphereLight){const e=t.get(s);e.skyColor.copy(s.color).multiplyScalar(x*_),e.groundColor.copy(s.groundColor).multiplyScalar(x*_),n.hemi[p]=e,p++}}u>0&&(!0===e.has("OES_texture_float_linear")?(n.rectAreaLTC1=rs.LTC_FLOAT_1,n.rectAreaLTC2=rs.LTC_FLOAT_2):(n.rectAreaLTC1=rs.LTC_HALF_1,n.rectAreaLTC2=rs.LTC_HALF_2)),n.ambient[0]=a,n.ambient[1]=o,n.ambient[2]=l;const b=n.hash;(b.directionalLength!==c||b.pointLength!==h||b.spotLength!==d||b.rectAreaLength!==u||b.hemiLength!==p||b.numDirectionalShadows!==m||b.numPointShadows!==g||b.numSpotShadows!==f||b.numSpotMaps!==A||b.numLightProbes!==v)&&(n.directional.length=c,n.spot.length=d,n.rectArea.length=u,n.point.length=h,n.hemi.length=p,n.directionalShadow.length=m,n.directionalShadowMap.length=m,n.pointShadow.length=g,n.pointShadowMap.length=g,n.spotShadow.length=f,n.spotShadowMap.length=f,n.directionalShadowMatrix.length=m,n.pointShadowMatrix.length=g,n.spotLightMatrix.length=f+A-y,n.spotLightMap.length=A,n.numSpotLightShadowsWithMaps=y,n.numLightProbes=v,b.directionalLength=c,b.pointLength=h,b.spotLength=d,b.rectAreaLength=u,b.hemiLength=p,b.numDirectionalShadows=m,b.numPointShadows=g,b.numSpotShadows=f,b.numSpotMaps=A,b.numLightProbes=v,n.version=xo++)},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 So(e){const t=new Co(e),i=[],n=[];return{init:function(){i.length=0,n.length=0},state:{lightsArray:i,shadowsArray:n,lights:t,transmissionRenderTarget:null},setupLights:function(e){t.setup(i,e)},setupLightsView:function(e){t.setupView(i,e)},pushLight:function(e){i.push(e)},pushShadow:function(e){n.push(e)}}}function Mo(e){let t=new WeakMap;return{get:function(i,n=0){const r=t.get(i);let s;return void 0===r?(s=new So(e),t.set(i,[s])):n>=r.length?(s=new So(e),r.push(s)):s=r[n],s},dispose:function(){t=new WeakMap}}}class Eo extends Wn{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=st,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 To extends Wn{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 Io(e,t,i){let n=new $r;const r=new Ht,s=new Ht,a=new Ai,o=new Eo({depthPacking:at}),l=new To,c={},h=i.maxTextureSize,d={[_]:b,[b]:_,[x]:x},u=new Fr({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Ht},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 ur;m.setAttribute("position",new tr(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new Pr(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 Po(e){const t=new function(){let t=!1;const i=new Ai;let n=null;const r=new Ai(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 Qn(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 Ai).fromArray(ge),ye=(new Ai).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,[N]:e.SRC_ALPHA,[V]:e.SRC_ALPHA_SATURATE,[G]:e.DST_COLOR,[j]:e.DST_ALPHA,[F]:e.ONE_MINUS_SRC_COLOR,[k]: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 Qn(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 Do(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 Ht,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):Jt("canvas")}function g(e,t,i){let n=1;const r=F(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?gt:si.getTransfer(s);r===e.FLOAT&&(o=e.RGBA32F),r===e.HALF_FLOAT&&(o=e.RGBA16F),r===e.UNSIGNED_BYTE&&(o=t===ft?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(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 _(e){const t=e.target;t.removeEventListener("dispose",_),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&&x(e),0===Object.keys(r).length&&u.delete(i)}n.remove(e)}(t),t.isVideoTexture&&h.delete(t)}function b(t){const i=t.target;i.removeEventListener("dispose",b),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 x(t){const i=n.get(t);e.deleteTexture(i.__webglTexture);const r=t.source;delete u.get(r)[i.__cacheKey],a.memory.textures--}let w=0;function C(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 P(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 S={[ge]:e.REPEAT,[fe]:e.CLAMP_TO_EDGE,[Ae]:e.MIRRORED_REPEAT},M={[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},E={[_t]:e.NEVER,[Et]:e.ALWAYS,[bt]:e.LESS,[wt]:e.LEQUAL,[xt]:e.EQUAL,[Mt]:e.GEQUAL,[Ct]:e.GREATER,[St]:e.NOTEQUAL};function T(i,s){if(s.type===Te&&!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,S[s.wrapS]),e.texParameteri(i,e.TEXTURE_WRAP_T,S[s.wrapT]),(i===e.TEXTURE_3D||i===e.TEXTURE_2D_ARRAY)&&e.texParameteri(i,e.TEXTURE_WRAP_R,S[s.wrapR]),e.texParameteri(i,e.TEXTURE_MAG_FILTER,M[s.magFilter]),e.texParameteri(i,e.TEXTURE_MIN_FILTER,M[s.minFilter]),s.compareFunction&&(e.texParameteri(i,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(i,e.TEXTURE_COMPARE_FUNC,E[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(s.magFilter===ye||s.minFilter!==_e&&s.minFilter!==we||s.type===Te&&!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 I(t,i){let n=!1;void 0===t.__webglInit&&(t.__webglInit=!0,i.addEventListener("dispose",_));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&&x(i)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return n}function P(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=I(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=si.getPrimaries(si.workingColorSpace),n=a.colorSpace===ct||a.colorSpace===mt?null:si.getPrimaries(a.colorSpace),u=a.colorSpace===ct||a.colorSpace===mt||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=U(a,p);const m=s.convert(a.format,a.colorSpace),_=s.convert(a.type);let b,x=y(a.internalFormat,m,_,a.colorSpace,a.isVideoTexture);T(l,a);const w=a.mipmaps,C=!0!==a.isVideoTexture&&x!==Ve,S=void 0===d.__version||!0===c,M=h.dataReady,E=v(a,p);if(a.isDepthTexture)x=e.DEPTH_COMPONENT16,a.type===Te?x=e.DEPTH_COMPONENT32F:a.type===Ee?x=e.DEPTH_COMPONENT24:a.type===Re&&(x=e.DEPTH24_STENCIL8),S&&(C?i.texStorage2D(e.TEXTURE_2D,1,x,p.width,p.height):i.texImage2D(e.TEXTURE_2D,0,x,p.width,p.height,0,m,_,null));else if(a.isDataTexture)if(w.length>0){C&&S&&i.texStorage2D(e.TEXTURE_2D,E,x,w[0].width,w[0].height);for(let t=0,n=w.length;t<n;t++)b=w[t],C?M&&i.texSubImage2D(e.TEXTURE_2D,t,0,0,b.width,b.height,m,_,b.data):i.texImage2D(e.TEXTURE_2D,t,x,b.width,b.height,0,m,_,b.data);a.generateMipmaps=!1}else C?(S&&i.texStorage2D(e.TEXTURE_2D,E,x,p.width,p.height),M&&i.texSubImage2D(e.TEXTURE_2D,0,0,0,p.width,p.height,m,_,p.data)):i.texImage2D(e.TEXTURE_2D,0,x,p.width,p.height,0,m,_,p.data);else if(a.isCompressedTexture)if(a.isCompressedArrayTexture){C&&S&&i.texStorage3D(e.TEXTURE_2D_ARRAY,E,x,w[0].width,w[0].height,p.depth);for(let t=0,n=w.length;t<n;t++)b=w[t],a.format!==Be?null!==m?C?M&&i.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,b.width,b.height,p.depth,m,b.data,0,0):i.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,x,b.width,b.height,p.depth,0,b.data,0,0):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):C?M&&i.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,b.width,b.height,p.depth,m,_,b.data):i.texImage3D(e.TEXTURE_2D_ARRAY,t,x,b.width,b.height,p.depth,0,m,_,b.data)}else{C&&S&&i.texStorage2D(e.TEXTURE_2D,E,x,w[0].width,w[0].height);for(let t=0,n=w.length;t<n;t++)b=w[t],a.format!==Be?null!==m?C?M&&i.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,b.width,b.height,m,b.data):i.compressedTexImage2D(e.TEXTURE_2D,t,x,b.width,b.height,0,b.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):C?M&&i.texSubImage2D(e.TEXTURE_2D,t,0,0,b.width,b.height,m,_,b.data):i.texImage2D(e.TEXTURE_2D,t,x,b.width,b.height,0,m,_,b.data)}else if(a.isDataArrayTexture)C?(S&&i.texStorage3D(e.TEXTURE_2D_ARRAY,E,x,p.width,p.height,p.depth),M&&i.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,m,_,p.data)):i.texImage3D(e.TEXTURE_2D_ARRAY,0,x,p.width,p.height,p.depth,0,m,_,p.data);else if(a.isData3DTexture)C?(S&&i.texStorage3D(e.TEXTURE_3D,E,x,p.width,p.height,p.depth),M&&i.texSubImage3D(e.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,m,_,p.data)):i.texImage3D(e.TEXTURE_3D,0,x,p.width,p.height,p.depth,0,m,_,p.data);else if(a.isFramebufferTexture){if(S)if(C)i.texStorage2D(e.TEXTURE_2D,E,x,p.width,p.height);else{let t=p.width,n=p.height;for(let r=0;r<E;r++)i.texImage2D(e.TEXTURE_2D,r,x,t,n,0,m,_,null),t>>=1,n>>=1}}else if(w.length>0){if(C&&S){const t=F(w[0]);i.texStorage2D(e.TEXTURE_2D,E,x,t.width,t.height)}for(let t=0,n=w.length;t<n;t++)b=w[t],C?M&&i.texSubImage2D(e.TEXTURE_2D,t,0,0,m,_,b):i.texImage2D(e.TEXTURE_2D,t,x,m,_,b);a.generateMipmaps=!1}else if(C){if(S){const t=F(p);i.texStorage2D(e.TEXTURE_2D,E,x,t.width,t.height)}M&&i.texSubImage2D(e.TEXTURE_2D,0,0,0,m,_,p)}else i.texImage2D(e.TEXTURE_2D,0,x,m,_,p);f(a)&&A(l),d.__version=h.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}function D(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),O(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,c,n.get(a).__webglTexture,0,L(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 R(t,i,n){if(e.bindRenderbuffer(e.RENDERBUFFER,t),i.depthBuffer&&!i.stencilBuffer){let r=e.DEPTH_COMPONENT24;if(n||O(i)){const t=i.depthTexture;t&&t.isDepthTexture&&(t.type===Te?r=e.DEPTH_COMPONENT32F:t.type===Ee&&(r=e.DEPTH_COMPONENT24));const n=L(i);O(i)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,n,r,i.width,i.height):e.renderbufferStorageMultisample(e.RENDERBUFFER,n,r,i.width,i.height)}else e.renderbufferStorage(e.RENDERBUFFER,r,i.width,i.height);e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t)}else if(i.depthBuffer&&i.stencilBuffer){const r=L(i);n&&!1===O(i)?e.renderbufferStorageMultisample(e.RENDERBUFFER,r,e.DEPTH24_STENCIL8,i.width,i.height):O(i)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,r,e.DEPTH24_STENCIL8,i.width,i.height):e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_STENCIL,i.width,i.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,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=L(i);n&&!1===O(i)?e.renderbufferStorageMultisample(e.RENDERBUFFER,d,h,i.width,i.height):O(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 B(t){const r=n.get(t),s=!0===t.isWebGLCubeRenderTarget;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),C(r.depthTexture,0);const s=n.get(r.depthTexture).__webglTexture,a=L(r);if(r.depthTexture.format===Le)O(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!==Oe)throw new Error("Unknown depthTexture format");O(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++)i.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[n]),r.__webglDepthbuffer[n]=e.createRenderbuffer(),R(r.__webglDepthbuffer[n],t,!1)}else i.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer),r.__webglDepthbuffer=e.createRenderbuffer(),R(r.__webglDepthbuffer,t,!1);i.bindFramebuffer(e.FRAMEBUFFER,null)}function L(e){return Math.min(r.maxSamples,e.samples)}function O(e){const i=n.get(e);return e.samples>0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==i.__useRenderToTexture}function U(e,t){const i=e.colorSpace,n=e.format,r=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||i!==dt&&i!==ct&&(si.getTransfer(i)===ft?(n!==Be||r!==Ce)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):i===mt||console.error("THREE.WebGLTextures: Unsupported texture color space:",i)),t}function F(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=w;return e>=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+r.maxTextures),w+=1,e},this.resetTextureUnits=function(){w=0},this.setTexture2D=C,this.setTexture2DArray=function(t,r){const s=n.get(t);t.version>0&&s.__version!==t.version?P(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?P(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=I(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=si.getPrimaries(si.workingColorSpace),n=a.colorSpace===ct||a.colorSpace===mt?null:si.getPrimaries(a.colorSpace),d=a.colorSpace===ct||a.colorSpace===mt||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]=U(a,m[e]);const _=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,I=v(a,_);if(T(e.TEXTURE_CUBE_MAP,a),u){C&&S&&i.texStorage2D(e.TEXTURE_CUBE_MAP,I,w,_.width,_.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!==Be?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&&I++;const t=F(m[0]);i.texStorage2D(e.TEXTURE_CUBE_MAP,I,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&&D(s.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),void 0!==r&&B(t)},this.setupRenderTarget=function(t){const r=t.texture,o=n.get(t),l=n.get(r);t.addEventListener("dispose",b);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===O(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=L(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(),R(o.__webglDepthRenderbuffer,t,!0)),i.bindFramebuffer(e.FRAMEBUFFER,null)}}if(h){i.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),T(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++)D(o.__webglFramebuffer[i][n],t,r,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+i,n);else D(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),T(e.TEXTURE_2D,s),D(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),T(n,r),r.mipmaps&&r.mipmaps.length>0)for(let i=0;i<r.mipmaps.length;i++)D(o.__webglFramebuffer[i],t,r,e.COLOR_ATTACHMENT0,n,i);else D(o.__webglFramebuffer,t,r,e.COLOR_ATTACHMENT0,n,0);f(r)&&A(n),i.unbindTexture()}t.depthBuffer&&B(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),T(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&&!1===O(t)){const r=t.textures,s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const c=[],h=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,d=n.get(t),u=r.length>1;if(u)for(let t=0;t<r.length;t++)i.bindFramebuffer(e.FRAMEBUFFER,d.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),i.bindFramebuffer(e.FRAMEBUFFER,d.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);i.bindFramebuffer(e.READ_FRAMEBUFFER,d.__webglMultisampledFramebuffer),i.bindFramebuffer(e.DRAW_FRAMEBUFFER,d.__webglFramebuffer);for(let i=0;i<r.length;i++){c.push(e.COLOR_ATTACHMENT0+i),t.depthBuffer&&c.push(h);const p=void 0!==d.__ignoreDepthValues&&d.__ignoreDepthValues;if(!1===p&&(t.depthBuffer&&(o|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&!0!==d.__isTransmissionRenderTarget&&(o|=e.STENCIL_BUFFER_BIT)),u&&e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,d.__webglColorRenderbuffer[i]),!0===p&&(e.invalidateFramebuffer(e.READ_FRAMEBUFFER,[h]),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[h])),u){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),l&&e.invalidateFramebuffer(e.READ_FRAMEBUFFER,c)}if(i.bindFramebuffer(e.READ_FRAMEBUFFER,null),i.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),u)for(let t=0;t<r.length;t++){i.bindFramebuffer(e.FRAMEBUFFER,d.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,d.__webglColorRenderbuffer[t]);const s=n.get(r[t]).__webglTexture;i.bindFramebuffer(e.FRAMEBUFFER,d.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,s,0)}i.bindFramebuffer(e.DRAW_FRAMEBUFFER,d.__webglMultisampledFramebuffer)}},this.setupDepthRenderbuffer=B,this.setupFrameBufferTexture=D,this.useMultisampledRTT=O}function Ro(e,t){return{convert:function(i,n=""){let r;const s=si.getTransfer(n);if(i===Ce)return e.UNSIGNED_BYTE;if(i===Pe)return e.UNSIGNED_SHORT_4_4_4_4;if(i===De)return e.UNSIGNED_SHORT_5_5_5_1;if(35902===i)return e.UNSIGNED_INT_5_9_9_9_REV;if(1010===i)return e.BYTE;if(1011===i)return e.SHORT;if(i===Se)return e.UNSIGNED_SHORT;if(i===Me)return e.INT;if(i===Ee)return e.UNSIGNED_INT;if(i===Te)return e.FLOAT;if(i===Ie)return e.HALF_FLOAT;if(1021===i)return e.ALPHA;if(1022===i)return e.RGB;if(i===Be)return e.RGBA;if(1024===i)return e.LUMINANCE;if(1025===i)return e.LUMINANCE_ALPHA;if(i===Le)return e.DEPTH_COMPONENT;if(i===Oe)return e.DEPTH_STENCIL;if(i===Ue)return e.RED;if(1029===i)return e.RED_INTEGER;if(i===Fe)return e.RG;if(1031===i)return e.RG_INTEGER;if(1033===i)return e.RGBA_INTEGER;if(i===Ne||i===ke||i===je||i===ze)if(s===ft){if(r=t.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(i===Ne)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===ke)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===je)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===ze)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=t.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(i===Ne)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===ke)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===je)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===ze)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(i===Ge||35841===i||i===Qe||35843===i){if(r=t.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(i===Ge)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===i)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Qe)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===i)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(i===Ve)return r=t.get("WEBGL_compressed_texture_etc1"),null!==r?r.COMPRESSED_RGB_ETC1_WEBGL:null;if(i===He||i===We){if(r=t.get("WEBGL_compressed_texture_etc"),null===r)return null;if(i===He)return s===ft?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(i===We)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}if(i===qe||37809===i||37810===i||37811===i||i===Xe||37813===i||37814===i||37815===i||37816===i||37817===i||37818===i||37819===i||37820===i||37821===i){if(r=t.get("WEBGL_compressed_texture_astc"),null===r)return null;if(i===qe)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Xe)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===i)return s===ft?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(i===Ye||36494===i||36495===i){if(r=t.get("EXT_texture_compression_bptc"),null===r)return null;if(i===Ye)return s===ft?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(36494===i)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(36495===i)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(36283===i||36284===i||36285===i||36286===i){if(r=t.get("EXT_texture_compression_rgtc"),null===r)return null;if(i===Ye)return r.COMPRESSED_RED_RGTC1_EXT;if(36284===i)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(36285===i)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(36286===i)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return i===Re?e.UNSIGNED_INT_24_8:void 0!==e[i]?e[i]:null}}}class Bo extends Gr{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}}class Lo extends En{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Oo={type:"move"};class Uo{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Lo,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 Lo,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new wi,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new wi),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Lo,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new wi,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new wi),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(Oo)))}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 Lo;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class Fo{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,i){if(null===this.texture){const n=new mi;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}}render(e,t){if(null!==this.texture){if(null===this.mesh){const e=t.cameras[0].viewport,i=new Fr({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:e.z},depthHeight:{value:e.w}}});this.mesh=new Pr(new is(20,20),i)}e.render(this.mesh,t)}}reset(){this.texture=null,this.mesh=null}}class No extends Bt{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 Fo,g=t.getContextAttributes();let f=null,A=null;const y=[],v=[],_=new Ht;let b=null;const x=new Gr;x.layers.enable(1),x.viewport=new Ai;const w=new Gr;w.layers.enable(2),w.viewport=new Ai;const C=[x,w],S=new Bo;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 Uo,y[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=y[e];return void 0===t&&(t=new Uo,y[e]=t),t.getGripSpace()},this.getHand=function(e){let t=y[e];return void 0===t&&(t=new Uo,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:Be,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?Oe:Le,s=g.stencil?Re:Ee);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:Be,type:Ce,depthTexture:new zs(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});e.properties.get(A).__ignoreDepthValues=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};const D=new wi,R=new wi;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;null!==m.texture&&(e.near=m.depthNear,e.far=m.depthFar),S.near=w.near=x.near=e.near,S.far=w.far=x.far=e.far,(M!==S.near||E!==S.far)&&(n.updateRenderState({depthNear:S.near,depthFar:S.far}),M=S.near,E=S.far,x.near=M,x.far=E,w.near=M,w.far=E,x.updateProjectionMatrix(),w.updateProjectionMatrix(),e.updateProjectionMatrix());const t=e.parent,i=S.cameras;B(S,t);for(let e=0;e<i.length;e++)B(i[e],t);2===i.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;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();const f=a+m,A=o+m,y=u-g,v=p+(n-g),_=l*o/A*f,b=c*o/A*f;e.projectionMatrix.makePerspective(y,v,_,b,f,A),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*Ft*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,S,t)},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};let L=null;this.onPreAnimationFrameCallback=null;const O=new es;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 Gr,a.layers.enable(n),a.viewport=new Ai,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)}m.render(e,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 ko=new hn,jo=new $i;function zo(e,t){function i(e,t){!0===e.matrixAutoUpdate&&e.updateMatrix(),t.value.copy(e.matrix)}function n(n,r){n.opacity.value=r.opacity,r.color&&n.diffuse.value.copy(r.color),r.emissive&&n.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(n.map.value=r.map,i(r.map,n.mapTransform)),r.alphaMap&&(n.alphaMap.value=r.alphaMap,i(r.alphaMap,n.alphaMapTransform)),r.bumpMap&&(n.bumpMap.value=r.bumpMap,i(r.bumpMap,n.bumpMapTransform),n.bumpScale.value=r.bumpScale,r.side===b&&(n.bumpScale.value*=-1)),r.normalMap&&(n.normalMap.value=r.normalMap,i(r.normalMap,n.normalMapTransform),n.normalScale.value.copy(r.normalScale),r.side===b&&n.normalScale.value.negate()),r.displacementMap&&(n.displacementMap.value=r.displacementMap,i(r.displacementMap,n.displacementMapTransform),n.displacementScale.value=r.displacementScale,n.displacementBias.value=r.displacementBias),r.emissiveMap&&(n.emissiveMap.value=r.emissiveMap,i(r.emissiveMap,n.emissiveMapTransform)),r.specularMap&&(n.specularMap.value=r.specularMap,i(r.specularMap,n.specularMapTransform)),r.alphaTest>0&&(n.alphaTest.value=r.alphaTest);const s=t.get(r),a=s.envMap,o=s.envMapRotation;if(a&&(n.envMap.value=a,ko.copy(o),ko.x*=-1,ko.y*=-1,ko.z*=-1,a.isCubeTexture&&!1===a.isRenderTargetTexture&&(ko.y*=-1,ko.z*=-1),n.envMapRotation.value.setFromMatrix4(jo.makeRotationFromEuler(ko)),n.flipEnvMap.value=a.isCubeTexture&&!1===a.isRenderTargetTexture?-1:1,n.reflectivity.value=r.reflectivity,n.ior.value=r.ior,n.refractionRatio.value=r.refractionRatio),r.lightMap){n.lightMap.value=r.lightMap;const t=!0===e._useLegacyLights?Math.PI:1;n.lightMapIntensity.value=r.lightMapIntensity*t,i(r.lightMap,n.lightMapTransform)}r.aoMap&&(n.aoMap.value=r.aoMap,n.aoMapIntensity.value=r.aoMapIntensity,i(r.aoMap,n.aoMapTransform))}return{refreshTransformUniform:i,refreshFogUniforms:function(t,i){i.color.getRGB(t.fogColor.value,Or(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.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 Go(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;0!==a&&n-a<r.boundary&&(i+=n-a),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 Qo{constructor(e={}){const{canvas:t=Zt(),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=ht,this._useLegacyLights=!1,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 Ai,I=new Ai;let P=null;const D=new Qn(0);let R=0,B=t.width,L=t.height,O=1,U=null,F=null;const N=new Ai(0,0,B,L),k=new Ai(0,0,B,L);let j=!1;const z=new $r;let G=!1,Q=!1;const V=new $i,H=new Ht,W=new wi,q={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};function X(){return null===S?O:1}let Y,K,J,Z,$,ee,te,ie,ne,re,se,ae,oe,le,ce,he,de,ue,pe,me,ge,fe,Ae,ye,ve=i;function _e(e,i){const n=t.getContext(e,i);return null!==n?n:null}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 r163"),t.addEventListener("webglcontextlost",Me,!1),t.addEventListener("webglcontextrestored",Le,!1),t.addEventListener("webglcontextcreationerror",Oe,!1),null===ve){const t="webgl2";if(ve=_e(t,e),null===ve)throw _e(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 be(){Y=new Os(ve),Y.init(),K=new ps(ve,Y,e),fe=new Ro(ve,Y),J=new Po(ve),Z=new Ns(ve),$=new fo,ee=new Do(ve,Y,J,$,K,fe,Z),te=new gs(y),ie=new Ls(y),ne=new ts(ve),Ae=new ds(ve,ne),re=new Us(ve,ne,Z,Ae),se=new js(ve,re,ne,Z),pe=new ks(ve,K,ee),he=new ms($),ae=new go(y,te,ie,Y,K,Ae,he),oe=new zo(y,$),le=new _o,ce=new Mo(Y),ue=new hs(y,te,ie,J,se,d,o),de=new Io(y,se,K),ye=new Go(ve,Z,K,J),me=new us(ve,Y,Z),ge=new Fs(ve,Y,Z),Z.programs=ae.programs,y.capabilities=K,y.extensions=Y,y.properties=$,y.renderLists=le,y.shadowMap=de,y.state=J,y.info=Z,y.background=ue,y.cubemaps=te,y.cubeuvmaps=ie,y.materials=oe}be();const xe=new No(y,ve);function Me(e){e.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),v=!0,y.onContextLost(e)}function Le(){console.log("THREE.WebGLRenderer: Context Restored."),v=!1;const e=y.info?y.info.autoReset:void 0,t=de.enabled,i=de.autoUpdate,n=de.needsUpdate,r=de.type;be(),y.info&&void 0!==e&&(y.info.autoReset=e),de.enabled=t,de.autoUpdate=i,de.needsUpdate=n,de.type=r,y.onContextRestore&&y.onContextRestore()}function Oe(e){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",e.statusMessage),y.onContextCreationError(e)}function Ue(e){const t=e.target;t.removeEventListener("dispose",Ue),function(e){(function(e){const t=$.get(e).programs;void 0!==t&&(t.forEach((function(e){ae.releaseProgram(e)})),e.isShaderMaterial&&ae.releaseShaderCache(e))})(e),$.remove(e)}(t)}function Fe(e,t,i){!0===e.transparent&&e.side===x&&!1===e.forceSinglePass?(e.side=b,e.needsUpdate=!0,We(e,t,i),e.side=_,e.needsUpdate=!0,We(e,t,i),e.side=x):We(e,t,i)}this.xr=xe,this.getContext=function(){return ve},this.getContextAttributes=function(){return ve.getContextAttributes()},this.forceContextLoss=function(){const e=Y.get("WEBGL_lose_context");e&&e.loseContext()},this.forceContextRestore=function(){const e=Y.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){xe.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(N)},this.setViewport=function(e,t,i,n){e.isVector4?N.set(e.x,e.y,e.z,e.w):N.set(e,t,i,n),J.viewport(T.copy(N).multiplyScalar(O).round())},this.getScissor=function(e){return e.copy(k)},this.setScissor=function(e,t,i,n){e.isVector4?k.set(e.x,e.y,e.z,e.w):k.set(e,t,i,n),J.scissor(I.copy(k).multiplyScalar(O).round())},this.getScissorTest=function(){return j},this.setScissorTest=function(e){J.setScissorTest(j=e)},this.setOpaqueSort=function(e){U=e},this.setTransparentSort=function(e){F=e},this.getClearColor=function(e){return e.copy(ue.getClearColor())},this.setClearColor=function(){ue.setClearColor.apply(ue,arguments)},this.getClearAlpha=function(){return ue.getClearAlpha()},this.setClearAlpha=function(){ue.setClearAlpha.apply(ue,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=1033===t||1031===t||1029===t}if(e){const e=S.texture.type,t=e===Ce||e===Ee||e===Se||e===Re||e===Pe||e===De,i=ue.getClearColor(),n=ue.getClearAlpha(),r=i.r,s=i.g,a=i.b;t?(u[0]=r,u[1]=s,u[2]=a,u[3]=n,ve.clearBufferuiv(ve.COLOR,0,u)):(p[0]=r,p[1]=s,p[2]=a,p[3]=n,ve.clearBufferiv(ve.COLOR,0,p))}else n|=ve.COLOR_BUFFER_BIT}t&&(n|=ve.DEPTH_BUFFER_BIT),i&&(n|=ve.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),ve.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",Le,!1),t.removeEventListener("webglcontextcreationerror",Oe,!1),le.dispose(),ce.dispose(),$.dispose(),te.dispose(),ie.dispose(),se.dispose(),Ae.dispose(),ye.dispose(),ae.dispose(),xe.dispose(),xe.removeEventListener("sessionstart",ke),xe.removeEventListener("sessionend",je),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),ee.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!==ht?S.texture.colorSpace:dt,l=(n.isMeshStandardMaterial?ie:te).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=$.get(n),_=g.state.lights;if(!0===G&&(!0===Q||e!==E)){const t=e===E&&n.id===M;he.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.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!==he.numPlanes||v.numIntersection!==he.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=We(n,t,r));let w=!1,C=!1,T=!1;const I=x.getUniforms(),P=v.uniforms;if(J.useProgram(x.program)&&(w=!0,C=!0,T=!0),n.id!==M&&(M=n.id,C=!0),w||E!==e){I.setValue(ve,"projectionMatrix",e.projectionMatrix),I.setValue(ve,"viewMatrix",e.matrixWorldInverse);const t=I.map.cameraPosition;void 0!==t&&t.setValue(ve,W.setFromMatrixPosition(e.matrixWorld)),K.logarithmicDepthBuffer&&I.setValue(ve,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(n.isMeshPhongMaterial||n.isMeshToonMaterial||n.isMeshLambertMaterial||n.isMeshBasicMaterial||n.isMeshStandardMaterial||n.isShaderMaterial)&&I.setValue(ve,"isOrthographic",!0===e.isOrthographicCamera),E!==e&&(E=e,C=!0,T=!0)}if(r.isSkinnedMesh){I.setOptional(ve,r,"bindMatrix"),I.setOptional(ve,r,"bindMatrixInverse");const e=r.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),I.setValue(ve,"boneTexture",e.boneTexture,ee))}r.isBatchedMesh&&(I.setOptional(ve,r,"batchingTexture"),I.setValue(ve,"batchingTexture",r._matricesTexture,ee));const D=i.morphAttributes;(void 0!==D.position||void 0!==D.normal||void 0!==D.color)&&pe.update(r,i,x),(C||v.receiveShadow!==r.receiveShadow)&&(v.receiveShadow=r.receiveShadow,I.setValue(ve,"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(ve,"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&&oe.refreshFogUniforms(P,s),oe.refreshMaterialUniforms(P,n,O,L,y.userData.transmissionRenderTarget||g.state.transmissionRenderTarget),Wa.upload(ve,qe(v),P,ee)),n.isShaderMaterial&&!0===n.uniformsNeedUpdate&&(Wa.upload(ve,qe(v),P,ee),n.uniformsNeedUpdate=!1),n.isSpriteMaterial&&I.setValue(ve,"center",r.center),I.setValue(ve,"modelViewMatrix",r.modelViewMatrix),I.setValue(ve,"normalMatrix",r.normalMatrix),I.setValue(ve,"modelMatrix",r.matrixWorld);const R=n.extraUniformsToUpload;if(R&&Object.entries(R).forEach((([e,t])=>{!1!==t.needsUpdate&&I.setValue(ve,e,t.value,ee)})),n.isShaderMaterial||n.isRawShaderMaterial){const e=n.uniformsGroups;for(let t=0,i=e.length;t<i;t++){const i=e[t];ye.update(i,x),ye.bind(i,x)}}return x}(e,t,i,n,r);J.setMaterial(n,a);let l=i.index,c=1;if(!0===n.wireframe){if(l=re.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;Ae.setup(r,n,o,i,l);let f,A=me;if(null!==l&&(f=ne.get(l),A=ge,A.setIndex(f)),r.isMesh)!0===n.wireframe?(J.setLineWidth(n.wireframeLinewidth*X()),A.setMode(ve.LINES)):A.setMode(ve.TRIANGLES);else if(r.isLine){let e=n.linewidth;void 0===e&&(e=1),J.setLineWidth(e*X()),r.isLineSegments?A.setMode(ve.LINES):r.isLineLoop?A.setMode(ve.LINE_LOOP):A.setMode(ve.LINE_STRIP)}else r.isPoints?A.setMode(ve.POINTS):r.isSprite&&A.setMode(ve.TRIANGLES);if(r.isBatchedMesh)A.renderMultiDraw(r._multiDrawStarts,r._multiDrawCounts,r._multiDrawCount);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=ce.get(i),g.init(),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(y._useLegacyLights);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];Fe(s,i,e),n.add(s)}else Fe(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){$.get(e).currentProgram.isReady()&&n.delete(e)})),0!==n.size?setTimeout(i,10):t(e)}null!==Y.get("KHR_parallel_shader_compile")?i():setTimeout(i,10)}))};let Ne=null;function ke(){ze.stop()}function je(){ze.start()}const ze=new es;function Ge(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=se.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=se.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++)Ge(r[e],t,i,n)}function Qe(e,t,i,n){const s=e.opaque,a=e.transmissive,o=e.transparent;if(g.setupLightsView(i),!0===G&&he.setGlobalState(y.clippingPlanes,i),void 0===y.userData.transmissionRender&&!1!==y.userData.renderTransmissionPass&&a.length>0&&function(e,t,i,n){if(console.warn("three.js internal render transmission pass should not be called"),null!==(!0===i.isScene?i.overrideMaterial:null))return;if(null===g.state.transmissionRenderTarget){g.state.transmissionRenderTarget=new vi(1,1,{generateMipmaps:!0,type:Y.has("EXT_color_buffer_half_float")||Y.has("EXT_color_buffer_float")?Ie:Ce,minFilter:we,samples:4,stencilBuffer:r});$.get(g.state.transmissionRenderTarget).__isTransmissionRenderTarget=!0}const s=g.state.transmissionRenderTarget;y.getDrawingBufferSize(H),s.setSize(H.x,H.y);const a=y.getRenderTarget();y.setRenderTarget(s),y.getClearColor(D),R=y.getClearAlpha(),R<1&&y.setClearColor(16777215,.5),y.clear();const o=y.toneMapping;y.toneMapping=0,Ve(e,i,n),ee.updateMultisampleRenderTarget(s),ee.updateRenderTargetMipmap(s);let l=!1;for(let e=0,r=t.length;e<r;e++){const r=t[e],s=r.object,a=r.geometry,o=r.material,c=r.group;if(o.side===x&&s.layers.test(n.layers)){const e=o.side;o.side=b,o.needsUpdate=!0,He(s,i,n,a,o,c),o.side=e,o.needsUpdate=!0,l=!0}}!0===l&&(ee.updateMultisampleRenderTarget(s),ee.updateRenderTargetMipmap(s)),y.setRenderTarget(a),y.setClearColor(D,R),y.toneMapping=o}([...s,...o],a,t,i),n&&J.viewport(T.copy(n)),!1!==y.userData.opaqueRender&&s.length>0&&Ve(s,t,i),!1!==y.userData.transparentRender&&o.length>0&&Ve(o,t,i),!1!==y.userData.transmissionRender&&a.length>0){g.state.transmissionRenderTarget||(g.state.transmissionRenderTarget=new vi(1,1));const e=(y.userData.transmissionRenderTarget||g.state.transmissionRenderTarget).texture,n=K.isWebGL2,r=e.generateMipmaps,s=e.minFilter;n&&y.userData.blurTransmissionTarget&&y.userData.transmissionRenderTarget&&(e.generateMipmaps=!0,e.minFilter=we,e.needsUpdate=!0,ee.updateMultisampleRenderTarget(y.userData.transmissionRenderTarget),ee.updateRenderTargetMipmap(y.userData.transmissionRenderTarget)),Ve(a,t,i),n&&y.userData.blurTransmissionTarget&&y.userData.transmissionRenderTarget&&(e.generateMipmaps=r,e.minFilter=s,e.needsUpdate=!0,ee.updateMultisampleRenderTarget(y.userData.transmissionRenderTarget),ee.updateRenderTargetMipmap(y.userData.transmissionRenderTarget))}J.buffers.depth.setTest(!0),J.buffers.depth.setMask(!0),J.buffers.color.setMask(!0),J.setPolygonOffset(!1)}function Ve(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)&&He(a,t,i,o,c,l)}Object.assign(y.userData,n)}function He(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 We(e,t,i){!0!==t.isScene&&(t=q);const n=$.get(e),r=g.state.lights,s=g.state.shadowsArray,a=r.state.version,o=ae.getParameters(e,r.state,s,t,i),l=ae.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?ie:te).get(e.envMap||n.environment),n.envMapRotation=null!==n.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation,void 0===c&&(e.addEventListener("dispose",Ue),c=new Map,n.programs=c);let h=c.get(l);if(void 0!==h){if(n.currentProgram===h&&n.lightsStateVersion===a)return Xe(e,o),h}else o.uniforms=ae.getUniforms(e),e.onBuild(i,o,y),e.onBeforeCompile(o,y),h=ae.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=he.uniform),Xe(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 qe(e){if(null===e.uniformsList){const t=e.currentProgram.getUniforms();e.uniformsList=Wa.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function Xe(e,t){const i=$.get(e);i.outputColorSpace=t.outputColorSpace,i.batching=t.batching,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){Ne&&Ne(e)})),typeof self<"u"&&ze.setContext(self),this.setAnimationLoop=function(e){Ne=e,xe.setAnimationLoop(e),null===e?ze.stop():ze.start()},xe.addEventListener("sessionstart",ke),xe.addEventListener("sessionend",je),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===xe.enabled&&!0===xe.isPresenting&&(!0===xe.cameraAutoUpdate&&xe.updateCamera(t),t=xe.getCamera()),!0===e.isScene&&e.onBeforeRender(y,e,t,S),g=ce.get(e,A.length),g.init(),A.push(g),V.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),z.setFromProjectionMatrix(V),Q=this.localClippingEnabled,G=he.init(this.clippingPlanes,Q),m=le.get(e,f.length),m.init(),f.push(m),Ge(e,t,0,y.sortObjects),m.finish(),!0===y.sortObjects&&m.sort(U,F),this.info.render.frame++,!1!==y.userData.shadowMapRender){!0===G&&he.beginShadows();const i=g.state.shadowsArray;i.length>0&&de.render(i,e,t),!0===G&&he.endShadows()}if(!0===this.info.autoReset&&this.info.reset(),!1!==y.userData.backgroundRender&&(!1===xe.enabled||!1===xe.isPresenting||!1===xe.hasDepthSensing())&&ue.render(m,e),!1!==y.userData.sceneRender)if(g.setupLights(y._useLegacyLights),t.isArrayCamera){const i=t.cameras;for(let t=0,n=i.length;t<n;t++){const n=i[t];Qe(m,e,n,n.viewport)}}else Qe(m,e,t);null!==S&&(ee.updateMultisampleRenderTarget(S),ee.updateRenderTargetMipmap(S)),!0===e.isScene&&e.onAfterRender(y,e,t),Ae.resetDefaultState(),M=-1,E=null,A.pop(),g=A.length>0?A[A.length-1]: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){$.get(e.texture).__webglTexture=t,$.get(e.depthTexture).__webglTexture=i;const n=$.get(e);n.__hasExternalTextures=!0,n.__autoAllocateDepthBuffer=void 0===i,n.__autoAllocateDepthBuffer||!0===Y.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=$.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=$.get(e);void 0!==o.__useDefaultFramebuffer?(J.bindFramebuffer(ve.FRAMEBUFFER,null),n=!1):void 0===o.__webglFramebuffer?ee.setupRenderTarget(e):o.__hasExternalTextures&&ee.rebindTextures(e,$.get(e.texture).__webglTexture,$.get(e.depthTexture).__webglTexture);const l=e.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const c=$.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(c[t])?c[t][i]:c[t],s=!0):r=e.samples>0&&!1===ee.useMultisampledRTT(e)?$.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[i]:c,T.copy(e.viewport),I.copy(e.scissor),P=e.scissorTest}else T.copy(N).multiplyScalar(O).floor(),I.copy(k).multiplyScalar(O).floor(),P=j;if(J.bindFramebuffer(ve.FRAMEBUFFER,r)&&n&&J.drawBuffers(e,r),J.viewport(T),J.scissor(I),J.setScissorTest(P),s){const n=$.get(e.texture);ve.framebufferTexture2D(ve.FRAMEBUFFER,ve.COLOR_ATTACHMENT0,ve.TEXTURE_CUBE_MAP_POSITIVE_X+t,n.__webglTexture,i)}else if(a){const n=$.get(e.texture),r=t||0;ve.framebufferTextureLayer(ve.FRAMEBUFFER,ve.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=$.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){J.bindFramebuffer(ve.FRAMEBUFFER,l);try{const a=Array.isArray(e.textures)?e.textures[o||0]:e.texture,l=a.format,c=a.type;if(l!==Be&&fe.convert(l)!==ve.getParameter(ve.IMPLEMENTATION_COLOR_READ_FORMAT))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");const h=c===Ie&&(Y.has("EXT_color_buffer_half_float")||Y.has("EXT_color_buffer_float"));if(c!==Ce&&fe.convert(c)!==ve.getParameter(ve.IMPLEMENTATION_COLOR_READ_TYPE)&&c!==Te&&!h)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)&&ve.readBuffer(ve.COLOR_ATTACHMENT0+(o||0)),ve.readPixels(t,i,n,r,fe.convert(l),fe.convert(c),s))}finally{const e=S?$.get(S).__webglFramebuffer:null;J.bindFramebuffer(ve.FRAMEBUFFER,e)}}},this.copyFramebufferToTexture=function(e,t,i=0){const n=Math.pow(2,-i),r=Math.floor(t.image.width*n),s=Math.floor(t.image.height*n);ee.setTexture2D(t,0),ve.copyTexSubImage2D(ve.TEXTURE_2D,i,0,0,e.x,e.y,r,s),J.unbindTexture()},this.copyTextureToTexture=function(e,t,i,n=0){const r=t.image.width,s=t.image.height,a=fe.convert(i.format),o=fe.convert(i.type);ee.setTexture2D(i,0),ve.pixelStorei(ve.UNPACK_FLIP_Y_WEBGL,i.flipY),ve.pixelStorei(ve.UNPACK_PREMULTIPLY_ALPHA_WEBGL,i.premultiplyAlpha),ve.pixelStorei(ve.UNPACK_ALIGNMENT,i.unpackAlignment),t.isDataTexture?ve.texSubImage2D(ve.TEXTURE_2D,n,e.x,e.y,r,s,a,o,t.image.data):t.isCompressedTexture?ve.compressedTexSubImage2D(ve.TEXTURE_2D,n,e.x,e.y,t.mipmaps[0].width,t.mipmaps[0].height,a,t.mipmaps[0].data):ve.texSubImage2D(ve.TEXTURE_2D,n,e.x,e.y,a,o,t.image),0===n&&i.generateMipmaps&&ve.generateMipmap(ve.TEXTURE_2D),J.unbindTexture()},this.copyTextureToTexture3D=function(e,t,i,n,r=0){const s=Math.round(e.max.x-e.min.x),a=Math.round(e.max.y-e.min.y),o=e.max.z-e.min.z+1,l=fe.convert(n.format),c=fe.convert(n.type);let h;if(n.isData3DTexture)ee.setTexture3D(n,0),h=ve.TEXTURE_3D;else{if(!n.isDataArrayTexture&&!n.isCompressedArrayTexture)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");ee.setTexture2DArray(n,0),h=ve.TEXTURE_2D_ARRAY}ve.pixelStorei(ve.UNPACK_FLIP_Y_WEBGL,n.flipY),ve.pixelStorei(ve.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n.premultiplyAlpha),ve.pixelStorei(ve.UNPACK_ALIGNMENT,n.unpackAlignment);const d=ve.getParameter(ve.UNPACK_ROW_LENGTH),u=ve.getParameter(ve.UNPACK_IMAGE_HEIGHT),p=ve.getParameter(ve.UNPACK_SKIP_PIXELS),m=ve.getParameter(ve.UNPACK_SKIP_ROWS),g=ve.getParameter(ve.UNPACK_SKIP_IMAGES),f=i.isCompressedTexture?i.mipmaps[r]:i.image;ve.pixelStorei(ve.UNPACK_ROW_LENGTH,f.width),ve.pixelStorei(ve.UNPACK_IMAGE_HEIGHT,f.height),ve.pixelStorei(ve.UNPACK_SKIP_PIXELS,e.min.x),ve.pixelStorei(ve.UNPACK_SKIP_ROWS,e.min.y),ve.pixelStorei(ve.UNPACK_SKIP_IMAGES,e.min.z),i.isDataTexture||i.isData3DTexture?ve.texSubImage3D(h,r,t.x,t.y,t.z,s,a,o,l,c,f.data):n.isCompressedArrayTexture?ve.compressedTexSubImage3D(h,r,t.x,t.y,t.z,s,a,o,l,f.data):ve.texSubImage3D(h,r,t.x,t.y,t.z,s,a,o,l,c,f),ve.pixelStorei(ve.UNPACK_ROW_LENGTH,d),ve.pixelStorei(ve.UNPACK_IMAGE_HEIGHT,u),ve.pixelStorei(ve.UNPACK_SKIP_PIXELS,p),ve.pixelStorei(ve.UNPACK_SKIP_ROWS,m),ve.pixelStorei(ve.UNPACK_SKIP_IMAGES,g),0===r&&n.generateMipmaps&&ve.generateMipmap(h),J.unbindTexture()},this.initTexture=function(e){e.isCubeTexture?ee.setTextureCube(e,0):e.isData3DTexture?ee.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?ee.setTexture2DArray(e,0):ee.setTexture2D(e,0),J.unbindTexture()},this.resetState=function(){w=0,C=0,S=null,J.reset(),Ae.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Pt}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=e===ut?"display-p3":"srgb",t.unpackColorSpace=si.workingColorSpace===pt?"display-p3":"srgb"}get useLegacyLights(){return this._useLegacyLights}set useLegacyLights(e){this._useLegacyLights=e}}class Vo{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new Qn(e),this.density=t}clone(){return new Vo(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class Ho{constructor(e,t=1,i=1e3){this.isFog=!0,this.name="",this.color=new Qn(e),this.near=t,this.far=i}clone(){return new Ho(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Wo extends En{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 hn,this.environmentIntensity=1,this.environmentRotation=new hn,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 qo{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Tt,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.version=0,this.uuid=Nt()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}get updateRange(){return ei("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=Nt()),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=Nt()),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 Xo=new wi;class Yo{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++)Xo.fromBufferAttribute(this,t),Xo.applyMatrix4(e),this.setXYZ(t,Xo.x,Xo.y,Xo.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)Xo.fromBufferAttribute(this,t),Xo.applyNormalMatrix(e),this.setXYZ(t,Xo.x,Xo.y,Xo.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)Xo.fromBufferAttribute(this,t),Xo.transformDirection(e),this.setXYZ(t,Xo.x,Xo.y,Xo.z);return this}getComponent(e,t){let i=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(i=Gt(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=Qt(i,this.array)),this.data.array[e*this.data.stride+this.offset+t]=i,this}setX(e,t){return this.normalized&&(t=Qt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Qt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Qt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Qt(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=Gt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Gt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Gt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Gt(t,this.array)),t}setXY(e,t,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=Qt(t,this.array),i=Qt(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=Qt(t,this.array),i=Qt(i,this.array),n=Qt(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=Qt(t,this.array),i=Qt(i,this.array),n=Qt(n,this.array),r=Qt(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 tr(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 Yo(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 Ko extends Wn{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Qn(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 Jo;const Zo=new wi,$o=new wi,el=new wi,tl=new Ht,il=new Ht,nl=new $i,rl=new wi,sl=new wi,al=new wi,ol=new Ht,ll=new Ht,cl=new Ht;class hl extends En{constructor(e=new Ko){if(super(),this.isSprite=!0,this.type="Sprite",void 0===Jo){Jo=new ur;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 qo(e,5);Jo.setIndex([0,1,2,0,2,3]),Jo.setAttribute("position",new Yo(t,3,0,!1)),Jo.setAttribute("uv",new Yo(t,2,3,!1))}this.geometry=Jo,this.material=e,this.center=new Ht(.5,.5)}raycast(e,t){null===e.camera&&console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),$o.setFromMatrixScale(this.matrixWorld),nl.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),el.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&!1===this.material.sizeAttenuation&&$o.multiplyScalar(-el.z);const i=this.material.rotation;let n,r;0!==i&&(r=Math.cos(i),n=Math.sin(i));const s=this.center;dl(rl.set(-.5,-.5,0),el,s,$o,n,r),dl(sl.set(.5,-.5,0),el,s,$o,n,r),dl(al.set(.5,.5,0),el,s,$o,n,r),ol.set(0,0),ll.set(1,0),cl.set(1,1);let a=e.ray.intersectTriangle(rl,sl,al,!1,Zo);if(null===a&&(dl(sl.set(-.5,.5,0),el,s,$o,n,r),ll.set(0,1),a=e.ray.intersectTriangle(rl,al,sl,!1,Zo),null===a))return;const o=e.ray.origin.distanceTo(Zo);o<e.near||o>e.far||t.push({distance:o,point:Zo.clone(),uv:Nn.getInterpolation(Zo,rl,sl,al,ol,ll,cl,new Ht),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 dl(e,t,i,n,r,s){tl.subVectors(e,i).addScalar(.5).multiply(n),void 0!==r?(il.x=s*tl.x-r*tl.y,il.y=r*tl.x+s*tl.y):il.copy(tl),e.copy(t),e.x+=il.x,e.y+=il.y,e.applyMatrix4(nl)}const ul=new wi,pl=new wi;class ml extends En{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){ul.setFromMatrixPosition(this.matrixWorld);const i=e.ray.origin.distanceTo(ul);this.getObjectForDistance(i).raycast(e,t)}}update(e){const t=this.levels;if(t.length>1){ul.setFromMatrixPosition(e.matrixWorld),pl.setFromMatrixPosition(this.matrixWorld);const i=ul.distanceTo(pl)/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 gl=new wi,fl=new Ai,Al=new Ai,yl=new wi,vl=new $i,_l=new wi,bl=new Vi,xl=new $i,wl=new Zi;class Cl extends Pr{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=le,this.bindMatrix=new $i,this.bindMatrixInverse=new $i,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const e=this.geometry;null===this.boundingBox&&(this.boundingBox=new Mi),this.boundingBox.makeEmpty();const t=e.getAttribute("position");for(let e=0;e<t.count;e++)this.getVertexPosition(e,_l),this.boundingBox.expandByPoint(_l)}computeBoundingSphere(){const e=this.geometry;null===this.boundingSphere&&(this.boundingSphere=new Vi),this.boundingSphere.makeEmpty();const t=e.getAttribute("position");for(let e=0;e<t.count;e++)this.getVertexPosition(e,_l),this.boundingSphere.expandByPoint(_l)}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(),bl.copy(this.boundingSphere),bl.applyMatrix4(n),!1!==e.ray.intersectsSphere(bl)&&(xl.copy(n).invert(),wl.copy(e.ray).applyMatrix4(xl),(null===this.boundingBox||!1!==wl.intersectsBox(this.boundingBox))&&this._computeIntersections(e,t,wl)))}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 Ai,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;fl.fromBufferAttribute(n.attributes.skinIndex,e),Al.fromBufferAttribute(n.attributes.skinWeight,e),gl.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let e=0;e<4;e++){const n=Al.getComponent(e);if(0!==n){const r=fl.getComponent(e);vl.multiplyMatrices(i.bones[r].matrixWorld,i.boneInverses[r]),t.addScaledVector(yl.copy(gl).applyMatrix4(vl),n)}}return t.applyMatrix4(this.bindMatrixInverse)}}class Sl extends En{constructor(){super(),this.isBone=!0,this.type="Bone"}}class Ml extends mi{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 El=new $i,Tl=new $i;class Il{constructor(e=[],t=[]){this.uuid=Nt(),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 $i)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){const t=new $i;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:Tl;El.multiplyMatrices(r,t[n]),El.toArray(i,16*n)}null!==n&&(n.needsUpdate=!0)}clone(){return new Il(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 Ml(t,e,e,Be,Te);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 Sl),this.bones.push(r),this.boneInverses.push((new $i).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 Pl extends tr{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 Dl=new $i,Rl=new $i,Bl=[],Ll=new Mi,Ol=new $i,Ul=new Pr,Fl=new Vi;class Nl extends Pr{constructor(e,t,i){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new Pl(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,Ol)}computeBoundingBox(){const e=this.geometry,t=this.count;null===this.boundingBox&&(this.boundingBox=new Mi),null===e.boundingBox&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,Dl),Ll.copy(e.boundingBox).applyMatrix4(Dl),this.boundingBox.union(Ll)}computeBoundingSphere(){const e=this.geometry,t=this.count;null===this.boundingSphere&&(this.boundingSphere=new Vi),null===e.boundingSphere&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<t;i++)this.getMatrixAt(i,Dl),Fl.copy(e.boundingSphere).applyMatrix4(Dl),this.boundingSphere.union(Fl)}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(Ul.geometry=this.geometry,Ul.material=this.material,void 0!==Ul.material&&(null===this.boundingSphere&&this.computeBoundingSphere(),Fl.copy(this.boundingSphere),Fl.applyMatrix4(i),!1!==e.ray.intersectsSphere(Fl)))for(let r=0;r<n;r++){this.getMatrixAt(r,Dl),Rl.multiplyMatrices(i,Dl),Ul.matrixWorld=Rl,Ul.raycast(e,Bl);for(let e=0,i=Bl.length;e<i;e++){const i=Bl[e];i.instanceId=r,i.object=this,t.push(i)}Bl.length=0}}setColorAt(e,t){null===this.instanceColor&&(this.instanceColor=new Pl(new Float32Array(3*this.instanceMatrix.count),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 Ml(new Float32Array(n*this.count),n,this.count,Ue,Te));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 kl(e,t){return e.z-t.z}function jl(e,t){return t.z-e.z}const zl="batchId",Gl=new $i,Ql=new $i,Vl=new $i,Hl=new $i,Wl=new $r,ql=new Mi,Xl=new Vi,Yl=new wi,Kl=new class{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,t){const i=this.pool,n=this.list;this.index>=i.length&&i.push({start:-1,count:-1,z:-1});const r=i[this.index];n.push(r),this.index++,r.start=e.start,r.count=e.count,r.z=t}reset(){this.list.length=0,this.index=0}},Jl=new Pr,Zl=[];function $l(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 ec extends Pr{get maxGeometryCount(){return this._maxGeometryCount}constructor(e,t,i=2*t,n){super(new ur,n),this.isBatchedMesh=!0,this.perObjectFrustumCulled=!0,this.sortObjects=!0,this.boundingBox=null,this.boundingSphere=null,this.customSort=null,this._drawRanges=[],this._reservedRanges=[],this._visibility=[],this._active=[],this._bounds=[],this._maxGeometryCount=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._visibilityChanged=!0,this._matricesTexture=null,this._initMatricesTexture()}_initMatricesTexture(){let e=Math.sqrt(4*this._maxGeometryCount);e=4*Math.ceil(e/4),e=Math.max(e,4);const t=new Float32Array(e*e*4),i=new Ml(t,e,e,Be,Te);this._matricesTexture=i}_initializeGeometry(e){const t=this.geometry,i=this._maxVertexCount,n=this._maxGeometryCount,r=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 tr(l,a,o);t.setAttribute(n,c)}if(null!==e.getIndex()){const e=i>65536?new Uint32Array(r):new Uint16Array(r);t.setIndex(new tr(e,1))}const s=n>65536?new Uint32Array(i):new Uint16Array(i);t.setAttribute(zl,new tr(s,1)),this._geometryInitialized=!0}}_validateGeometry(e){if(e.getAttribute(zl))throw new Error(`BatchedMesh: Geometry cannot use attribute "${zl}"`);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(i===zl)continue;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 Mi);const e=this._geometryCount,t=this.boundingBox,i=this._active;t.makeEmpty();for(let n=0;n<e;n++)!1!==i[n]&&(this.getMatrixAt(n,Gl),this.getBoundingBoxAt(n,ql).applyMatrix4(Gl),t.union(ql))}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new Vi);const e=this._geometryCount,t=this.boundingSphere,i=this._active;t.makeEmpty();for(let n=0;n<e;n++)!1!==i[n]&&(this.getMatrixAt(n,Gl),this.getBoundingSphereAt(n,Xl).applyMatrix4(Gl),t.union(Xl))}addGeometry(e,t=-1,i=-1){if(this._initializeGeometry(e),this._validateGeometry(e),this._geometryCount>=this._maxGeometryCount)throw new Error("BatchedMesh: Maximum geometry 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._visibility,d=this._active,u=this._matricesTexture,p=this._matricesTexture.image.data;h.push(!0),d.push(!0);const m=this._geometryCount;this._geometryCount++,Vl.toArray(p,16*m),u.needsUpdate=!0,s.push(n),a.push({start:c?n.indexStart:n.vertexStart,count:-1}),o.push({boxInitialized:!1,box:new Mi,sphereInitialized:!1,sphere:new Vi});const g=this.geometry.getAttribute(zl);for(let e=0;e<n.vertexCount;e++)g.setX(n.vertexStart+e,m);return g.needsUpdate=!0,this.setGeometryAt(m,e),m}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){if(e===zl)continue;const n=t.getAttribute(e),r=i.getAttribute(e);$l(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}deleteGeometry(e){const t=this._active;return e>=t.length||!1===t[e]||(t[e]=!1,this._visibilityChanged=!0),this}getBoundingBoxAt(e,t){if(!1===this._active[e])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(Yl.fromBufferAttribute(s,i))}i.boxInitialized=!0}return t.copy(n),t}getBoundingSphereAt(e,t){if(!1===this._active[e])return null;const i=this._bounds[e],n=i.sphere,r=this.geometry;if(!1===i.sphereInitialized){n.makeEmpty(),this.getBoundingBoxAt(e,ql),ql.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)),Yl.fromBufferAttribute(s,i),o=Math.max(o,n.center.distanceToSquared(Yl))}n.radius=Math.sqrt(o),i.sphereInitialized=!0}return t.copy(n),t}setMatrixAt(e,t){const i=this._active,n=this._matricesTexture,r=this._matricesTexture.image.data;return e>=this._geometryCount||!1===i[e]||(t.toArray(r,16*e),n.needsUpdate=!0),this}getMatrixAt(e,t){const i=this._active,n=this._matricesTexture.image.data;return e>=this._geometryCount||!1===i[e]?null:t.fromArray(n,16*e)}setVisibleAt(e,t){const i=this._visibility,n=this._active;return e>=this._geometryCount||!1===n[e]||i[e]===t||(i[e]=t,this._visibilityChanged=!0),this}getVisibleAt(e){const t=this._visibility,i=this._active;return!(e>=this._geometryCount||!1===i[e])&&t[e]}raycast(e,t){const i=this._visibility,n=this._active,r=this._drawRanges,s=this._geometryCount,a=this.matrixWorld,o=this.geometry;Jl.material=this.material,Jl.geometry.index=o.index,Jl.geometry.attributes=o.attributes,null===Jl.geometry.boundingBox&&(Jl.geometry.boundingBox=new Mi),null===Jl.geometry.boundingSphere&&(Jl.geometry.boundingSphere=new Vi);for(let o=0;o<s;o++){if(!i[o]||!n[o])continue;const s=r[o];Jl.geometry.setDrawRange(s.start,s.count),this.getMatrixAt(o,Jl.matrixWorld).premultiply(a),this.getBoundingBoxAt(o,Jl.geometry.boundingBox),this.getBoundingSphereAt(o,Jl.geometry.boundingSphere),Jl.raycast(e,Zl);for(let e=0,i=Zl.length;e<i;e++){const i=Zl[e];i.object=this,i.batchId=o,t.push(i)}Zl.length=0}Jl.material=null,Jl.geometry.index=null,Jl.geometry.attributes={},Jl.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._visibility=e._visibility.slice(),this._active=e._active.slice(),this._bounds=e._bounds.map((e=>({boxInitialized:e.boxInitialized,box:e.box.clone(),sphereInitialized:e.sphereInitialized,sphere:e.sphere.clone()}))),this._maxGeometryCount=e._maxGeometryCount,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.slice(),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=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._active,l=this._visibility,c=this._multiDrawStarts,h=this._multiDrawCounts,d=this._drawRanges,u=this.perObjectFrustumCulled;u&&(Hl.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse).multiply(this.matrixWorld),Wl.setFromProjectionMatrix(Hl,e.coordinateSystem));let p=0;if(this.sortObjects){Ql.copy(this.matrixWorld).invert(),Yl.setFromMatrixPosition(i.matrixWorld).applyMatrix4(Ql);for(let e=0,t=l.length;e<t;e++)if(l[e]&&o[e]){this.getMatrixAt(e,Gl),this.getBoundingSphereAt(e,Xl).applyMatrix4(Gl);let t=!1;if(u&&(t=!Wl.intersectsSphere(Xl)),!t){const t=Yl.distanceTo(Xl.center);Kl.push(d[e],t)}}const e=Kl.list,t=this.customSort;null===t?e.sort(r.transparent?jl:kl):t.call(this,e,i);for(let t=0,i=e.length;t<i;t++){const i=e[t];c[p]=i.start*a,h[p]=i.count,p++}Kl.reset()}else for(let e=0,t=l.length;e<t;e++)if(l[e]&&o[e]){let t=!1;if(u&&(this.getMatrixAt(e,Gl),this.getBoundingSphereAt(e,Xl).applyMatrix4(Gl),t=!Wl.intersectsSphere(Xl)),!t){const t=d[e];c[p]=t.start*a,h[p]=t.count,p++}}this._multiDrawCount=p,this._visibilityChanged=!1}onBeforeShadow(e,t,i,n,r,s){this.onBeforeRender(e,null,n,r,s)}}class tc extends Wn{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Qn(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 ic=new wi,nc=new wi,rc=new $i,sc=new Zi,ac=new Vi;class oc extends En{constructor(e=new ur,t=new tc){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++)ic.fromBufferAttribute(t,e-1),nc.fromBufferAttribute(t,e),i[e]=i[e-1],i[e]+=ic.distanceTo(nc);e.setAttribute("lineDistance",new rr(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(),ac.copy(i.boundingSphere),ac.applyMatrix4(n),ac.radius+=r,!1===e.ray.intersectsSphere(ac))return;rc.copy(n).invert(),sc.copy(e.ray).applyMatrix4(rc);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=new wi,c=new wi,h=new wi,d=new wi,u=this.isLineSegments?2:1,p=i.index,m=i.attributes.position;if(null!==p){for(let i=Math.max(0,s.start),n=Math.min(p.count,s.start+s.count)-1;i<n;i+=u){const n=p.getX(i),r=p.getX(i+1);if(l.fromBufferAttribute(m,n),c.fromBufferAttribute(m,r),sc.distanceSqToSegment(l,c,d,h)>o)continue;d.applyMatrix4(this.matrixWorld);const s=e.ray.origin.distanceTo(d);s<e.near||s>e.far||t.push({distance:s,point:h.clone().applyMatrix4(this.matrixWorld),index:i,face:null,faceIndex:null,object:this})}}else{for(let i=Math.max(0,s.start),n=Math.min(m.count,s.start+s.count)-1;i<n;i+=u){if(l.fromBufferAttribute(m,i),c.fromBufferAttribute(m,i+1),sc.distanceSqToSegment(l,c,d,h)>o)continue;d.applyMatrix4(this.matrixWorld);const n=e.ray.origin.distanceTo(d);n<e.near||n>e.far||t.push({distance:n,point:h.clone().applyMatrix4(this.matrixWorld),index:i,face:null,faceIndex:null,object: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}}}}}const lc=new wi,cc=new wi;class hc extends oc{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)lc.fromBufferAttribute(t,e),cc.fromBufferAttribute(t,e+1),i[e]=0===e?0:i[e-1],i[e+1]=i[e]+lc.distanceTo(cc);e.setAttribute("lineDistance",new rr(i,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class dc extends oc{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}}class uc extends Wn{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Qn(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 pc=new $i,mc=new Zi,gc=new Vi,fc=new wi;class Ac extends En{constructor(e=new ur,t=new uc){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(),gc.copy(i.boundingSphere),gc.applyMatrix4(n),gc.radius+=r,!1===e.ray.intersectsSphere(gc))return;pc.copy(n).invert(),mc.copy(e.ray).applyMatrix4(pc);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);fc.fromBufferAttribute(c,r),yc(fc,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++)fc.fromBufferAttribute(c,i),yc(fc,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 yc(e,t,i,n,r,s,a){const o=mc.distanceSqToPoint(e);if(o<i){const i=new wi;mc.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 vc extends mi{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 mi{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 bc 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}}class xc 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 wc extends mi{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 Cc{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 Ht:new wi);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 wi,n=[],r=[],s=[],a=new wi,o=new $i;for(let t=0;t<=e;t++){const i=t/e;n[t]=this.getTangentAt(i,new wi)}r[0]=new wi,s[0]=new wi;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(kt(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(kt(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 Sc extends Cc{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 Ht){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 Mc extends Sc{constructor(e,t,i,n,r,s){super(e,t,i,i,n,r,s),this.isArcCurve=!0,this.type="ArcCurve"}}function Ec(){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 Tc=new wi,Ic=new Ec,Pc=new Ec,Dc=new Ec;class Rc extends Cc{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 wi){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]:(Tc.subVectors(n[0],n[1]).add(n[0]),a=Tc);const h=n[l%r],d=n[(l+1)%r];if(this.closed||l+2<r?o=n[(l+2)%r]:(Tc.subVectors(n[r-1],n[r-2]).add(n[r-1]),o=Tc),"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),Ic.initNonuniformCatmullRom(a.x,h.x,d.x,o.x,t,i,n),Pc.initNonuniformCatmullRom(a.y,h.y,d.y,o.y,t,i,n),Dc.initNonuniformCatmullRom(a.z,h.z,d.z,o.z,t,i,n)}else"catmullrom"===this.curveType&&(Ic.initCatmullRom(a.x,h.x,d.x,o.x,this.tension),Pc.initCatmullRom(a.y,h.y,d.y,o.y,this.tension),Dc.initCatmullRom(a.z,h.z,d.z,o.z,this.tension));return i.set(Ic.calc(c),Pc.calc(c),Dc.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 wi).fromArray(i))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}}function Bc(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 Lc(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 Oc(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 Uc extends Cc{constructor(e=new Ht,t=new Ht,i=new Ht,n=new Ht){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=i,this.v3=n}getPoint(e,t=new Ht){const i=t,n=this.v0,r=this.v1,s=this.v2,a=this.v3;return i.set(Oc(e,n.x,r.x,s.x,a.x),Oc(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 Fc extends Cc{constructor(e=new wi,t=new wi,i=new wi,n=new wi){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=i,this.v3=n}getPoint(e,t=new wi){const i=t,n=this.v0,r=this.v1,s=this.v2,a=this.v3;return i.set(Oc(e,n.x,r.x,s.x,a.x),Oc(e,n.y,r.y,s.y,a.y),Oc(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 Nc extends Cc{constructor(e=new Ht,t=new Ht){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new Ht){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 Ht){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 kc extends Cc{constructor(e=new wi,t=new wi){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new wi){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 wi){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 jc extends Cc{constructor(e=new Ht,t=new Ht,i=new Ht){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=i}getPoint(e,t=new Ht){const i=t,n=this.v0,r=this.v1,s=this.v2;return i.set(Lc(e,n.x,r.x,s.x),Lc(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 zc extends Cc{constructor(e=new wi,t=new wi,i=new wi){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=i}getPoint(e,t=new wi){const i=t,n=this.v0,r=this.v1,s=this.v2;return i.set(Lc(e,n.x,r.x,s.x),Lc(e,n.y,r.y,s.y),Lc(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 Gc extends Cc{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new Ht){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(Bc(a,o.x,l.x,c.x,h.x),Bc(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 Ht).fromArray(i))}return this}}var Qc=Object.freeze({__proto__:null,ArcCurve:Mc,CatmullRomCurve3:Rc,CubicBezierCurve:Uc,CubicBezierCurve3:Fc,EllipseCurve:Sc,LineCurve:Nc,LineCurve3:kc,QuadraticBezierCurve:jc,QuadraticBezierCurve3:zc,SplineCurve:Gc});class Vc extends Cc{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 Qc[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 Qc[i.type]).fromJSON(i))}return this}}class Hc extends Vc{constructor(e){super(),this.type="Path",this.currentPoint=new Ht,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 Nc(this.currentPoint.clone(),new Ht(e,t));return this.curves.push(i),this.currentPoint.set(e,t),this}quadraticCurveTo(e,t,i,n){const r=new jc(this.currentPoint.clone(),new Ht(e,t),new Ht(i,n));return this.curves.push(r),this.currentPoint.set(i,n),this}bezierCurveTo(e,t,i,n,r,s){const a=new Uc(this.currentPoint.clone(),new Ht(e,t),new Ht(i,n),new Ht(r,s));return this.curves.push(a),this.currentPoint.set(r,s),this}splineThru(e){const t=[this.currentPoint.clone()].concat(e),i=new Gc(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 Sc(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 Wc extends ur{constructor(e=[new Ht(0,-.5),new Ht(.5,0),new Ht(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=kt(n,0,2*Math.PI);const r=[],s=[],a=[],o=[],l=[],c=1/t,h=new wi,d=new Ht,u=new wi,p=new wi,m=new wi;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 rr(s,3)),this.setAttribute("uv",new rr(a,2)),this.setAttribute("normal",new rr(l,3))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Wc(e.points,e.segments,e.phiStart,e.phiLength)}}class qc extends Wc{constructor(e=1,t=1,i=4,n=8){const r=new Hc;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 qc(e.radius,e.length,e.capSegments,e.radialSegments)}}class Xc extends ur{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 wi,c=new Ht;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 rr(s,3)),this.setAttribute("normal",new rr(a,3)),this.setAttribute("uv",new rr(o,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Xc(e.radius,e.segments,e.thetaStart,e.thetaLength)}}class Yc extends ur{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 Ht,m=new wi;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 wi,A=new wi;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 rr(h,3)),this.setAttribute("normal",new rr(d,3)),this.setAttribute("uv",new rr(u,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Yc(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Kc extends Yc{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 Kc(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Jc extends ur{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 wi,n=new wi,r=new wi;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 wi;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 wi;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 wi,t=new wi,i=new wi,n=new wi,a=new Ht,o=new Ht,l=new Ht;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 rr(r,3)),this.setAttribute("normal",new rr(r.slice(),3)),this.setAttribute("uv",new rr(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 Jc(e.vertices,e.indices,e.radius,e.details)}}class Zc extends Jc{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 Zc(e.radius,e.detail)}}const $c=new wi,eh=new wi,th=new wi,ih=new Nn;class nh extends ur{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(Ut*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}=ih;if(t.fromBufferAttribute(s,o[0]),a.fromBufferAttribute(s,o[1]),u.fromBufferAttribute(s,o[2]),ih.getNormal(th),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=ih[l[e]],a=ih[l[t]],u=`${i}_${r}`,p=`${r}_${i}`;p in h&&h[p]?(th.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:th.clone()})}}for(const e in h)if(h[e]){const{index0:t,index1:i}=h[e];$c.fromBufferAttribute(s,t),eh.fromBufferAttribute(s,i),d.push($c.x,$c.y,$c.z),d.push(eh.x,eh.y,eh.z)}this.setAttribute("position",new rr(d,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}class rh extends Hc{constructor(e){super(e),this.uuid=Nt(),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 Hc).fromJSON(i))}return this}}const sh=function(e,t,i=2){const n=t&&t.length,r=n?t[0]*i:e.length;let s=ah(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=ah(e,o,l,n,!1),c===c.next&&(c.steiner=!0),r.push(Ah(c));for(r.sort(ph),s=0;s<r.length;s++)i=mh(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 lh(s,a,i,o,l,p,0),a};function ah(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=Eh(s,e[s],e[s+1],a);else for(s=i-n;s>=t;s-=n)a=Eh(s,e[s],e[s+1],a);return a&&bh(a,a.next)&&(Th(a),a=a.next),a}function oh(e,t){if(!e)return e;t||(t=e);let i,n=e;do{if(i=!1,n.steiner||!bh(n,n.next)&&0!==_h(n.prev,n,n.next))n=n.next;else{if(Th(n),n=t=n.prev,n===n.next)break;i=!0}}while(i||n!==t);return t}function lh(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=fh(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?hh(e,n,r,s):ch(e))t.push(o.i/i|0),t.push(e.i/i|0),t.push(l.i/i|0),Th(e),e=l.next,c=l.next;else if((e=l)===c){a?1===a?lh(e=dh(oh(e),t,i),t,i,n,r,s,2):2===a&&uh(e,t,i,n,r,s):lh(oh(e),t,i,n,r,s,1);break}}function ch(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&&yh(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 hh(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=fh(p,m,t,i,n),y=fh(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&&yh(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&&yh(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&&yh(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&&yh(o,h,l,d,c,u,_.x,_.y)&&_h(_.prev,_,_.next)>=0)return!1;_=_.nextZ}return!0}function dh(e,t,i){let n=e;do{const r=n.prev,s=n.next.next;!bh(r,s)&&xh(r,n,n.next,s)&&Sh(r,s)&&Sh(s,r)&&(t.push(r.i/i|0),t.push(n.i/i|0),t.push(s.i/i|0),Th(n),Th(n.next),n=e=s),n=n.next}while(n!==e);return oh(n)}function uh(e,t,i,n,r,s){let a=e;do{let e=a.next.next;for(;e!==a.prev;){if(a.i!==e.i&&vh(a,e)){let o=Mh(a,e);return a=oh(a,a.next),o=oh(o,o.next),lh(a,t,i,n,r,s,0),void lh(o,t,i,n,r,s,0)}e=e.next}a=a.next}while(a!==e)}function ph(e,t){return e.x-t.x}function mh(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&&yh(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),Sh(n,e)&&(h<d||h===d&&(n.x>i.x||n.x===i.x&&gh(i,n)))&&(i=n,d=h)),n=n.next}while(n!==o);return i}(e,t);if(!i)return t;const n=Mh(i,e);return oh(n,n.next),oh(i,i.next)}function gh(e,t){return _h(e.prev,e,t.prev)<0&&_h(t.next,e,e.next)<0}function fh(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 Ah(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 yh(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 vh(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&&xh(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(Sh(e,t)&&Sh(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))||bh(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 bh(e,t){return e.x===t.x&&e.y===t.y}function xh(e,t,i,n){const r=Ch(_h(e,t,i)),s=Ch(_h(e,t,n)),a=Ch(_h(i,n,e)),o=Ch(_h(i,n,t));return!!(r!==s&&a!==o||0===r&&wh(e,i,t)||0===s&&wh(e,n,t)||0===a&&wh(i,e,n)||0===o&&wh(i,t,n))}function wh(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 Ch(e){return e>0?1:e<0?-1:0}function Sh(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 Mh(e,t){const i=new Ih(e.i,e.x,e.y),n=new Ih(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 Eh(e,t,i,n){const r=new Ih(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 Th(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 Ih(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 Ph{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 Ph.area(e)<0}static triangulateShape(e,t){const i=[],n=[],r=[];Dh(e),Rh(i,e);let s=e.length;t.forEach(Dh);for(let e=0;e<t.length;e++)n.push(s),s+=t[e].length,Rh(i,t[e]);const a=sh(i,n);for(let e=0;e<a.length;e+=3)r.push(a.slice(e,e+3));return r}}function Dh(e){const t=e.length;t>2&&e[t-1].equals(e[0])&&e.pop()}function Rh(e,t){for(let i=0;i<t.length;i++)e.push(t[i].x),e.push(t[i].y)}class Bh extends ur{constructor(e=new rh([new Ht(.5,.5),new Ht(-.5,.5),new Ht(-.5,-.5),new Ht(.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:Lh;let f,A,y,v,_,b=!1;m&&(f=m.getSpacedPoints(o),b=!0,c=!1,A=m.computeFrenetFrames(o,!1),y=new wi,v=new wi,_=new wi),c||(p=0,h=0,d=0,u=0);const x=e.extractPoints(a);let w=x.shape;const C=x.holes;if(!Ph.isClockWise(w)){w=w.reverse();for(let e=0,t=C.length;e<t;e++){const t=C[e];Ph.isClockWise(t)&&(C[e]=t.reverse())}}const S=Ph.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 Ht(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 Ht(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);k(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 N(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 k(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];N(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];N(i[0]+t,i[1]+t,i[2]+t)}}else{for(let e=0;e<I;e++){const t=S[e];N(t[2],t[1],t[0])}for(let e=0;e<I;e++){const t=S[e];N(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 rr(n,3)),this.setAttribute("uv",new rr(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 Qc[n.type]).fromJSON(n)),new Bh(i,e.options)}}const Lh={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 Ht(s,a),new Ht(o,l),new Ht(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 Ht(a,1-l),new Ht(c,1-d),new Ht(u,1-m),new Ht(g,1-A)]:[new Ht(o,1-l),new Ht(h,1-d),new Ht(p,1-m),new Ht(f,1-A)]}};class Oh extends Jc{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 Oh(e.radius,e.detail)}}class Uh extends Jc{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 Uh(e.radius,e.detail)}}class Fh extends ur{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 wi,p=new Ht;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 rr(o,3)),this.setAttribute("normal",new rr(l,3)),this.setAttribute("uv",new rr(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Fh(e.innerRadius,e.outerRadius,e.thetaSegments,e.phiSegments,e.thetaStart,e.thetaLength)}}class Nh extends ur{constructor(e=new rh([new Ht(0,.5),new Ht(-.5,-.5),new Ht(.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===Ph.isClockWise(c)&&(c=c.reverse());for(let e=0,t=h.length;e<t;e++){const t=h[e];!0===Ph.isClockWise(t)&&(h[e]=t.reverse())}const d=Ph.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 rr(n,3)),this.setAttribute("normal",new rr(r,3)),this.setAttribute("uv",new rr(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 Nh(i,e.curveSegments)}}class kh extends ur{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 wi,d=new wi,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 rr(p,3)),this.setAttribute("normal",new rr(m,3)),this.setAttribute("uv",new rr(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new kh(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class jh extends Jc{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 jh(e.radius,e.detail)}}class zh extends ur{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 wi,h=new wi,d=new wi;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 rr(a,3)),this.setAttribute("normal",new rr(o,3)),this.setAttribute("uv",new rr(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new zh(e.radius,e.tube,e.radialSegments,e.tubularSegments,e.arc)}}class Gh extends ur{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 wi,d=new wi,u=new wi,p=new wi,m=new wi,g=new wi,f=new wi;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 rr(o,3)),this.setAttribute("normal",new rr(l,3)),this.setAttribute("uv",new rr(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Gh(e.radius,e.tube,e.tubularSegments,e.radialSegments,e.p,e.q)}}class Qh extends ur{constructor(e=new zc(new wi(-1,-1,0),new wi(-1,1,0),new wi(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 wi,o=new wi,l=new Ht;let c=new wi;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 rr(h,3)),this.setAttribute("normal",new rr(d,3)),this.setAttribute("uv",new rr(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 Qh((new Qc[e.path.type]).fromJSON(e.path),e.tubularSegments,e.radius,e.radialSegments,e.closed)}}class Vh extends ur{constructor(e=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:e},null!==e){const t=[],i=new Set,n=new wi,r=new wi;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===Hh(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===Hh(n,r,i)&&(t.push(n.x,n.y,n.z),t.push(r.x,r.y,r.z))}}this.setAttribute("position",new rr(t,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}}function Hh(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 Wh=Object.freeze({__proto__:null,BoxGeometry:Rr,CapsuleGeometry:qc,CircleGeometry:Xc,ConeGeometry:Kc,CylinderGeometry:Yc,DodecahedronGeometry:Zc,EdgesGeometry:nh,ExtrudeGeometry:Bh,IcosahedronGeometry:Oh,LatheGeometry:Wc,OctahedronGeometry:Uh,PlaneGeometry:is,PolyhedronGeometry:Jc,RingGeometry:Fh,ShapeGeometry:Nh,SphereGeometry:kh,TetrahedronGeometry:jh,TorusGeometry:zh,TorusKnotGeometry:Gh,TubeGeometry:Qh,WireframeGeometry:Vh});class qh extends Wn{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Qn(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 Xh extends Fr{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Yh extends Wn{constructor(e){super(),this.isMeshStandardMaterial=!0,this.defines={STANDARD:""},this.type="MeshStandardMaterial",this.color=new Qn(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 Qn(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ot,this.normalScale=new Ht(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 hn,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 Kh extends Yh{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 Ht(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return kt(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 Qn(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 Qn(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Qn(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=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 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.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 Jh extends Wn{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Qn(16777215),this.specular=new Qn(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Qn(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ot,this.normalScale=new Ht(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hn,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 Zh extends Wn{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Qn(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Qn(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ot,this.normalScale=new Ht(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 $h extends Wn{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ot,this.normalScale=new Ht(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 ed extends Wn{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Qn(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Qn(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ot,this.normalScale=new Ht(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new hn,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 td extends Wn{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Qn(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=ot,this.normalScale=new Ht(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 id extends tc{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 nd(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 rd(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function sd(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 ad(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 od(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 ld={convertArray:nd,isTypedArray:rd,getKeyframeOrder:sd,sortedArray:ad,flattenJSON:od,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=nd(l,t.times.constructor),t.values=nd(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 xi).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)xi.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 cd{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)break e;{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}}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 hd extends cd{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:tt,endingEnd:tt}}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 it:r=e,a=2*t-i;break;case nt: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 it:s=e,o=2*i-t;break;case nt: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 dd extends cd{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 ud extends cd{constructor(e,t,i,n){super(e,t,i,n)}interpolate_(e){return this.copySampleValue_(e-1)}}class pd{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=nd(t,this.TimeBufferType),this.values=nd(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:nd(e.times,Array),values:nd(e.values,Array)};const t=e.getInterpolation();t!==e.DefaultInterpolation&&(i.interpolation=t)}return i.type=e.ValueTypeName,i}InterpolantFactoryMethodDiscrete(e){return new ud(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new dd(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new hd(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case Ze:t=this.InterpolantFactoryMethodDiscrete;break;case $e:t=this.InterpolantFactoryMethodLinear;break;case et: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 Ze;case this.InterpolantFactoryMethodLinear:return $e;case this.InterpolantFactoryMethodSmooth:return et}}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&&rd(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()===et,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}}pd.prototype.TimeBufferType=Float32Array,pd.prototype.ValueBufferType=Float32Array,pd.prototype.DefaultInterpolation=$e;class md extends pd{}md.prototype.ValueTypeName="bool",md.prototype.ValueBufferType=Array,md.prototype.DefaultInterpolation=Ze,md.prototype.InterpolantFactoryMethodLinear=void 0,md.prototype.InterpolantFactoryMethodSmooth=void 0;class gd extends pd{}gd.prototype.ValueTypeName="color";class fd extends pd{}fd.prototype.ValueTypeName="number";class Ad extends cd{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)xi.slerpFlat(r,0,s,l-a,s,l,o);return r}}class yd extends pd{InterpolantFactoryMethodLinear(e){return new Ad(this.times,this.values,this.getValueSize(),e)}}yd.prototype.ValueTypeName="quaternion",yd.prototype.DefaultInterpolation=$e,yd.prototype.InterpolantFactoryMethodSmooth=void 0;class vd extends pd{}vd.prototype.ValueTypeName="string",vd.prototype.ValueBufferType=Array,vd.prototype.DefaultInterpolation=Ze,vd.prototype.InterpolantFactoryMethodLinear=void 0,vd.prototype.InterpolantFactoryMethodSmooth=void 0;class _d extends pd{}_d.prototype.ValueTypeName="vector";class bd{constructor(e="",t=-1,i=[],n=rt){this.name=e,this.tracks=i,this.duration=t,this.blendMode=n,this.uuid=Nt(),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(xd(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(pd.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=sd(a);a=ad(a,1,l),o=ad(o,1,l),!n&&0===a[0]&&(a.push(r),o.push(o[0])),s.push(new fd(".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=[];od(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 fd(".morphTargetInfluence["+i+"]",e,s))}o=e.length*s}else{const s=".bones["+t[e].name+"]";i(_d,s+".position",r,"pos",n),i(yd,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 xd(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 fd;case"vector":case"vector2":case"vector3":case"vector4":return _d;case"color":return gd;case"quaternion":return yd;case"bool":case"boolean":return md;case"string":return vd}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}(e.type);if(void 0===e.times){const t=[],i=[];od(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 wd={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 Cd{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 Sd=new Cd;class Md{constructor(e){this.manager=void 0!==e?e:Sd,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}}Md.DEFAULT_MATERIAL_NAME="__DEFAULT";const Ed={};class Td extends Error{constructor(e,t){super(e),this.response=t}}class Id extends Md{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?wd.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!==Ed[e])return void Ed[e].push({onLoad:t,onProgress:i,onError:n});Ed[e]=[],Ed[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=Ed[e],n=t.body.getReader(),r=t.headers.get("Content-Length")||t.headers.get("X-File-Size"),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()}}))}()}});return new Response(l)}throw new Td(`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&&wd.add(e,t,this.responseType);const i=Ed[e];delete Ed[e];for(let e=0,n=i.length;e<n;e++){const n=i[e];n.onLoad&&n.onLoad(t)}})).catch((t=>{const i=Ed[e];if(void 0===i)throw this.manager.itemError(e),t;delete Ed[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 Pd extends Md{constructor(e){super(e)}load(e,t,i,n){const r=this,s=[],a=new _c,o=new Id(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 Dd extends Md{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=wd.get(e);if(void 0!==a)return s.manager.itemStart(e),setTimeout((function(){t&&t(a),s.manager.itemEnd(e)}),0),a;const o=Jt("img");function l(){h(),wd.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),wd.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 Id(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"})),wd.add(e,t,"blob"),o.src=URL.createObjectURL(t)}),i,(e=>{h(),n&&n(e)}))})),o}}class Rd extends Md{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new Ml,a=new Id(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 Bd extends Md{constructor(e){super(e)}load(e,t,i,n){const r=new mi,s=new Dd(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 Ld extends En{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Qn(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()),t}}class Od extends Ld{constructor(e,t,i){super(e,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(En.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Qn(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}const Ud=new $i,Fd=new wi,Nd=new wi;class kd{constructor(e){this.camera=e,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Ht(512,512),this.map=null,this.mapPass=null,this.matrix=new $i,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new $r,this._frameExtents=new Ht(1,1),this._viewportCount=1,this._viewports=[new Ai(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,i=this.matrix;Fd.setFromMatrixPosition(e.matrixWorld),t.position.copy(Fd),Nd.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Nd),t.updateMatrixWorld(),Ud.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Ud),i.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),i.multiply(Ud)}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.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 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 jd extends kd{constructor(){super(new Gr(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){const t=this.camera,i=2*Ft*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 zd extends Ld{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(En.DEFAULT_UP),this.updateMatrix(),this.target=new En,this.distance=i,this.angle=n,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new jd}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 Gd=new $i,Qd=new wi,Vd=new wi;class Hd extends kd{constructor(){super(new Gr(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Ht(4,2),this._viewportCount=6,this._viewports=[new Ai(2,1,1,1),new Ai(0,1,1,1),new Ai(3,1,1,1),new Ai(1,1,1,1),new Ai(3,0,1,1),new Ai(1,0,1,1)],this._cubeDirections=[new wi(1,0,0),new wi(-1,0,0),new wi(0,0,1),new wi(0,0,-1),new wi(0,1,0),new wi(0,-1,0)],this._cubeUps=[new wi(0,1,0),new wi(0,1,0),new wi(0,1,0),new wi(0,1,0),new wi(0,0,1),new wi(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()),Qd.setFromMatrixPosition(e.matrixWorld),i.position.copy(Qd),Vd.copy(i.position),Vd.add(this._cubeDirections[t]),i.up.copy(this._cubeUps[t]),i.lookAt(Vd),i.updateMatrixWorld(),n.makeTranslation(-Qd.x,-Qd.y,-Qd.z),Gd.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Gd)}}class Wd extends Ld{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 Hd}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 qd extends kd{constructor(){super(new fs(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Xd extends Ld{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(En.DEFAULT_UP),this.updateMatrix(),this.target=new En,this.shadow=new qd}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class Yd extends Ld{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Kd extends Ld{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 Jd{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new wi)}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 Zd extends Ld{constructor(e=new Jd,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 $d extends Md{constructor(e){super(e),this.textures={}}load(e,t,i,n){const r=this,s=new Id(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?dt:void 0,r=$d.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 Qn).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.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 Qn).setHex(s.value,n);break;case"v2":r.uniforms[t].value=(new Ht).fromArray(s.value);break;case"v3":r.uniforms[t].value=(new wi).fromArray(s.value);break;case"v4":r.uniforms[t].value=(new Ai).fromArray(s.value);break;case"m3":r.uniforms[t].value=(new Wt).fromArray(s.value);break;case"m4":r.uniforms[t].value=(new $i).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 Ht).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 Ht).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:qh,SpriteMaterial:Ko,RawShaderMaterial:Xh,ShaderMaterial:Fr,PointsMaterial:uc,MeshPhysicalMaterial:Kh,MeshStandardMaterial:Yh,MeshPhongMaterial:Jh,MeshToonMaterial:Zh,MeshNormalMaterial:$h,MeshLambertMaterial:ed,MeshDepthMaterial:Eo,MeshDistanceMaterial:To,MeshBasicMaterial:Xn,MeshMatcapMaterial:td,LineDashedMaterial:id,LineBasicMaterial:tc,Material:Wn}[e]}}class eu{static decodeText(e){if(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 tu extends ur{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 iu extends Md{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new Id(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=Kt(r.type,s),o=new qo(a,r.stride);return o.uuid=r.uuid,t[n]=o,o}const r=e.isInstancedBufferGeometry?new tu:new ur,s=e.data.index;if(void 0!==s){const e=Kt(s.type,s.array);r.setIndex(new tr(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 Yo(t,i.itemSize,i.offset,i.normalized)}else{const e=Kt(i.type,i.array);s=new(i.isInstancedBufferAttribute?Pl:tr)(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 Yo(t,r.itemSize,r.offset,r.normalized)}else{const e=Kt(r.type,r.array);a=new tr(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 wi;void 0!==c.center&&e.fromArray(c.center),r.boundingSphere=new Vi(e,c.radius)}return e.name&&(r.name=e.name),e.userData&&(r.userData=e.userData),r}}class nu extends Md{constructor(e){super(e)}load(e,t,i,n){const r=this,s=""===this.path?eu.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||s;const a=new Id(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?eu.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||i;const n=new Id(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),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),o}parseShapes(e){const t={};if(void 0!==e)for(let i=0,n=e.length;i<n;i++){const n=(new rh).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 Il).fromJSON(e[t],n);i[r.uuid]=r}return i}parseGeometries(e,t){const i={};if(void 0!==e){const n=new iu;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 Wh?s=Wh[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 $d;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=bd.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:Kt(e.type,e.data),width:e.width,height:e.height,complete:!0}:null}if(void 0!==e&&e.length>0){const i=new Cd(t);r=new Dd(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 Ml(i.data,i.width,i.height)))}n[i.uuid]=new di(e)}else{const e=s(i.url);n[i.uuid]=new di(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:Kt(e.type,e.data),width:e.width,height:e.height,complete:!0}:null}if(void 0!==e&&e.length>0){n=new Dd(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 Ml(n.data,n.width,n.height)))}i[n.uuid]=new di(e)}else{const e=await r(n.url);i[n.uuid]=new di(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 Hr,6===o.length&&(l.needsUpdate=!0)):(l=o&&o.data?new Ml:new mi,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,ru)),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],su),l.wrapT=i(s.wrap[1],su)),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,au)),void 0!==s.magFilter&&(l.magFilter=i(s.magFilter,au)),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?dt: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 Wo,void 0!==e.background&&(Number.isInteger(e.background)?s.background=(new Qn).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 Ho(e.fog.color,e.fog.near,e.fog.far):"FogExp2"===e.fog.type&&(s.fog=new Vo(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 Gr(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 fs(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 Yd(e.color,e.intensity);break;case"DirectionalLight":s=new Xd(e.color,e.intensity);break;case"PointLight":s=new Wd(e.color,e.intensity,e.distance,e.decay);break;case"RectAreaLight":s=new Kd(e.color,e.intensity,e.width,e.height);break;case"SpotLight":s=new zd(e.color,e.intensity,e.distance,e.angle,e.penumbra,e.decay);break;case"HemisphereLight":s=new Od(e.color,e.groundColor,e.intensity);break;case"LightProbe":s=(new Zd).fromJSON(e);break;case"SkinnedMesh":h=o(e.geometry),d=l(e.material),s=new Cl(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 Pr(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 Nl(h,d,t),s.instanceMatrix=new Pl(new Float32Array(i.array),16),void 0!==n&&(s.instanceColor=new Pl(new Float32Array(n.array),n.itemSize));break;case"BatchedMesh":h=o(e.geometry),d=l(e.material),s=new ec(e.maxGeometryCount,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 Mi;t.min.fromArray(e.boxMin),t.max.fromArray(e.boxMax);const i=new Vi;return i.radius=e.sphereRadius,i.center.fromArray(e.sphereCenter),{boxInitialized:e.boxInitialized,box:t,sphereInitialized:e.sphereInitialized,sphere:i}})),s._maxGeometryCount=e.maxGeometryCount,s._maxVertexCount=e.maxVertexCount,s._maxIndexCount=e.maxIndexCount,s._geometryInitialized=e.geometryInitialized,s._geometryCount=e.geometryCount,s._matricesTexture=c(e.matricesTexture.uuid);break;case"LOD":s=new ml;break;case"Line":s=new oc(o(e.geometry),l(e.material));break;case"LineLoop":s=new dc(o(e.geometry),l(e.material));break;case"LineSegments":s=new hc(o(e.geometry),l(e.material));break;case"PointCloud":case"Points":s=new Ac(o(e.geometry),l(e.material));break;case"Sprite":s=new hl(l(e.material));break;case"Group":s=new Lo;break;case"Bone":s=new Sl;break;default:s=new En}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.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)}}))}}const ru={UVMapping:ce,CubeReflectionMapping:he,CubeRefractionMapping:de,EquirectangularReflectionMapping:ue,EquirectangularRefractionMapping:pe,CubeUVReflectionMapping:me},su={RepeatWrapping:ge,ClampToEdgeWrapping:fe,MirroredRepeatWrapping:Ae},au={NearestFilter:ye,NearestMipmapNearestFilter:ve,NearestMipmapLinearFilter:_e,LinearFilter:be,LinearMipmapNearestFilter:xe,LinearMipmapLinearFilter:we};class ou extends Md{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=wd.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 wd.add(e,t,"blob"),createImageBitmap(t,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(i){return wd.add(e,i),t&&t(i),r.manager.itemEnd(e),i})).catch((function(t){n&&n(t),wd.remove(e),r.manager.itemError(e),r.manager.itemEnd(e)}));wd.add(e,o),r.manager.itemStart(e)}}let lu;class cu{static getContext(){return void 0===lu&&(lu=new(window.AudioContext||window.webkitAudioContext)),lu}static setContext(e){lu=e}}const hu=new $i,du=new $i,uu=new $i;class pu{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=mu(),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=mu();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function mu(){return(typeof performance>"u"?Date:performance).now()}const gu=new wi,fu=new xi,Au=new wi,yu=new wi;class vu extends En{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 wi,bu=new xi,xu=new wi,wu=new wi;class Cu{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){xi.slerpFlat(e,t,e,t,e,i,n)}_slerpAdditive(e,t,i,n,r){const s=this._workIndex*r;xi.multiplyQuaternionsFlat(e,s,e,t,e,i),xi.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 Su="\\[\\]\\.:\\/",Mu=new RegExp("["+Su+"]","g"),Eu="[^"+Su+"]",Tu="[^"+Su.replace("\\.","")+"]",Iu=/((?:WC+[\/:])*)/.source.replace("WC",Eu),Pu=/(WCOD+)?/.source.replace("WCOD",Tu),Du=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Eu),Ru=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Eu),Bu=new RegExp("^"+Iu+Pu+Du+Ru+"$"),Lu=["material","materials","bones","map"];class Ou{constructor(e,t,i){this.path=t,this.parsedPath=i||Ou.parseTrackName(t),this.node=Ou.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 Ou.Composite(e,t,i):new Ou(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(Mu,"")}static parseTrackName(e){const t=Bu.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!==Lu.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=Ou.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}}Ou.Composite=class{constructor(e,t,i){const n=i||Ou.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()}},Ou.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Ou.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Ou.prototype.GetterByBindingType=[Ou.prototype._getValue_direct,Ou.prototype._getValue_array,Ou.prototype._getValue_arrayElement,Ou.prototype._getValue_toArray],Ou.prototype.SetterByBindingTypeAndVersioning=[[Ou.prototype._setValue_direct,Ou.prototype._setValue_direct_setNeedsUpdate,Ou.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Ou.prototype._setValue_array,Ou.prototype._setValue_array_setNeedsUpdate,Ou.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Ou.prototype._setValue_arrayElement,Ou.prototype._setValue_arrayElement_setNeedsUpdate,Ou.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Ou.prototype._setValue_fromArray,Ou.prototype._setValue_fromArray_setNeedsUpdate,Ou.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class Uu{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:tt,endingEnd:tt};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=Je,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===Ke){-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=it,n.endingEnd=it):(n.endingStart=e?this.zeroSlopeAtStart?it:tt:nt,n.endingEnd=t?this.zeroSlopeAtEnd?it:tt:nt)}_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 Fu=new Float32Array(1);class Nu extends Bt{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 Cu(Ou.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 dd(new Float32Array(2),new Float32Array(2),1,Fu),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?bd.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:rt),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 Uu(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?bd.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 ku{constructor(e){this.value=e}clone(){return new ku(void 0===this.value.clone?this.value:this.value.clone())}}let ju=0;class zu extends qo{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 Gu=new $i;class Qu{constructor(e,t,i=0,n=1/0){this.ray=new Zi(e,t),this.near=i,this.far=n,this.camera=null,this.layers=new dn,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 Gu.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(Gu),this}intersectObject(e,t=!0,i=[]){return Hu(e,this,i,t),i.sort(Vu),i}intersectObjects(e,t=!0,i=[]){for(let n=0,r=e.length;n<r;n++)Hu(e[n],this,i,t);return i.sort(Vu),i}}function Vu(e,t){return e.distance-t.distance}function Hu(e,t,i,n){if(e.layers.test(t.layers)&&e.raycast(t,i),!0===n){const n=e.children;for(let e=0,r=n.length;e<r;e++)Hu(n[e],t,i,!0)}}class Wu{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(kt(t/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}}class qu{constructor(e,t,i,n){qu.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 Xu=new Ht;class Yu{constructor(e=new Ht(1/0,1/0),t=new Ht(-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=Xu.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,Xu).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 Ku=new wi,Ju=new wi;class Zu{constructor(e=new wi,t=new wi){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){Ku.subVectors(e,this.start),Ju.subVectors(this.end,this.start);const i=Ju.dot(Ju);let n=Ju.dot(Ku)/i;return t&&(n=kt(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 $u=new wi;const ep=new wi,tp=new $i,ip=new $i;function np(e){const t=[];!0===e.isBone&&t.push(e);for(let i=0;i<e.children.length;i++)t.push.apply(t,np(e.children[i]));return t}const rp=new wi,sp=new Qn,ap=new Qn;const op=new wi,lp=new wi,cp=new wi;const hp=new wi,dp=new Nr;function up(e,t,i,n,r,s,a){hp.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],hp.x,hp.y,hp.z)}}const pp=new Mi;const mp=new wi;let gp,fp;typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"163"}})),typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="163");
/**
 * @license
 * ts-browser-helpers v0.19.4
 * Copyright 2022-2025 repalash <palash@shaders.app>
 * MIT License
 * See ./dependencies.txt for bundled third-party dependencies and licenses.
 */
let Ap=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 yp(e){return new Promise((t=>setTimeout(t,Math.max(0,e))))}function vp(){return(typeof performance>"u"?Date:performance).now()}class _p extends Ap{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=vp();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=vp();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:vp()},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=vp();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 bp{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)}}
/* @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */const xp=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)}};xp.SETTLING_TIME=1e4,xp.MIN_DECAY_MILLISECONDS=.001,xp.DECAY_MILLISECONDS=50;let wp=xp;function Cp(){const e=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");return e.style.display="block",e}function Sp({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 Mp(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 Ep(e,t=document.head){const i=document.createElement("style");return i.type="text/css",i.innerText=e,t?.appendChild(i),i}function Tp(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 Ip(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 Pp(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 Dp={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function Rp(e,t){return new Dp[e](t)}function Bp(e){return e.replace(/\w\S*/g,(function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()}))}function Lp(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 Op(e){return RegExp.escape?RegExp.escape(e):e.replace(/[.*+?^${}()|[\]/\\=!:]/g,"\\$&")}function Up(e,t,i){return e.replace(new RegExp(Op(t),"g"),i)}function Fp(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 Np=(e,...t)=>String.raw({raw:e},...t),kp=(e,...t)=>String.raw({raw:e},...t),jp=(e,...t)=>{let i=String.raw({raw:e},...t);return i=Up(i,"%","%25"),i=Up(i,"> <","><"),i=Up(i,"; }",";}"),i=Up(i,"<","%3c"),i=Up(i,">","%3e"),i=Up(i,'"',"'"),i=Up(i,"#","%23"),i=Up(i,"{","%7b"),i=Up(i,"}","%7d"),i=Up(i,"|","%7c"),i=Up(i,"^","%5e"),i=Up(i,"`","%60"),i=Up(i,"@","%40"),i=Up(i,"&","&amp;"),i=Up(i,"\n","%0A"),"data:image/svg+xml;charset=UTF-8,"+i};function zp(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 Gp(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 Qp(e,t){return zp(e,t??e.name)}async function Vp(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 Hp(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}function Wp(e,t){let i;do{i=Object.getOwnPropertyDescriptor(e,t)}while(!i&&(e=Object.getPrototypeOf(e)));return i}function qp(e,t,i=!0,n=!1){const r=Wp(e,t);return!(null==r||!r.set)||i&&!1!==r?.writable&&void 0===r?.get||n&&!r}function Xp(e,t,i,n=!0,r=!1){return!(!e||!qp(e,t,n,r))&&(e[t]=i,!0)}function Yp(e,...t){return"function"==typeof e&&(e=e(...t)),e}function Kp(e,t,i){for(const n of i){const i=e[n];void 0!==i&&Xp(t,n,i,!0)}return t}function Jp(e,t){for(const i of t)if(!e.includes(i))return!1;return!0}function Zp(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1}function $p(e,t){return function(...i){return e(...i),t&&t.call(this,...i)}}function em(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 tm(e,t){return Object.hasOwn?Object.hasOwn(e,t):e.hasOwnProperty(t)}function im(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 nm(e,t){return Object.fromEntries(Object.entries(e).map((e=>t(e))))}const rm={priority:1/0,serialize:(e,t)=>nm(e,(([e,i])=>[e,am.Serialize(i,t,!1)])),deserialize:(e,t,i)=>Object.assign(t||{},nm(e,(([e,n])=>[e,am.Deserialize(n,t?.[e],i,!1)]))),isType:e=>(e.constructor||Object)===Object},sm=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=Zp(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=e[t.uuid];if(!r)return console.warn(`Serialization: Resource ${t.resource} with uuid ${t.uuid} not found`),i;if("object"==typeof(t=r)&&(t.__useCount=t.__useCount?t.__useCount+1:1),i===t)return i;if(t&&"object"==typeof t){if((t.constructor||Object)!==Object)return i&&console.warn("Serialization: replacing object",i,"with deserialized object",t),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!==rm)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 rm.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&&Xp(i,a,o,!0)}s=Object.getPrototypeOf(s)}return i}};sm.TypeMap=new Map,sm.SerializableClasses=new Map,sm.Serializers=[{priority:0,isType:e=>Array.isArray(e),serialize:(e,t)=>e.map((e=>sm.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?sm.Deserialize(n,t[r],i,!1):sm.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}},rm];let am=sm;const om=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)}};om.methodMap=new WeakMap;let lm=om;function cm(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&&lm.callFunction(e,this,a)}};if(r)return tm(r,"value")&&delete r.value,tm(r,"writable")&&delete r.writable,tm(r,"initializer")&&delete r.initializer,Object.assign(r,s);Object.defineProperty(i,n,s)}}function hm(e,t="void"){if(!e)throw new Error("onChange: fnKey is undefined, make sure the function exists or provide a string");return cm(e,t)}function dm(e,t="object"){if(!e)throw new Error("onChange: fnKey is undefined, make sure the function exists or provide a string");return cm(e,t)}function um(e){return cm(((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 pm(e){return(t,i)=>{const n=t.constructor;if(n===Object)throw new Error("All properties in an object are serialized by default");am.TypeMap.has(n)||am.TypeMap.set(n,[]),am.TypeMap.get(n).push([e||i,i])}}function mm(e){return t=>(t=class extends t{constructor(){super(...arguments),this.serializableClassId=e}},am.SerializableClasses.set(e,t),t)}async function gm(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 fm(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 Am(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 ym(e,t=8192,i=!1,n="image/png"){if(!e.width&&!e.videoWidth||!e.height&&!e.videoHeight)return"";const r=Am(e,t,!1),s=r.toDataURL(n);return r.remove(),i&&e instanceof ImageBitmap&&e.close(),s}async function vm(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 _m(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 bm(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 xm=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`,wm=async(e,t)=>_m(await Mp(e),t),Cm=async(e,t)=>await wm(e,t).then((e=>e.toDataURL("image/png"))),Sm=async e=>Gp(await(await fetch(e)).blob());async function Mm(e,t=Sm){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 Em(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?jp(s):s}function Tm(e,t){return Math.abs(e)>Math.abs(t)?e:t}function Im(e,t,i){return e&~(1<<t)|(i?1:0)<<t}function Pm(){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 Dm(e,t=null){var i;return null!=(i=window?.location)&&i.href?new URL(window.location.href).searchParams.get(e)??t:t}const Rm={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 Bm=null;function Lm(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">${Fp(e)}</span></a>`}))}(Fp(e)).replace(/\n/g,"<br>")}function Om(e){return`\n${e.title?`<div class="dialog-title">${Fp(e.title)}</div>`:""}\n<div class="dialog-message">${Lm(e.message)}</div>\n`}const Um=e=>`\n<div class="dialog-content">\n${Om(e)}\n</div>\n<div class="dialog-footer">\n    ${e.ok&&`<button class="dialog-button dialog-ok">${Fp(e.ok)}</button>`||""}\n</div>\n`,Fm=e=>`\n<div class="dialog-content">\n${Om(e)}\n</div>\n<div class="dialog-footer">\n    ${e.cancel&&`<button class="dialog-button dialog-cancel">${Fp(e.cancel)}</button>`||""}\n    ${e.ok&&`<button class="dialog-button dialog-ok">${Fp(e.ok)}</button>`||""}\n</div>\n`,Nm=e=>`\n<div class="dialog-content">\n    ${Om(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">${Fp(e.cancel)}</button>`||""}\n    ${e.ok&&`<button class="dialog-button dialog-ok">${Fp(e.ok)}</button>`||""}\n</div>\n`;function km(e,{message:t,...i}){Bm||(Bm=document.createElement("style"),Bm.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(Bm));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 jm={alert:async e=>{const t=km(Um,{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=km(Nm,{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=km(Fm,{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 zm(e){return null===e||"object"!=typeof e?e:Array.isArray(e)?e.map(zm):e._ui_isPrimitive||"function"!=typeof e.clone||!1===e._ui_primitiveClone?e:e.clone()}function Gm(e,t){return null===e||"object"!=typeof e?e===t:Array.isArray(e)?Array.isArray(t)&&e.length===t.length&&e.every(((e,i)=>Gm(e,t[i]))):e._ui_isPrimitive||"function"!=typeof e.equals||!1===e._ui_primitiveEquals?e===t:!!e.equals(t)}function Qm(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]=Qm(e[i],t[i]);for(let i=e.length;i<t.length;i++)e.push(zm(t[i]))}else{for(let i=0;i<t.length;i++)e[i]=Qm(e[i],t[i]);e.length=t.length}return e}return zm(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?zm(t):(e.copy(t),e)}function Vm(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=zm(r.val),e.replaceLast(r)):a=!1}a||Gm(r.lastVal,r.val)||(r.val=zm(r.val),e.record(r))}function Hm(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=Gm(u,i),f=zm(u);p=g?!m:!h||Qm(u,i)!==u&&!Xp(h,d,i,!0,!0);const A=!p&&(m||!g);return a&&A&&e&&Vm(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 Wm(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 qm(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("data:")||e.startsWith("asset://")||e.startsWith("/")||e.startsWith("//")}const Xm={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"},Ym=class{};
/**
 * @license
 * uiconfig.js v0.3.1
 * Copyright 2022-2025 repalash <palash@shaders.app>
 * MIT License
 * See ./dependencies.txt for bundled third-party dependencies and licenses.
 */Ym.Map=new Map;let Km=Ym;function Jm(e,t,i,n,r=!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=$m(i,n,{},"folder",r):s&&(a={type:s,label:i,property:[e,t]})}return a&&!a.label&&(a.label=i),a}function Zm(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=Jm(e,n,n+"",t,!0);r&&i.push(r)}}return n.reverse().forEach((t=>{var n;null==(n=Km.Map.get(t))||n.forEach((({params:t,propKey:n,uiType:r})=>{let s;if(r||(s=()=>Jm(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 $m(e,t,i={},n="folder",r=!1){return{type:n,label:e,children:r?[()=>Zm(t)]:Zm(t),uuid:Pm(),...i}}function eg(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");Km.Map.has(n)||Km.Map.set(n,[]),e(t,i,Km.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 tg(e,t,i="panel"){return n=>class extends n{constructor(){super(...arguments),this.uiConfig=$m(Yp(e,this)||"",this,t||{},i)}}}function ig(e,t){return eg("monitor",{label:e,params:t})}function ng(e,t,i,n){return eg("slider",{label:e,bounds:t,stepSize:i,params:n})}function rg(e,t,i,n){return eg("vec",{label:e,bounds:t,stepSize:i,params:n})}function sg(e,t,i){return Array.isArray(t)&&"string"==typeof t[0]&&(t=t.map((e=>({label:e,value:e})))),eg("dropdown",{label:e,children:t,params:i})}function ag(e,t){return eg("button",{label:e,params:t})}function og(e,t){return eg("input",{label:e,params:t})}function lg(e,t){return eg("number",{label:e,params:t})}function cg(e,t){return eg("color",{label:e,params:t})}function hg(e,t){return eg("image",{label:e,params:t})}function dg(e,t){return eg("checkbox",{label:e,params:t})}function ug(e,t){return tg(e,t,"panel")}function pg(e,t){return tg(e,t,"folder")}const mg="UiConfigMethods_set",gg="UiConfigMethods_action";class fg{constructor(e){this._renderer=e,this.undoEditingWaitTime=2e3,this.undoPresets={[mg]:e=>{const t=()=>{var t,i;e.onUndoRedo&&e.onUndoRedo(e),null==(i=(t=e.uid).uiRefresh)||i.call(t,!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)}}},[gg]:e=>{const t=()=>{var t,i;e.onUndoRedo&&e.onUndoRedo(e),null==(i=(t=e.uid).uiRefresh)||i.call(t,!1)};return{undo:async()=>{await e.undo.call(e.target,...e.args),t()},redo:async()=>{await e.redo.call(e.target,...e.args),t()}}}}}getBinding(e,t=!0){let i=Yp(e.property,e);const n=Yp(e.path,e);if(void 0===i&&Object.hasOwn(e,"value")&&(i=[e,"value"]),void 0===i&&t&&(i=Yp(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}getRawValue(e){const[t,i]=this.getBinding(e);return t?t[i]:void 0}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?Gm(t,s)&&!i?void 0:Qm(t,s):zm(s)}dispatchOnChangeSync(e,t,...i){var n;const r=[{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(...r):Array.isArray(e.onChange)?e.onChange.flat().forEach((e=>"function"==typeof e&&e?.(...r))):e.onChange&&console.error("Invalid onChange type, must be a function or array of functions",e.onChange),null==(n=e.parentOnChange)||n.call(e,...r)}recordUndo(e){Vm(this._renderer.undoManager,e,mg,this.undoEditingWaitTime)}async performAction(e,t,i,n,r){var s,a,o;const l=()=>void 0===e?t(...i):t.call(e,...i);let c=await l();const h="function"==typeof c?c:null==(s=c?.undo)?void 0:s.bind(c),d="function"!=typeof c?null==(a=c?.action)?void 0:a.bind(c):null,u="function"==typeof c?l:(null==(o=c?.redo)?void 0:o.bind(c))??d;"function"==typeof d&&(c=await d()),"function"==typeof h&&this.recordUndo({type:"UiConfigMethods_action",uid:n,target:e,undo:h,redo:u,args:i,onUndoRedo:r})}async setValue(e,t,i,n,r=!0){return this.runAtEvent(e,(()=>{const s=this.getBinding(e),a=Hm(this._renderer.undoManager,s,t,i,e,mg,r,this.undoEditingWaitTime,!1,void 0);return!(!a.undoable&&!n)&&(this.dispatchOnChangeSync(e,{...i,...a}),!0)}))}async dispatchOnChange(e,t){return this.runAtEvent(e,(()=>{this.dispatchOnChangeSync(e,t)}))}getLabel(e){var t;return(Yp(e.label,e)??(null==(t=this.getBinding(e))?void 0:t[1]))+""}getChildren(e){return(Yp(e.children,e)??[]).map((e=>Yp(e))).flat(2).filter((e=>e))}async clickButton(e,t){return this.runAtEvent(e,(async()=>{const i=this.getBinding(e,!1),n=i[0],r=i[1],s=!1===Yp(e.sendArgs,e)?[]:t?.args??[],a=[];if(n){const e=n[r]??n.value;"function"==typeof e?a.push([e,n]):e&&console.warn("Invalid action type for button",e)}"function"==typeof e.onClick&&a.push([e.onClick,e]);for(const[t,i]of a)await this.performAction(i,t,s,e);await this.dispatchOnChange(e,{})}))}async runAtEvent(e,t){const i=Yp(e.dispatchMode,e)??"postFrame";return"immediate"===i?t():new Promise((e=>{const n=async()=>{this._renderer.removeEventListener(i,n),e(await t())};this._renderer.addEventListener(i,n)}))}initUiConfig(e){e&&(e.type||(console.warn("No type for config",e),e.type="input"),e.uuid||(e.uuid=Pm()),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))}getBounds(e,t=!1){const i=Yp(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:Yp(e.stepSize)||(t?.01:Math.pow(10,Math.floor(Math.log10((n-r)/100))))}}}class Ag extends Ap{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 fg(this),this.undoManager=!1===i?void 0:i||new bp({bindHotKeys:!0,limit:1e3,debug:null!==Dm("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=vp(),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){var i,n;e&&(e.uiRef&&(t&&(null==(n=(i=e.uiRef).dispose)||n.call(i)),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?yp(n).then((()=>this._refreshUiConfigObject(t))):this._addToRefreshQueue(e,t,n)}_flattenUiConfig(e,t){var i;return t=t??[],!e||!e.uiRef||(t.push(e),"function"==typeof e.children)||null==(i=e.children)||i.forEach((e=>{"function"!=typeof e&&e&&(Array.isArray(e)?e.forEach((e=>t=this._flattenUiConfig(e,t))):t=this._flattenUiConfig(e,t))})),t}}var yg=Object.defineProperty,vg=Object.getOwnPropertyDescriptor,_g=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?vg(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&&yg(t,i,s),s};e.ViewerTimeline=class extends Bt{constructor(){super(...arguments),this._time=0,this.delta=0,this.endTime=2,this.resetOnEnd=!0,this.stopOnEnd=!1,this.running=!1,this._clock=new pu(!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"})}},_g([og("Time",{readOnly:!0})],e.ViewerTimeline.prototype,"time",1),_g([og("Delta",{readOnly:!0})],e.ViewerTimeline.prototype,"delta",2),_g([og("Max Time"),pm(),um("endTimeChanged")],e.ViewerTimeline.prototype,"endTime",2),_g([dg("Reset on End"),pm(),um("resetOnEndChanged")],e.ViewerTimeline.prototype,"resetOnEnd",2),_g([dg("Stop on End"),pm(),um("stopOnEndChanged")],e.ViewerTimeline.prototype,"stopOnEnd",2),_g([og("Running",{readOnly:!0})],e.ViewerTimeline.prototype,"running",2),_g([ag("Start")],e.ViewerTimeline.prototype,"start",1),_g([ag("Stop")],e.ViewerTimeline.prototype,"stop",1),_g([ag("Reset")],e.ViewerTimeline.prototype,"reset",1),e.ViewerTimeline=_g([mm("ViewerTimeline"),pg("Timeline")],e.ViewerTimeline);var bg,xg={exports:{}};var wg,Cg=(bg||(bg=1,xg.exports=((wg=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 wg.Panel("FPS","#0ff","#002")),l=e(new wg.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var c=e(new wg.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))}}},wg)),xg.exports);const Sg=(Mg=Cg)&&Mg.__esModule&&Object.prototype.hasOwnProperty.call(Mg,"default")?Mg.default:Mg;var Mg;class Eg{constructor(e){this._stats=new Sg,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 Tg=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}};Tg.Element=void 0,Tg._inited=!1;let Ig=Tg;const Pg=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()));this._loadNextEntry(new Map,e,t)}else 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})}};Pg.USE_DATA_TRANSFER_ITEMS=!0;let Dg=Pg;const Rg={type:"change"},Bg={type:"start"},Lg={type:"end"},Og=new Zi,Ug=new Kr,Fg=Math.cos(70*Vt.DEG2RAD);class Ng extends Bt{constructor(e,t){super(),this.object=e,this.domElement=t,this.domElement.style.touchAction="none",this.enabled=!0,this.target=new wi,this.cursor=new wi,this.minDistance=1e-5,this.maxDistance=1/0,this.autoPushTarget=!0,this.autoPullTarget=!0,this.clampMax=new wi(1/0,1/0,1/0),this.clampMin=new wi(-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.getPolarAngle=function(){return a.phi},this.getAzimuthalAngle=function(){return a.theta},this.getDistance=function(){return this.object.position.distanceTo(this.target)},this.listenToKeyEvents=function(e){e.addEventListener("keydown",ie),this._domElementKeyEvents=e},this.stopListenToKeyEvents=function(){this._domElementKeyEvents.removeEventListener("keydown",ie),this._domElementKeyEvents=null},this.saveState=function(){i.target0.copy(i.target),i.position0.copy(i.object.position),i.zoom0=i.object.zoom},this.reset=function(){i.target.copy(i.target0),i.object.position.copy(i.position0),i.object.zoom=i.zoom0,i.object.updateProjectionMatrix(),i.dispatchEvent(Rg),i.update(),r=n.NONE},this.update=function(){const t=new wi,h=(new xi).setFromUnitVectors(e.up,new wi(0,1,0)),d=h.clone().invert(),u=new wi,p=new xi,m=new wi,g=2*Math.PI;return function(f=null){if(this.throttleUpdate&&this.throttleUpdate>=1&&Date.now()-0<1e3/this.throttleUpdate)return;const A=i.object.position;t.copy(A).sub(i.target),t.applyQuaternion(h),a.setFromVector3(t),i.autoRotate&&r===n.NONE&&B(function(e){return null!==e?2*Math.PI/60*i.autoRotateSpeed*e:2*Math.PI/60/60*i.autoRotateSpeed}(f)),i.enableDamping?(a.theta+=o.theta*i.dampingFactor,a.phi+=o.phi*i.dampingFactor):(a.theta+=o.theta,a.phi+=o.phi);let y=i.minAzimuthAngle,v=i.maxAzimuthAngle;isFinite(y)&&isFinite(v)&&(y<-Math.PI?y+=g:y>Math.PI&&(y-=g),v<-Math.PI?v+=g:v>Math.PI&&(v-=g),a.theta=y<=v?Math.max(y,Math.min(v,a.theta)):a.theta>(y+v)/2?Math.max(y,a.theta):Math.min(v,a.theta)),a.phi=Math.max(i.minPolarAngle,Math.min(i.maxPolarAngle,a.phi)),a.makeSafe(),!0===i.enableDamping?i.target.addScaledVector(c,i.dampingFactor):i.target.add(c),i.target.sub(i.cursor),i.target.clampLength(i.minTargetRadius,i.maxTargetRadius),i.target.add(i.cursor);let _=0,b=!1;if(i.zoomToCursor&&T||i.object.isOrthographicCamera)a.radius=z(a.radius);else{const e=a.radius;Math.abs(o.radius)>0&&(i.dollyZoom&&(i.object.zoom=Math.max(Math.max(i.minZoom,.1),Math.min(Math.min(i.maxZoom,20),i.object.zoom*(1+o.radius*(i.enableDamping?i.dampingFactor:1)))),i.object.updateProjectionMatrix(),(i.object.zoom>=Math.min(i.maxZoom,20)||i.object.zoom<=Math.max(i.minZoom,.1))&&(o.radius=0)),a.radius*=1+o.radius*(i.enableDamping?i.dampingFactor:1)),Math.abs(l-1)>1e-5&&(i.dollyZoom&&(i.object.zoom=Math.max(Math.max(i.minZoom,.1),Math.min(Math.min(i.maxZoom,20),i.object.zoom*l)),i.object.updateProjectionMatrix(),(i.object.zoom>=Math.min(i.maxZoom,20)||i.object.zoom<=Math.max(i.minZoom,.1))&&(l=1)),a.radius*=l),i.autoPushTarget&&a.radius<i.minDistance&&(_=i.minDistance-a.radius),i.autoPullTarget&&a.radius>i.maxDistance&&(_=i.maxDistance-a.radius),a.radius=z(a.radius),b=e!=a.radius}t.setFromSpherical(a),t.applyQuaternion(d),A.copy(i.target).add(t),i.target.add(t.normalize().multiplyScalar(-_)),A.clamp(i.clampMin,i.clampMax),i.target.clamp(i.clampMin,i.clampMax),i.object.lookAt(i.target);let x=!1;if(!0===i.enableDamping&&Math.abs(o.theta)+Math.abs(o.phi)+Math.abs(o.radius)+c.length()>.001?(o.theta*=1-i.dampingFactor,o.phi*=1-i.dampingFactor,o.radius*=1-i.dampingFactor,c.multiplyScalar(1-i.dampingFactor),x=!0):(o.set(0,0,0),c.set(0,0,0)),i.zoomToCursor&&T){let t=null;if(i.object.isPerspectiveCamera){const e=a.radius;t=a.radius*l,t=z(t);const n=e-t;i.object.position.addScaledVector(M,n),i.object.updateMatrixWorld(),b=!!n}else if(i.object.isOrthographicCamera){const e=new wi(E.x,E.y,0);e.unproject(i.object);const n=i.object.zoom;i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/l)),i.object.updateProjectionMatrix(),b=n!==i.object.zoom;const r=new wi(E.x,E.y,0);r.unproject(i.object),i.object.position.sub(r).add(e),i.object.updateMatrixWorld(),t=a.radius}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),i.zoomToCursor=!1;null!==t&&(this.screenSpacePanning?i.target.set(0,0,-1).transformDirection(i.object.matrix).multiplyScalar(t).add(i.object.position):(Og.origin.copy(i.object.position),Og.direction.set(0,0,-1).transformDirection(i.object.matrix),Math.abs(i.object.up.dot(Og.direction))<Fg?e.lookAt(i.target):(Ug.setFromNormalAndCoplanarPoint(i.object.up,i.target),Og.intersectPlane(Ug,i.target))))}else if(i.object.isOrthographicCamera){const e=i.object.zoom;i.object.zoom=Math.max(i.minZoom,Math.min(i.maxZoom,i.object.zoom/l)),e!==i.object.zoom&&(i.object.updateProjectionMatrix(),b=!0)}return l=1,T=!1,!!(b||x||u.distanceToSquared(i.object.position)>s||8*(1-p.dot(i.object.quaternion))>s||m.distanceToSquared(i.target)>s)&&(i.dispatchEvent(Rg),u.copy(i.object.position),p.copy(i.object.quaternion),m.copy(i.target),!0)}}(),this.stopDamping=function(){o.set(0,0,0),c.set(0,0,0)},this.dispose=function(){i.domElement.removeEventListener("contextmenu",re),i.domElement.removeEventListener("pointerdown",K),i.domElement.removeEventListener("pointercancel",Z),i.domElement.removeEventListener("wheel",$),i.domElement.removeEventListener("pointermove",J),i.domElement.removeEventListener("pointerup",Z),i.domElement.getRootNode().removeEventListener("keydown",ee,{capture:!0}),null!==i._domElementKeyEvents&&(i._domElementKeyEvents.removeEventListener("keydown",ie),i._domElementKeyEvents=null)};const i=this,n={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let r=n.NONE;const s=1e-6,a=new Wu,o=new Wu(0,0,0);let l=1;const c=new wi,h=new Ht,d=new Ht,u=new Ht,_=new Ht,b=new Ht,x=new Ht,w=new Ht,C=new Ht,S=new Ht,M=new wi,E=new Ht;let T=!1;const I=[],P={};let D=!1;function R(e){return!i.enableDamping||i.zoomToCursor||i.object.isOrthographicCamera?Math.pow(.95,i.zoomSpeed):1}function B(e){o.theta-=e}function L(e){o.phi-=e}this.rotateUp=L,this.rotateLeft=B;const O=function(){const e=new wi;return function(t,i){e.setFromMatrixColumn(i,0),e.multiplyScalar(-t),c.add(e)}}(),U=function(){const e=new wi;return function(t,n){!0===i.screenSpacePanning?e.setFromMatrixColumn(n,1):(e.setFromMatrixColumn(n,0),e.crossVectors(i.object.up,e)),e.multiplyScalar(t),c.add(e)}}(),F=function(){const e=new wi;return function(t,n){const r=i.domElement;if(i.object.isPerspectiveCamera){const s=i.object.position;e.copy(s).sub(i.target);let a=e.length();a*=Math.tan(i.object.fov/2*Math.PI/180),O(2*t*a/r.clientHeight,i.object.matrix),U(2*n*a/r.clientHeight,i.object.matrix)}else i.object.isOrthographicCamera?(O(t*(i.object.right-i.object.left)/i.object.zoom/r.clientWidth,i.object.matrix),U(n*(i.object.top-i.object.bottom)/i.object.zoom/r.clientHeight,i.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),i.enablePan=!1)}}();function N(e,t=0){i.object.isPerspectiveCamera||i.object.isOrthographicCamera?(l/=e,o.radius=Math.max(-i.maxZoomSpeed,Math.min(i.maxZoomSpeed,o.radius-t))):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function k(e,t=0){i.object.isPerspectiveCamera||i.object.isOrthographicCamera?(l*=e,o.radius=Math.max(-i.maxZoomSpeed,Math.min(i.maxZoomSpeed,o.radius+t))):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),i.enableZoom=!1)}function j(e,t){if(!i.zoomToCursor)return;T=!0;const n=i.domElement.getBoundingClientRect(),r=e-n.left,s=t-n.top,a=n.width,o=n.height;E.x=r/a*2-1,E.y=-s/o*2+1,M.set(E.x,E.y,1).unproject(i.object).sub(i.object.position).normalize()}function z(e){return Math.max(i.minDistance,Math.min(i.maxDistance,e))}function G(e){h.set(e.clientX,e.clientY)}function Q(e){_.set(e.clientX,e.clientY)}function V(e){if(1===I.length)h.set(e.pageX,e.pageY);else{const t=ae(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);h.set(i,n)}}function H(e){if(1===I.length)_.set(e.pageX,e.pageY);else{const t=ae(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);_.set(i,n)}}function W(e){const t=ae(e),i=e.pageX-t.x,n=e.pageY-t.y,r=Math.sqrt(i*i+n*n);w.set(0,r)}function q(e){if(1==I.length)d.set(e.pageX,e.pageY);else{const t=ae(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);d.set(i,n)}u.subVectors(d,h).multiplyScalar(i.rotateSpeed);const t=i.domElement;B(2*Math.PI*u.x/t.clientHeight),L(2*Math.PI*u.y/t.clientHeight),h.copy(d)}function X(e){if(1===I.length)b.set(e.pageX,e.pageY);else{const t=ae(e),i=.5*(e.pageX+t.x),n=.5*(e.pageY+t.y);b.set(i,n)}x.subVectors(b,_).multiplyScalar(i.panSpeed),F(x.x,x.y),_.copy(b)}function Y(e){const t=ae(e),n=e.pageX-t.x,r=e.pageY-t.y,s=Math.sqrt(n*n+r*r);C.set(0,s),S.set(0,Math.pow(C.y/w.y,6*i.zoomSpeed)),N(S.y),w.copy(C);j(.5*(e.pageX+t.x),.5*(e.pageY+t.y))}function K(e){!1!==i.enabled&&(0===I.length&&(i.domElement.setPointerCapture(e.pointerId),i.domElement.addEventListener("pointermove",J),i.domElement.addEventListener("pointerup",Z)),!function(e){for(let t=0;t<I.length;t++)if(I[t]==e.pointerId)return!0;return!1}(e)&&(function(e){I.push(e.pointerId)}(e),"touch"===e.pointerType?ne(e):function(e){let t;switch(e.button){case 0:t=i.mouseButtons.LEFT;break;case 1:t=i.mouseButtons.MIDDLE;break;case 2:t=i.mouseButtons.RIGHT;break;default:t=-1}switch(t){case m:if(!1===i.enableZoom)return;(function(e){j(e.clientX,e.clientX),w.set(e.clientX,e.clientY)})(e),r=n.DOLLY;break;case p:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===i.enablePan)return;Q(e),r=n.PAN}else{if(!1===i.enableRotate)return;G(e),r=n.ROTATE}break;case g:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===i.enableRotate)return;G(e),r=n.ROTATE}else{if(!1===i.enablePan)return;Q(e),r=n.PAN}break;default:r=n.NONE}r!==n.NONE&&i.dispatchEvent(Bg)}(e)))}function J(e){!1!==i.enabled&&("touch"===e.pointerType?function(e){switch(se(e),r){case n.TOUCH_ROTATE:if(!1===i.enableRotate)return;q(e),i.update();break;case n.TOUCH_PAN:if(!1===i.enablePan)return;X(e),i.update();break;case n.TOUCH_DOLLY_PAN:if(!1===i.enableZoom&&!1===i.enablePan)return;(function(e){i.enableZoom&&Y(e),i.enablePan&&X(e)})(e),i.update();break;case n.TOUCH_DOLLY_ROTATE:if(!1===i.enableZoom&&!1===i.enableRotate)return;(function(e){i.enableZoom&&Y(e),i.enableRotate&&q(e)})(e),i.update();break;default:r=n.NONE}}(e):e.buttons?function(e){switch(r){case n.ROTATE:if(!1===i.enableRotate)return;!function(e){d.set(e.clientX,e.clientY),u.subVectors(d,h).multiplyScalar(i.rotateSpeed);const t=i.domElement;B(2*Math.PI*u.x/t.clientHeight),L(2*Math.PI*u.y/t.clientHeight),h.copy(d),i.update()}(e);break;case n.DOLLY:if(!1===i.enableZoom)return;!function(e){C.set(e.clientX,e.clientY),S.subVectors(C,w),S.y>0?N(R(S.y)):S.y<0&&k(R(S.y)),w.copy(C),i.update()}(e);break;case n.PAN:if(!1===i.enablePan)return;!function(e){b.set(e.clientX,e.clientY),x.subVectors(b,_).multiplyScalar(i.panSpeed),F(x.x,x.y),_.copy(b),i.update()}(e)}}(e):Z(e))}function Z(e){switch(function(e){delete P[e.pointerId];for(let t=0;t<I.length;t++)if(I[t]==e.pointerId)return void I.splice(t,1)}(e),I.length){case 0:i.domElement.releasePointerCapture(e.pointerId),i.domElement.removeEventListener("pointermove",J),i.domElement.removeEventListener("pointerup",Z),i.dispatchEvent(Lg),r=n.NONE;break;case 1:const t=I[0],s=P[t];ne({pointerId:t,pageX:s.x,pageY:s.y})}}function $(e){!1===i.enabled||!1===i.enableZoom||r!==n.NONE||(e.preventDefault(),i.dispatchEvent(Bg),function(e){j(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?i.zoomToCursor||i.object.isOrthographicCamera?k(R()):k(1,t*i.zoomSpeed):e.deltaY>0&&(i.zoomToCursor||i.object.isOrthographicCamera?N(R()):N(1,-t*i.zoomSpeed)),i.update()}(function(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&&!D&&(i.deltaY*=10),i}(e)),i.dispatchEvent(Lg))}function ee(e){"Control"===e.key&&(D=!0,i.domElement.getRootNode().addEventListener("keyup",te,{passive:!0,capture:!0}))}function te(e){"Control"===e.key&&(D=!1,i.domElement.getRootNode().removeEventListener("keyup",te,{passive:!0,capture:!0}))}function ie(e){!1===i.enabled||!1===i.enablePan||function(e){let t=!1;switch(e.code){case i.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?L(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):F(0,i.keyPanSpeed),t=!0;break;case i.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?L(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):F(0,-i.keyPanSpeed),t=!0;break;case i.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?B(2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):F(i.keyPanSpeed,0),t=!0;break;case i.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?B(-2*Math.PI*i.rotateSpeed/i.domElement.clientHeight):F(-i.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),i.update())}(e)}function ne(e){switch(se(e),I.length){case 1:switch(i.touches.ONE){case f:if(!1===i.enableRotate)return;V(e),r=n.TOUCH_ROTATE;break;case A:if(!1===i.enablePan)return;H(e),r=n.TOUCH_PAN;break;default:r=n.NONE}break;case 2:switch(i.touches.TWO){case y:if(!1===i.enableZoom&&!1===i.enablePan)return;(function(e){i.enableZoom&&W(e),i.enablePan&&H(e)})(e),r=n.TOUCH_DOLLY_PAN;break;case v:if(!1===i.enableZoom&&!1===i.enableRotate)return;(function(e){i.enableZoom&&W(e),i.enableRotate&&V(e)})(e),r=n.TOUCH_DOLLY_ROTATE;break;default:r=n.NONE}break;default:r=n.NONE}r!==n.NONE&&i.dispatchEvent(Bg)}function re(e){!1!==i.enabled&&e.preventDefault()}function se(e){let t=P[e.pointerId];void 0===t&&(t=new Ht,P[e.pointerId]=t),t.set(e.pageX,e.pageY)}function ae(e){const t=e.pointerId===I[0]?I[1]:I[0];return P[t]}this.zoomIn=function(e){N(1,e*i.zoomSpeed)},this.zoomOut=function(e){k(1,e*i.zoomSpeed)},i.domElement.addEventListener("contextmenu",re),i.domElement.addEventListener("pointerdown",K),i.domElement.addEventListener("pointercancel",Z),i.domElement.addEventListener("wheel",$,{passive:!1}),i.domElement.getRootNode().addEventListener("keydown",ee,{passive:!0,capture:!0}),this.update()}}var kg=Object.defineProperty,jg=Object.getOwnPropertyDescriptor,zg=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?jg(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&&kg(t,i,s),s};e.OrbitControls3=class extends Ng{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 wi(-1e6,-1e6,-1e6),this.clampMax=new wi(1e6,1e6,1e6),this.screenSpacePanning=!0,this.keyPanSpeed=7,this.throttleUpdate=60}},zg([pm()],e.OrbitControls3.prototype,"type",2),zg([dg()],e.OrbitControls3.prototype,"enabled",2),zg([dg(),pm()],e.OrbitControls3.prototype,"dollyZoom",2),zg([dg(),pm()],e.OrbitControls3.prototype,"zoomToCursor",2),zg([dg(),pm()],e.OrbitControls3.prototype,"enableDamping",2),zg([og(),pm()],e.OrbitControls3.prototype,"dampingFactor",2),zg([dg(),pm()],e.OrbitControls3.prototype,"autoRotate",2),zg([og(),pm()],e.OrbitControls3.prototype,"autoRotateSpeed",2),zg([dg(),pm()],e.OrbitControls3.prototype,"enableZoom",2),zg([og(),pm()],e.OrbitControls3.prototype,"zoomSpeed",2),zg([og(),pm()],e.OrbitControls3.prototype,"maxZoomSpeed",2),zg([dg(),pm()],e.OrbitControls3.prototype,"enableRotate",2),zg([og(),pm()],e.OrbitControls3.prototype,"rotateSpeed",2),zg([dg(),pm()],e.OrbitControls3.prototype,"enablePan",2),zg([og(),pm()],e.OrbitControls3.prototype,"panSpeed",2),zg([og(),pm()],e.OrbitControls3.prototype,"autoPushTarget",2),zg([og(),pm()],e.OrbitControls3.prototype,"autoPullTarget",2),zg([og(),pm()],e.OrbitControls3.prototype,"minDistance",2),zg([og(),pm()],e.OrbitControls3.prototype,"maxDistance",2),zg([og(),pm()],e.OrbitControls3.prototype,"minZoom",2),zg([og(),pm()],e.OrbitControls3.prototype,"maxZoom",2),zg([og(),pm()],e.OrbitControls3.prototype,"minPolarAngle",2),zg([og(),pm()],e.OrbitControls3.prototype,"maxPolarAngle",2),zg([og(),pm()],e.OrbitControls3.prototype,"minAzimuthAngle",2),zg([og(),pm()],e.OrbitControls3.prototype,"maxAzimuthAngle",2),zg([rg(),pm()],e.OrbitControls3.prototype,"clampMin",2),zg([rg(),pm()],e.OrbitControls3.prototype,"clampMax",2),zg([pm()],e.OrbitControls3.prototype,"screenSpacePanning",2),zg([pm()],e.OrbitControls3.prototype,"keyPanSpeed",2),e.OrbitControls3=zg([ug("Orbit Controls")],e.OrbitControls3);const Gg=new Qu;Gg.params.Line2={threshold:.01};const Qg=new wi,Vg=new wi,Hg=new xi,Wg={X:new wi(1,0,0),Y:new wi(0,1,0),Z:new wi(0,0,1)},qg={type:"change"},Xg={type:"mouseDown",mode:null},Yg={type:"mouseUp",mode:null},Kg={type:"objectChange"};class Jg extends En{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 vf;this._gizmo=i,this.add(i);const n=new _f;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(qg))}}),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 wi,o=new wi,l=new xi,c=new xi,h=new wi,d=new xi,u=new wi,p=new wi,m=new wi,g=new wi;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 wi,this._startNorm=new wi,this._endNorm=new wi,this._cameraScale=new wi,this._parentPosition=new wi,this._parentQuaternion=new xi,this._parentQuaternionInv=new xi,this._parentScale=new wi,this._worldScaleStart=new wi,this._worldQuaternionInv=new xi,this._worldScale=new wi,this._positionStart=new wi,this._quaternionStart=new xi,this._scaleStart=new wi,this._getPointer=Zg.bind(this),this._onPointerDown=ef.bind(this),this._onPointerHover=$g.bind(this),this._onPointerMove=tf.bind(this),this._onPointerUp=nf.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&&Gg.setFromCamera(e,this.camera);const t=rf(this._gizmo.picker[this.mode],Gg);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&&Gg.setFromCamera(e,this.camera);const t=rf(this._plane,Gg,!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,Xg.mode=this.mode,this.dispatchEvent(Xg)}}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&&Gg.setFromCamera(e,this.camera);const a=rf(this._plane,Gg,!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(Hg.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(Qg.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(Qg.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),Vg.set(e,e,e)}else Qg.copy(this.pointStart),Vg.copy(this.pointEnd),Qg.applyQuaternion(this._worldQuaternionInv),Vg.applyQuaternion(this._worldQuaternionInv),Vg.divide(Qg),-1===t.search("X")&&(Vg.x=1),-1===t.search("Y")&&(Vg.y=1),-1===t.search("Z")&&(Vg.z=1);n.scale.copy(this._scaleStart).multiply(Vg),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(Qg.setFromMatrixPosition(this.camera.matrixWorld));let i=!1;"XYZE"===t?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(Qg.copy(this.rotationAxis).cross(this.eye))*e):("X"===t||"Y"===t||"Z"===t)&&(this.rotationAxis.copy(Wg[t]),Qg.copy(Wg[t]),"local"===s&&Qg.applyQuaternion(this.worldQuaternion),Qg.cross(this.eye),0===Qg.length()?i=!0:this.rotationAngle=this._offset.dot(Qg.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(Hg.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),n.quaternion.copy(Hg.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),n.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(qg),this.dispatchEvent(Kg)}}pointerUp(e){null!==e&&0!==e.button||(this.dragging&&null!==this.axis&&(Yg.mode=this.mode,this.dispatchEvent(Yg)),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(qg),this.dispatchEvent(Kg),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Gg}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 Zg(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 $g(e){if(this.enabled)switch(e.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(e))}}function ef(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 tf(e){this.enabled&&this.pointerMove(this._getPointer(e))}function nf(e){this.enabled&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(e)))}function rf(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}Jg.ObjectConstructors={MeshBasicMaterial:Xn,LineBasicMaterial:tc};const sf=new hn,af=new wi(0,1,0),of=new wi(0,0,0),lf=new $i,cf=new xi,hf=new xi,df=new wi,uf=new $i,pf=new wi(1,0,0),mf=new wi(0,1,0),gf=new wi(0,0,1),ff=new wi,Af=new wi,yf=new wi;class vf extends En{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new Jg.ObjectConstructors.MeshBasicMaterial({allowOverride:!1,depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new Jg.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 Yc(0,.04,.1,12);f.translate(0,.05,0);const A=new Rr(.08,.08,.08);A.translate(0,.04,0);const y=new ur;y.setAttribute("position",new rr([0,0,0,1,0,0],3));const v=new Yc(.0075,.0075,.5,3);function _(e,t){const i=new zh(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 zh(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 Pr(f,o),[.5,0,0],[0,0,-Math.PI/2]],[new Pr(v,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new Pr(f,l),[0,.5,0]],[new Pr(v,s)]],Z:[[new Pr(f,c),[0,0,.5],[Math.PI/2,0,0]],[new Pr(v,a),null,[Math.PI/2,0,0]]],XYZ:[[new Pr(new Uh(.1,2),p.clone()),[0,0,0]]],XY:[[new Pr(new Rr(.2,.2,.01),u.clone()),[.2,.2,0]]],YZ:[[new Pr(new Rr(.2,.2,.01),h.clone()),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new Pr(new Rr(.2,.2,.01),d.clone()),[.2,0,.2],[-Math.PI/2,0,0]]]},w={X:[[new Pr(new Yc(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]]],Y:[[new Pr(new Yc(.2,0,.6,4),i),[0,.3,0]]],Z:[[new Pr(new Yc(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]]],XYZ:[[new Pr(new Uh(.2,0),i)]],XY:[[new Pr(new Rr(.25,.25,.01),i),[.2,.2,0]]],YZ:[[new Pr(new Rr(.25,.25,.01),i),[0,.2,.2],[0,Math.PI/2,0]]],XZ:[[new Pr(new Rr(.25,.25,.01),i),[.2,0,.2],[-Math.PI/2,0,0]]]},C={START:[[new Pr(new Uh(.01,2),n),null,null,null,"helper"]],END:[[new Pr(new Uh(.01,2),n),null,null,null,"helper"]],DELTA:[[new oc(function(){const e=new ur;return e.setAttribute("position",new rr([0,0,0,1,1,1],3)),e}(),n),null,null,null,"helper"]],X:[[new oc(y,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new oc(y,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new oc(y,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},S={XYZE:[[new Pr(new kh(.1,10,8),p)],[new Pr(_(.5,1),g),null,[0,Math.PI/2,0]]],X:[[new Pr(_(.5,.5),r)],[new Pr(v,r),[0,0,0],[0,0,-Math.PI/2]],[new Pr(f.clone().translate(.5,0,0),o),[0,0,0],[-Math.PI/2,-Math.PI/2,-Math.PI/2]]],Y:[[new Pr(_(.5,.5),s),null,[0,0,-Math.PI/2]],[new Pr(v,s)],[new Pr(f.clone().rotateZ(-Math.PI/2).translate(0,.5,0),l),[0,0,0],[Math.PI/2,0,0]]],Z:[[new Pr(_(.5,.5),a),null,[0,Math.PI/2,0]],[new Pr(v,a),null,[Math.PI/2,0,0]],[new Pr(f.clone().rotateZ(-Math.PI).translate(0,0,.5),c),[0,0,0],[0,Math.PI/2,0]]]},M={AXIS:[[new oc(y,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},E={XYZE:[[new Pr(new kh(.25,10,8),i)]],X:[[new Pr(b(.5,.5),i)]],Y:[[new Pr(b(.5,.5),i),[0,0,0],[0,0,-Math.PI/2]]],Z:[[new Pr(b(.5,.5),i),[0,0,0],[0,Math.PI/2,0]]]},T={X:[[new Pr(A,o),[.5,0,0],[0,0,-Math.PI/2]],[new Pr(v,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new Pr(A,l),[0,.5,0]],[new Pr(v,s)]],Z:[[new Pr(A,c),[0,0,.5],[Math.PI/2,0,0]],[new Pr(v,a),[0,0,0],[Math.PI/2,0,0]]],XY:[[new Pr(new Rr(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new Pr(new Rr(.15,.15,.01),h),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new Pr(new Rr(.15,.15,.01),d),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new Pr(new Rr(.1,.1,.1),p.clone())]]},I={X:[[new Pr(new Yc(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new Pr(new Yc(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new Pr(new Yc(.2,0,.6,4),i),[0,.3,0]],[new Pr(new Yc(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new Pr(new Yc(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new Pr(new Yc(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new Pr(new Rr(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new Pr(new Rr(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new Pr(new Rr(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new Pr(new Rr(.2,.2,.2),i),[0,0,0]]]},P={X:[[new oc(y,n.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new oc(y,n.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new oc(y,n.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function D(e){const t=new En;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:hf;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(af.copy(pf).applyQuaternion(i).dot(this.eye))>.99&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1),"Y"===t.name&&Math.abs(af.copy(mf).applyQuaternion(i).dot(this.eye))>.99&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1),"Z"===t.name&&Math.abs(af.copy(gf).applyQuaternion(i).dot(this.eye))>.99&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1),"XY"===t.name&&Math.abs(af.copy(gf).applyQuaternion(i).dot(this.eye))<.2&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1),"YZ"===t.name&&Math.abs(af.copy(pf).applyQuaternion(i).dot(this.eye))<.2&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1),"XZ"===t.name&&Math.abs(af.copy(mf).applyQuaternion(i).dot(this.eye))<.2&&(t.scale.set(1e-10,1e-10,1e-10),t.visible=!1)):"rotate"===this.mode&&(cf.copy(i),af.copy(this.eye).applyQuaternion(Hg.copy(i).invert()),-1!==t.name.search("E")&&t.quaternion.setFromRotationMatrix(lf.lookAt(this.eye,of,mf)),"X"===t.name&&(Hg.setFromAxisAngle(pf,Math.atan2(-af.y,af.z)),Hg.multiplyQuaternions(cf,Hg),t.quaternion.copy(Hg)),"Y"===t.name&&(Hg.setFromAxisAngle(mf,Math.atan2(af.x,af.z)),Hg.multiplyQuaternions(cf,Hg),t.quaternion.copy(Hg)),"Z"===t.name&&(Hg.setFromAxisAngle(gf,Math.atan2(af.y,af.x)),Hg.multiplyQuaternions(cf,Hg),t.quaternion.copy(Hg))),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&&(Hg.setFromEuler(sf.set(0,0,0)),t.quaternion.copy(i).multiply(Hg),Math.abs(af.copy(pf).applyQuaternion(i).dot(this.eye))>.9&&(t.visible=!1)),"Y"===this.axis&&(Hg.setFromEuler(sf.set(0,0,Math.PI/2)),t.quaternion.copy(i).multiply(Hg),Math.abs(af.copy(mf).applyQuaternion(i).dot(this.eye))>.9&&(t.visible=!1)),"Z"===this.axis&&(Hg.setFromEuler(sf.set(0,Math.PI/2,0)),t.quaternion.copy(i).multiply(Hg),Math.abs(af.copy(gf).applyQuaternion(i).dot(this.eye))>.9&&(t.visible=!1)),"XYZE"===this.axis&&(Hg.setFromEuler(sf.set(0,Math.PI/2,0)),af.copy(this.rotationAxis),t.quaternion.setFromRotationMatrix(lf.lookAt(of,af,mf)),t.quaternion.multiply(Hg),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),Qg.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),Qg.applyQuaternion(this.worldQuaternionStart.clone().invert()),t.scale.copy(Qg),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 _f extends Pr{constructor(){super(new is(1e5,1e5,2,2),new Jg.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"),ff.copy(pf).applyQuaternion("local"===i?this.worldQuaternion:hf),Af.copy(mf).applyQuaternion("local"===i?this.worldQuaternion:hf),yf.copy(gf).applyQuaternion("local"===i?this.worldQuaternion:hf),af.copy(Af),this.mode){case"translate":case"scale":switch(this.axis){case"X":af.copy(this.eye).cross(ff),df.copy(ff).cross(af);break;case"Y":af.copy(this.eye).cross(Af),df.copy(Af).cross(af);break;case"Z":af.copy(this.eye).cross(yf),df.copy(yf).cross(af);break;case"XY":df.copy(yf);break;case"YZ":df.copy(ff);break;case"XZ":af.copy(yf),df.copy(Af);break;case"XYZ":case"E":df.set(0,0,0)}break;default:df.set(0,0,0)}0===df.length()?this.quaternion.copy(this.cameraQuaternion):(uf.lookAt(Qg.set(0,0,0),df,af),this.quaternion.setFromRotationMatrix(uf)),super.updateMatrixWorld(e)}}function bf(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 xf=new wi,wf=new wi;function Cf(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:(xf.copy(n).multiplyScalar(r/a).sub(t),wf.copy(n).multiplyScalar(s/a).add(i).sub(e),-xf.dot(wf)/xf.dot(xf))}const Sf=new $i,Mf=new $i,Ef=new $i,Tf=new $i,If=new $i,Pf=new $i,Df=new $i,Rf=new $i,Bf=new $i,Lf=new $i,Of=new $i,Uf=new Ht,Ff=new wi,Nf=new wi,kf=new wi,jf=new Zi,zf=new wi,Gf=new wi(0,1,0),Qf=new wi(1,0,0),Vf=new wi(0,1,0),Hf=new wi(0,0,1),Wf=class e extends Lo{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 Qu,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 Lo,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&&bf(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=[Qf,Vf,Hf];for(let e=0;e<3;e++){const t=n(this.axisColors[e]),i=r(),a=new Yc(.0075,.0075,.5,3);a.translate(0,.25,0);const o=new Pr(a,t);o.renderOrder=500,o.raycast=()=>{};const l=new Yc(0,.04,.1,12);l.translate(0,.05,0);const c=new Pr(l,t);c.position.set(0,.5,0),c.renderOrder=500,c.raycast=()=>{};const h=new Yc(.2,0,.6,4);h.translate(0,.3,0);const d=new Pr(h,i);d.visible=!1;const u=(new xi).setFromUnitVectors(Gf,s[e]),p=new Lo;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,Qf,Vf],[1,Hf,Qf],[0,Vf,Hf]];for(const[e,t,i]of a){const s=n(this.axisColors[e],.75),a=r(),o=.2,l=new Rr(o,o,.01),c=new Pr(l,s);c.renderOrder=500,c.raycast=()=>{};const h=new Rr(1.25*o,1.25*o,.01),d=new Pr(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 Lo,A=(new $i).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,Qf,Vf],[1,Hf,Qf],[0,Vf,Hf]];for(const[e,t,i]of o){const s=n(this.axisColors[e]),a=r(),o=.5,l=new zh(o,.0075,3,16,Math.PI/2),c=new Pr(l,s);c.renderOrder=500,c.raycast=()=>{};const h=new zh(o,.1,4,12,Math.PI/2),d=new Pr(h,a);d.visible=!1;const u=t.clone().normalize(),p=i.clone().normalize(),m=u.clone().cross(p),g=new Lo,f=(new $i).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 kh(i,12,12),a=new Pr(r,t);a.renderOrder=500;const o=(new xi).setFromUnitVectors(Gf,s[e]),l=new Lo;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 wi).setFromMatrixPosition(this.object.matrixWorld);if(this.position.copy(e),"local"!==this.space||this.object.userData?.isMultiSelectDummy?this.quaternion.identity():this.object.matrixWorld.decompose(Ff,this.quaternion,Nf),this.fixed){let t;if(Ff.copy(e),Nf.setFromMatrixPosition(this.camera.matrixWorld),this.camera.isOrthographicCamera){const e=this.camera;t=(e.top-e.bottom)/e.zoom}else{const e=this.camera;t=Ff.distanceTo(Nf)*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 Uf.x=(e.clientX-t.left)/t.width*2-1,Uf.y=-(e.clientY-t.top)/t.height*2+1,Uf}_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,Sf.copy(this.object.matrix),Mf.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 $i).extractRotation(n.matrixWorld),r=Gf.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 wi).setFromMatrixColumn(n.matrixWorld,0).normalize(),r=(new wi).setFromMatrixColumn(n.matrixWorld,1).normalize(),s=(new wi).setFromMatrixColumn(n.matrixWorld,2).normalize(),a=(new wi).setFromMatrixPosition(n.matrixWorld),o=(new Kr).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 wi).setFromMatrixPosition(n.matrixWorld),r=(new wi).setFromMatrixColumn(n.matrixWorld,2).normalize(),s=(new wi).setFromMatrixPosition(this.camera.matrixWorld).sub(i).normalize(),a=r.clone().cross(s);0===a.length()&&a.copy(s).cross(Gf),a.normalize();const o=20/i.distanceTo((new wi).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 $i).extractRotation(n.matrixWorld),r=Gf.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=Cf(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,Bf.makeTranslation(r.x*o,r.y*o,r.z*o),Bf}if("slider"===e.type){const{clickPoint:n,e1:r,e2:s,plane:a}=e.clickInfo,{x0:o,y0:l}=e.extraState;jf.copy(t),jf.intersectPlane(a,zf),jf.direction.negate(),jf.intersectPlane(a,zf),zf.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,zf);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,Bf.makeTranslation(c*r.x+h*s.x,c*r.y+h*s.y,c*r.z+h*s.z),Bf}if("rotator"===e.type){const{clickPoint:n,origin:r,normal:s,tangent:a,rotSpeed:o}=e.clickInfo,l=this.rotationLimits?.[e.axis],c=(new Kr).setFromNormalAndCoplanarPoint(s,r);jf.copy(t),jf.intersectPlane(c,zf)||(jf.direction.negate(),jf.intersectPlane(c,zf)),zf.sub(n);let h=zf.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=Vt.clamp(h,l[0],l[1])),e.extraState.angle=h,Lf.makeRotationAxis(s,h),kf.copy(r).applyMatrix4(Lf).sub(r).negate(),Lf.setPosition(kf),Lf}if("scaler"===e.type){const{clickPoint:n,dir:r,mPLG:s,mPLGInv:a}=e.clickInfo,o=this.scaleLimits?.[e.axis],l=Cf(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?Of.makeScale(c,c,c):Of.makeScale(1,c,1).premultiply(s).multiply(a),Of}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?Ef.copy(this.object.parent.matrixWorld):Ef.identity(),Tf.copy(Ef).invert(),If.copy(Mf).premultiply(e),Pf.copy(If).premultiply(Tf),Df.copy(Sf).invert(),Rf.copy(Pf).multiply(Df),this.autoTransform&&(this.object.matrix.copy(Pf),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"}};Wf.ObjectConstructors={MeshBasicMaterial:Xn,LineBasicMaterial:tc};let qf=Wf;var Xf=Object.defineProperty,Yf=Object.getOwnPropertyDescriptor,Kf=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?Yf(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&&Xf(t,i,s),s};const Jf=new wi,Zf=new Wu,$f=new wi,eA={type:"change"};e.FirstPersonControls2=class extends Bt{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 wi,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;Jf.set(0,0,-1).applyQuaternion(e),Zf.setFromVector3(Jf),this.lat=90-Vt.radToDeg(Zf.phi),this.lon=Vt.radToDeg(Zf.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?$f.copy(e):void 0===t||void 0===i?console.error("FirstPersonControls2.lookAt: y and z parameters are required"):$f.set(e,t,i),this.object.lookAt($f),this.setOrientation(),this}update(){const e=vp(),t=(this._lastTime<0?16:Math.min(e-this._lastTime,1e3))/1e3;if(this._lastTime=e,!this.enabled)return;if(this.heightSpeed){const e=Vt.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=Vt.degToRad(90-this.lat);const a=Vt.degToRad(this.lon);this.constrainVertical&&(s=Vt.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(eA)}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()}},Kf([pm(),dg()],e.FirstPersonControls2.prototype,"enabled",2),Kf([pm(),dg()],e.FirstPersonControls2.prototype,"enableKeys",2),Kf([pm(),og()],e.FirstPersonControls2.prototype,"movementSpeed",2),Kf([pm(),og()],e.FirstPersonControls2.prototype,"lookSpeed",2),Kf([pm(),dg()],e.FirstPersonControls2.prototype,"lookVertical",2),Kf([pm(),dg()],e.FirstPersonControls2.prototype,"autoForward",2),Kf([pm(),dg()],e.FirstPersonControls2.prototype,"activeLook",2),Kf([pm(),dg()],e.FirstPersonControls2.prototype,"heightSpeed",2),Kf([pm(),og()],e.FirstPersonControls2.prototype,"heightCoef",2),Kf([pm(),og()],e.FirstPersonControls2.prototype,"heightMin",2),Kf([pm(),og()],e.FirstPersonControls2.prototype,"heightMax",2),Kf([pm(),dg()],e.FirstPersonControls2.prototype,"constrainVertical",2),Kf([pm(),og()],e.FirstPersonControls2.prototype,"verticalMin",2),Kf([pm(),og()],e.FirstPersonControls2.prototype,"verticalMax",2),Kf([pm(),dg()],e.FirstPersonControls2.prototype,"mouseDragOn",2),e.FirstPersonControls2=Kf([ug("First Person Controls")],e.FirstPersonControls2);var tA=Object.defineProperty,iA=Object.getOwnPropertyDescriptor,nA=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?iA(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&&tA(t,i,s),s};const rA=new hn(0,0,0,"YXZ"),sA=new wi,aA={type:"change"},oA={type:"lock"},lA={type:"unlock"},cA=Math.PI/2;e.PointerLockControls2=class extends Bt{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 wi(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(oA),this.isLocked=!0):(this.dispatchEvent(lA),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){sA.setFromMatrixColumn(this.object.matrix,0),sA.crossVectors(this.object.up,sA),this.object.position.addScaledVector(sA,e)}moveRight(e){sA.setFromMatrixColumn(this.object.matrix,0),this.object.position.addScaledVector(sA,e)}lock(){this.domElement.requestPointerLock()}unlock(){this.domElement.ownerDocument.exitPointerLock()}update(){Math.abs(this._movementX)<1e-4&&Math.abs(this._movementY)<1e-4||(rA.setFromQuaternion(this.object.quaternion),rA.y-=.002*this._movementX*this.pointerSpeed,rA.x-=.002*this._movementY*this.pointerSpeed,this._movementX=0,this._movementY=0,rA.x=Math.max(cA-this.maxPolarAngle,Math.min(cA-this.minPolarAngle,rA.x)),this.object.quaternion.setFromEuler(rA),this.dispatchEvent(aA))}},nA([dg(),pm()],e.PointerLockControls2.prototype,"enabled",2),nA([og(),pm()],e.PointerLockControls2.prototype,"minPolarAngle",2),nA([og(),pm()],e.PointerLockControls2.prototype,"maxPolarAngle",2),nA([og(),pm()],e.PointerLockControls2.prototype,"pointerSpeed",2),nA([dg(),pm()],e.PointerLockControls2.prototype,"autoLockOnClick",2),e.PointerLockControls2=nA([ug("Pointer Lock Controls")],e.PointerLockControls2);var hA=Object.defineProperty,dA=Object.getOwnPropertyDescriptor,uA=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?dA(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&&hA(t,i,s),s};const pA=new wi(0,0,1),mA=new hn,gA=new xi,fA=new xi(-Math.sqrt(.5),0,0,Math.sqrt(.5)),AA=new xi,yA={type:"change"};e.DeviceOrientationControls2=class extends Bt{constructor(e){super(),this.enabled=!1,this.lastOrder="XYZ",this.dampingFactor=.05,this.lastQuaternion=new xi,this.onDeviceOrientationChangeEvent=e=>{this.deviceOrientation=e},this.onScreenOrientationChangeEvent=()=>{this.screenOrientation=screen.orientation},this._initQuaternion=new xi,this._initQuaternionInvert=new xi,this._initQuaternionDest=new xi,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 xi,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?Vt.degToRad(e.alpha):0,i=null!==e.beta?Vt.degToRad(e.beta):0,n=null!==e.gamma?Vt.degToRad(e.gamma):0,r=this.screenOrientation?Vt.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(yA))}}dispose(){this.disconnect()}setObjectQuaternion(e,t,i,n){const r=vp()/1e3;mA.set(t,e,-i,"YXZ"),AA.setFromEuler(mA),AA.multiply(fA),AA.multiply(gA.setFromAxisAngle(pA,-n)),this._initQuaternionDest.__init||(this._initQuaternionDest.copy(AA).invert(),this._initQuaternionDest.__init=!0),AA.premultiply(this._initQuaternionDest);this.object.quaternion.multiply(this._initQuaternionInvert),this.object.quaternion.slerp(AA,this.dampingFactor/(Math.min(1,r-this._lastTime)/(1/60))),this.object.quaternion.multiply(this._initQuaternion),this._lastTime=r}},uA([pm(),ng("Damping",[0,1],.01)],e.DeviceOrientationControls2.prototype,"dampingFactor",2),uA([ag("Reset View")],e.DeviceOrientationControls2.prototype,"resetView",1),uA([ag()],e.DeviceOrientationControls2.prototype,"connect",1),uA([ag()],e.DeviceOrientationControls2.prototype,"disconnect",1),e.DeviceOrientationControls2=uA([ug("Device Orientation Controls")],e.DeviceOrientationControls2);const vA=new wi,_A=new wi,bA=new wi,xA=new wi,wA=new wi,CA=new wi;let SA=1;const MA=new wi(0,1,0);const EA=class e extends Mi{constructor(){super(...arguments),this._vector=new wi}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===ur.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 wi(this.min.x,this.min.y,this.min.z),new wi(this.min.x,this.min.y,this.max.z),new wi(this.min.x,this.max.y,this.min.z),new wi(this.min.x,this.max.y,this.max.z),new wi(this.max.x,this.min.y,this.min.z),new wi(this.max.x,this.min.y,this.max.z),new wi(this.max.x,this.max.y,this.min.z),new wi(this.max.x,this.max.y,this.max.z)]}getScreenSpaceBounds(e){const t=this.getPoints(),i=new Yu;for(const n of t){const t=n.project(e);i.min.min(t),i.max.max(t)}return i}};EA._box=new EA;let TA=EA;function IA(e){if(wd._orig&&wd._storage){if(wd._storage===e)return;Object.assign(wd,wd._orig),delete wd._orig,delete wd._storage}const t={...wd};wd._orig=t,wd._storage=e,wd.get=(i,n,r)=>n?i.startsWith("data:")||i.startsWith("blob")||i.startsWith("chrome-extension")?Promise.resolve(void 0):e?.match(i).then((async e=>{if(e)switch(n){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,r??"text/html")));case"json":return e.json();default:if(void 0===r)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(r),i=t&&t[1]?t[1].toLowerCase():void 0,n=new TextDecoder(i);return e.arrayBuffer().then((e=>n.decode(e)))}}})):t.get(i),wd.add=async(i,n,r)=>{if(!r)return t.add(i,n);i.startsWith("data:")||i.startsWith("blob")||i.startsWith("chrome-extension")||i.startsWith("asset://")||(await(e?.match(i))&&await(e?.delete(i)),await(e?.put(i,new Response(n,{status:200})).catch((e=>{console.warn(e)}))))},wd.remove=(i,n)=>{if(!n)return t.remove(i);e?.delete(i)}}function PA(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*Zn.fromHalfFloat(e[c*t]),r=65504*Zn.fromHalfFloat(e[c*t+1]),s=65504*Zn.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 DA({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,Xp(this,"uniformsNeedUpdate",!0,!0),n&&lm.callFunction(n,this,[o,e]))}};if(l)return tm(l,"value")&&delete l.value,tm(l,"writable")&&delete l.writable,tm(l,"initializer")&&delete l.initializer,Object.assign(l,h);Object.defineProperty(i,o,h)}}function RA(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)),Xp(t,s,e,!0),void 0===e&&delete t[s],n&&"function"==typeof n?lm.callFunction(n,this,[s,e]):Xp(i?this:this.material,"needsUpdate",!0,!0)}};if(h)return tm(h,"value")&&delete h.value,tm(h,"writable")&&delete h.writable,tm(h,"initializer")&&delete h.initializer,Object.assign(h,u);Object.defineProperty(l,c,u)}}function BA(e,t,i=!1,n,r=!1){return RA(e,t,i,n,(e=>e?"1":r?void 0:"0"),(e=>!(!e||"0"===e)))}function LA({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=Yp(e)||i;"string"==typeof n&&(n=i[n]);let r,s=o&&Yp(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)),Xp(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&&lm.callFunction(o,this,s?[n,e]:[])}};if(h)return tm(h,"value")&&delete h.value,tm(h,"writable")&&delete h.writable,tm(h,"initializer")&&delete h.initializer,Object.assign(h,u);Object.defineProperty(l,c,u)}}function OA(e,t){let i;switch(t){case ct:case dt:case ht:i="";break;case mt:i="RGBM16ToLinear";break;default:console.warn("THREE.WebGLProgram: Unsupported color space:",t),i=""}return`#define ${e}( value ) ${i} ( value )`}function UA(e,t){return OA(e+"TexelToLinear",t??dt)+"\n"}function FA(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 ur;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=NA(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=NA(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 NA(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 tr(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 kA(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 Pl(s,n,r,e.meshPerAttribute):new tr(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 jA(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 tr(new n.array.constructor(n.count*n.itemSize),n.itemSize,n.normalized);const r=e.morphAttributes[i];r&&(h[i]=new tr(new r.array.constructor(r.count*r.itemSize),r.itemSize,r.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 tr(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 tr(i.array.slice(0,o*i.itemSize),i.itemSize,i.normalized)}}return y.setIndex(d),y}function zA(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 GA(e,t=-1){return jA(e,t)}function QA(){return Vt.generateUUID()}function VA(e,t,i=new xi){return t.premultiply(e.getWorldQuaternion(i).invert())}function HA(e,t,i,n=!1){const r=n?em(e,t,!1):e in t?t[e]:void 0;r&&r.isTexture&&i.set(e,r)}function WA(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?Ie:i?Te:Ce}function qA(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*Zn.fromHalfFloat(e.data[i]):e.data[i],t===dt&&(n[i]=255*Hp(n[i]/255));return i??new ImageData(n,e.width,e.height)}function XA(e,t,i=!1){let n;return n=e.isDataTexture?qA(e.image,e.colorSpace):e.image,YA(n,t,i)}function YA(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?bm(s):s}const KA={UV:ce,Cube:he,CubeUV:me,Equirectangular:ue},JA={None:"",SRGB:ht,LinearSRGB:dt,RGBM16:mt,DisplayP3:ut},ZA={UnsignedByte:Ce,Byte:1010,Short:1011,UnsignedShort:Se,Int:Me,UnsignedInt:Ee,Float:Te,HalfFloat:Ie,UnsignedShort4444:Pe,UnsignedShort5551:De,UnsignedInt248:Re},$A={Basic:st,RGBADepthPacking:at};function ey(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 ty={Blending:ey({None:w,Normal:C,Additive:S,Subtractive:M,Multiply:E,Custom:T}),AnyMapping:ey(KA),ColorSpace:ey(JA),TextureDataType:ey(ZA),DepthPackingStrategies:ey($A)},iy=new ImageData(new Uint8ClampedArray([255,255,255,255]),1,1),ny=new mi(iy);var ry=Object.defineProperty,sy=(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&&ry(t,i,s),s};const ay=(t=class extends Bt{constructor(e,i,n,r){super(),this.hoverEnabled=!1,this.multiSelectEnabled=!0,this.selectionMode="object",this.pickingMode="auto",this.extraObjects=[],this._mouseDownPos=new Ht,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 Qu,this.raycaster.params.Line2={threshold:.01},this.mouse=new Ht,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=vp(),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);sy([um("multiSelectChanged")],ay.prototype,"multiSelectEnabled"),sy([um("selectionModeChanged")],ay.prototype,"selectionMode"),sy([um("pickingModeChanged")],ay.prototype,"pickingMode");let oy=ay;function ly(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 Nl(i.geometry,i.material,t.length),s=i.userData;i.userData={},r.copy(i),uv(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 tr(o,3),ROTATION:new tr(l,4),SCALE:new tr(c,3)},r.instanceMatrix.needsUpdate=!0,a.add(r),a.setDirty()}}const cy={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}"},hy={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 dy{constructor(e){this._viewer=e,this.horizontalBlurMaterial=new Fr(cy),this.verticalBlurMaterial=new Fr(hy),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 uy(e,t,i,n=7,r=new wi(0,0,1.5),s=new Gr(45,1,.1,1e3)){const a=t.visible;t.visible=!0;const o=(new TA).expandByObject(t,!0,!0),l=o.getCenter(new wi),c=o.getSize(new wi);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),e.clear(),"function"==typeof e.renderWithModes?e.renderWithModes({backgroundRender:!1},(()=>{e.render(i??t,s)})):e.render(i??t,s);const h=e.domElement.toDataURL("image/png");return e.clear(),t.visible=a,t.traverseVisible((e=>{e.layers.disable(n)})),s.layers.enableAll(),h}class py{constructor(){this._lights=[],this.shapes={sphere:new Pr(new kh(1)),cube:new Pr(new Rr(1,1,1)),cylinder:new Pr(new Yc(.5,.5,1))};const e=new Wo;this._channel=7;const t=new Od(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 Pr(new kh(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=uy(t,r,this._scene,this._channel,new wi(0,0,1.5));return"number"==typeof s&&(e.envMapIntensity=s),this._scene.remove(r),r.material=void 0,a}}const my=new Mi,gy=new wi;class fy extends tu{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 rr([-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 rr([-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 zu(t,6,1);return this.setAttribute("instanceStart",new Yo(i,3,0)),this.setAttribute("instanceEnd",new Yo(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 zu(t,6,1);return this.setAttribute("instanceColorStart",new Yo(i,3,0)),this.setAttribute("instanceColorEnd",new Yo(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 Vh(e.geometry)),this}fromLineSegments(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Mi);const e=this.attributes.instanceStart,t=this.attributes.instanceEnd;void 0!==e&&void 0!==t&&(this.boundingBox.setFromBufferAttribute(e),my.setFromBufferAttribute(t),this.boundingBox.union(my))}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new Vi),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++)gy.fromBufferAttribute(e,r),n=Math.max(n,i.distanceToSquared(gy)),gy.fromBufferAttribute(t,r),n=Math.max(n,i.distanceToSquared(gy));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)}}rs.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new Ht(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},ss.line={uniforms:Ur.merge([rs.common,rs.fog,rs.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 Ay extends Fr{constructor(e){super({type:"LineMaterial",uniforms:Ur.clone(ss.line.uniforms),vertexShader:ss.line.vertexShader,fragmentShader:ss.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 yy=new wi,vy=new wi,_y=new Ai,by=new Ai,xy=new Ai,wy=new wi,Cy=new $i,Sy=new Zu,My=new wi,Ey=new Mi,Ty=new Vi,Iy=new Ai;let Py,Dy;function Ry(e,t,i){return Iy.set(0,0,-t,1).applyMatrix4(e.projectionMatrix),Iy.multiplyScalar(1/Iy.w),Iy.x=Dy/i.width,Iy.y=Dy/i.height,Iy.applyMatrix4(e.projectionMatrixInverse),Iy.multiplyScalar(1/Iy.w),Math.abs(Math.max(Iy.x,Iy.y))}class By extends Pr{constructor(e=new fy,t=new Ay({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)yy.fromBufferAttribute(t,e),vy.fromBufferAttribute(i,e),n[r]=0===r?0:n[r-1],n[r+1]=n[r]+yy.distanceTo(vy);const r=new zu(n,2,1);return e.setAttribute("instanceDistanceStart",new Yo(r,1,0)),e.setAttribute("instanceDistanceEnd",new Yo(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;Py=e.ray;const s=this.matrixWorld,a=this.geometry,o=this.material;let l,c;if(Dy=o.linewidth+r,null===a.boundingSphere&&a.computeBoundingSphere(),Ty.copy(a.boundingSphere).applyMatrix4(s),i)l=.5*Dy;else{l=Ry(n,Math.max(n.near,Ty.distanceToPoint(Py.origin)),o.resolution)}if(Ty.radius+=l,!1!==Py.intersectsSphere(Ty)){if(null===a.boundingBox&&a.computeBoundingBox(),Ey.copy(a.boundingBox).applyMatrix4(s),i)c=.5*Dy;else{c=Ry(n,Math.max(n.near,Ey.distanceToPoint(Py.origin)),o.resolution)}Ey.expandByScalar(c),!1!==Py.intersectsBox(Ey)&&(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++){Sy.start.fromBufferAttribute(r,a),Sy.end.fromBufferAttribute(s,a),Sy.applyMatrix4(i);const n=new wi,o=new wi;Py.distanceSqToSegment(Sy.start,Sy.end,o,n),o.distanceTo(n)<.5*Dy&&t.push({point:o,pointOnLine:n,distance:Py.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;Py.at(1,xy),xy.w=1,xy.applyMatrix4(t.matrixWorldInverse),xy.applyMatrix4(n),xy.multiplyScalar(1/xy.w),xy.x*=r.x/2,xy.y*=r.y/2,xy.z=0,wy.copy(xy),Cy.multiplyMatrices(t.matrixWorldInverse,s);for(let t=0,a=c;t<a;t++){if(_y.fromBufferAttribute(o,t),by.fromBufferAttribute(l,t),_y.w=1,by.w=1,_y.applyMatrix4(Cy),by.applyMatrix4(Cy),_y.z>h&&by.z>h)continue;if(_y.z>h){const e=_y.z-by.z,t=(_y.z-h)/e;_y.lerp(by,t)}else if(by.z>h){const e=by.z-_y.z,t=(by.z-h)/e;by.lerp(_y,t)}_y.applyMatrix4(n),by.applyMatrix4(n),_y.multiplyScalar(1/_y.w),by.multiplyScalar(1/by.w),_y.x*=r.x/2,_y.y*=r.y/2,by.x*=r.x/2,by.y*=r.y/2,Sy.start.copy(_y),Sy.start.z=0,Sy.end.copy(by),Sy.end.z=0;const a=Sy.closestPointToPointParameter(wy,!0);Sy.at(a,My);const c=Vt.lerp(_y.z,by.z,a),d=c>=-1&&c<=1,u=wy.distanceTo(My)<.5*Dy;if(d&&u){Sy.start.fromBufferAttribute(o,t),Sy.end.fromBufferAttribute(l,t),Sy.start.applyMatrix4(s),Sy.end.applyMatrix4(s);const n=new wi,r=new wi;Py.distanceSqToSegment(Sy.start,Sy.end,r,n),i.push({point:r,pointOnLine:n,distance:Py.origin.distanceTo(r),object:e,face:null,faceIndex:t,uv:null,uv1:null})}}}(this,n,t))}}}var Ly=Object.defineProperty;const[Oy,Uy,Fy,Ny,ky,jy]=Array(6).fill(0).map(((e,t)=>t)),zy=[new Qn(16725587),new Qn(9100032),new Qn(2920447)],Gy=new pu,Qy=new wi,Vy=new xi,Hy=new xi,Wy=new xi,qy=new wi,Xy=2*Math.PI,Yy=new Qu,Ky=new Ht,Jy=new En;let Zy=0;class $y extends En{constructor(e,t,i="bottom-right",n=128,r=2){super(),this.orthoCamera=new fs(-1.8,1.8,1.8,-1.8,0,4),this.isViewHelper=!0,this.animating=!1,this.target=new wi,this.viewport=new Ai,this.offsetHeight=0,this.renderer=new Qo({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 kh(1.6);return new Pr(e,new Xn({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?zy[0].toArray():t<4?zy[1].toArray():zy[2].toArray())).flat(),i=new fy;return i.setPositions(e),i.setColors(t),new By(i,new Ay({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=zy[i%3],o=new hl(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 wc(i);return o.wrapS=o.wrapT=ge,o.repeat.x=.5,o.colorSpace=ht,o.minFilter=be,o.magFilter=be,o.generateMipmaps=!1,o.needsUpdate=!0,new Ko({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,iv(this.spritePoints),this.domContainer.style.cursor="",this.dispatchEvent({type:"update",event:e,change:"pointer"})}handleClick(e){const t=tv(e,this.domRect,this.orthoCamera,this.spritePoints);t&&this.setOrientation(t.userData.type)}handleHover(e){const t=tv(e,this.domRect,this.orthoCamera,this.spritePoints);iv(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=Gy.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){qy.set(0,0,1),qy.applyQuaternion(t.quaternion),qy.x>=0?(e[Oy].material.opacity=1,e[Ny].material.opacity=.5):(e[Oy].material.opacity=.5,e[Ny].material.opacity=1),qy.y>=0?(e[Uy].material.opacity=1,e[ky].material.opacity=.5):(e[Uy].material.opacity=.5,e[ky].material.opacity=1),qy.z>=0?(e[Fy].material.opacity=1,e[jy].material.opacity=.5):(e[Fy].material.opacity=.5,e[jy].material.opacity=1)}(this.spritePoints,this.camera)}update(){this.domRect=this.domContainer.getBoundingClientRect(),this.offsetHeight=this.domElement.offsetHeight,ev(this.camera,this.target),this.renderer.getViewport(this.viewport),this.updateOrientation()}animate(e){const t=e*Xy;Hy.rotateTowards(Wy,t),this.camera.position.set(0,0,1).applyQuaternion(Hy).multiplyScalar(Zy).add(this.target),this.camera.quaternion.rotateTowards(Vy,t),this.updateOrientation(),0===Hy.angleTo(Wy)&&(this.animating=!1)}setOrientation(e){(function(e,t,i){switch(i){case"+x":Qy.set(1,0,0),Vy.setFromEuler(new hn(0,.5*Math.PI,0));break;case"+y":Qy.set(0,1,0),Vy.setFromEuler(new hn(.5*-Math.PI,0,0));break;case"+z":Qy.set(0,0,1),Vy.setFromEuler(new hn);break;case"-x":Qy.set(-1,0,0),Vy.setFromEuler(new hn(0,.5*-Math.PI,0));break;case"-y":Qy.set(0,-1,0),Vy.setFromEuler(new hn(.5*Math.PI,0,0));break;case"-z":Qy.set(0,0,-1),Vy.setFromEuler(new hn(0,Math.PI,0));break;default:console.error("ViewHelper: Invalid axis.")}ev(e,t),function(e,t){Qy.multiplyScalar(Zy).add(t),Jy.position.copy(t),Jy.lookAt(e.position),Hy.copy(Jy.quaternion),Jy.lookAt(Qy),Wy.copy(Jy.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 ev(e,t){Zy=e.position.distanceTo(t)}function tv(e,t,i,n){!function(e,t,i){Ky.x=(e.clientX-t.left)/t.width*2-1,Ky.y=-(e.clientY-t.top)/t.height*2+1,Yy.setFromCamera(Ky,i)}(e,t,i);const r=Yy.intersectObjects(n);return r.length?r[0].object:null}function iv(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&&Ly(t,i,r)})([um()],$y.prototype,"animating");const nv=class extends Vc{constructor(){super(),this.type="CurvePath3"}};am.SerializableClasses.set("CurvePath3",nv);let rv=nv;function sv(e,t){const i=t.getSize(new wi);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 av=e=>(t,i)=>i?.copy?.(t)??(new e).copy(t),ov=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:av(e),type:t.startsWith("is")?t.slice(2):e.name}}static Init(){this._init||(this._init=!0,Wu.prototype.isSpherical=!0,am.RegisterSerializer(...e.Primitives.map((t=>e.PrimitiveSerializer(t[0],t[1],t[2],t[3])))),am.RegisterSerializer(e.Texture),am.RegisterSerializer(e.Material),am.RegisterSerializer(e.RenderTarget),am.SerializableClasses.set("Shape",rh),am.SerializableClasses.set("Curve",Cc),am.SerializableClasses.set("CurvePath",Vc),am.SerializableClasses.set("Path",Hc),am.SerializableClasses.set("ArcCurve",Mc),am.SerializableClasses.set("CatmullRomCurve3",Rc),am.SerializableClasses.set("CubicBezierCurve",Uc),am.SerializableClasses.set("CubicBezierCurve3",Fc),am.SerializableClasses.set("EllipseCurve",Sc),am.SerializableClasses.set("LineCurve",Nc),am.SerializableClasses.set("LineCurve3",kc),am.SerializableClasses.set("QuadraticBezierCurve",jc),am.SerializableClasses.set("QuadraticBezierCurve3",zc),am.SerializableClasses.set("SplineCurve",Gc),am.SerializableClasses.set("AnimationClip",bd))}static MakeSerializable(e,t,i){e.prototype.serializableClassId=t,am.SerializableClasses.set(t,e),i&&am.TypeMap.set(e,i.map((e=>"string"==typeof e?[e,e]:e)))}static Serialize(e,t,i=!1){return this._init||this.Init(),am.Serialize(e,t,i)}static Deserialize(e,t,i,n=!1){return this._init||this.Init(),am.Deserialize(e,t,i,n)}};ov.Primitives=[[Ht,"isVector2",["x","y"],1],[wi,"isVector3",["x","y","z"],1],[Ai,"isVector4",["x","y","z","w"],1],[xi,"isQuaternion",["x","y","z","w"],1],[hn,"isEuler",["x","y","z","order"],1],[Qn,"isColor",["r","g","b"],1],[qu,"isMatrix2",["elements"],1],[Wt,"isMatrix3",["elements"],1],[$i,"isMatrix4",["elements"],1],[Wu,"isSpherical",["radius","phi","theta"],1]],ov.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&&qm(e.userData.rootPath);let r={};const s=e.userData;try{n&&e.source.data&&(e.userData.embedUrlImagePreviews?e.source.data=XA(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=am.Serialize(hv({},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 nu(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=ov.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)}},ov.SerializableMaterials=new Set,ov.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=am.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={},dv(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=am.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=am.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 ov.SerializableMaterials)if(e.TYPE===s){c=e;break}if(!c)for(const e of ov.SerializableMaterials)if(e.TypeAlias?.includes(s)){c=e;break}if(c){const e=new c;if(e)return l&&Xp(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 $d;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&&Xp(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)}},ov.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)}},ov._init=!1;let lv=ov;function cv(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]=cv(Array.isArray(r)?[]:{},r,[]):e[n]=r.clone()}return e}function hv(e,t,i=["uuid"]){return cv(e,t,i)}function dv(e,t,i=["uuid"]){return cv(e,t,i)}function uv(e,t,i=["uuid"]){return cv(e,t,i)}function pv(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,"+Ip(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,"+Ip(e.url.data.buffer)):e.url.data instanceof ArrayBuffer?e.url.data="data:application/octet-stream;base64,"+Ip(e.url.data.buffer):console.warn("Unsupported buffer type",e.url.type)))}))}))}function mv(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=Pp(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 gv(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},_context:{}}}class fv{static async ImportMeta(e,t){if(e.__isLoadedResources)return e;const i=yv();i.__isLoadedResources=!0,i._context=e._context,mv(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 nu(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 fv.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=lv.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 wc(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]=lv.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]=lv.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([Rp(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]=lv.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 di(n.data);return s.image&&(r.uuid=s.image),s.image=r.uuid,i.constructor!==mi&&i.constructor!==Ml&&i.constructor!==Hr&&(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 Av(e){if(!e)return{};const t={...e};return t._context&&delete t._context,t}function yv(e,t){return{...e,...gv(e),_context:{assetManager:t?.assetManager,assetImporter:t?.assetManager.importer,renderManager:t?.renderManager,viewer:t}}}function vv(e){const t=new Blob([JSON.stringify(e)],{type:"application/json"});return t.ext="json",t}function _v(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:hv({},e.userData),type:e.type,name:i||e.name};return t?.extras?(t.extras[e.uuid]=s,{uuid:e.uuid,resource:"extras"}):s}function bv(e,t){const i={},n=Array.isArray(t)?t:[];for(const t of n){let n;n=t.startsWith("userData.")?em(t.slice(9),e.userData,!1):e[t],void 0!==n&&(i[t]=n)}return i}function xv(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?em(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 wv="shaderReplaceString: str must be passed if str is a RegExp and append/prepend is true";function Cv(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(wv);c=i+a}else if(s){if("string"!=typeof a)throw new Error(wv);c=a+i}return n?e.replaceAll(t,c):e.replace(t,c)}function Sv(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 Mv(e,t){const i=Sv(e),n=new DataView(new ArrayBuffer(8));n.setUint32(0,i.byteLength,!0),n.setUint32(4,5130562,!0);const r=Sv((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 Ev(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 Tv=(e,t,i)=>Math.min(Math.max(i,e),t),Iv=.001;function Pv({duration:e=800,bounce:t=.25,velocity:i=0,mass:n=1}){let r,s,a=1-t;a=Tv(.05,1,a),e=Tv(.01,10,e/1e3),a<1?(r=t=>{const n=t*a,r=n*e,s=n-i,o=Rv(t,a),l=Math.exp(-r);return Iv-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=Rv(Math.pow(t,2),a);return(-r(t)+Iv>0?-1:1)*((s-o)*l)/c}):(r=t=>Math.exp(-t*e)*((t-i)*e+1)-Iv,s=t=>Math.exp(-t*e)*(e*e*(i-t)));const o=function(e,t,i){let n=i;for(let i=1;i<Dv;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 Dv=12;function Rv(e,t){return e*Math.sqrt(1-t*t)}const Bv=["duration","bounce"],Lv=["stiffness","damping","mass"];function Ov(e,t){return t.some((t=>void 0!==e[t]))}function Uv(e){var{from:t=0,to:i=1,restSpeed:n=2,restDelta:r}=e,s=Ev(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(!Ov(e,Lv)&&Ov(e,Bv)){const i=Pv(e);t=Object.assign(Object.assign(Object.assign({},t),i),{velocity:0,mass:1}),t.isResolvedFromDuration=!0}return t}(s),p=Fv,m=Fv;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=Rv(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()}}}Uv.needsInterpolation=(e,t)=>"string"==typeof e||"string"==typeof t;const Fv=e=>0,Nv=(e,t,i)=>{const n=t-e;return 0===n?1:(i-e)/n},kv=(e,t,i)=>-i*e+i*t+e,jv=(e,t)=>i=>Math.max(Math.min(i,t),e),zv=e=>e%1?Number(e.toFixed(5)):e,Gv=/(-)?([\d]*\.?[\d])+/g,Qv=/(#[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,Vv=/^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;function Hv(e){return"string"==typeof e}const Wv={test:e=>"number"==typeof e,parse:parseFloat,transform:e=>e},qv=Object.assign(Object.assign({},Wv),{transform:jv(0,1)});Object.assign(Object.assign({},Wv),{default:1});const Xv={test:e=>Hv(e)&&e.endsWith("%")&&1===e.split(" ").length,parse:parseFloat,transform:e=>`${e}%`};Object.assign(Object.assign({},Xv),{parse:e=>Xv.parse(e)/100,transform:e=>Xv.transform(100*e)});const Yv=(e,t)=>i=>!!(Hv(i)&&Vv.test(i)&&i.startsWith(e)||t&&Object.prototype.hasOwnProperty.call(i,t)),Kv=(e,t,i)=>n=>{if(!Hv(n))return n;const[r,s,a,o]=n.match(Gv);return{[e]:parseFloat(r),[t]:parseFloat(s),[i]:parseFloat(a),alpha:void 0!==o?parseFloat(o):1}},Jv={test:Yv("hsl","hue"),parse:Kv("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:i,alpha:n=1})=>"hsla("+Math.round(e)+", "+Xv.transform(zv(t))+", "+Xv.transform(zv(i))+", "+zv(qv.transform(n))+")"},Zv=jv(0,255),$v=Object.assign(Object.assign({},Wv),{transform:e=>Math.round(Zv(e))}),e_={test:Yv("rgb","red"),parse:Kv("red","green","blue"),transform:({red:e,green:t,blue:i,alpha:n=1})=>"rgba("+$v.transform(e)+", "+$v.transform(t)+", "+$v.transform(i)+", "+zv(qv.transform(n))+")"};const t_={test:Yv("#"),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:e_.transform},i_=e=>e_.test(e)||t_.test(e)||Jv.test(e),n_=e=>e_.test(e)?e_.parse(e):Jv.test(e)?Jv.parse(e):t_.parse(e),r_=e=>Hv(e)?e:e.hasOwnProperty("red")?e_.transform(e):Jv.transform(e),s_="${c}",a_="${n}";function o_(e){"number"==typeof e&&(e=`${e}`);const t=[];let i=0;const n=e.match(Qv);n&&(i=n.length,e=e.replace(Qv,s_),t.push(...n.map(n_)));const r=e.match(Gv);return r&&(e=e.replace(Gv,a_),t.push(...r.map(Wv.parse))),{values:t,numColors:i,tokenised:e}}function l_(e){return o_(e).values}function c_(e){const{values:t,numColors:i,tokenised:n}=o_(e),r=t.length;return e=>{let t=n;for(let n=0;n<r;n++)t=t.replace(n<i?s_:a_,n<i?r_(e[n]):zv(e[n]));return t}}const h_=e=>"number"==typeof e?0:e;const d_={test:function(e){var t,i,n,r;return isNaN(e)&&Hv(e)&&(null!==(i=null===(t=e.match(Gv))||void 0===t?void 0:t.length)&&void 0!==i?i:0)+(null!==(r=null===(n=e.match(Qv))||void 0===n?void 0:n.length)&&void 0!==r?r:0)>0},parse:l_,createTransformer:c_,getAnimatableNone:function(e){const t=l_(e);return c_(e)(t.map(h_))}};function u_(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 p_({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=u_(o,n,e+1/3),s=u_(o,n,e),a=u_(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 m_=(e,t,i)=>{const n=e*e,r=t*t;return Math.sqrt(Math.max(0,i*(r-n)+n))},g_=[t_,e_,Jv],f_=e=>g_.find((t=>t.test(e))),A_=(e,t)=>{let i=f_(e),n=f_(t),r=i.parse(e),s=n.parse(t);i===Jv&&(r=p_(r),i=e_),n===Jv&&(s=p_(s),n=e_);const a=Object.assign({},r);return e=>{for(const t in a)"alpha"!==t&&(a[t]=m_(r[t],s[t],e));return a.alpha=kv(r.alpha,s.alpha,e),i.transform(a)}},y_=(e,t)=>i=>t(e(i)),v_=(...e)=>e.reduce(y_);function __(e,t){return(e=>"number"==typeof e)(e)?i=>kv(e,t,i):i_(e)?A_(e,t):C_(e,t)}const b_=(e,t)=>{const i=[...e],n=i.length,r=e.map(((e,i)=>__(e,t[i])));return e=>{for(let t=0;t<n;t++)i[t]=r[t](e);return i}},x_=(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]=__(e[r],t[r]));return e=>{for(const t in n)i[t]=n[t](e);return i}};function w_(e){const t=d_.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 C_=(e,t)=>{const i=d_.createTransformer(t),n=w_(e),r=w_(t);return n.numHSL===r.numHSL&&n.numRGB===r.numRGB&&n.numNumbers>=r.numNumbers?v_(b_(n.parsed,r.parsed),i):i=>`${i>0?t:e}`},S_=(e,t)=>i=>kv(e,t,i);function M_(e,t,i){const n=[],r=i||function(e){return"number"==typeof e?S_:"string"==typeof e?i_(e)?A_:C_:Array.isArray(e)?b_:"object"==typeof e?x_: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=v_(e,s)}n.push(s)}return n}function E_(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=M_(t,n,r),o=2===s?function([e,t],[i]){return n=>i(Nv(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=Nv(e[s],e[s+1],r);return t[s](o)}}(e,a);return i?t=>o(Tv(e[0],e[s-1],t)):o}const T_=e=>t=>1-e(1-t),I_=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,P_=e=>t=>t*t*((e+1)*t-e),D_=4/11,R_=8/11,B_=(e=>t=>Math.pow(t,e))(2),L_=T_(B_),O_=I_(B_),U_=e=>1-Math.sin(Math.acos(e)),F_=T_(U_),N_=I_(F_),k_=P_(1.525),j_=T_(k_),z_=I_(k_),G_=(e=>{const t=P_(e);return e=>(e*=2)<1?.5*t(e):.5*(2-Math.pow(2,-10*(e-1)))})(1.525),Q_=4356/361,V_=35442/1805,H_=16061/1805,W_=e=>{if(1===e||0===e)return e;const t=e*e;return e<D_?7.5625*t:e<R_?9.075*t-9.9*e+3.4:e<.9?Q_*t-V_*e+H_:10.8*e*e-20.52*e+10.72},q_=T_(W_);function X_(e,t){return e.map((()=>t||O_)).splice(0,e.length-1)}function Y_({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 E_(o,a,{ease:Array.isArray(i)?i:X_(a,i)})}let c=l();return{next:e=>(s.value=c(e),s.done=e>=r,s),flipTarget:()=>{a.reverse(),c=l()}}}const K_={keyframes:Y_,spring:Uv,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 J_=1/60*1e3,Z_=typeof performance<"u"?()=>performance.now():()=>Date.now(),$_=typeof window<"u"?e=>window.requestAnimationFrame(e):e=>setTimeout((()=>e(Z_())),J_);let eb=!0,tb=!1,ib=!1;const nb={delta:0,timestamp:0},rb=["read","update","preRender","render","postRender"],sb=rb.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}((()=>tb=!0)),e)),{}),ab=rb.reduce(((e,t)=>{const i=sb[t];return e[t]=(e,t=!1,n=!1)=>(tb||hb(),i.schedule(e,t,n)),e}),{}),ob=rb.reduce(((e,t)=>(e[t]=sb[t].cancel,e)),{});rb.reduce(((e,t)=>(e[t]=()=>sb[t].process(nb),e)),{});const lb=e=>sb[e].process(nb),cb=e=>{tb=!1,nb.delta=eb?J_:Math.max(Math.min(e-nb.timestamp,40),1),nb.timestamp=e,ib=!0,rb.forEach(lb),ib=!1,tb&&(eb=!1,$_(cb))},hb=()=>{tb=!0,eb=!0,ib||$_(cb)};function db(e,t,i=0){return e-t-i}const ub=e=>{const t=({delta:t})=>e(t);return{start:()=>ab.update(t,!0),stop:()=>ob.update(t)}};function pb(e){var t,i,{from:n,autoplay:r=!0,driver:s=ub,elapsed:a=0,repeat:o=0,repeatType:l="loop",repeatDelay:c=0,onPlay:h,onStop:d,onComplete:u,onRepeat:p,onUpdate:m}=e,g=Ev(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 Y_;if(K_[e.type])return K_[e.type];const t=new Set(Object.keys(e));return t.has("ease")||t.has("duration")&&!t.has("dampingRatio")?Y_:t.has("dampingRatio")||t.has("stiffness")||t.has("mass")||t.has("damping")||t.has("restSpeed")||t.has("restDelta")?Uv:Y_}(g);null!==(i=(t=C).needsInterpolation)&&void 0!==i&&i.call(t,n,v)&&(y=E_([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?db(t+-e,t,i):t-(e-t)+i}(a,b,c,w)):(a=db(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 mb={linear:e=>e,easeIn:B_,easeOut:L_,easeInOut:O_,circIn:U_,circOut:F_,circInOut:N_,backIn:k_,backOut:j_,backInOut:z_,anticipate:G_,bounceOut:W_,bounceIn:q_,bounceInOut:e=>e<.5?.5*(1-W_(1-2*e)):.5*W_(2*e-1)+.5,easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2};function gb(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 fb(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=pb(e);t&&t.push(l)}))}function Ab(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 yb=Vt.lerp;function vb({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=Y_({...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 _b(e){const t=e.position.clone();t.sub(e.target);const i=(new Wu).setFromVector3(t);return i.makeSafe(),i}function bb(e,t){const i=e.parent,n=e.target.clone(),r=e.getWorldPosition(new wi),s={target:n,zoom:e.zoom,spherical:_b({position:r,target:n})},a={position:new wi,target:new wi,zoom:1,spherical:new Wu},o={position:t.position,target:t.target,zoom:t.zoom,spherical:_b(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=Ab(s.spherical.phi,o.spherical.phi,e),a.spherical.theta=Ab(s.spherical.theta,o.spherical.theta,e),a.spherical.radius=yb(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=yb(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 xb(e,t){const i=e.parent,n=e.target.clone(),r={position:e.getWorldPosition(new wi),target:n,quaternion:e.getWorldQuaternion(new xi),zoom:e.zoom},s={position:new wi,target:new wi,quaternion:new xi,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?VA(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=yb(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 wb(e,t,i){return"number"==typeof t&&"number"==typeof i?Cb(e,t,i):"number"==typeof t?.r&&"number"==typeof i?.r?(new Qn).set(Cb(e.from?{...e,from:e.from.r}:e,t.r,i.r),Cb(e.from?{...e,from:e.from.g}:e,t.g,i.g),Cb(e.from?{...e,from:e.from.b}:e,t.b,i.b)):t?.toArray&&i?.toArray&&t.clone&&t.fromArray?Sb(e,t,i):e.t>=1?i:t}function Cb(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 Sb(e,t,i){const n=t.toArray(),r=i.toArray(),s=e.from?e.from.toArray():void 0,a=n.map(((t,i)=>wb(s?{...e,from:s[i]}:e,t,r[i])));return t.clone().fromArray(a)}function Mb(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||ny;let l,c=!1;if(t&&t.userData?._lerpTexture&&t.isRenderTargetTexture)l=t._target;else{const t=a||i||ny,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||ny,respectColorSpace:!1,transparent:!0,clear:!1,blendAlpha:void 0!==e.from?n:a}),s=l.texture}else s=t}return s}function Eb(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=Cb(a,s,o);t===s?delete e[r]:e[r]=t}if(s?.isColor&&o?.isColor){const t=wb(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=Mb(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=Sb(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)=>wb(a,e,o[t])));t.every(((e,t)=>e===s[t]))?delete e[r]:e[r]=t}}}function Tb(e,t){return e.multiplyScalar(e.w*t),e.w=1,e}function Ib(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 Pb(){return navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}const Db=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=Pb()||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=Pb()||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:vp()})}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}};Db.Debug=!1;let Rb=Db;var Bb=Object.defineProperty,Lb=Object.getOwnPropertyDescriptor,Ob=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?Lb(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&&Bb(t,i,s),s};const Ub={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 Fb(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=em(n,r),{key:s,tar:r,onChange:i}}function Nb(e){return{processObject:t=>{const i=Yp(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 kb(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&&jb(e,n),e.userData.geometriesCentered=!0};e._loadingPromise?e._loadingPromise.finally(o):o()}function jb(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 Bt{constructor(e,t,i=""){super(),this.uuid=QA(),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(Ub).map((([e,t])=>({label:e,value:t})))},()=>this.values.flatMap(((e,t)=>[{...Jm(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])),Zm(this)],uuid:QA()},this.target=e,this.viewer=t,this.name=i,this.dispatchEvent=this.dispatchEvent.bind(this)}get targetObject(){return Yp(this.target)??this.parent?.targetObject}getViewer(){return this.viewer?Yp(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),lv.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(Ub).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}=Fb(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=QA();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}},Ob([pm(),cm("setDirty")],e.AnimationObject.prototype,"name",2),Ob([pm(),cm(e.AnimationObject.prototype._onAccessChanged)],e.AnimationObject.prototype,"access",2),Ob([pm()],e.AnimationObject.prototype,"values",2),Ob([pm()],e.AnimationObject.prototype,"offsets",2),Ob([pm()],e.AnimationObject.prototype,"options",2),Ob([pm(),ng(void 0,[0,1e4],1,(e=>({hidden:()=>!e.access}))),cm("setDirty")],e.AnimationObject.prototype,"duration",2),Ob([pm(),ng(void 0,[0,1e4],1,(e=>({hidden:()=>!e.access}))),cm("setDirty")],e.AnimationObject.prototype,"delay",2),Ob([pm(),cm("setDirty")],e.AnimationObject.prototype,"repeat",2),Ob([pm(),cm("setDirty")],e.AnimationObject.prototype,"repeatDelay",2),Ob([pm(),cm("setDirty")],e.AnimationObject.prototype,"repeatType",2),Ob([pm(),sg("ease",Object.keys(mb).map((e=>({label:e}))),(e=>({hidden:()=>!e.access}))),cm("setDirty")],e.AnimationObject.prototype,"ease",2),Ob([pm(),dg(void 0,(e=>({hidden:()=>!e.access}))),cm("setDirty")],e.AnimationObject.prototype,"updateScene",2),Ob([pm(),dg(void 0,(e=>({hidden:()=>!e.access}))),cm("setDirty")],e.AnimationObject.prototype,"updateCamera",2),Ob([pm(),dg(void 0,(e=>({hidden:()=>!e.access}))),cm("setDirty")],e.AnimationObject.prototype,"updateViewer",2),Ob([pm(),cm("setDirty")],e.AnimationObject.prototype,"updateTarget",2),Ob([cm(e.AnimationObject.prototype._onAccessChanged)],e.AnimationObject.prototype,"target",2),Ob([cm(e.AnimationObject.prototype._onAccessChanged)],e.AnimationObject.prototype,"viewer",2),Ob([ag("Animate")],e.AnimationObject.prototype,"animate",1),Ob([ag("Stop")],e.AnimationObject.prototype,"stop",1),Ob([ag("Delete")],e.AnimationObject.prototype,"removeFromParent2",1),Ob([pm()],e.AnimationObject.prototype,"animSetParallel",2),Ob([pm()],e.AnimationObject.prototype,"animSet",2),e.AnimationObject=Ob([mm("AnimationObject")],e.AnimationObject);class zb extends Id{constructor(e){super(e),this.responseType="blob"}load(e,t,i,n){return super.load(e,(e=>{try{t?.(Gp(e))}catch(e){n?.(e)}}),i,n)}}var Gb=Object.defineProperty,Qb=Object.getOwnPropertyDescriptor,Vb=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?Qb(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&&Gb(t,i,s),s};const Hb=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}}},Vb([og("Text",Hb)],e.TextSVGOptions.prototype,"text",2),Vb([ng("Font Size",[2,1024],1,Hb)],e.TextSVGOptions.prototype,"fontSize",2),Vb([ng("Width",[2,4096],1,Hb)],e.TextSVGOptions.prototype,"width",2),Vb([ng("Height",[2,4096],1,Hb)],e.TextSVGOptions.prototype,"height",2),Vb([ng("X Offset",[-1024,1024],1,Hb)],e.TextSVGOptions.prototype,"xOffset",2),Vb([ng("Y Offset",[-1024,1024],1,Hb)],e.TextSVGOptions.prototype,"yOffset",2),Vb([ng("V-Width",[2,4096],1,Hb)],e.TextSVGOptions.prototype,"boxWidth",2),Vb([ng("V-Height",[2,4096],1,Hb)],e.TextSVGOptions.prototype,"boxHeight",2),Vb([sg("Text Anchor",["start","middle","end"].map((e=>({label:e}))),Hb)],e.TextSVGOptions.prototype,"textAnchor",2),Vb([og("Font",Hb)],e.TextSVGOptions.prototype,"fontFamily",2),Vb([og("Font Url",Hb)],e.TextSVGOptions.prototype,"fontPath",2),Vb([og("Font Weight",Hb)],e.TextSVGOptions.prototype,"fontWeight",2),Vb([sg("Font Style",["normal","italic","oblique"].map((e=>({label:e}))),Hb)],e.TextSVGOptions.prototype,"fontStyle",2),Vb([og("Line Height",Hb)],e.TextSVGOptions.prototype,"lineHeight",2),Vb([og("Letter Spacing",Hb)],e.TextSVGOptions.prototype,"letterSpacing",2),Vb([sg("White Space",["normal","pre","nowrap","pre-wrap","pre-line"].map((e=>({label:e}))),Hb)],e.TextSVGOptions.prototype,"whiteSpace",2),Vb([sg("Direction",["auto","ltr","rtl"].map((e=>({label:e}))),Hb)],e.TextSVGOptions.prototype,"direction",2),Vb([dg("Mask Text",Hb)],e.TextSVGOptions.prototype,"maskText",2),Vb([dg("Inner Shadow",Hb)],e.TextSVGOptions.prototype,"innerShadow",2),Vb([og("Text Color",Hb)],e.TextSVGOptions.prototype,"textColor",2),Vb([og("BG Fill",Hb)],e.TextSVGOptions.prototype,"bgFillColor",2),Vb([og("SVG BG",Hb)],e.TextSVGOptions.prototype,"svgBackground",2),e.TextSVGOptions=Vb([pg("Text SVG Options")],e.TextSVGOptions);const Wb={woff:"woff",woff2:"woff2",ttf:"truetype",otf:"opentype",eot:"embedded-opentype"};function qb({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 Xb={roboto:"https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2"};const Yb=class extends Bt{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=lv.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:(lv.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}};Yb.PluginType="AViewerPlugin";let Kb=Yb;class Jb extends Kb{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 Zb(){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??Yx.defaultMinNear,setValue:e=>{e===Yx.defaultMinNear?delete this.userData.minNearPlane:this.userData.minNearPlane=e}},{type:"number",label:"Max Far",hidden:()=>!this.autoNearFar,getValue:()=>this.userData.maxFarPlane??Yx.defaultMaxFar,setValue:e=>{e===Yx.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 $b(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)}},...ix.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 wi(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=Zb.call(this);i.children.push(...e)}return i.children.push(ex.call(this)),this.uiConfig=i,i}function ex(){return e=>this.objectExtensions?.flatMap((t=>(t.uuid=t.uuid||QA(),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=>Yp(t,e)))))).filter((e=>e))}function tx(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 ix(){return[{type:"button",label:"Duplicate Object",tags:["context-menu"],value:async e=>kx.duplicateObject(this,e)},{type:"button",label:"Delete Object",tags:["context-menu"],value:async e=>kx.deleteObject(this,e)}]}const nx={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 nx.upgradeGeometry.call(e.call(this))},upgradeGeometry:function(){return"geometry"===this.assetType?this:this.isBufferGeometry?(this.assetType="geometry",this.dispose=nx.dispose(this.dispose),this.center=nx.center(this.center),this.clone=nx.clone(this.clone),this.center2||(this.center2=nx.center2),this.setDirty||(this.setDirty=nx.setDirty),this.refreshUi||(this.refreshUi=nx.refreshUi),this.appliedMeshes||(this.appliedMeshes=new Set),this.userData||(this.userData={}),this.uiConfig=nx.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 wi,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 wi;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;GA(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?")&&ly(this)}},{type:"input",label:"Mesh count",getValue:()=>this.appliedMeshes?.size??0,disabled:!0}]}}};const rx=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=Yp(i.parsFragmentSnippet,n,e)??"";r.length&&(t.fragmentShader=Cv(t.fragmentShader,this.VoidMain,"\n"+r+"\n",{prepend:!0})),r=Yp(i.parsVertexSnippet,n,e)??"",r.length&&(t.vertexShader=Cv(t.vertexShader,this.VoidMain,"\n"+r+"\n",{prepend:!0})),i.extraUniforms&&(t.uniforms=Object.assign(t.uniforms,im(i.extraUniforms,(e=>Yp(e,t)||{value:null})))),i.extraDefines&&ax(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+=Yp(t.computeCacheKey,e):i+=t.uuid,t.extraDefines&&(i+=Object.values(t.extraDefines).map((e=>Yp(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=QA()),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",ox),e.addEventListener("afterRender",lx),e.addEventListener("addToMesh",cx),e.addEventListener("removeFromMesh",hx),e.addEventListener("materialUpdate",dx));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",ox),e.removeEventListener("afterRender",lx),e.removeEventListener("addToMesh",cx),e.removeEventListener("removeFromMesh",hx),e.removeEventListener("materialUpdate",dx),delete e.__extListen)}};Object.assign(ns,Xm),rx.VoidMain="void main()";let sx=rx;function ax(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=Yp(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 ox({target:e,object:t,renderer:i}){const n=e;if(!n||!t||!i)throw new Error("Invalid material, object or renderer");if(n.materialExtensions)for(const e of n.materialExtensions){if(e.onObjectRender&&e.onObjectRender(t,n,i),n.lastShader){const t=Yp(e.updaters)||[];for(const e of t)e&&e.updateShaderProperties(n.lastShader)}const r="_"+e.uuid+"_version";e.updateVersion!==n.userData[r]&&(n.userData[r]=e.updateVersion,n.needsUpdate=!0)}}function lx({target:e,object:t,renderer:i}){const n=e;if(!n||!t||!i)throw new Error("Invalid material, object or renderer");if(n.materialExtensions)for(const e of n.materialExtensions)e.onAfterRender&&e.onAfterRender(t,n,i)}function cx({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 hx({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 dx({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 ux(e,t){const i=t||QA();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 px(e,t,i,n,r){return{type:"folder",label:i??t+" Sampler",hidden:()=>!e[t]||n&&n(),onChange:r=r??(()=>e.setDirty&&e.setDirty()),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",dt],["sRGB",ht]].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 mx=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"]},px(e,"map")],gx=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",N],["One Minus Src Alpha",k],["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",N],["One Minus Src Alpha",k],["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?px(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"})}}:{}]}),fx=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"]}]}),Ax=e=>({type:"folder",label:"AO/Lightmap",children:[{type:"slider",bounds:[0,2],property:[e,"aoMapIntensity"]},{type:"image",property:[e,"aoMap"]},px(e,"aoMap"),{type:"slider",bounds:[0,2],property:[e,"lightMapIntensity"]},{type:"image",property:[e,"lightMap"]},px(e,"lightMap")]}),yx=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"})}}]}),vx=e=>[()=>e.materialExtensions?.map((t=>(t.uuid=t.uuid||QA(),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:()=>{zp(new Blob([JSON.stringify(e.toJSON(),null,2)],{type:"application/json"}),`material.${e.constructor.TypeSlug}`)}},{type:"button",label:`Select ${e.constructor.TypeSlug}`,value:async()=>Vp(!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,gv()),{undo:()=>e.fromJSON(n,gv()),redo:()=>e.fromJSON(i,gv())}}))}],_x=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"]},px(e,"roughnessMap"),{type:"image",property:[e,"metalnessMap"]},px(e,"metalnessMap")]}),bx=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"]},px(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",ot],["ObjectSpace",lt]].map((e=>({label:e[0],value:e[1]})))},px(e,"normalMap"),{type:"input",property:[e,"displacementScale"],hidden:()=>!e.displacementMap},{type:"image",property:[e,"displacementMap"]},px(e,"displacementMap")]}),xx=e=>({type:"folder",label:"Emission",children:[{type:"color",property:[e,"emissive"]},{type:"slider",bounds:[0,100],property:[e,"emissiveIntensity"]},{type:"image",property:[e,"emissiveMap"]},px(e,"emissiveMap")]}),wx=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"]},px(e,"transmissionMap"),{type:"image",property:[e,"thicknessMap"]},px(e,"thicknessMap"),{type:"number",property:[e,"attenuationDistance"]},{type:"color",property:[e,"attenuationColor"]}]}),Cx=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"]},px(e,"clearcoatMap"),{type:"slider",bounds:[0,1],property:[e,"clearcoatRoughness"]},{type:"image",property:[e,"clearcoatRoughnessMap"]},px(e,"clearcoatRoughnessMap"),{type:"image",property:[e,"clearcoatNormalMap"]},{type:"vec2",property:[e,"clearcoatNormalScale"],hidden:()=>!e.clearcoatNormalMap},px(e,"clearcoatNormalMap")]}),Sx=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"]},px(e,"iridescenceMap"),{type:"image",property:[e,"iridescenceThicknessMap"]},px(e,"iridescenceThicknessMap")]}),Mx=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"]},px(e,"sheenColorMap"),{type:"slider",bounds:[0,1],property:[e,"sheenRoughness"]},{type:"image",property:[e,"sheenRoughnessMap"]},px(e,"sheenRoughnessMap")]}),Ex={name:"",blending:C,side:_,vertexColors:!1,opacity:1,transparent:!1,blendSrc:N,blendDst:k,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},Tx=["opacity","blendColor","blendAlpha","alphaTest"],Ix=class extends Xn{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isUnlitMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Dx.setDirty,this.envMap=null,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Dx.registerMaterialExtensions,this.unregisterMaterialExtensions=Dx.unregisterMaterialExtensions,this.onBeforeRender=Dx.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=Dx.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:[...mx(this),...Zm(this),gx(this),Ax(this),fx(this),...vx(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Dx.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Dx.dispose(super.dispose).call(this)}clone(e=!1){return Dx.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Dx.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=Cv(e.vertexShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);for(const t of i)e.fragmentShader=Cv(e.fragmentShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);Dx.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)?(Dx.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),...lv.Serialize(this,e,!0)}:lv.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(lv.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};Ix.TypeSlug="bmat",Ix.TYPE="UnlitMaterial",Ix.TypeAlias=["unlit","basic",Ix.TYPE,Ix.TypeSlug,"MeshBasicMaterial","MeshBasicMaterial2"],lv.SerializableMaterials.add(Ix),Ix.MaterialProperties={...Ex,color:new Qn(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},Ix.MapProperties=["map","aoMap","lightMap","specularMap","alphaMap","envMap"],Ix.InterpolateProperties=[...Tx,"color","color","specular","emissive","reflectivity","refractionRatio","envMapIntensity","lightMapIntensity","aoMapIntensity","wireframeLinewidth"];let Px=Ix;const Dx={threeMaterialPropList:Ex,threeMaterialInterpolateProps:Tx,setDirty:function(e){!1!==e?.needsUpdate&&(this.needsUpdate=!0),Dx.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=si.enabled;s&&(si.enabled=!1);const o=this.constructor.MaterialProperties,l=o?Kp(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||Px.InterpolateProperties,...this.constructor.MapProperties||Px.MapProperties]);return r&&Eb(l,this,h,r),e.call(this,l),c&&dv(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&&(si.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){t&&(this.userData.cloneId||(this.userData.cloneId="0"),this.userData.cloneCount||(this.userData.cloneCount=0),this.userData.cloneCount+=1);const i=(new this.constructor)?.setValues(this,!1)??e.call(this);return 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 sx.CacheKeyForExtensions(this,this.materialExtensions)+this.userData.inverseAlphaMap},registerMaterialExtensions:function(e){sx.RegisterExtensions(this,e)},unregisterMaterialExtensions:function(e){sx.UnregisterExtensions(this,e)},onBeforeCompile:function(e,t){this.materialExtensions&&sx.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){Dx.onBeforeCompile.call(this,t,i),e.call(this,t,i)},onBeforeRenderOverride:e=>function(...t){e.call(this,...t),Dx.onBeforeRender.call(this,...t)},onAfterRenderOverride:e=>function(...t){e.call(this,...t),Dx.onAfterRender.call(this,...t)},customProgramCacheKeyOverride:e=>function(){return e.call(this)+Dx.customProgramCacheKey.call(this)},upgradeMaterial:Ox,getMapsForMaterial:function(){const e=new Map;for(const t of this.constructor?.MapProperties||Bx)HA(t,this,e);if(this.userData)for(const t of Lx)HA(t,this.userData,e,!0);return e},refreshTextureRefs:function(){this.__textureUpdate||(this.__textureUpdate=Rx.bind(this));const e=Dx.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})}},Rx=function(e){!this||"material"!==this.assetType||this.dispatchEvent({texture:e.target,bubbleToParent:!0,bubbleToObject:!0,...e,type:"textureUpdate"})},Bx=new Set([]),Lx=new Set([]);function Ox(){if(!this.isMaterial)return console.error("Material is not a material",this),this;if(this.setDirty||(this.setDirty=Dx.setDirty),this.appliedMeshes||(this.appliedMeshes=new Set),this.userData||(this.userData={}),this.userData.uuid=this.uuid,this.__upgradeSetup||(this.dispatchEvent=Dx.dispatchEvent(this.dispatchEvent),this.__upgradeSetup=!0),"material"===this.assetType)return this;this.assetType="material",this.setValues=Dx.setValues(this.setValues),this.dispose=Dx.dispose(this.dispose),this.clone=Dx.clone(this.clone),this.extraUniformsToUpload||(this.extraUniformsToUpload={}),this.materialExtensions||(this.materialExtensions=[]),this.registerMaterialExtensions||(this.registerMaterialExtensions=Dx.registerMaterialExtensions),this.unregisterMaterialExtensions||(this.unregisterMaterialExtensions=Dx.unregisterMaterialExtensions);const e=!this.isDerivedMaterial;return this.onBeforeCompile=e?Dx.onBeforeCompileOverride(this.onBeforeCompile):Dx.onBeforeCompile,this.onBeforeRender=Dx.onBeforeRenderOverride(this.onBeforeRender),this.onAfterRender=Dx.onAfterRenderOverride(this.onAfterRender),this.customProgramCacheKey=Dx.customProgramCacheKeyOverride(this.customProgramCacheKey),this.setDirty({change:"upgradeMaterial"}),this}const Ux=class extends Fr{constructor({customMaterialExtensions:e,...t}={},i=!1){super(),this.assetType="material",this.isAShaderMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Dx.setDirty,this.type="ShaderMaterial",this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Dx.registerMaterialExtensions,this.unregisterMaterialExtensions=Dx.unregisterMaterialExtensions,this.isRawShaderMaterial=i,i&&(this.type="RawShaderMaterial"),e&&this.registerMaterialExtensions(e),Dx.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Dx.dispose(super.dispose).call(this)}clone(e=!1){return Dx.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Dx.customProgramCacheKey.call(this)}onBeforeCompile(e,t){Dx.onBeforeCompile.call(this,e,t),super.onBeforeCompile(e,t)}onBeforeRender(e,t,i,n,r,s){super.onBeforeRender(e,t,i,n,r,s),Dx.onBeforeRender.call(this,e,t,i,n,r,s)}onAfterRender(e,t,i,n,r,s){super.onAfterRender(e,t,i,n,r,s),Dx.onAfterRender.call(this,e,t,i,n,r,s)}setValues(e){return Dx.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}};Ux.TypeSlug="shaderMat",Ux.TYPE="ShaderMaterial2",Ux.MaterialProperties={...Ex,fragmentShader:"",vertexShader:"",uniforms:{},defines:{},extensions:{},isRawShaderMaterial:!1,uniformsGroups:{},wireframe:!1,wireframeLinewidth:1,clipping:!1,lights:!1,fog:!1,glslVersion:null,defaultAttributeValues:{}},Ux.InterpolateProperties=[...Tx,"wireframeLinewidth"];let Fx=Ux;class Nx extends Fx{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:Ur.merge([rs.common,rs.bumpmap,rs.normalmap,rs.displacementmap,{cameraNearFar:{value:new Ht(.1,1e3)},flags:{value:new Ai(255,255,255,255)}}]),defines:{IS_GLSL3:e?"1":"0"},glslVersion:e?It:"100",...t}),this.flagUpdaters=new Map,this.normalMapType=ot,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)ax({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),ax({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=ot,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 kx={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=kx.dispatchEvent(this.dispatchEvent),this.dispose=kx.dispose(this.dispose),this.clone=kx.clone(this.clone),this.copy=kx.copy(this.copy),this.add=kx.add(this.add),this.setDirty||(this.setDirty=kx.setDirty),this.refreshUi||(this.refreshUi=kx.refreshUi),this.autoScale||(this.autoScale=kx.autoScale.bind(this)),this.autoCenter||(this.autoCenter=kx.autoCenter.bind(this)),this.pivotToBoundsCenter||(this.pivotToBoundsCenter=kx.pivotToBoundsCenter.bind(this)),this.pivotToPoint||(this.pivotToPoint=kx.pivotToPoint.bind(this)),this.traverseModels||(this.traverseModels=kx.traverseModels.bind(this)),this.addEventListener("added",kx.eventCallbacks.onAddedToParent),this.addEventListener("removed",kx.eventCallbacks.onRemovedFromParent),(this.isLineSegments2||this.isLine2)&&(this.isMesh=!0),(this.isMesh||this.isLine)&&!this.__meshSetup){if(this.__meshSetup=!0,this._onGeometryUpdate=e=>kx.eventCallbacks.onGeometryUpdate.call(this,e),kx.initMaterial.call(this),kx.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)&&kx.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:$b,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 TA).expandByObject(this,!0,!0).getCenter(new wi);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 TA).expandByObject(this,!0,!0).getSize(new wi).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 TA).expandByObject(this,!0,!0).getCenter(new wi);return kx.pivotToPoint.call(this,t,e)},pivotToPoint:function(e,t=!0,i=!0){const n=(new wi).copy(e),r=(new wi).copy(n),s=(new $i).copy(this.matrixWorld).invert(),a=this.parent?.matrixWorld,o=new $i;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 wi(-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(tm(this,"_currentMaterial"))return;this._currentMaterial=null;const{protoDesc:e}=Wm(this,"material"),t=this.material;delete this.material,Object.defineProperty(this,"currentMaterial",{configurable:!0,enumerable:!0,get(){return e?.get?e.get.call(this):kx.getMaterial.call(this)},set(t){kx.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:kx.getMaterials,set:kx.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 Eo({depthPacking:at,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=Cv(n.fragmentShader,"void main()","\nvarying vec2 vHighPrecisionZW;\n#include <packing>\n",{prepend:!0}),i.fragmentShader=Cv(i.fragmentShader,"#include <logdepthbuf_fragment>",r+"\n//end-frag-patch\n",{append:!0}),i.fragmentShader=i.fragmentShader.split("//end-frag-patch")[0],i.vertexShader=Cv(n.vertexShader,"void main()","\nvarying vec2 vHighPrecisionZW;\n",{prepend:!0}),i.vertexShader=Cv(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 Nx(!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=Cv(n.fragmentShader,"void main()",r+"\n",{prepend:!0}),i.fragmentShader=Cv(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=Cv(n.vertexShader,"void main()",a,{prepend:!0}),i.vertexShader=Cv(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||Dx.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}=Wm(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):kx.getGeometry.call(this))},set(t){this.forcedOverrideGeometry&&console.warn("IObject3D: Geometry is being set on an object with forcedOverrideGeometry set"),kx.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||nx.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,uv(r.userData,n),kx.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,uv(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)kx.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||Vx)HA(t,this,e);if(this.isScene)for(const t of Qx)HA(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);tx(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 jx(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 zx(t){const i=jx(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 Gx(e){const t=jx(e),i=[],n=new Map;for(const e of t){const t=e.clone(!0);tx(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 Qx=new Set(["environmentMap","background"]),Vx=new Set([]);var Hx=Object.defineProperty,Wx=Object.getOwnPropertyDescriptor,qx=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?Wx(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&&Hx(t,i,s),s};function Xx(e){const t="chordal",i=e.map((e=>e.position.clone())),n=new Rc(i,!0,t,.75),r=e.map((e=>e.target.clone())),s=new Rc(r,!0,t,.75);return{getPosition:(e,t,r)=>{r=r||new wi;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 wi;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 Bt{constructor(e,t,i,n,r,s=1,a){super(),this.uuid=QA(),this.name="Camera View",this.position=new wi,this.target=new wi,this.quaternion=new xi,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)}},qx([dm("setDirty"),pm(),og()],e.CameraView.prototype,"name",2),qx([dm("setDirty"),pm(),rg()],e.CameraView.prototype,"position",2),qx([dm("setDirty"),pm(),rg()],e.CameraView.prototype,"target",2),qx([dm("setDirty"),pm(),rg()],e.CameraView.prototype,"quaternion",2),qx([dm("setDirty"),pm(),lg()],e.CameraView.prototype,"zoom",2),qx([dm("setDirty"),pm(),lg()],e.CameraView.prototype,"duration",2),qx([dm("setDirty"),pm()],e.CameraView.prototype,"isWorldSpace",2),qx([ag()],e.CameraView.prototype,"set",2),qx([ag()],e.CameraView.prototype,"update",2),qx([ag()],e.CameraView.prototype,"delete",2),qx([ag()],e.CameraView.prototype,"animate",2),e.CameraView=qx([mm("CameraView"),ug("Camera View")],e.CameraView);const Yx={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}),kx.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 wi)),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 wi)),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,kx.upgradeObject3D.call(this),this.copy=Yx.copy(this.copy),this.target||(this.target=new wi),this._positionWorld||(this._positionWorld=new wi),this.refreshTarget||(this.refreshTarget=Yx.refreshTarget),this.refreshAspect||(this.refreshAspect=Yx.refreshAspect),this.updateShaderProperties||(this.updateShaderProperties=Yx.updateShaderProperties),this.activateMain||(this.activateMain=Yx.activateMain),this.deactivateMain||(this.deactivateMain=Yx.deactivateMain),this.refreshUi||(this.refreshUi=Yx.refreshUi),this.setDirty||(this.setDirty=Yx.setDirty),this.getView||(this.getView=Yx.getView),this.setView||(this.setView=Yx.setView),this.fitObject||(this.fitObject=Yx.fitObject),this.setViewFromCamera||(this.setViewFromCamera=Yx.setViewFromCamera),this.setViewToMain||(this.setViewToMain=Yx.setViewToMain),this.setCanvas||(this.setCanvas=()=>Kx("setCanvas")),this.setControlsCtor||(this.setControlsCtor=()=>Kx("setControlsCtor")),this.removeControlsCtor||(this.removeControlsCtor=()=>Kx("removeControlsCtor")),this.refreshCameraControls||(this.refreshCameraControls=()=>Kx("refreshCameraControls")),this.setInteractions||(this.setInteractions=()=>Kx("setInteractions")),this.dispose||(this.dispose=()=>Kx("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 wi))}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 wi;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 TA).expandByObject(n[0],!1,!0);for(let e=1;e<n.length;e++)r.expandByObject(n[e],!1,!0);const s=sv(this,r),a=r.getCenter(new wi);r.getSize(new wi).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 wi).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 Kx(e){console.warn(`ICamera.${e} is not supported on this object. Please use objects of PerspectiveCamera2 or OrthographicCamera2 classes.`)}var Jx=Object.defineProperty,Zx=(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&&Jx(t,i,s),s};const $x=class extends Gr{constructor(t,i,n,r,s){super(r,s),this.assetType="camera",this._currentControlsMode="",this.userData={},this.target=new wi(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=Yx.refreshAspect,this.refreshUi=Yx.refreshUi,this.refreshTarget=Yx.refreshTarget,this.activateMain=Yx.activateMain,this.deactivateMain=Yx.deactivateMain,this.updateShaderProperties=Yx.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=Yx.getView,this.setView=Yx.setView,this.fitObject=Yx.fitObject,this.setViewFromCamera=Yx.setViewFromCamera,this.setViewToMain=Yx.setViewToMain,this._positionWorld=new wi,this._camUi=[...Zm(this)||[],{type:"input",label:"Dolly FoV",property:[this,"dollyFov"]},...Zb.call(this),ex.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,Yx.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){Yx.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 wi),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(En.DEFAULT_UP)}e&&this.setDirty(),this.refreshUi()}}toJSON(e,t=!1){return t?{...super.toJSON(e),...lv.Serialize(this,e,!0)}:lv.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),lv.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()}};Zx([og("Name")],$x.prototype,"name"),Zx([pm("camControls")],$x.prototype,"_controls"),Zx([sg("Controls Mode",void 0,(e=>({children:["none",...e.controlsCtors.keys()].map((e=>({label:e,value:"none"===e?"":e})))}))),pm(),hm($x.prototype.refreshCameraControls)],$x.prototype,"controlsMode"),Zx([pm()],$x.prototype,"userData"),Zx([dm($x.prototype.setDirty),ng("Field Of View",[1,180],.001),pm()],$x.prototype,"fov"),Zx([dm($x.prototype.setDirty),pm()],$x.prototype,"focus"),Zx([dm($x.prototype.setDirty),lg("FoV Zoom"),pm()],$x.prototype,"zoom"),Zx([rg("Position",void 0,void 0,(e=>({onChange:()=>e.setDirty({change:"position"})}))),pm()],$x.prototype,"position"),Zx([rg("Up",void 0,void 0,(e=>({onChange:()=>e.setDirty({change:"up"})}))),pm()],$x.prototype,"up"),Zx([rg("Rotation",void 0,void 0,(e=>({onChange:()=>e.setDirty({change:"rotation"}),disabled:()=>e.autoLookAtTarget})))],$x.prototype,"rotation"),Zx([rg("Target",void 0,void 0,(e=>({onChange:()=>e.setDirty({change:"target"}),disabled:()=>!e.autoLookAtTarget}))),pm()],$x.prototype,"target"),Zx([pm(),hm("refreshAspect"),dg("Auto Aspect")],$x.prototype,"autoAspect"),Zx([pm(),hm("refreshAspect"),lg("Aspect Ratio",(e=>({hidden:()=>e.autoAspect})))],$x.prototype,"aspect"),Zx([LA({obj:"userData",onChange:"setDirty"})],$x.prototype,"autoLookAtTarget"),Zx([LA({obj:"userData",onChange:"setDirty"})],$x.prototype,"autoNearFar"),Zx([LA({obj:"userData",onChange:"setDirty"})],$x.prototype,"minNearPlane"),Zx([LA({obj:"userData",onChange:"setDirty"})],$x.prototype,"maxFarPlane"),Zx([LA({obj:"userData"})],$x.prototype,"dollyFov"),Zx([cm(((e,t)=>{t||console.warn("Setting camera invisible is not supported",e,t)}))],$x.prototype,"visible");let ew=$x;class tw extends ew{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 iw=Object.defineProperty,nw=Object.getOwnPropertyDescriptor,rw=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?nw(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&&iw(t,i,s),s};const sw=class extends fs{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 wi(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=Yx.refreshAspect,this.refreshUi=Yx.refreshUi,this.refreshTarget=Yx.refreshTarget,this.activateMain=Yx.activateMain,this.deactivateMain=Yx.deactivateMain,this.updateShaderProperties=Yx.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=Yx.getView,this.setView=Yx.setView,this.fitObject=Yx.fitObject,this.setViewFromCamera=Yx.setViewFromCamera,this.setViewToMain=Yx.setViewToMain,this._positionWorld=new wi,this._camUi=[...Zm(this)||[],...Zb.call(this),ex.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,Yx.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){Yx.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 wi),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(En.DEFAULT_UP)}e&&this.setDirty(),this.refreshUi()}}toJSON(e,t=!1){return t?{...super.toJSON(e),...lv.Serialize(this,e,!0)}:lv.Serialize(this,e,!1)}fromJSON(e,t){return lv.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()}};rw([og("Name")],sw.prototype,"name",2),rw([pm("camControls")],sw.prototype,"_controls",2),rw([sg("Controls Mode",void 0,(e=>({children:["none",...e.controlsCtors.keys()].map((e=>({label:e,value:"none"===e?"":e})))}))),pm(),hm(sw.prototype.refreshCameraControls)],sw.prototype,"controlsMode",2),rw([pm()],sw.prototype,"userData",2),rw([dm(sw.prototype.setDirty),lg("Zoom"),pm()],sw.prototype,"zoom",2),rw([dm(sw.prototype.setDirty),lg("Left",(e=>({hidden:()=>void 0!==e._frustumSize}))),pm()],sw.prototype,"left",2),rw([dm(sw.prototype.setDirty),lg("Right",(e=>({hidden:()=>void 0!==e._frustumSize}))),pm()],sw.prototype,"right",2),rw([dm(sw.prototype.setDirty),lg("Top",(e=>({hidden:()=>void 0!==e._frustumSize}))),pm()],sw.prototype,"top",2),rw([dm(sw.prototype.setDirty),lg("Bottom",(e=>({hidden:()=>void 0!==e._frustumSize}))),pm()],sw.prototype,"bottom",2),rw([og("Frustum Size")],sw.prototype,"frustumSize",1),rw([rg("Position",void 0,void 0,(e=>({onChange:()=>e.setDirty({change:"position"})}))),pm()],sw.prototype,"position",2),rw([rg("Up",void 0,void 0,(e=>({onChange:()=>e.setDirty({change:"up"})}))),pm()],sw.prototype,"up",2),rw([rg("Rotation",void 0,void 0,(e=>({onChange:()=>e.setDirty({change:"rotation"}),disabled:()=>e.autoLookAtTarget})))],sw.prototype,"rotation",2),rw([rg("Target",void 0,void 0,(e=>({onChange:()=>e.setDirty({change:"target"}),disabled:()=>!e.autoLookAtTarget}))),pm()],sw.prototype,"target",2),rw([pm(),hm("refreshAspect"),dg("Auto Aspect")],sw.prototype,"autoAspect",2),rw([pm(),hm("refreshAspect"),lg("Aspect Ratio",(e=>({hidden:()=>e.autoAspect})))],sw.prototype,"aspect",2),rw([LA({obj:"userData",onChange:"setDirty"})],sw.prototype,"autoLookAtTarget",2),rw([LA({obj:"userData",onChange:"setDirty"})],sw.prototype,"autoNearFar",2),rw([LA({obj:"userData",onChange:"setDirty"})],sw.prototype,"minNearPlane",2),rw([LA({obj:"userData",onChange:"setDirty"})],sw.prototype,"maxFarPlane",2),rw([cm(((e,t)=>{t||console.warn("Setting camera invisible is not supported",e,t)}))],sw.prototype,"visible",2);let aw=sw;class ow extends aw{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 lw extends Fx{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:dt}))),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 Ht));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`+UA(e.id??"input",e.colorSpace))).join("\n");e.fragmentShader.includes("#include <encodings_pars_fragment>")?e.fragmentShader=Cv(e.fragmentShader,"#include <encodings_pars_fragment>",i,{append:!0}):e.fragmentShader.includes("precision highp float;")?e.fragmentShader=Cv(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 cw=class extends Kh{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isPhysicalMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Dx.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=Dx.registerMaterialExtensions,this.unregisterMaterialExtensions=Dx.unregisterMaterialExtensions,this.onAfterRender=Dx.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:[...mx(this),...Zm(this),gx(this),_x(this),bx(this),xx(this),wx(this),yx(this),Ax(this),Cx(this),Sx(this),Mx(this),fx(this),...vx(this)]},this.fog=!1,this.attenuationDistance=0,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Dx.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Dx.dispose(super.dispose).call(this)}clone(e=!1){return Dx.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Dx.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=Cv(e.vertexShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);for(const t of i)e.fragmentShader=Cv(e.fragmentShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);e.fragmentShader=Cv(e.fragmentShader,"#include <opaque_fragment>","gl_FragColor = clamp(gl_FragColor, 0.0, 1000.0);\n",{append:!0}),Dx.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),Dx.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),Dx.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),...lv.Serialize(this,e,!0)}:lv.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(lv.Deserialize(e,this,t,!0),this.setValues(e),this):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};cw.TypeSlug="pmat",cw.TYPE="PhysicalMaterial",cw.TypeAlias=["physical","standard",cw.TYPE,cw.TypeSlug,"MeshStandardMaterial","MeshStandardMaterial2","MeshPhysicalMaterial"],lv.SerializableMaterials.add(cw),cw.MaterialProperties={...Ex,color:new Qn(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:ot,normalScale:new Ht(1,1),displacementMap:null,displacementScale:1,displacementBias:0,roughnessMap:null,metalnessMap:null,alphaMap:null,envMap:null,envMapRotation:new hn,envMapIntensity:1,wireframe:!1,wireframeLinewidth:1,wireframeLinecap:"round",wireframeLinejoin:"round",flatShading:!1,fog:!0,clearcoat:0,clearcoatMap:null,clearcoatRoughness:0,clearcoatRoughnessMap:null,clearcoatNormalScale:new Ht(1,1),clearcoatNormalMap:null,dispersion:0,reflectivity:.5,iridescence:0,iridescenceMap:null,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],iridescenceThicknessMap:null,sheen:0,sheenColor:new Qn(0),sheenColorMap:null,sheenRoughness:1,sheenRoughnessMap:null,transmission:0,transmissionMap:null,thickness:0,thicknessMap:null,attenuationDistance:1/0,attenuationColor:new Qn(1,1,1),specularIntensity:1,specularIntensityMap:null,specularColor:new Qn(1,1,1),specularColorMap:null,anisotropy:0,anisotropyRotation:0,anisotropyMap:null},cw.MapProperties=["map","lightMap","aoMap","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap","envMap","clearcoatMap","clearcoatRoughnessMap","clearcoatNormalMap","iridescenceMap","iridescenceThicknessMap","sheenColorMap","sheenRoughnessMap","transmissionMap","thicknessMap","specularIntensityMap","specularColorMap","anisotropyMap"],cw.InterpolateProperties=[...Tx,"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 hw=cw;const dw=class extends Fr{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isObjectShaderMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Dx.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Dx.registerMaterialExtensions,this.unregisterMaterialExtensions=Dx.unregisterMaterialExtensions,this.onBeforeRender=Dx.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=Dx.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:[...Zm(this),...mx(this),gx(this),fx(this),...vx(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Dx.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Dx.dispose(super.dispose).call(this)}clone(e=!1){return Dx.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Dx.customProgramCacheKey.call(this)}onBeforeCompile(e,t){Dx.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)?(Dx.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),...lv.Serialize(this,e,!0)}:lv.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(lv.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};dw.TypeSlug="shmat",dw.TYPE="ObjectShaderMaterial",dw.TypeAlias=["shader",dw.TYPE,dw.TypeSlug,"ShaderMaterial"],lv.SerializableMaterials.add(dw),dw.MaterialProperties={...Ex,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},dw.InterpolateProperties=[...Tx,"linewidth","wireframeLinewidth"];let uw=dw;const pw=class extends tc{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isUnlitLineMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Dx.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Dx.registerMaterialExtensions,this.unregisterMaterialExtensions=Dx.unregisterMaterialExtensions,this.onBeforeRender=Dx.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=Dx.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"]},px(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})))},gx(this),fx(this),...vx(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Dx.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Dx.dispose(super.dispose).call(this)}clone(e=!1){return Dx.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Dx.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=Cv(e.vertexShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);for(const t of i)e.fragmentShader=Cv(e.fragmentShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);Dx.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)?(Dx.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),...lv.Serialize(this,e,!0)}:lv.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(lv.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};pw.TypeSlug="blmat",pw.TYPE="UnlitLineMaterial",pw.TypeAlias=["unlitline","basicline",pw.TYPE,pw.TypeSlug,"LineBasicMaterial"],lv.SerializableMaterials.add(pw),pw.MaterialProperties={...Ex,color:new Qn(16777215),map:null,linewidth:1,linecap:"round",linejoin:"round",fog:!0},pw.MapProperties=["map"],pw.InterpolateProperties=[...Tx,"color","linewidth"];let mw=pw;var gw=Object.defineProperty,fw=(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&&gw(t,i,s),s};const Aw=(i=class extends Ay{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isLineMaterial2=!0,this.appliedMeshes=new Set,this.setDirty=Dx.setDirty,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Dx.registerMaterialExtensions,this.unregisterMaterialExtensions=Dx.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:[...Zm(this)||[],gx(this),fx(this),...vx(this)]},this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Dx.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Dx.dispose(super.dispose).call(this)}clone(e=!1){return Dx.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Dx.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=Cv(e.vertexShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);for(const t of i)e.fragmentShader=Cv(e.fragmentShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);Dx.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),Dx.onBeforeRender.call(this,e,t,i,n,r,s)}onAfterRender(e,t,i,n,r,s){super.onAfterRender(e,t,i,n,r,s),Dx.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?(Dx.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),...lv.Serialize(this,e,!0)}:lv.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(lv.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"],lv.SerializableMaterials.add(i),i.MaterialProperties={...Ex,color:new Qn(16777215),dashed:!1,dashScale:1,dashSize:1,dashOffset:0,gapSize:1,linewidth:1,resolution:new Ht(1,1),alphaToCoverage:!1,worldUnits:!1,uniforms:{},defines:{},extensions:{},clipping:!1,fog:!0,fragmentShader:"",vertexShader:""},i.InterpolateProperties=[...Tx,"color","dashScale","dashSize","dashOffset","gapSize","linewidth","resolution"],i);fw([og()],Aw.prototype,"name"),fw([cg()],Aw.prototype,"color"),fw([dg()],Aw.prototype,"dashed"),fw([lg()],Aw.prototype,"dashScale"),fw([lg()],Aw.prototype,"dashSize"),fw([lg()],Aw.prototype,"dashOffset"),fw([lg()],Aw.prototype,"gapSize"),fw([lg()],Aw.prototype,"linewidth"),fw([rg()],Aw.prototype,"resolution"),fw([dg()],Aw.prototype,"alphaToCoverage"),fw([dg()],Aw.prototype,"worldUnits");let yw=Aw;const vw=class extends Jh{constructor({customMaterialExtensions:e,...t}={}){super(),this.assetType="material",this.isLegacyPhongMaterial=!0,this.appliedMeshes=new Set,this.setDirty=Dx.setDirty,this.envMap=null,this.materialExtensions=[],this.extraUniformsToUpload={},this.registerMaterialExtensions=Dx.registerMaterialExtensions,this.unregisterMaterialExtensions=Dx.unregisterMaterialExtensions,this.onBeforeRender=Dx.onBeforeRenderOverride(super.onBeforeRender),this.onAfterRender=Dx.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:[...mx(this),gx(this),fx(this),Ax(this),{type:"folder",label:"Specular",children:[{type:"color",property:[this,"specular"]},{type:"image",property:[this,"specularMap"]},px(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}]},bx(this),xx(this),{type:"folder",label:"Env Map",children:[{type:"image",property:[this,"envMap"]},px(this,"envMap"),{type:"slider",label:"Env Map Intensity",property:[this,"envMapIntensity"],bounds:[0,5],stepSize:.01}]},...vx(this)]},!this.defines&&(this.defines={}),this.fog=!1,this.setDirty=this.setDirty.bind(this),e&&this.registerMaterialExtensions(e),Dx.upgradeMaterial.call(this),this.setValues(t)}dispose(){return Dx.dispose(super.dispose).call(this)}clone(e=!1){return Dx.clone(super.clone).call(this,e)}customProgramCacheKey(){return super.customProgramCacheKey()+Dx.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=Cv(e.vertexShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);for(const t of i)e.fragmentShader=Cv(e.fragmentShader,t[0],"#glMarker "+t[1]+"\n"+t[0]);Dx.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)?(Dx.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),...lv.Serialize(this,e,!0)}:lv.Serialize(this,e,!1)}fromJSON(e,t,i=!1){return i?(lv.Deserialize(e,this,t,!0),this.setValues(e)):(this.dispatchEvent({type:"beforeDeserialize",data:e,meta:t,bubbleToObject:!0,bubbleToParent:!0}),this)}};vw.TypeSlug="phongmat",vw.TYPE="LegacyPhongMaterial",vw.TypeAlias=["phong",vw.TYPE,vw.TypeSlug,"MeshPhongMaterial"],lv.SerializableMaterials.add(vw),vw.MaterialProperties={...Ex,color:new Qn(16777215),specular:new Qn(1118481),shininess:30,map:null,lightMap:null,lightMapIntensity:1,aoMap:null,aoMapIntensity:1,emissive:new Qn(0),emissiveIntensity:1,emissiveMap:null,bumpMap:null,bumpScale:1,normalMap:null,normalMapType:"TangentSpaceNormalMap",normalScale:new Ht(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},vw.MapProperties=["map","lightMap","aoMap","emissiveMap","bumpMap","normalMap","displacementMap","specularMap","alphaMap","envMap"],vw.InterpolateProperties=[...Tx,"color","specular","emissive","shininess","lightMapIntensity","aoMapIntensity","emissiveIntensity","bumpScale","normalScale","displacementScale","displacementBias","envMapIntensity","reflectivity","refractionRatio","wireframeLinewidth"];let _w=vw;class bw extends En{constructor(){super(),this.assetType="model",this.setDirty=kx.setDirty,this.refreshUi=kx.refreshUi,kx.upgradeObject3D.call(this)}get modelObject(){return this}dispose(){}}class xw extends Lo{constructor(){super(),this.assetType="model",this.setDirty=kx.setDirty,this.refreshUi=kx.refreshUi,kx.upgradeObject3D.call(this)}get modelObject(){return this}dispose(){}}class ww extends Pr{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=kx.setDirty,this.refreshUi=kx.refreshUi,kx.upgradeObject3D.call(this)}get modelObject(){return this}}class Cw extends fy{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 Sw extends By{constructor(e=new Cw,t=new Ay({color:16777215*Math.random()})){super(e,t),this.isLine2=!0,this.type="Line2"}}class Mw extends Sw{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=kx.setDirty,this.refreshUi=kx.refreshUi,this.isMeshLine=!0,kx.upgradeObject3D.call(this)}get modelObject(){return this}}class Ew extends By{constructor(e,t){super(e,t),this.assetType="model",this.setDirty=kx.setDirty,this.refreshUi=kx.refreshUi,this.isMeshLineSegments=!0,kx.upgradeObject3D.call(this)}get modelObject(){return this}}class Tw extends ur{constructor(){super(),this.center2=nx.center2,this.setDirty=nx.setDirty,this.refreshUi=nx.refreshUi,this.appliedMeshes=new Set,nx.upgradeGeometry.call(this)}}class Iw extends Cw{constructor(){super(),this.center2=nx.center2,this.setDirty=nx.setDirty,this.refreshUi=nx.refreshUi,this.appliedMeshes=new Set,nx.upgradeGeometry.call(this)}getPositions(){return Pw(this.attributes.instanceStart)}getColors(){return Pw(this.attributes.instanceColorStart)}}function Pw(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 Dw extends fy{constructor(){super(),this.center2=nx.center2,this.setDirty=nx.setDirty,this.refreshUi=nx.refreshUi,this.appliedMeshes=new Set,nx.upgradeGeometry.call(this)}getPositions(){return this.attributes.instanceStart?.data.array||null}getColors(){return this.attributes.instanceColorStart?.data.array||null}}class Rw extends fy{constructor(e){super(),this.isWireframeGeometry2=!0,this.type="WireframeGeometry2",this.fromWireframeGeometry(new Vh(e))}}class Bw extends ur{constructor(e,t,i=32,n=64,r=!1,s=new Ht(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 wi,c=new wi,h=new wi,d=new Ht;let u=new wi;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 rr(p,3)),this.setAttribute("uv",new rr(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 Lw=class extends Sc{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 wi)}};am.SerializableClasses.set("EllipseCurve3D",Lw);let Ow=Lw;const Uw={setDirty:function(e,...t){"string"==typeof e&&(e={change:e}),kx.setDirty.call(this,e,...t)},upgradeLight:function(e){this&&kx.upgradeObject3D.call(this,e)},refreshUi:kx.refreshUi};var Fw=Object.defineProperty,Nw=(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&&Fw(t,i,s),s};class kw extends Yd{constructor(e,t){super(e,t),this.assetType="light",this.setDirty=Uw.setDirty,this.refreshUi=Uw.refreshUi,this.uiConfig={type:"folder",label:"Ambient Light",children:[...Zm(this),...ix.call(this)]},this.isAmbientLight2=!0,Uw.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}}Nw([dg("Enabled"),dm("setDirty")],kw.prototype,"visible"),Nw([og("Name"),dm("setDirty")],kw.prototype,"name"),Nw([cg("Color",(e=>({onChange:()=>e.setDirty()})))],kw.prototype,"color"),Nw([lg("Intensity"),dm("setDirty")],kw.prototype,"intensity");var jw=Object.defineProperty,zw=(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&&jw(t,i,s),s};const Gw=class extends Xd{constructor(e,t){super(e,t),this.assetType="light",this.setDirty=Uw.setDirty,this.refreshUi=Uw.refreshUi,this.uiConfig={type:"folder",label:"Directional Light",children:[...Zm(this),...ix.call(this)]},this.isDirectionalLight2=!0,this.target.position.set(0,0,-1),this.add(this.target),Uw.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}};zw([dg("Enabled"),dm("setDirty")],Gw.prototype,"visible"),zw([og("Name"),dm("setDirty")],Gw.prototype,"name"),zw([cg("Color",(e=>({onChange:()=>e.setDirty()})))],Gw.prototype,"color"),zw([ng("Intensity",[0,100],.01),dm("setDirty")],Gw.prototype,"intensity"),zw([rg("Position",void 0,void 0,(e=>({onChange:()=>e.setDirty()})))],Gw.prototype,"position"),zw([rg("Rotation",void 0,void 0,(e=>({onChange:()=>e.setDirty()})))],Gw.prototype,"rotation"),zw([dg("Cast Shadow"),dm("setDirty")],Gw.prototype,"castShadow"),zw([rg("Shadow Map Size",void 0,void 0,(e=>({onChange:()=>e._mapSizeChanged()}))),LA({obj:"shadow",key:"mapSize",onChange:Gw.prototype._mapSizeChanged,onChangeParams:!1})],Gw.prototype,"shadowMapSize"),zw([ng("Shadow Bias",[-.001,.001],1e-5),LA({obj:"shadow",key:"bias",onChange:"setDirty"})],Gw.prototype,"shadowBias"),zw([ng("Shadow Normal Bias",[-.1,.1],.005),LA({obj:"shadow",key:"normalBias",onChange:"setDirty"})],Gw.prototype,"shadowNormalBias"),zw([ng("Shadow Radius",[0,5],.01),LA({obj:"shadow",key:"radius",onChange:"setDirty"})],Gw.prototype,"shadowRadius"),zw([lg("Shadow Frustum"),hm(Gw.prototype._shadowFrustumChanged)],Gw.prototype,"shadowFrustum"),zw([lg("Shadow Near"),LA({obj:"shadow",key:["camera","near"],onChange:Gw.prototype._shadowCamUpdate})],Gw.prototype,"shadowNear"),zw([lg("Shadow Far"),LA({obj:"shadow",key:["camera","far"],onChange:Gw.prototype._shadowCamUpdate})],Gw.prototype,"shadowFar");let Qw=Gw;var Vw=Object.defineProperty,Hw=(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&&Vw(t,i,s),s};class Ww extends Od{constructor(e,t,i){super(e,t,i),this.assetType="light",this.setDirty=Uw.setDirty,this.refreshUi=Uw.refreshUi,this.uiConfig={type:"folder",label:"Hemisphere Light",children:[...Zm(this),...ix.call(this)]},this.isHemisphereLight2=!0,Uw.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}}Hw([dg("Enabled"),dm("setDirty")],Ww.prototype,"visible"),Hw([og("Name"),dm("setDirty")],Ww.prototype,"name"),Hw([cg("Sky Color",(e=>({onChange:()=>e.setDirty()})))],Ww.prototype,"color"),Hw([cg("Ground Color",(e=>({onChange:()=>e.setDirty()})))],Ww.prototype,"groundColor"),Hw([lg("Intensity"),dm("setDirty")],Ww.prototype,"intensity"),Hw([rg("Position",void 0,void 0,(e=>({onChange:()=>e.setDirty()})))],Ww.prototype,"position");var qw=Object.defineProperty,Xw=(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&&qw(t,i,s),s};const Yw=class extends Wd{constructor(e,t,i,n){super(e,t,i,n),this.assetType="light",this.setDirty=Uw.setDirty,this.refreshUi=Uw.refreshUi,this.uiConfig={type:"folder",label:"Point Light",children:[...Zm(this),...ix.call(this)]},this.isPointLight2=!0,Uw.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}};Xw([dg("Enabled"),dm("setDirty")],Yw.prototype,"visible"),Xw([og("Name"),dm("setDirty")],Yw.prototype,"name"),Xw([cg("Color",(e=>({onChange:()=>e.setDirty()})))],Yw.prototype,"color"),Xw([lg("Intensity"),dm("setDirty")],Yw.prototype,"intensity"),Xw([lg("Distance"),dm("setDirty")],Yw.prototype,"distance"),Xw([lg("Decay"),dm("setDirty")],Yw.prototype,"decay"),Xw([lg("Power"),dm("setDirty")],Yw.prototype,"power"),Xw([rg("Position",void 0,void 0,(e=>({onChange:()=>e.setDirty()})))],Yw.prototype,"position"),Xw([dg("Cast Shadow"),dm("setDirty")],Yw.prototype,"castShadow"),Xw([rg("Shadow Map Size",void 0,void 0,(e=>({onChange:()=>e._mapSizeChanged()}))),LA({obj:"shadow",key:"mapSize",onChange:Yw.prototype._mapSizeChanged,onChangeParams:!1})],Yw.prototype,"shadowMapSize"),Xw([ng("Shadow Bias",[-.001,.001],1e-5),LA({obj:"shadow",key:"bias",onChange:"setDirty"})],Yw.prototype,"shadowBias"),Xw([ng("Shadow Radius",[0,5],.01),LA({obj:"shadow",key:"radius",onChange:"setDirty"})],Yw.prototype,"shadowRadius"),Xw([lg("Shadow Near"),LA({obj:"shadow",key:["camera","near"],onChange:Yw.prototype._shadowCamUpdate})],Yw.prototype,"shadowNear"),Xw([lg("Shadow Far"),LA({obj:"shadow",key:["camera","far"],onChange:Yw.prototype._shadowCamUpdate})],Yw.prototype,"shadowFar"),Xw([lg("Shadow Aspect"),LA({obj:"shadow",key:"aspect",onChange:Yw.prototype._shadowCamUpdate})],Yw.prototype,"shadowAspect"),Xw([ng("Shadow FOV",[1,179],1),LA({obj:"shadow",key:"fov",onChange:Yw.prototype._shadowCamUpdate})],Yw.prototype,"shadowFov");let Kw=Yw;var Jw=Object.defineProperty,Zw=(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&&Jw(t,i,s),s};class $w extends Kd{constructor(e,t,i,n){super(e,t,i,n),this.assetType="light",this.setDirty=Uw.setDirty,this.refreshUi=Uw.refreshUi,this.uiConfig={type:"folder",label:"RectArea Light",children:[...Zm(this),...ix.call(this)]},this.isRectAreaLight2=!0,Uw.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}}Zw([dg("Enabled"),dm("setDirty")],$w.prototype,"visible"),Zw([og("Name"),dm("setDirty")],$w.prototype,"name"),Zw([cg("Color",(e=>({onChange:()=>e.setDirty()})))],$w.prototype,"color"),Zw([lg("Intensity"),dm("setDirty")],$w.prototype,"intensity"),Zw([lg("Width"),dm("setDirty")],$w.prototype,"width"),Zw([lg("Height"),dm("setDirty")],$w.prototype,"height"),Zw([lg("Power"),dm("setDirty")],$w.prototype,"power");var eC=Object.defineProperty,tC=(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&&eC(t,i,s),s};const iC=class extends zd{constructor(e,t,i,n,r,s){super(e,t,i,n,r,s),this.assetType="light",this.setDirty=Uw.setDirty,this.refreshUi=Uw.refreshUi,this.uiConfig={type:"folder",label:"Spot Light",children:[...Zm(this),...ix.call(this)]},this.isSpotLight2=!0,this.target.position.set(0,0,-1),this.add(this.target),Uw.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}};tC([dg("Enabled"),dm("setDirty")],iC.prototype,"visible"),tC([og("Name"),dm("setDirty")],iC.prototype,"name"),tC([cg("Color",(e=>({onChange:()=>e.setDirty()})))],iC.prototype,"color"),tC([lg("Intensity"),dm("setDirty")],iC.prototype,"intensity"),tC([ng("Angle",[0,2],.01),dm("setDirty")],iC.prototype,"angle"),tC([ng("Penumbra",[0,.9999],.01),dm("setDirty")],iC.prototype,"penumbra"),tC([og("Distance"),dm("setDirty")],iC.prototype,"distance"),tC([og("Decay"),dm("setDirty")],iC.prototype,"decay"),tC([rg("Position",void 0,void 0,(e=>({onChange:()=>e.setDirty()})))],iC.prototype,"position"),tC([rg("Rotation",void 0,void 0,(e=>({onChange:()=>e.setDirty()})))],iC.prototype,"rotation"),tC([dg("Cast Shadow"),dm("setDirty")],iC.prototype,"castShadow"),tC([rg("Shadow Map Size",void 0,void 0,(e=>({onChange:()=>e._mapSizeChanged()}))),LA({obj:"shadow",key:"mapSize",onChange:iC.prototype._mapSizeChanged,onChangeParams:!1})],iC.prototype,"shadowMapSize"),tC([ng("Shadow Bias",[-.001,.001],1e-5),LA({obj:"shadow",key:"bias",onChange:"setDirty"})],iC.prototype,"shadowBias"),tC([ng("Shadow Radius",[0,5],.01),LA({obj:"shadow",key:"radius",onChange:"setDirty"})],iC.prototype,"shadowRadius"),tC([ng("Shadow Focus",[0,1],.001),LA({obj:"shadow",key:"focus",onChange:"setDirty"})],iC.prototype,"shadowFocus"),tC([lg("Shadow Near"),LA({obj:"shadow",key:["camera","near"],onChange:iC.prototype._shadowCamUpdate})],iC.prototype,"shadowNear"),tC([lg("Shadow Far"),LA({obj:"shadow",key:["camera","far"],onChange:iC.prototype._shadowCamUpdate})],iC.prototype,"shadowFar"),tC([lg("Shadow Aspect"),LA({obj:"shadow",key:"aspect",onChange:iC.prototype._shadowCamUpdate})],iC.prototype,"shadowAspect"),tC([ng("Shadow FOV",[1,179],1),LA({obj:"shadow",key:"fov",onChange:iC.prototype._shadowCamUpdate})],iC.prototype,"shadowFov");let nC=iC;function rC(){this.assetType="texture",this.userData||(this.userData={}),this.appliedObjects||(this.appliedObjects=new Set),this.setDirty||(this.setDirty=()=>this.needsUpdate=!0)}function sC(e){return this.userData?.__isIWebGLRenderer||(this.userData||(this.userData={__isIWebGLRenderer:!0}),this.userData.__isIWebGLRenderer=!0,this.renderWithModes||(this.renderWithModes=aC),this.renderManager=e,this.baseRenderer||Object.defineProperty(this,"baseRenderer",{get:()=>(console.warn("IWebGLRenderer.baseRenderer is deprecated, use IWebGLRenderer.renderManager instead"),this.renderManager)})),this}function aC(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 oC=aC;var lC=Object.defineProperty,cC=Object.getOwnPropertyDescriptor,hC=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?cC(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&&lC(t,i,s),s};e.RootScene=class extends Wo{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 ew(""),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 TA,this._sceneBoundingRadius=0,this.refreshUi=kx.refreshUi.bind(this),this.traverseModels=kx.traverseModels.bind(this),this._v1=new wi,this._v2=new wi,this._autoNearFarDisabled=new Set,this.overrideRenderEnvironment=null,this._isMainRendering=!1,this.setDirty=this.setDirty.bind(this),this.name="RootScene",this.objectProcessor=t,kx.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 En,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 Qn(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))}kb(n,i),this.setDirty({refreshScene:!0})}centerAllGeometries(e=!0,t){return jb(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 Qn(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}),kx.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 wi).length()/2,this.dispatchEvent({...e,type:"sceneUpdate",hierarchyChanged:["addedToParent","removedFromParent"].includes(e?.change||"")}),t||kx.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 TA).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 TA:(new TA).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=>ly(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??Yx.defaultMinNear,t=i.userData.maxFarPlane??Yx.defaultMaxFar,Yx.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 Yx.setNearFar(t,i,n,e,"RootScene");const r=this.getBounds(!1),s=r.getSize(this._v2).length();if(s<.001)return Yx.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 wi)));return i=Math.max(Math.max(t.userData.minNearPlane??Yx.defaultMinNear,.001),l*(o-a)),n=Math.min(Math.max(i+a,l*(o+a)),t.userData.maxFarPlane??Yx.defaultMaxFar),(n<i||n-i<.1)&&(n=i+.1),Yx.setNearFar(t,i,n,e,"RootScene")}dollyActiveCameraFov(){const e=this.mainCamera;if(!e||!e.userData.dollyFov)return!1;const t=1.5*sv(e,this.getModelBounds(!1,!0,!0)),i=(new wi).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=lv.Serialize(this,e,!0);return t.envMapIntensity=t.environmentIntensity,t}fromJSON(e,t){const i=e.environment;return void 0!==i&&(this.environment=lv.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,lv.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 wi(1,1,1),i=new wi(0,0,0)){if(this._mainCamera){this.matrixWorldNeedsUpdate=!0,this.updateMatrixWorld(!0);const n=e?(new TA).expandByObject(e,!0,!0):this.getBounds(!0),r=n.getCenter(new wi),s=.5*n.getSize(new wi).length();r.add(i.clone().multiplyScalar(s)),this._mainCamera.position=new wi(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}},hC([pm(),hm(e.RootScene.prototype.onBackgroundChange)],e.RootScene.prototype,"backgroundColor",2),hC([cg("Background Color",(e=>({hidden:()=>null===e.backgroundColor||void 0===e.backgroundColor||"environment"===e.background})))],e.RootScene.prototype,"_backgroundColorUi",1),hC([dm(e.RootScene.prototype.onBackgroundChange),pm(),hg("Background Image",(e=>({hidden:()=>null===e.backgroundColor||void 0===e.backgroundColor||"environment"===e.background})))],e.RootScene.prototype,"background",2),hC([ag(void 0,(e=>({label:()=>e.backgroundColor?"Set Transparent BG":"Set Color Background",tags:["context-menu"]})))],e.RootScene.prototype,"toggleTransparentBackground",1),hC([ag(void 0,(e=>({label:()=>"environment"===e.background?"Remove Env Background":"Set Env Background",disabled:()=>!e.environment,tags:["context-menu"]})))],e.RootScene.prototype,"toggleEnvironmentBackground",1),hC([pm(),dm(e.RootScene.prototype.setDirty),ng("Background Intensity",[0,10],.01)],e.RootScene.prototype,"backgroundIntensity",2),hC([dg("Background Tonemap"),dm(e.RootScene.prototype.setDirty),pm()],e.RootScene.prototype,"backgroundTonemap",2),hC([hg("Environment"),pm()],e.RootScene.prototype,"environment",2),hC([ng("Environment Intensity",[0,10],.01),pm(),dm(e.RootScene.prototype.setDirty)],e.RootScene.prototype,"environmentIntensity",2),hC([pm(),rg("Environment Rotation",void 0,void 0,(e=>({disabled:()=>e.fixedEnvMapDirection||!e.environment})))],e.RootScene.prototype,"environmentRotation",2),hC([pm(),rg("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),hC([pm()],e.RootScene.prototype,"textureSlots",2),hC([dg("Fixed Env Direction"),pm(),dm(e.RootScene.prototype.setDirty)],e.RootScene.prototype,"fixedEnvMapDirection",2),hC([eg(),pm()],e.RootScene.prototype,"defaultCamera",2),hC([ag("Center All Geometries",{sendArgs:!1,tags:["context-menu"]})],e.RootScene.prototype,"centerAllGeometries",1),hC([ag("Auto GPU Instance Meshes",{tags:["context-menu"]})],e.RootScene.prototype,"autoGPUInstanceMeshes",1),e.RootScene=hC([pg("Root Scene")],e.RootScene);class dC{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 uC=new fs(-1,1,1,-1,0,1);const pC=new class extends ur{constructor(){super(),this.setAttribute("position",new rr([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new rr([0,2,0,0,2,0],2))}};class mC{constructor(e){this._mesh=new Pr(pC,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,uC)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class gC extends dC{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 Qn}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)),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 fC={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 AC extends dC{constructor(e,t){super(),this.textureID=void 0!==t?t:"tDiffuse",e instanceof Fr?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=Ur.clone(e.uniforms),this.material=new Fr({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 mC(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 yC=Object.defineProperty;const vC=(n=class extends AC{constructor(e,...t){super(e.isMaterial?e:new lw(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&&yC(t,i,r)})([dg("Enabled"),pm(),hm(vC.prototype.setDirty)],vC.prototype,"enabled");let _C=vC;class bC extends _C{constructor(e,t="c = a + b;",i="",n,r=120){super({vertexShader:fC.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 xC=Object.defineProperty;class wC extends gC{constructor(e,t,i=new Qn(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:Zm(this)},this.renderManager=e,this._blendPass=new bC({},"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:ct,type:this.renderManager.renderer.extensions.has("EXT_color_buffer_half_float")?Ie:Ce,format:Be,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:Ie,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 the @repalash/three.js-modded to 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&&xC(t,i,r)})([dg("Enabled"),pm()],wC.prototype,"enabled");class CC extends _C{constructor(e,t=!0){super({uniforms:Ur.clone(fC.uniforms),vertexShader:fC.vertexShader,fragmentShader:Np`
                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?Yp(e,"diffuseColor"):""}
                    #ifdef OPAQUE
                    diffuseColor.a = 1.0;
                    #endif
                    gl_FragColor = diffuseColor;
                    ${t?"#include <colorspace_fragment>":""}
                }
            `},"tDiffuse")}}var SC=Object.defineProperty,MC=Object.getOwnPropertyDescriptor,EC=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?MC(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&&SC(t,i,s),s};e.GBufferRenderPass=class extends gC{constructor(e,t,i,n=new Qn(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,Yp(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}},EC([dg("Enabled")],e.GBufferRenderPass.prototype,"enabled",2),e.GBufferRenderPass=EC([pg((e=>e.passId+" Render Pass"))],e.GBufferRenderPass);const TC="#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 IC=Object.defineProperty,PC=Object.getOwnPropertyDescriptor,DC=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?PC(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&&IC(t,i,s),s};function RC(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)&&Jp(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 _C{constructor(e="",...t){super(e?.fragmentShader||e?.isShaderMaterial?e:function(e){const t=Cv(TC,"void main()",(Array.isArray(e)?e[0]:e?.pars||"")+"\n",{prepend:!0}),i=t.includes("#glMarker")?Cv(t,"#glMarker",(Array.isArray(e)?e[1]:"string"==typeof e?e:e?.main||"")+"\n",{prepend:!0}):t;return{...fC,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=ht,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}},DC([sg("Output Color Space",ty.ColorSpace.uiConfig,(e=>({onChange:e.setDirty})))],e.ScreenPass.prototype,"outputColorSpace",2),DC([BA("CLIP_BACKGROUND_FORCE",void 0,void 0,e.ScreenPass.prototype.setDirty,!0)],e.ScreenPass.prototype,"clipBackgroundForce",2),DC([BA("CLIP_BACKGROUND",void 0,void 0,e.ScreenPass.prototype.setDirty),dg()],e.ScreenPass.prototype,"clipBackground",2),e.ScreenPass=DC([pg("Screen Pass")],e.ScreenPass);class BC extends dC{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 LC extends dC{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class OC{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),void 0===t){const i=e.getSize(new Ht);this._width=i.width,this._height=i.height,(t=new vi(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Ie})).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 AC(fC),this.copyPass.material.blending=w,this.clock=new pu}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!==BC&&(n instanceof BC?i=!0:n instanceof LC&&(i=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(void 0===e){const t=this.renderer.getSize(new Ht);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 UC extends OC{constructor(e,t){super(e,t),this.copyPass2=new CC}setPixelRatio(e,t=!0){const i=this.setSize;t||(this.setSize=()=>{}),super.setPixelRatio(e),t||(this.setSize=i)}}function FC(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 NC extends Bt{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=Be,stencilBuffer:s=!1,depthBuffer:a=!0,depthTexture:o=!1,depthTextureType:l=Ee,depthTextureFormat:c=Le,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 zs(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=FC(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===Wr.prototype){if(e!==t)throw"Width and height of cube render target must be equal";r=[e]}return this._createTargetClass(n??vi,r,{format:Be,minFilter:be,magFilter:be,generateMipmaps:!1,type:Ce,colorSpace:ct,...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 kC{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 jC=class extends Bt{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 kC(Id,["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 Cd(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)}}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:eu.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??Lp(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)e.loader?.dispose&&e.loader?.dispose();this._loaderCache=[]}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&&Yp(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))||Yp(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=Lp(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);return r?(Yp(n.ext)?.forEach((e=>{const t=new RegExp(e.startsWith("data:")?"^"+Op(e)+"[\\/\\+\\:\\,\\;]":"\\."+e+"$","i");this._loadingManager.addHandler(t,r)})),n.mime?.forEach((e=>{const t=new RegExp("^data:"+Op(e)+"[\\/\\+\\:\\,\\;]","i");this._loadingManager.addHandler(t,r)})),this._loaderCache.push({loader:r,ext:Yp(n.ext)||[],mime:n.mime}),this.dispatchEvent({type:"loaderCreate",loader:r}),r):void 0}_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&&(wd.enabled=!0);IA(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)}};jC.DummyMaterial=new Px({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),jC.DummyLineBasicMaterial=new mw({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),jC.DummyLineMaterial=new yw({color:"#ff00ff",name:"NoneMaterial",userData:{isPlaceholder:!0,runtimeMaterial:!0}}),jC.DummyGeometry=new ur,jC.DummyMaterial.uiConfig={},jC.DummyLineBasicMaterial.uiConfig={},jC.DummyLineMaterial.uiConfig={},jC.DummyGeometry.uiConfig={};let zC,GC,QC,VC,HC=jC;function WC(e,t=1/0,i=null){GC||(GC=new is(2,2,1,1)),QC||(QC=new Fr({uniforms:{blitTexture:new ku(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 = LinearTosRGB( 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}"})),QC.uniforms.blitTexture.value=e,QC.defines.IS_SRGB=e.colorSpace==ht,QC.needsUpdate=!0,VC||(VC=new Pr(GC,QC),VC.frustumCulled=!1);const n=new Gr,r=new Wo;r.add(VC),null===i&&(i=zC=new Qo({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 wc(o);return c.minFilter=e.minFilter,c.magFilter=e.magFilter,c.wrapS=e.wrapS,c.wrapT=e.wrapT,c.name=e.name,zC&&(zC.forceContextLoss(),zC.dispose(),zC=null),c}const qC={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 XC{constructor(){this.pluginCallbacks=[],this.register((function(e){return new TS(e)})),this.register((function(e){return new IS(e)})),this.register((function(e){return new RS(e)})),this.register((function(e){return new BS(e)})),this.register((function(e){return new LS(e)})),this.register((function(e){return new OS(e)})),this.register((function(e){return new PS(e)})),this.register((function(e){return new DS(e)})),this.register((function(e){return new US(e)})),this.register((function(e){return new FS(e)})),this.register((function(e){return new NS(e)})),this.register((function(e){return new kS(e)})),this.register((function(e){return new jS(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 ES,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 YC=0,KC=1,JC=2,ZC=3,$C=4,eS=5120,tS=5121,iS=5122,nS=5123,rS=5124,sS=5125,aS=5126,oS=34962,lS=34963,cS=9728,hS=9729,dS=9984,uS=9985,pS=9986,mS=9987,gS=33071,fS=33648,AS=10497,yS="KHR_mesh_quantization",vS={};vS[ye]=cS,vS[ve]=dS,vS[_e]=pS,vS[be]=hS,vS[xe]=uS,vS[we]=mS,vS[fe]=gS,vS[ge]=AS,vS[Ae]=fS;const _S={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},bS=new Qn;function xS(e,t){return e.length===t.length&&e.every((function(e,i){return e===t[i]}))}function wS(e){return 4*Math.ceil(e/4)}function CS(e,t=0){const i=wS(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 SS(){return typeof document>"u"&&typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas")}function MS(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 ES{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"}},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=CS(e.result),n=new DataView(new ArrayBuffer(8));n.setUint32(0,i.byteLength,!0),n.setUint32(4,5130562,!0);const r=CS(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 wi;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 wi;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===ht?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=WC(e)),t instanceof _c&&(t=WC(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=SS();o.width=s,o.height=a;const l=o.getContext("2d");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 di(o),h.colorSpace=ct,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 eS:case tS:a=1;break;case iS:case nS:a=2;break;default:a=4}let o=e.itemSize*a;r===oS&&(o=4*Math.ceil(o/4));const l=wS(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=Vt.normalize(n,e.array))),t===aS?c.setFloat32(h,n,!0):t===rS?c.setInt32(h,n,!0):t===sS?c.setUint32(h,n,!0):t===iS?c.setInt16(h,n,!0):t===nS?c.setUint16(h,n,!0):t===eS?c.setInt8(h,n):t===tS&&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===oS&&(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=CS(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=CS(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=aS;else if(e.array.constructor===Int32Array)s=rS;else if(e.array.constructor===Uint32Array)s=sS;else if(e.array.constructor===Int16Array)s=iS;else if(e.array.constructor===Uint16Array)s=nS;else if(e.array.constructor===Int8Array)s=eS;else{if(e.array.constructor!==Uint8Array)throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);s=tS}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=Vt.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?lS:oS);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=SS();m.width=Math.min(r||e.width,c.maxTextureSize),m.height=Math.min(s||e.height,c.maxTextureSize);const g=m.getContext("2d");if(!0===i&&(g.translate(0,m.height),g.scale(1,-1)),void 0!==e.data){t!==Be&&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(MS(m,n).then((e=>a.processBufferViewImage(e))).then((e=>{p.bufferView=e}))):void 0!==m.toDataURL?p.uri=m.toDataURL(n):h.push(MS(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:vS[e.magFilter],minFilter:vS[e.minFilter],wrapS:vS[e.wrapS],wrapT:vS[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=WC(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(xS(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?KC:e.isLineLoop?JC:e.isLine?ZC:e.isPoints?YC:e.material.wireframe?KC:$C;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 tr(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[yS])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];qC[n]&&qC[n].includes(i)&&(this.extensionsUsed[yS]=!0,this.extensionsRequired[yS]=!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:Vt.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=XC.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=Ou.parseTrackName(i.name);let l=Ou.findNode(t,o.nodeName);const c=_S[o.propertyName];if("bones"===o.objectName&&(l=!0===l.isSkinnedMesh?l.skeleton.getBoneByName(o.objectIndex):void 0),!l||!c)return console.warn('THREE.GLTFExporter: Could not export animation track "%s".',i.name),null;const h=1;let d,u=i.values.length/i.times.length;c===_S.morphTargetInfluences&&(u/=l.morphTargetInfluences.length),!0===i.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline?(d="CUBICSPLINE",u/=3):d=i.getInterpolation()===Ze?"STEP":"LINEAR",a.push({input:this.processAccessor(new tr(i.times,h)),output:this.processAccessor(new tr(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 $i;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 tr(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();xS(t,[0,0,0,1])||(r.rotation=t),xS(i,[0,0,0])||(r.translation=i),xS(n,[1,1,1])||(r.scale=n)}else e.matrixAutoUpdate&&e.updateMatrix(),!1===function(e){return xS(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 Wo;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 Wo?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 TS{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 IS=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}},PS=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};i.applyTextureTransform(t,e.clearcoatNormalMap),r.clearcoatNormalTexture=t}t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},DS=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}},RS=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}},BS=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}r.attenuationDistance=e.attenuationDistance,r.attenuationColor=e.attenuationColor.toArray(),t.extensions=t.extensions||{},t.extensions[this.name]=r,n[this.name]=!0}},LS=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}},OS=class{constructor(e){this.writer=e,this.name="KHR_materials_specular"}writeMaterial(e,t){if(!e.isMeshPhysicalMaterial||1===e.specularIntensity&&e.specularColor.equals(bS)&&!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}},US=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}},FS=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}},NS=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}},kS=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}},jS=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 $i,l=new wi,c=new xi,h=new wi;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 tr(r,3)),ROTATION:i.processAccessor(new tr(s,4)),SCALE:i.processAccessor(new tr(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}};XC.Utils={GLTFWriter:ES,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=Ou.parseTrackName(s.name),o=Ou.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($e)}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 zS extends XC.Utils.GLTFWriter{constructor(){super(),this.TPAssetVersion=1,this.serializationMeta=gv(),this._defaultMaterial=new Yh,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=lv.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(Gp(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&&qm(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 GS=class{};GS.WebGiLightExtrasExtension="WEBGI_light_extras",GS.Import=e=>({name:"__"+GS.WebGiLightExtrasExtension,afterRoot:async e=>{(e.scenes||(e.scene?[e.scene]:[])).forEach((e=>{e.traverse((e=>{if(!e.isLight)return;const t=e.userData?.gltfExtensions?.[GS.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 nu).parseObject(t.shadow.camera,{},{},{},{}))),delete e.userData.gltfExtensions[GS.WebGiLightExtrasExtension])}))}))}}),GS.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[GS.WebGiLightExtrasExtension]=n,e.extensionsUsed[GS.WebGiLightExtrasExtension]=!0)}}),GS.Textures=void 0;let QS=GS;const VS=class{};VS.WebGiMaterialExtrasExtension="WEBGI_material_extras",VS.Import=e=>t=>({name:"__"+VS.WebGiMaterialExtrasExtension,afterRoot:async i=>{const n=i.scenes||(i.scene?[i.scene]:[]);for(const i of n){const n=i.userData?.gltfExtensions?.[VS.WebGiMaterialExtrasExtension],r=n?.resources?await e(n.resources):{};i.traverse((e=>{const i=e?.material;if(!i?.isMaterial)return;const n=i.userData?.gltfExtensions?.[VS.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]=lv.Deserialize(t,i[e],r))})),delete i.userData.gltfExtensions[VS.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[VS.WebGiMaterialExtrasExtension]}}}),VS.Export=e=>({writeMaterial(t,i){if(!t?.isMaterial)return;i.extensions||(i.extensions={});const n={};void 0!==t.fog&&t.fog!==hw.MaterialProperties.fog&&(n.fog=t.fog),void 0!==t.flatShading&&t.flatShading!==hw.MaterialProperties.flatShading&&(n.flatShading=t.flatShading),void 0!==t.blending&&t.blending!==Ex.blending&&(n.blending=t.blending),void 0!==t.side&&t.side!==x&&(n.side=t.side),void 0!==t.shadowSide&&t.shadowSide!==Ex.shadowSide&&(n.shadowSide=t.shadowSide),void 0!==t.depthFunc&&t.depthFunc!==Ex.depthFunc&&(n.depthFunc=t.depthFunc),void 0!==t.depthTest&&t.depthTest!==Ex.depthTest&&(n.depthTest=t.depthTest),void 0!==t.depthWrite&&t.depthWrite!==Ex.depthWrite&&(n.depthWrite=t.depthWrite),void 0!==t.colorWrite&&t.colorWrite!==Ex.colorWrite&&(n.colorWrite=t.colorWrite),void 0!==t.vertexColors&&t.vertexColors!==Ex.vertexColors&&(n.vertexColors=t.vertexColors),void 0!==t.alphaTest&&t.alphaTest!==Ex.alphaTest&&(n.alphaTest=t.alphaTest),void 0!==t.alphaHash&&t.alphaHash!==Ex.alphaHash&&(n.alphaHash=t.alphaHash),void 0!==t.envMapIntensity&&t.envMapIntensity!==hw.MaterialProperties.envMapIntensity&&(n.envMapIntensity=t.envMapIntensity),void 0!==t.envMapRotation&&!t.envMapRotation.equals(hw.MaterialProperties.envMapRotation)&&(n.envMapRotation=t.envMapRotation.toArray()),void 0!==t.blendSrc&&t.blendSrc!==Ex.blendSrc&&(n.blendSrc=t.blendSrc),void 0!==t.blendDst&&t.blendDst!==Ex.blendDst&&(n.blendDst=t.blendDst),void 0!==t.blendEquation&&t.blendEquation!==Ex.blendEquation&&(n.blendEquation=t.blendEquation),void 0!==t.blendSrcAlpha&&t.blendSrcAlpha!==Ex.blendSrcAlpha&&(n.blendSrcAlpha=t.blendSrcAlpha),void 0!==t.blendDstAlpha&&t.blendDstAlpha!==Ex.blendDstAlpha&&(n.blendDstAlpha=t.blendDstAlpha),void 0!==t.blendEquationAlpha&&t.blendEquationAlpha!==Ex.blendEquationAlpha&&(n.blendEquationAlpha=t.blendEquationAlpha),void 0!==t.blendColor&&t.blendColor!==Ex.blendColor&&(n.blendColor=t.blendColor.getHex()),void 0!==t.blendAlpha&&t.blendAlpha!==Ex.blendAlpha&&(n.blendAlpha=t.blendAlpha),void 0!==t.stencilWrite&&t.stencilWrite!==Ex.stencilWrite&&(n.stencilWrite=t.stencilWrite),void 0!==t.stencilWriteMask&&t.stencilWriteMask!==Ex.stencilWriteMask&&(n.stencilWriteMask=t.stencilWriteMask),void 0!==t.stencilFunc&&t.stencilFunc!==Ex.stencilFunc&&(n.stencilFunc=t.stencilFunc),void 0!==t.stencilRef&&t.stencilRef!==Ex.stencilRef&&(n.stencilRef=t.stencilRef),void 0!==t.stencilFuncMask&&t.stencilFuncMask!==Ex.stencilFuncMask&&(n.stencilFuncMask=t.stencilFuncMask),void 0!==t.stencilFail&&t.stencilFail!==Ex.stencilFail&&(n.stencilFail=t.stencilFail),void 0!==t.stencilZFail&&t.stencilZFail!==Ex.stencilZFail&&(n.stencilZFail=t.stencilZFail),void 0!==t.stencilZPass&&t.stencilZPass!==Ex.stencilZPass&&(n.stencilZPass=t.stencilZPass),void 0!==t.wireframe&&t.wireframe!==hw.MaterialProperties.wireframe&&(n.wireframe=t.wireframe),void 0!==t.wireframeLinewidth&&t.wireframeLinewidth!==hw.MaterialProperties.wireframeLinewidth&&(n.wireframeLinewidth=t.wireframeLinewidth),void 0!==t.wireframeLinecap&&t.wireframeLinecap!==hw.MaterialProperties.wireframeLinecap&&(n.wireframeLinecap=t.wireframeLinecap),void 0!==t.wireframeLinejoin&&t.wireframeLinejoin!==hw.MaterialProperties.wireframeLinejoin&&(n.wireframeLinejoin=t.wireframeLinejoin),void 0!==t.rotation&&(n.rotation=t.rotation),void 0!==t.linewidth&&t.linewidth!==yw.MaterialProperties.linewidth&&(n.linewidth=t.linewidth),void 0!==t.worldUnits&&t.worldUnits!==yw.MaterialProperties.worldUnits&&(n.worldUnits=t.worldUnits),void 0!==t.dashed&&t.dashed!==yw.MaterialProperties.dashed&&(n.dashed=t.dashed),void 0!==t.dashSize&&t.dashSize!==yw.MaterialProperties.dashSize&&(n.dashSize=t.dashSize),void 0!==t.dashScale&&t.dashScale!==yw.MaterialProperties.dashScale&&(n.dashScale=t.dashScale),void 0!==t.dashOffset&&t.dashOffset!==yw.MaterialProperties.dashOffset&&(n.dashOffset=t.dashOffset),void 0!==t.gapSize&&t.gapSize!==yw.MaterialProperties.gapSize&&(n.gapSize=t.gapSize),void 0!==t.polygonOffset&&t.polygonOffset!==Ex.polygonOffset&&(n.polygonOffset=t.polygonOffset),void 0!==t.polygonOffsetFactor&&t.polygonOffsetFactor!==Ex.polygonOffsetFactor&&(n.polygonOffsetFactor=t.polygonOffsetFactor),void 0!==t.polygonOffsetUnits&&t.polygonOffsetUnits!==Ex.polygonOffsetUnits&&(n.polygonOffsetUnits=t.polygonOffsetUnits),void 0!==t.dithering&&t.dithering!==Ex.dithering&&(n.dithering=t.dithering),void 0!==t.alphaToCoverage&&t.alphaToCoverage!==Ex.alphaToCoverage&&(n.alphaToCoverage=t.alphaToCoverage),void 0!==t.premultipliedAlpha&&t.premultipliedAlpha!==Ex.premultipliedAlpha&&(n.premultipliedAlpha=t.premultipliedAlpha),void 0!==t.toneMapped&&t.toneMapped!==Ex.toneMapped&&(n.toneMapped=t.toneMapped),void 0!==t.normalScale&&t.normalScale.isVector2&&(t.normalScale.x!==hw.MaterialProperties.normalScale.x||t.normalScale.y!==hw.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]=lv.Serialize(i,this.serializedMeta),i?.userData&&r&&delete i.userData.embedUrlImagePreviews})),Object.keys(n).length>0&&(i.extensions[VS.WebGiMaterialExtrasExtension]=n,e.extensionsUsed[VS.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&&qm(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[VS.WebGiMaterialExtrasExtension]={resources:this.serializedMeta},e.extensionsUsed[VS.WebGiMaterialExtrasExtension]=!0}}),VS.Textures=void 0;let HS=VS;const WS=class{};WS.WebGiMaterialsAlphaMapExtension="WEBGI_materials_alphamap",WS.Import=e=>new XS(e),WS.Export=e=>new YS(e),WS.Textures={alphaTexture:"G"};let qS=WS;class XS{constructor(e){this.parser=e,this.name=qS.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 YS{constructor(e){this.writer=e,this.name=qS.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 KS=class{};KS.WebGiMaterialsBumpMapExtension="WEBGI_materials_bumpmap",KS.Import=e=>new ZS(e),KS.Export=e=>new $S(e),KS.Textures={bumpTexture:"R"};let JS=KS;class ZS{constructor(e){this.parser=e,this.name=JS.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 $S{constructor(e){this.writer=e,this.name=JS.WebGiMaterialsBumpMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||0===e.bumpScale)return;const i=this.writer,n=i.extensionsUsed,r={};if(e.bumpScale!==hw.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 eM=class{};eM.WebGiMaterialsDisplacementMapExtension="WEBGI_materials_displacementmap",eM.Import=e=>new iM(e),eM.Export=e=>new nM(e),eM.Textures={displacementTexture:"R"};let tM=eM;class iM{constructor(e){this.parser=e,this.name=tM.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 nM{constructor(e){this.writer=e,this.name=tM.WebGiMaterialsDisplacementMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||0===e.displacementScale)return;const i=this.writer,n=i.extensionsUsed,r={};if(e.displacementScale!==hw.MaterialProperties.displacementScale&&(r.displacementScale=e.displacementScale),e.displacementBias!==hw.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 rM=class{};rM.WebGiMaterialsLightMapExtension="WEBGI_materials_lightmap",rM.Import=e=>new aM(e),rM.Export=e=>new oM(e),rM.Textures={lightMapTexture:"RGB"};let sM=rM;class aM{constructor(e){this.parser=e,this.name=sM.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 oM{constructor(e){this.writer=e,this.name=sM.WebGiMaterialsLightMapExtension}writeMaterial(e,t){if(!e.isMeshStandardMaterial||0===e.lightMapIntensity)return;const i=this.writer,n=i.extensionsUsed,r={};if(e.lightMapIntensity!==hw.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 lM=class{};lM.WebGiObject3DExtrasExtension="WEBGI_object3d_extras",lM.Import=e=>({name:"__"+lM.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?.[lM.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[lM.WebGiObject3DExtrasExtension]):e.isLight&&!e.isAmbientLight&&(e.castShadow=!0)}))}))}}),lM.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[lM.WebGiObject3DExtrasExtension]=n,e.extensionsUsed[lM.WebGiObject3DExtrasExtension]=!0)}}),lM.Textures=void 0;let cM=lM;class hM extends Id{constructor(e){super(e),this.type=Ie}async loadAsync(e,t){const i=await this.parseAsync(e,t,!1),n=new Ml(i.data,i.width,i.height,Be,this.type);return n.needsUpdate=!0,n.flipY=!0,n.colorSpace=ht,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 vm(e);n&&URL.revokeObjectURL(e);let s=Uint8Array;return this.type===Ie?s=Uint16Array:this.type===Te&&(s=Float32Array),{data:dM(r.data,4,s,i),width:r.width,height:r.height}}setDataType(e){return this.type=e,this}}function dM(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]=Zn.toHalfFloat(Math.min(e[4*i]*r,65504)),a[i*t+1]=Zn.toHalfFloat(Math.min(e[4*i+1]*r,65504)),a[i*t+2]=Zn.toHalfFloat(Math.min(e[4*i+2]*r,65504))),4===t&&(a[i*t+3]=Zn.toHalfFloat(1));return a}const uM=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 hM).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=PA(e.data,4),n=new ImageData(t,e.width,e.height),r=ci.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]={})}))}};uM.ViewerConfigGLTFExtension="WEBGI_viewer";let pM=uM;class mM extends Md{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register((function(e){return new _M(e)})),this.register((function(e){return new IM(e)})),this.register((function(e){return new PM(e)})),this.register((function(e){return new DM(e)})),this.register((function(e){return new xM(e)})),this.register((function(e){return new wM(e)})),this.register((function(e){return new CM(e)})),this.register((function(e){return new SM(e)})),this.register((function(e){return new vM(e)})),this.register((function(e){return new MM(e)})),this.register((function(e){return new bM(e)})),this.register((function(e){return new TM(e)})),this.register((function(e){return new EM(e)})),this.register((function(e){return new AM(e)})),this.register((function(e){return new RM(e)})),this.register((function(e){return new BM(e)}))}load(e,t,i,n){const r=this;let s;if(""!==this.resourcePath)s=this.resourcePath;else if(""!==this.path){const t=eu.extractUrlBase(e);s=eu.resolveURL(t,this.path)}else s=eu.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 Id(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))===LM){try{a[fM.KHR_BINARY_GLTF]=new FM(e)}catch(e){return void(n&&n(e))}s=JSON.parse(a[fM.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 cE(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 fM.KHR_MATERIALS_UNLIT:a[t]=new yM;break;case fM.KHR_DRACO_MESH_COMPRESSION:a[t]=new NM(s,this.dracoLoader);break;case fM.KHR_TEXTURE_TRANSFORM:a[t]=new kM;break;case fM.KHR_MESH_QUANTIZATION:a[t]=new jM;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 gM(){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={}}}}mM.ObjectConstructors={DirectionalLight:Xd,PointLight:Wd,SpotLight:zd,MeshStandardMaterial:Yh,MeshBasicMaterial:Xn,MeshPhysicalMaterial:Kh,LineBasicMaterial:tc,PointsMaterial:uc,PerspectiveCamera:Gr,OrthographicCamera:fs};const fM={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_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 AM{constructor(e){this.parser=e,this.name=fM.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 Qn(16777215);void 0!==s.color&&o.setRGB(s.color[0],s.color[1],s.color[2],dt);const l=void 0!==s.range?s.range:0;switch(s.type){case"directional":a=new mM.ObjectConstructors.DirectionalLight(o),a.target.position.set(0,0,-1),a.add(a.target);break;case"point":a=new mM.ObjectConstructors.PointLight(o),a.distance=l;break;case"spot":a=new mM.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,nE(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 yM{constructor(){this.name=fM.KHR_MATERIALS_UNLIT}getMaterialType(){return mM.ObjectConstructors.MeshBasicMaterial}extendParams(e,t,i){const n=[];e.color=new Qn(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],dt),e.opacity=t[3]}void 0!==r.baseColorTexture&&n.push(i.assignTexture(e,"map",r.baseColorTexture,ht))}return Promise.all(n)}}class vM{constructor(e){this.parser=e,this.name=fM.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 _M{constructor(e){this.parser=e,this.name=fM.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?mM.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 Ht(e,e)}return Promise.all(r)}}class bM{constructor(e){this.parser=e,this.name=fM.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?mM.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 xM{constructor(e){this.parser=e,this.name=fM.KHR_MATERIALS_SHEEN}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?mM.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 Qn(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],dt)}return void 0!==s.sheenRoughnessFactor&&(t.sheenRoughness=s.sheenRoughnessFactor),void 0!==s.sheenColorTexture&&r.push(i.assignTexture(t,"sheenColorMap",s.sheenColorTexture,ht)),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 wM{constructor(e){this.parser=e,this.name=fM.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?mM.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 CM{constructor(e){this.parser=e,this.name=fM.KHR_MATERIALS_VOLUME}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?mM.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 Qn).setRGB(a[0],a[1],a[2],dt),Promise.all(r)}}class SM{constructor(e){this.parser=e,this.name=fM.KHR_MATERIALS_IOR}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?mM.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 MM{constructor(e){this.parser=e,this.name=fM.KHR_MATERIALS_SPECULAR}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?mM.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 Qn).setRGB(a[0],a[1],a[2],dt),void 0!==s.specularColorTexture&&r.push(i.assignTexture(t,"specularColorMap",s.specularColorTexture,ht)),Promise.all(r)}}class EM{constructor(e){this.parser=e,this.name=fM.EXT_MATERIALS_BUMP}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?mM.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 TM{constructor(e){this.parser=e,this.name=fM.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const t=this.parser.json.materials[e];return t.extensions&&t.extensions[this.name]?mM.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 IM{constructor(e){this.parser=e,this.name=fM.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 PM{constructor(e){this.parser=e,this.name=fM.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 DM{constructor(e){this.parser=e,this.name=fM.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 RM{constructor(e){this.name=fM.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 BM{constructor(e){this.name=fM.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!==VM.TRIANGLES&&e.mode!==VM.TRIANGLE_STRIP&&e.mode!==VM.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 $i,i=new wi,s=new xi,o=new wi(1,1,1),l=new Nl(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 Pl(e.array,e.itemSize,e.normalized)}else"TRANSLATION"!==t&&"ROTATION"!==t&&"SCALE"!==t&&e.geometry.setAttribute(t,a[t]);En.prototype.copy.call(l,e),this.parser.assignFinalMaterial(l),r.push(l)}return t.isGroup?(t.clear(),t.add(...r),t):r[0]})))}}const LM="glTF",OM=1313821514,UM=5130562;class FM{constructor(e){this.name=fM.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!==LM)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===OM){const n=new Uint8Array(e,12+s,t);this.content=i.decode(n)}else if(n===UM){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 NM{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=fM.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=YM[e]||e.toLowerCase();a[t]=s[e]}for(const t in e.attributes){const n=YM[t]||t.toLowerCase();if(void 0!==s[t]){const r=i.accessors[e.attributes[t]],s=HM[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,dt,i)}))}))}}class kM{constructor(){this.name=fM.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 jM{constructor(){this.name=fM.KHR_MESH_QUANTIZATION}}class zM extends cd{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 GM=new xi;class QM extends zM{interpolate_(e,t,i,n){const r=super.interpolate_(e,t,i,n);return GM.fromArray(r).normalize().toArray(r),r}}const VM={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},HM={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},WM={9728:ye,9729:be,9984:ve,9985:xe,9986:_e,9987:we},qM={33071:fe,33648:Ae,10497:ge},XM={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},YM={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"},KM={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},JM={CUBICSPLINE:void 0,LINEAR:$e,STEP:Ze},ZM="OPAQUE",$M="MASK",eE="BLEND";function tE(e){return void 0===e.DefaultMaterial&&(e.DefaultMaterial=new mM.ObjectConstructors.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:_})),e.DefaultMaterial}function iE(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 nE(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 rE(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 sE(e){let t;const i=e.extensions&&e.extensions[fM.KHR_DRACO_MESH_COMPRESSION];if(t=i?"draco:"+i.bufferView+":"+i.indices+":"+aE(i.attributes):e.indices+":"+aE(e.attributes)+":"+e.mode,void 0!==e.targets)for(let i=0,n=e.targets.length;i<n;i++)t+=":"+aE(e.targets[i]);return t}function aE(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 oE(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 lE=new $i;class cE{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new gM,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;typeof navigator<"u"&&(i=!0===/^((?!chrome|android).)*safari/i.test(navigator.userAgent),n=navigator.userAgent.indexOf("Firefox")>-1,r=n?navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1]:-1),typeof createImageBitmap>"u"||i||n&&r<98?this.textureLoader=new Bd(this.options.manager):this.textureLoader=new ou(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Id(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 iE(r,s,n),nE(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[fM.KHR_BINARY_GLTF].body);const n=this.options;return new Promise((function(e,r){i.load(eu.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=XM[n.type],t=HM[n.componentType],i=!0===n.normalized,r=new t(n.count*e);return Promise.resolve(new tr(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=XM[n.type],a=HM[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 qo(u,h/o),t.cache.add(i,l)),p=new Yo(l,s,c%h/o,d)}else u=null===r?new a(n.count*s):new a(r,c,n.count*s),p=new tr(u,s,d);if(void 0!==n.sparse){const t=XM.SCALAR,i=HM[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 tr(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=WM[i.magFilter]||be,t.minFilter=WM[i.minFilter]||we,t.wrapS=qM[i.wrapS]||ge,t.wrapT=qM[i.wrapT]||ge,i.extras&&void 0!==i.extras.uuid&&(t.uuid=i.extras.uuid,t.__hasGLTFUuid=!0),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 mi(e);t.needsUpdate=!0,i(t)}),t.load(eu.resolveURL(e,a.path),s,void 0,(function(o){!0===t.isImageBitmapLoader?(t=new Bd(r.options.manager),s=i,t.setCrossOrigin(r.options.crossOrigin),t.setRequestHeader(r.options.requestHeader),t.load(eu.resolveURL(e,a.path),s,void 0,n)):n(o)}))}))})).then((function(n){if(!0===h&&l.revokeObjectURL(c),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)}return o.uri&&"string"==typeof o.uri&&!1===h&&(n.userData.rootPath=eu.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.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[fM.KHR_TEXTURE_TRANSFORM]){const e=void 0!==i.extensions?i.extensions[fM.KHR_TEXTURE_TRANSFORM]:void 0;if(e){const t=r.associations.get(s);s=r.extensions[fM.KHR_TEXTURE_TRANSFORM].extendTexture(s,e),r.associations.set(s,t)}}return void 0!==n&&(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 mM.ObjectConstructors.PointsMaterial,Wn.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 mM.ObjectConstructors.LineBasicMaterial,Wn.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 mM.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||{})[fM.KHR_MATERIALS_UNLIT]){const e=n[fM.KHR_MATERIALS_UNLIT];s=e.getMaterialType(),o.push(e.extendParams(a,r,t))}else{const i=r.pbrMetallicRoughness||{};if(a.color=new Qn(1,1,1),a.opacity=1,Array.isArray(i.baseColorFactor)){const e=i.baseColorFactor;a.color.setRGB(e[0],e[1],e[2],dt),a.opacity=e[3]}void 0!==i.baseColorTexture&&o.push(t.assignTexture(a,"map",i.baseColorTexture,ht)),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||ZM;if(l===eE?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,l===$M&&(a.alphaTest=void 0!==r.alphaCutoff?r.alphaCutoff:.5)),void 0!==r.normalTexture&&s!==mM.ObjectConstructors.MeshBasicMaterial&&(o.push(t.assignTexture(a,"normalMap",r.normalTexture)),a.normalScale=new Ht(1,1),void 0!==r.normalTexture.scale)){const e=r.normalTexture.scale;a.normalScale.set(e,e)}if(void 0!==r.occlusionTexture&&s!==mM.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!==mM.ObjectConstructors.MeshBasicMaterial){const e=r.emissiveFactor;a.emissive=(new Qn).setRGB(e[0],e[1],e[2],dt)}return void 0!==r.emissiveTexture&&s!==mM.ObjectConstructors.MeshBasicMaterial&&o.push(t.assignTexture(a,"emissiveMap",r.emissiveTexture,ht)),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),nE(i,r),t.associations.set(i,{materials:e}),r.extensions&&iE(n,i,r),i}))}createUniqueName(e){const t=Ou.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[fM.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then((function(i){return hE(i,e,t)}))}const s=[];for(let i=0,a=e.length;i<a;i++){const a=e[i],o=sE(a),l=n[o];if(l)s.push(l.promise);else{let e;e=a.extensions&&a.extensions[fM.KHR_DRACO_MESH_COMPRESSION]?r(a):hE(new ur,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?tE(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===VM.TRIANGLES||h.mode===VM.TRIANGLE_STRIP||h.mode===VM.TRIANGLE_FAN||void 0===h.mode)d=!0===r.isSkinnedMesh?new Cl(c,u):new Pr(c,u),!0===d.isSkinnedMesh&&d.normalizeSkinWeights(),h.mode===VM.TRIANGLE_STRIP?d.geometry=zA(d.geometry,1):h.mode===VM.TRIANGLE_FAN&&(d.geometry=zA(d.geometry,2));else if(h.mode===VM.LINES)d=new hc(c,u);else if(h.mode===VM.LINE_STRIP)d=new oc(c,u);else if(h.mode===VM.LINE_LOOP)d=new dc(c,u);else{if(h.mode!==VM.POINTS)throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+h.mode);d=new Ac(c,u)}Object.keys(d.geometry.morphAttributes).length>0&&rE(d,r),d.name=t.createUniqueName(r.name||"mesh_"+e),d.geometry&&r.extras&&r.extras.isGeometryUserData?(nE(d.geometry,r),h.extensions&&iE(n,d.geometry,h)):(nE(d,r),h.extensions&&iE(n,d,h)),t.assignFinalMaterial(d),l.push(d)}r.extensions&&l.forEach((e=>iE(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&&iE(n,l[0],r),l[0];const c=new Lo;r.extensions&&iE(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 mM.ObjectConstructors.PerspectiveCamera(Vt.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):"orthographic"===i.type&&(t=new mM.ObjectConstructors.OrthographicCamera(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),nE(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 $i;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 Il(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 bd(r,void 0,c);return nE(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,lE)}));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 Sl:t.length>1?new Lo:1===t.length?t[0]:new En,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),nE(a,r),r.extensions&&iE(i,a,r),void 0!==r.matrix){const e=new $i;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 Lo;i.name&&(r.name=n.createUniqueName(i.name)),nE(r,i),i.extensions&&iE(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 Wn||e instanceof mi)&&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(KM[r.path]===KM.weights?e.traverse((function(e){e.morphTargetInfluences&&o.push(e.name?e.name:e.uuid)})):o.push(a),KM[r.path]){case KM.weights:l=fd;break;case KM.rotation:l=yd;break;case KM.position:case KM.scale:l=_d;break;default:if(1===i.itemSize)l=fd;else l=_d}const c=void 0!==n.interpolation?JM[n.interpolation]:$e,h=this._getArrayFromAccessor(i);for(let e=0,i=o.length;e<i;e++){const i=new l(o[e]+"."+KM[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=oE(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 yd?QM:zM)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function hE(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=YM[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 si.workingColorSpace!==dt&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${si.workingColorSpace}" not supported.`),nE(e,t),function(e,t,i){const n=t.attributes,r=new Mi;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 wi(t[0],t[1],t[2]),new wi(s[0],s[1],s[2])),e.normalized){const t=oE(HM[e.componentType]);r.min.multiplyScalar(t),r.max.multiplyScalar(t)}}const s=t.targets;if(void 0!==s){const e=new wi,t=new wi;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=oE(HM[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 Vi;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 dE=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 Mv(await gm(new Uint8Array(e),t.encryptKey),{asset:{version:"2.0",generator:"ThreePipeGLBWrapper",encryption:{type:"aesgcm",version:1}}})},uE={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 FM(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 Yp(this.key,s,n,t)||"";try{r=(await fm(new Uint8Array(r),e)).buffer}catch{throw new ErrorEvent("decryption error")}}return r}},pE=class extends Id{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)}};pE.SupportedJSONTypes=[],pE.SupportedJSONExtensions=[];let mE=pE;const gE=class e extends mE{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||gv();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 lv.Deserialize(r,n||void 0,s)}};gE.SupportedJSONTypes=()=>["Material",...[...lv.SerializableMaterials.values()].flatMap((e=>[e.TYPE,...e.TypeAlias||[]]))],gE.SupportedJSONExtensions=()=>["mat",...[...lv.SerializableMaterials.values()].map((e=>e.TypeSlug))],gE.FindExistingMaterial=!1;let fE=gE;class AE extends Md{constructor(e){super(e)}load(e,t,i,n){const r=this,s=""===this.path?eu.extractUrlBase(e):this.path,a=new Id(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 yE(this.resourcePath||t,this.materialOptions);return a.setCrossOrigin(this.crossOrigin),a.setManager(this.manager),a.setMaterials(s),a}}class yE{constructor(e="",t={}){this.baseUrl=e,this.options=t,this.materialsInfo={},this.materials={},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.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(){for(const e in this.materialsInfo)await this.create(e)}getIndex(e){return this.nameLookup[e]}async getAsArray(){let e=0;for(const t in this.materialsInfo)this.materialsArray[e]=await this.create(t),this.nameLookup[t]=e,e++;return this.materialsArray}async create(e){return void 0===this.materials[e]&&await this.createMaterial_(e),this.materials[e]}async createMaterial_(e){const t=this,i=this.materialsInfo[e],n={name:e,side:this.side};async function r(e,i){if(n[e])return;const r=t.getTextureParams(i,n);return new Promise(((i,s)=>{let a=!1,o=()=>!a&&(a=!0)&&i();const l=t.loadTexture(function(e,t){return"string"!=typeof t||""===t?"":/^https?:\/\//i.test(t)?t:e+t}(t.baseUrl,r.url),void 0,(t=>{n[e]=t,o()}),void 0,o);setTimeout(o,50),l.repeat.copy(r.scale),l.offset.copy(r.offset),l.wrapS=t.wrap,l.wrapT=t.wrap,("map"===e||"emissiveMap"===e)&&(l.colorSpace=ht)}))}const s=Array.from(Object.keys(i||{}));let a=s.includes("d")||s.includes("D");for(const e of s){const t=i[e];let s;if(""!==t)switch(e.toLowerCase()){case"kd":n.color=(new Qn).fromArray(t).convertSRGBToLinear();break;case"ks":n.specular=(new Qn).fromArray(t).convertSRGBToLinear();break;case"ke":n.emissive=(new Qn).fromArray(t).convertSRGBToLinear();break;case"map_kd":await r("map",t);break;case"map_ks":await r("specularMap",t);break;case"map_ke":await r("emissiveMap",t);break;case"norm":await r("normalMap",t);break;case"map_bump":case"bump":await r("bumpMap",t);break;case"map_d":await r("alphaMap",t),n.transparent=!0;break;case"ns":n.shininess=parseFloat(t);break;case"d":s=parseFloat(t),s<1&&(n.opacity=s,n.transparent=!0);break;case"tr":if(a)break;s=parseFloat(t),this.options&&this.options.invertTrProperty&&(s=1-s),s>0&&(n.opacity=1-s,n.transparent=!0)}}return this.materials[e]=new Jh(n),this.materials[e]}getTextureParams(e,t){const i={scale:new Ht(1,1),offset:new Ht(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:Sd;let a=s.getHandler(e);null===a&&(a=new Bd(s)),a.setCrossOrigin&&a.setCrossOrigin(this.crossOrigin);const o=a.load(e,i,n,r);return void 0!==t&&(o.mapping=t),o}}const vE=/^[og]\s*(.+)?/,_E=/^mtllib /,bE=/^usemtl /,xE=/^usemap /,wE=/\s+/,CE=new wi,SE=new wi,ME=new wi,EE=new wi,TE=new wi,IE=new Qn;function PE(){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;CE.fromArray(n,e),SE.fromArray(n,t),ME.fromArray(n,i),TE.subVectors(ME,SE),EE.subVectors(CE,SE),TE.cross(EE),TE.normalize(),r.push(TE.x,TE.y,TE.z),r.push(TE.x,TE.y,TE.z),r.push(TE.x,TE.y,TE.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 DE extends Md{constructor(e){super(e),this.materials=null}load(e,t,i,n){const r=this,s=new Id(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 PE;-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(wE);switch(e[0]){case"v":t.vertices.push(parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3])),e.length>=7?(IE.setRGB(parseFloat(e[4]),parseFloat(e[5]),parseFloat(e[6])).convertSRGBToLinear(),t.colors.push(IE.r,IE.g,IE.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(wE),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=vE.exec(r))){const e=(" "+n[0].slice(1).trim()).slice(1);t.startObject(e)}else if(bE.test(r))t.object.startMaterial(r.substring(7).trim(),t.materialLibraries);else if(_E.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 AE(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(xE.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 Lo;if(r.materialLibraries=[].concat(t.materialLibraries),!0==!(1===t.objects.length&&0===t.objects[0].geometry.vertices.length))for(let e=0,i=t.objects.length;e<i;e++){const i=t.objects[e],n=i.geometry,s=i.materials,a="Line"===n.type,o="Points"===n.type;let l=!1;if(0===n.vertices.length)continue;const c=new ur;c.setAttribute("position",new rr(n.vertices,3)),n.normals.length>0&&c.setAttribute("normal",new rr(n.normals,3)),n.colors.length>0&&(l=!0,c.setAttribute("color",new rr(n.colors,3))),!0===n.hasUVIndices&&c.setAttribute("uv",new rr(n.uvs,2));const h=[];for(let e=0,i=s.length;e<i;e++){const i=s[e],n=i.name+"_"+i.smooth+"_"+l;let r=t.materials[n];if(null!==this.materials)if(r=await this.materials.create(i.name),!a||!r||r instanceof tc){if(o&&r&&!(r instanceof uc)){const e=new uc({size:10,sizeAttenuation:!1});Wn.prototype.copy.call(e,r),e.color.copy(r.color),e.map=r.map,r=e}}else{const e=new tc;Wn.prototype.copy.call(e,r),e.color.copy(r.color),r=e}void 0===r&&(r=a?new tc:o?new uc({size:1,sizeAttenuation:!1}):new Yh,r.name=i.name,r.flatShading=!i.smooth,r.vertexColors=l,t.materials[n]=r),h.push(r)}let d;if(h.length>1){for(let e=0,t=s.length;e<t;e++){const t=s[e];c.addGroup(t.groupStart,t.groupCount,e)}d=a?new hc(c,h):o?new Ac(c,h):new Pr(c,h)}else d=a?new hc(c,h[0]):o?new Ac(c,h[0]):new Pr(c,h[0]);d.name=i.name,r.add(d)}else if(t.vertices.length>0){const e=new uc({size:1,sizeAttenuation:!1}),i=new ur;i.setAttribute("position",new rr(t.vertices,3)),t.colors.length>0&&void 0!==t.colors[0]&&(i.setAttribute("color",new rr(t.colors,3)),e.vertexColors=!0);const n=new Ac(i,e);r.add(n)}return r}}
/*!
fflate - fast JavaScript compression/decompression
<https://101arrowz.github.io/fflate>
Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
version 0.8.2
*/var RE={},BE=Uint8Array,LE=Uint16Array,OE=Int32Array,UE=new BE([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]),FE=new BE([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]),NE=new BE([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),kE=function(e,t){for(var i=new LE(31),n=0;n<31;++n)i[n]=t+=1<<e[n-1];var r=new OE(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}},jE=kE(UE,2),zE=jE.b,GE=jE.r;zE[28]=258,GE[258]=28;for(var QE=kE(FE,0),VE=QE.b,HE=QE.r,WE=new LE(32768),qE=0;qE<32768;++qE){var XE=(43690&qE)>>1|(21845&qE)<<1;XE=(61680&(XE=(52428&XE)>>2|(13107&XE)<<2))>>4|(3855&XE)<<4,WE[qE]=((65280&XE)>>8|(255&XE)<<8)>>1}var YE=function(e,t,i){for(var n=e.length,r=0,s=new LE(t);r<n;++r)e[r]&&++s[e[r]-1];var a,o=new LE(t);for(r=1;r<t;++r)o[r]=o[r-1]+s[r-1]<<1;if(i){a=new LE(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[WE[d]>>l]=c}else for(a=new LE(n),r=0;r<n;++r)e[r]&&(a[r]=WE[o[e[r]-1]++]>>15-e[r]);return a},KE=new BE(288);for(qE=0;qE<144;++qE)KE[qE]=8;for(qE=144;qE<256;++qE)KE[qE]=9;for(qE=256;qE<280;++qE)KE[qE]=7;for(qE=280;qE<288;++qE)KE[qE]=8;var JE=new BE(32);for(qE=0;qE<32;++qE)JE[qE]=5;var ZE=YE(KE,9,0),$E=YE(KE,9,1),eT=YE(JE,5,0),tT=YE(JE,5,1),iT=function(e){for(var t=e[0],i=1;i<e.length;++i)e[i]>t&&(t=e[i]);return t},nT=function(e,t,i){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&i},rT=function(e,t){var i=t/8|0;return(e[i]|e[i+1]<<8|e[i+2]<<16)>>(7&t)},sT=function(e){return(e+7)/8|0},aT=function(e,t,i){return(null==t||t<0)&&(t=0),(null==i||i>e.length)&&(i=e.length),new BE(e.subarray(t,i))},oT=["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"],lT=function(e,t,i){var n=new Error(t||oT[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,lT),!i)throw n;return n},cT=function(e,t,i,n){var r=e.length,s=n?n.length:0;if(!r||t.f&&!t.l)return i||new BE(0);var a=!i,o=a||2!=t.i,l=t.i;a&&(i=new BE(3*r));var c=function(e){var t=i.length;if(e>t){var n=new BE(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=nT(e,d,1);var y=nT(e,d+1,3);if(d+=3,!y){var v=e[(P=sT(d)+4)-4]|e[P-3]<<8,_=P+v;if(_>r){l&&lT(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=$E,m=tT,g=9,f=5;else if(2==y){var b=nT(e,d,31)+257,x=nT(e,d+10,15)+4,w=b+nT(e,d+5,31)+1;d+=14;for(var C=new BE(w),S=new BE(19),M=0;M<x;++M)S[NE[M]]=nT(e,d+3*M,7);d+=3*x;var E=iT(S),T=(1<<E)-1,I=YE(S,E,1);for(M=0;M<w;){var P,D=I[nT(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+nT(e,d,3),d+=2,R=C[M-1]):17==P?(B=3+nT(e,d,7),d+=3):18==P&&(B=11+nT(e,d,127),d+=7);B--;)C[M++]=R}}var L=C.subarray(0,b),O=C.subarray(b);g=iT(L),f=iT(O),p=YE(L,g,1),m=YE(O,f,1)}else lT(1);if(d>A){l&&lT(0);break}}o&&c(u+131072);for(var U=(1<<g)-1,F=(1<<f)-1,N=d;;N=d){var k=(R=p[rT(e,d)&U])>>4;if((d+=15&R)>A){l&&lT(0);break}if(R||lT(2),k<256)i[u++]=k;else{if(256==k){N=d,p=null;break}var j=k-254;if(k>264){var z=UE[M=k-257];j=nT(e,d,(1<<z)-1)+zE[M],d+=z}var G=m[rT(e,d)&F],Q=G>>4;G||lT(3),d+=15&G;O=VE[Q];if(Q>3){z=FE[Q];O+=rT(e,d)&(1<<z)-1,d+=z}if(d>A){l&&lT(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&&lT(3);u<W;++u)i[u]=n[H+u]}for(;u<V;++u)i[u]=i[u-O]}}t.l=p,t.p=N,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?aT(i,0,u):i.subarray(0,u)},hT=function(e,t,i){i<<=7&t;var n=t/8|0;e[n]|=i,e[n+1]|=i>>8},dT=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},uT=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:vT,l:0};if(1==r){var a=new BE(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 LE(u+1),m=pT(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 BE(p),l:m}},pT=function(e,t,i){return-1==e.s?Math.max(pT(e.l,t,i+1),pT(e.r,t,i+1)):t[e.s]=i},mT=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new LE(++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}},gT=function(e,t){for(var i=0,n=0;n<t.length;++n)i+=e[n]*t[n];return i},fT=function(e,t,i){var n=i.length,r=sT(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)},AT=function(e,t,i,n,r,s,a,o,l,c,h){hT(t,h++,i),++r[256];for(var d=uT(r,15),u=d.t,p=d.l,m=uT(s,15),g=m.t,f=m.l,A=mT(u),y=A.c,v=A.n,_=mT(g),b=_.c,x=_.n,w=new LE(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=uT(w,7),M=S.t,E=S.l,T=19;T>4&&!M[NE[T-1]];--T);var I,P,D,R,B=c+5<<3,L=gT(r,KE)+gT(s,JE)+a,O=gT(r,u)+gT(s,g)+a+14+3*T+gT(w,M)+2*w[16]+3*w[17]+7*w[18];if(l>=0&&B<=L&&B<=O)return fT(t,h,e.subarray(l,l+c));if(hT(t,h,1+(O<L)),h+=2,O<L){I=YE(u,p,0),P=u,D=YE(g,f,0),R=g;var U=YE(M,E,0);hT(t,h,v-257),hT(t,h+5,x-1),hT(t,h+10,T-4),h+=14;for(C=0;C<T;++C)hT(t,h+3*C,M[NE[C]]);h+=3*T;for(var F=[y,b],N=0;N<2;++N){var k=F[N];for(C=0;C<k.length;++C){var j=31&k[C];hT(t,h,U[j]),h+=M[j],j>15&&(hT(t,h,k[C]>>5&127),h+=k[C]>>12)}}}else I=ZE,P=KE,D=eT,R=JE;for(C=0;C<o;++C){var z=n[C];if(z>255){dT(t,h,I[(j=z>>18&31)+257]),h+=P[j+257],j>7&&(hT(t,h,z>>23&31),h+=UE[j]);var G=31&z;dT(t,h,D[G]),h+=R[G],G>3&&(dT(t,h,z>>5&8191),h+=FE[G])}else dT(t,h,I[z]),h+=P[z]}return dT(t,h,I[256]),h+P[256]},yT=new OE([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),vT=new BE(0),_T=function(e,t,i,n,r,s){var a=s.z||e.length,o=new BE(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=yT[t-1],u=d>>13,p=8191&d,m=(1<<i)-1,g=s.p||new LE(32768),f=s.h||new LE(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 OE(25e3),b=new LE(288),x=new LE(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=AT(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 N=Math.min(u,R)-1,k=Math.min(32767,S),j=Math.min(258,R);F<=k&&--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>N)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|GE[L]<<18|HE[O];var W=31&GE[L],q=31&HE[O];C+=UE[W]+FE[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=AT(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=fT(l,h+1,e.subarray(S,X))}s.i=a}return aT(o,0,n+sT(h)+r)},bT=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}(),xT=function(){var e=-1;return{p:function(t){for(var i=e,n=0;n<t.length;++n)i=bT[255&i^t[n]]^i>>>8;e=i},d:function(){return~e}}},wT=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}}},CT=function(e,t,i,n,r){if(!r&&(r={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),a=new BE(s.length+e.length);a.set(s),a.set(e,s.length),e=a,r.w=s.length}return _T(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)},ST=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},MT=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},ET=[],TT=function(e,t,i,n){if(!ET[i]){for(var r="",s={},a=e.length-1,o=0;o<a;++o)r=MT(e[o],r,s);ET[i]={c:MT(e[a],r,s),e:s}}var l=ST({},ET[i].e);return function(e,t,i,n,r){var s=new Worker(RE[t]||(RE[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}(ET[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)},IT=function(){return[BE,LE,OE,UE,FE,NE,zE,VE,$E,tT,WE,oT,YE,iT,nT,rT,sT,aT,lT,cT,rI,OT,UT]},PT=function(){return[BE,LE,OE,UE,FE,NE,GE,HE,ZE,KE,eT,JE,WE,yT,vT,YE,hT,dT,uT,pT,mT,gT,fT,AT,sT,aT,_T,CT,eI,OT]},DT=function(){return[VT,qT,QT,xT,bT]},RT=function(){return[HT,WT]},BT=function(){return[XT,QT,wT]},LT=function(){return[YT]},OT=function(e){return postMessage(e,[e.buffer])},UT=function(e){return e&&{out:e.size&&new BE(e.size),dictionary:e.dictionary}},FT=function(e,t,i,n,r,s){var a=TT(i,n,r,(function(e,t){a.terminate(),s(e,t)}));return a.postMessage([e,t],t.consume?[e.buffer]:[]),function(){a.terminate()}},NT=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()}},kT=function(e,t,i,n,r,s,a){var o,l=TT(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||lT(5),o&&t.ondata(lT(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([])})},jT=function(e,t){return e[t]|e[t+1]<<8},zT=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},GT=function(e,t){return zT(e,t)+4294967296*zT(e,t+4)},QT=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8},VT=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&&QT(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)}},HT=function(e){(31!=e[0]||139!=e[1]||8!=e[2])&&lT(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)},WT=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},qT=function(e){return 10+(e.filename?e.filename.length+1:0)},XT=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=wT();r.p(t.dictionary),QT(e,2,r.d())}},YT=function(e,t){return(8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31)&&lT(6,"invalid zlib data"),(e[1]>>5&1)==+!t&&lT(6,"invalid zlib data: "+(32&e[1]?"need":"unexpected")+" dictionary"),2+(e[1]>>3&4)};function KT(e,t){return"function"==typeof e&&(t=e,e={}),this.ondata=t,e}var JT=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 BE(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(CT(e,this.o,0,0,this.s),t)},e.prototype.push=function(e,t){this.ondata||lT(5),this.s.l&&lT(4);var i=e.length+this.s.z;if(i>this.b.length){if(i>2*this.b.length-32768){var n=new BE(-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||lT(5),this.s.l&&lT(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},e}(),ZT=function(e,t){kT([PT,function(){return[NT,JT]}],this,KT.call(this,e,t),(function(e){var t=new JT(e.data);onmessage=NT(t)}),6,1)};function $T(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&lT(7),FT(e,t,[PT],(function(e){return OT(eI(e.data[0],e.data[1]))}),0,i)}function eI(e,t){return CT(e,t||{},0,0)}var tI=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 BE(32768),this.p=new BE(0),i&&this.o.set(i)}return e.prototype.e=function(e){if(this.ondata||lT(5),this.d&&lT(4),this.p.length){if(e.length){var t=new BE(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=cT(this.p,this.s,this.o);this.ondata(aT(i,t,this.s.b),this.d),this.o=aT(i,this.s.b-32768),this.s.b=this.o.length,this.p=aT(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),iI=function(e,t){kT([IT,function(){return[NT,tI]}],this,KT.call(this,e,t),(function(e){var t=new tI(e.data);onmessage=NT(t)}),7,0)};function nI(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&lT(7),FT(e,t,[IT],(function(e){return OT(rI(e.data[0],UT(e.data[1])))}),1,i)}function rI(e,t){return cT(e,{i:2},t&&t.out,t&&t.dictionary)}var sI=function(){function e(e,t){this.c=xT(),this.l=0,this.v=1,JT.call(this,e,t)}return e.prototype.push=function(e,t){this.c.p(e),this.l+=e.length,JT.prototype.push.call(this,e,t)},e.prototype.p=function(e,t){var i=CT(e,this.o,this.v&&qT(this.o),t&&8,this.s);this.v&&(VT(i,this.o),this.v=0),t&&(QT(i,i.length-8,this.c.d()),QT(i,i.length-4,this.l)),this.ondata(i,t)},e.prototype.flush=function(){JT.prototype.flush.call(this)},e}(),aI=function(e,t){kT([PT,DT,function(){return[NT,JT,sI]}],this,KT.call(this,e,t),(function(e){var t=new sI(e.data);onmessage=NT(t)}),8,1)};function oI(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&lT(7),FT(e,t,[PT,DT,function(){return[lI]}],(function(e){return OT(lI(e.data[0],e.data[1]))}),2,i)}function lI(e,t){t||(t={});var i=xT(),n=e.length;i.p(e);var r=CT(e,t,qT(t),8),s=r.length;return VT(r,t),QT(r,s-8,i.d()),QT(r,s-4,n),r}var cI=function(){function e(e,t){this.v=1,this.r=0,tI.call(this,e,t)}return e.prototype.push=function(e,t){if(tI.prototype.e.call(this,e),this.r+=e.length,this.v){var i=this.p.subarray(this.v-1),n=i.length>3?HT(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}tI.prototype.c.call(this,t),this.s.f&&!this.s.l&&!t&&(this.v=sT(this.s.p)+9,this.s={i:0},this.o=new BE(0),this.push(new BE(0),t))},e}(),hI=function(e,t){var i=this;kT([IT,RT,function(){return[NT,tI,cI]}],this,KT.call(this,e,t),(function(e){var t=new cI(e.data);t.onmember=function(e){return postMessage(e)},onmessage=NT(t)}),9,0,(function(e){return i.onmember&&i.onmember(e)}))};function dI(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&lT(7),FT(e,t,[IT,RT,function(){return[uI]}],(function(e){return OT(uI(e.data[0],e.data[1]))}),3,i)}function uI(e,t){var i=HT(e);return i+8>e.length&&lT(6,"invalid gzip data"),cT(e.subarray(i,-8),{i:2},t&&t.out||new BE(WT(e)),t&&t.dictionary)}var pI=function(){function e(e,t){this.c=wT(),this.v=1,JT.call(this,e,t)}return e.prototype.push=function(e,t){this.c.p(e),JT.prototype.push.call(this,e,t)},e.prototype.p=function(e,t){var i=CT(e,this.o,this.v&&(this.o.dictionary?6:2),t&&4,this.s);this.v&&(XT(i,this.o),this.v=0),t&&QT(i,i.length-4,this.c.d()),this.ondata(i,t)},e.prototype.flush=function(){JT.prototype.flush.call(this)},e}(),mI=function(e,t){kT([PT,BT,function(){return[NT,JT,pI]}],this,KT.call(this,e,t),(function(e){var t=new pI(e.data);onmessage=NT(t)}),10,1)};function gI(e,t){t||(t={});var i=wT();i.p(e);var n=CT(e,t,t.dictionary?6:2,4);return XT(n,t),QT(n,n.length-4,i.d()),n}var fI=function(){function e(e,t){tI.call(this,e,t),this.v=e&&e.dictionary?2:1}return e.prototype.push=function(e,t){if(tI.prototype.e.call(this,e),this.v){if(this.p.length<6&&!t)return;this.p=this.p.subarray(YT(this.p,this.v-1)),this.v=0}t&&(this.p.length<4&&lT(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),tI.prototype.c.call(this,t)},e}(),AI=function(e,t){kT([IT,LT,function(){return[NT,tI,fI]}],this,KT.call(this,e,t),(function(e){var t=new fI(e.data);onmessage=NT(t)}),11,0)};function yI(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&lT(7),FT(e,t,[IT,LT,function(){return[vI]}],(function(e){return OT(vI(e.data[0],UT(e.data[1])))}),5,i)}function vI(e,t){return cT(e.subarray(YT(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}var _I=function(){function e(e,t){this.o=KT.call(this,e,t)||{},this.G=cI,this.I=tI,this.Z=fI}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||lT(5),this.s)this.s.push(e,t);else{if(this.p&&this.p.length){var i=new BE(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}(),bI=function(){function e(e,t){_I.call(this,e,t),this.queuedSize=0,this.G=hI,this.I=iI,this.Z=AI}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,_I.prototype.push.call(this,e,t)},e}();var xI=function(e,t,i,n){for(var r in e){var s=e[r],a=t+r,o=n;Array.isArray(s)&&(o=ST(n,s[1]),s=s[0]),s instanceof BE?i[a]=[s,o]:(i[a+="/"]=[new BE(0),o],xI(s,a,i,n))}},wI=typeof TextEncoder<"u"&&new TextEncoder,CI=typeof TextDecoder<"u"&&new TextDecoder,SI=0;try{CI.decode(vT,{stream:!0}),SI=1}catch{}var MI=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:aT(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)}},EI=function(){function e(e){this.ondata=e,SI?this.t=new TextDecoder:this.p=vT}return e.prototype.push=function(e,t){if(this.ondata||lT(5),t=!!t,this.t)return this.ondata(this.t.decode(e,{stream:!0}),t),void(t&&(this.t.decode().length&&lT(8),this.t=null));this.p||lT(4);var i=new BE(this.p.length+e.length);i.set(this.p),i.set(e,this.p.length);var n=MI(i),r=n.s,s=n.r;t?(s.length&&lT(8),this.p=null):this.p=s,this.ondata(r,t)},e}(),TI=function(){function e(e){this.ondata=e}return e.prototype.push=function(e,t){this.ondata||lT(5),this.d&&lT(4),this.ondata(II(e),this.d=t||!1)},e}();function II(e,t){if(t){for(var i=new BE(e.length),n=0;n<e.length;++n)i[n]=e.charCodeAt(n);return i}if(wI)return wI.encode(e);var r=e.length,s=new BE(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 BE(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 aT(s,0,a)}function PI(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(CI)return CI.decode(e);var r=MI(e),s=r.s;return(i=r.r).length&&lT(8),s}var DI=function(e){return 1==e?3:e<6?2:9==e?1:0},RI=function(e,t){return t+30+jT(e,t+26)+jT(e,t+28)},BI=function(e,t,i){var n=jT(e,t+28),r=PI(e.subarray(t+46,t+46+n),!(2048&jT(e,t+8))),s=t+46+n,a=zT(e,t+20),o=i&&4294967295==a?LI(e,s):[a,zT(e,t+24),zT(e,t+42)],l=o[0],c=o[1],h=o[2];return[jT(e,t+10),l,c,r,s+jT(e,t+30)+jT(e,t+32),h]},LI=function(e,t){for(;1!=jT(e,t);t+=4+jT(e,t+2));return[GT(e,t+12),GT(e,t+4),GT(e,t+20)]},OI=function(e){var t=0;if(e)for(var i in e){var n=e[i].length;n>65535&&lT(9),t+=n+4}return t},UI=function(e,t,i,n,r,s,a,o){var l=n.length,c=i.extra,h=o&&o.length,d=OI(c);QT(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)&&lT(10),QT(e,t,p<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),t+=4,-1!=s&&(QT(e,t,i.crc),QT(e,t+4,s<0?-s-2:s),QT(e,t+8,i.size)),QT(e,t+12,l),QT(e,t+14,d),t+=16,null!=a&&(QT(e,t,h),QT(e,t+6,i.attrs),QT(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;QT(e,t,+m),QT(e,t+2,f),e.set(g,t+4),t+=4+f}return h&&(e.set(o,t),t+=h),t},FI=function(e,t,i,n,r){QT(e,t,101010256),QT(e,t+8,i),QT(e,t+10,i),QT(e,t+12,n),QT(e,t+16,r)},NI=function(){function e(e){this.filename=e,this.c=xT(),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||lT(5),this.c.p(e),this.size+=e.length,t&&(this.crc=this.c.d()),this.process(e,t||!1)},e}(),kI=function(){function e(e,t){var i=this;t||(t={}),NI.call(this,e),this.d=new JT(t,(function(e,t){i.ondata(null,e,t)})),this.compression=8,this.flag=DI(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){NI.prototype.push.call(this,e,t)},e}(),jI=function(){function e(e,t){var i=this;t||(t={}),NI.call(this,e),this.d=new ZT(t,(function(e,t,n){i.ondata(e,t,n)})),this.compression=8,this.flag=DI(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){NI.prototype.push.call(this,e,t)},e}(),zI=function(){function e(e){this.ondata=e,this.u=[],this.d=1}return e.prototype.add=function(e){var t=this;if(this.ondata||lT(5),2&this.d)this.ondata(lT(4+8*(1&this.d),0,1),null,!1);else{var i=II(e.filename),n=i.length,r=e.comment,s=r&&II(r),a=n!=e.filename.length||s&&r.length!=s.length,o=n+OI(e.extra)+30;n>65535&&this.ondata(lT(11,0,1),null,!1);var l=new BE(o);UI(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=ST(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 BE(16);QT(s,0,134695760),QT(s,4,e.crc),QT(s,8,m),QT(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(lT(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+OI(l.extra)+(l.o?l.o.length:0)}for(var s=new BE(i+22),a=0,o=this.u;a<o.length;a++){var l=o[a];UI(s,e,l,l.f,l.u,-l.c-2,t,l.o),e+=46+l.f.length+OI(l.extra)+(l.o?l.o.length:0),t+=l.b}FI(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 GI(e,t){t||(t={});var i={},n=[];xI(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=II(a)).length,u=c.comment,p=u&&II(u),m=p&&p.length,g=OI(c.extra);d>65535&&lT(11);var f=h?eI(l,c):l,A=f.length,y=xT();y.p(l),n.push(ST(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 BE(s+22),_=r,b=s-r,x=0;x<n.length;++x){var w=n[x];UI(v,w.o,w,w.f,w.u,w.c.length);var C=30+w.f.length+OI(w.extra);v.set(w.c,w.o+C),UI(v,r,w,w.f,w.u,w.c.length,w.o,w.m),r+=16+C+(w.m?w.m.length:0)}return FI(v,r,n.length,b,_),v}var QI=function(){function e(){}return e.prototype.push=function(e,t){this.ondata(null,e,t)},e.compression=0,e}(),VI=function(){function e(){var e=this;this.i=new tI((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}(),HI=function(){function e(e,t){var i=this;t<32e4?this.i=new tI((function(e,t){i.ondata(null,e,t)})):(this.i=new iI((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=aT(e,0)),this.i.push(e,t)},e.compression=8,e}(),WI=function(){function e(e){this.onfile=e,this.k=[],this.o={0:QI},this.p=vT}return e.prototype.push=function(e,t){var i=this;if(this.onfile||lT(5),this.p||lT(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 BE(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=zT(l,a);if(67324752==t){s=1,o=a,p.d=null,p.c=0;var n=jT(l,a+6),r=jT(l,a+8),d=2048&n,u=8&n,m=jT(l,a+26),g=jT(l,a+28);if(c>a+30+m+g){var f=[];p.k.unshift(f),s=2;var A=zT(l,a+18),y=zT(l,a+22),v=PI(l.subarray(a+30,a+=30+m),!d);4294967295==A?(e=u?[-2]:LI(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||lT(5),A){var e=i.o[r];e||b.ondata(lT(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(vT,!0)}else b.ondata(null,vT,!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=vT,h<0){var m=s?l.subarray(0,o-12-(-2==h&&8)-(134695760==zT(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&&lT(13),this.p=null)},e.prototype.register=function(e){this.o[e.compression]=e},e}(),qI="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function XI(e,t){for(var i={},n=e.length-22;101010256!=zT(e,n);--n)(!n||e.length-n>65558)&&lT(13);var r=jT(e,n+8);if(!r)return{};var s=zT(e,n+16),a=4294967295==s||65535==r;if(a){var o=zT(e,n-12);(a=101075792==zT(e,o))&&(r=zT(e,o+32),s=zT(e,o+48))}for(var l=t&&t.filter,c=0;c<r;++c){var h=BI(e,s,a),d=h[0],u=h[1],p=h[2],m=h[3],g=h[4],f=h[5],A=RI(e,f);s=g,(!l||l({name:m,size:u,originalSize:p,compression:d}))&&(d?8==d?i[m]=rI(e.subarray(A,A+u),{out:new BE(p)}):lT(14,"unknown compression type "+d):i[m]=aT(e,A,A+u))}return i}function YI(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 KI(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 JI(e,t,i,n,r){const s=function(e,t,i,n,r){const s=r<e?r:e,a=[],o=YI(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 Ai(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 wi(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(KI(e,i)*n[i]));r[e]=t.divideScalar(n[0])}return r}(s)}class ZI extends Cc{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 Ai(t.x,t.y,t.z,t.w)}}getPoint(e,t=new wi){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=YI(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 Ai(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 wi){const i=t,n=this.knots[0]+e*(this.knots[this.knots.length-1]-this.knots[0]),r=JI(this.degree,this.knots,this.controlPoints,n,1);return i.copy(r[1]).normalize(),i}}let $I,eP,tP;class iP extends Md{constructor(e){super(e)}load(e,t,i,n){const r=this,s=""===r.path?eu.extractUrlBase(e):r.path,a=new Id(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===vP(e,0,t.length)}(e))$I=(new oP).parse(e);else{const t=vP(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(hP(t)<7e3)throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: "+hP(t));$I=(new aP).parse(t)}const i=new Bd(this.manager).setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin),n=new nP(i,this.manager).parse($I);return $I=null,eP=null,tP=null,n}}class nP{constructor(e,t){this.textureLoader=e,this.manager=t}parse(){eP=this.parseConnections();const e=this.parseImages(),t=this.parseTextures(e),i=this.parseMaterials(t),n=this.parseDeformers(),r=(new rP).parse(n);return this.parseScene(n,r,i),tP}parseConnections(){const e=new Map;return"Connections"in $I&&$I.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 $I.Objects){const i=$I.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 $I.Objects){const i=$I.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){let i;const n=this.textureLoader.path,r=eP.get(e.id).children;let s;void 0!==r&&r.length>0&&void 0!==t[r[0].ID]&&(i=t[r[0].ID],(0===i.indexOf("blob:")||0===i.indexOf("data:"))&&this.textureLoader.setPath(void 0));const a=e.FileName.slice(-3).toLowerCase();if("tga"===a){const t=this.manager.getHandler(".tga");null===t?(console.warn("FBXLoader: TGA loader not found, creating placeholder texture for",e.RelativeFilename),s=new mi):(t.setPath(this.textureLoader.path),s=t.load(i))}else if("dds"===a){const t=this.manager.getHandler(".dds");null===t?(console.warn("FBXLoader: DDS loader not found, creating placeholder texture for",e.RelativeFilename),s=new mi):(t.setPath(this.textureLoader.path),s=t.load(i))}else"psd"===a?(console.warn("FBXLoader: PSD textures are not supported, creating placeholder texture for",e.RelativeFilename),s=new mi):s=this.textureLoader.load(i);return this.textureLoader.setPath(n),s}parseMaterials(e){const t=new Map;if("Material"in $I.Objects){const i=$I.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),!eP.has(i))return null;const s=this.parseParameters(e,t,i);let a;switch(r.toLowerCase()){case"phong":a=new Jh;break;case"lambert":a=new ed;break;default:console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',r),a=new Jh}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 Qn).fromArray(e.Diffuse.value).convertSRGBToLinear():e.DiffuseColor&&("Color"===e.DiffuseColor.type||"ColorRGB"===e.DiffuseColor.type)&&(n.color=(new Qn).fromArray(e.DiffuseColor.value).convertSRGBToLinear()),e.DisplacementFactor&&(n.displacementScale=e.DisplacementFactor.value),e.Emissive?n.emissive=(new Qn).fromArray(e.Emissive.value).convertSRGBToLinear():e.EmissiveColor&&("Color"===e.EmissiveColor.type||"ColorRGB"===e.EmissiveColor.type)&&(n.emissive=(new Qn).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 Qn).fromArray(e.Specular.value).convertSRGBToLinear():e.SpecularColor&&"Color"===e.SpecularColor.type&&(n.specular=(new Qn).fromArray(e.SpecularColor.value).convertSRGBToLinear());const r=this;return eP.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=ht);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=ht);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=ht);break;case"SpecularColor":n.specularMap=r.getTexture(t,e.ID),void 0!==n.specularMap&&(n.specularMap.colorSpace=ht);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 $I.Objects&&t in $I.Objects.LayeredTexture&&(console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."),t=eP.get(t).children[0].ID),e.get(t)}parseDeformers(){const e={},t={};if("Deformer"in $I.Objects){const i=$I.Objects.Deformer;for(const n in i){const r=i[n],s=eP.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 $i).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=eP.get(parseInt(r.ID)).children.filter((function(e){return void 0===e.relationship}))[0].ID,i.push(a)}return i}parseScene(e,t,i){tP=new Lo;const n=this.parseModels(e.skeletons,t,i),r=$I.Objects.Model,s=this;n.forEach((function(e){const t=r[e.ID];s.setLookAtProperties(e,t),eP.get(e.ID).parents.forEach((function(t){const i=n.get(t.ID);void 0!==i&&i.add(e)})),null===e.parent&&tP.add(e)})),this.bindSkeleton(e.skeletons,t,n),this.addGlobalSceneSettings(),tP.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=fP(e.userData.transformData);e.applyMatrix4(t),e.updateWorldMatrix()}}));const a=(new sP).parse();1===tP.children.length&&tP.children[0].isGroup&&(tP.children[0].animations=a,tP=tP.children[0]),tP.animations=a}parseModels(e,t,i){const n=new Map,r=$I.Objects.Model;for(const s in r){const a=parseInt(s),o=r[s],l=eP.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 Sl;break;default:c=new Lo}c.name=o.attrName?Ou.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 Sl,r.matrixWorld.copy(t.transformLink),r.name=n?Ou.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=$I.Objects.NodeAttribute[e.ID];void 0!==t&&(i=t)})),void 0===i)t=new En;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 Gr(l,o,n,r),null!==c&&t.setFocalLength(c);break;case 1:t=new fs(-s/2,s/2,a/2,-a/2,n,r);break;default:console.warn("THREE.FBXLoader: Unknown camera type "+e+"."),t=new En}}return t}createLight(e){let t,i;if(e.children.forEach((function(e){const t=$I.Objects.NodeAttribute[e.ID];void 0!==t&&(i=t)})),void 0===i)t=new En;else{let e;e=void 0===i.LightType?0:i.LightType.value;let n=16777215;void 0!==i.Color&&(n=(new Qn).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 Wd(n,r,s,a);break;case 1:t=new Xd(n,r);break;case 2:let e=Math.PI/3;void 0!==i.InnerAngle&&(e=Vt.degToRad(i.InnerAngle.value));let o=0;void 0!==i.OuterAngle&&(o=Vt.degToRad(i.OuterAngle.value),o=Math.max(o,1)),t=new zd(n,r,s,e,o,a);break;default:console.warn("THREE.FBXLoader: Unknown light type "+i.LightType.value+", defaulting to a PointLight."),t=new Wd(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 Jh({name:Md.DEFAULT_MATERIAL_NAME,color:13421772}),a.push(s)),"color"in r.attributes&&a.forEach((function(e){e.vertexColors=!0})),r.FBX_Deformer?(n=new Cl(r,s),n.normalizeSkinWeights()):n=new Pr(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 tc({name:Md.DEFAULT_MATERIAL_NAME,color:3342591,linewidth:1});return new oc(i,n)}getTransformData(e,t){const i={};"InheritType"in t&&(i.inheritType=parseInt(t.InheritType.value)),i.eulerOrder="RotationOrder"in t?AP(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&&eP.get(e.ID).children.forEach((function(t){if("LookAtProperty"===t.relationship){const i=$I.Objects.Model[t.ID];if("Lcl_Translation"in i){const t=i.Lcl_Translation.value;void 0!==e.target?(e.target.position.fromArray(t),tP.add(e.target)):e.lookAt((new wi).fromArray(t))}}}))}bindSkeleton(e,t,i){const n=this.parsePoseNodes();for(const r in e){const s=e[r];eP.get(parseInt(s.ID)).parents.forEach((function(e){if(t.has(e.ID)){const t=e.ID;eP.get(t).parents.forEach((function(e){i.has(e.ID)&&i.get(e.ID).bind(new Il(s.bones),n[e.ID])}))}}))}}parsePoseNodes(){const e={};if("Pose"in $I.Objects){const t=$I.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 $i).fromArray(t.Matrix.a)})):e[n.Node]=(new $i).fromArray(n.Matrix.a)}}return e}addGlobalSceneSettings(){if("GlobalSettings"in $I){if("AmbientColor"in $I.GlobalSettings){const e=$I.GlobalSettings.AmbientColor.value,t=e[0],i=e[1],n=e[2];if(0!==t||0!==i||0!==n){const e=new Qn(t,i,n).convertSRGBToLinear();tP.add(new Yd(e,1))}}"UnitScaleFactor"in $I.GlobalSettings&&(tP.userData.unitScaleFactor=$I.GlobalSettings.UnitScaleFactor.value)}}}class rP{constructor(){this.negativeMaterialIndices=!1}parse(e){const t=new Map;if("Geometry"in $I.Objects){const i=$I.Objects.Geometry;for(const n in i){const r=eP.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 $I.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=AP(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=fP(l);return this.genGeometry(t,a,r,c)}genGeometry(e,t,i,n){const r=new ur;e.attrName&&(r.name=e.attrName);const s=this.parseGeoNode(e,t),a=this.genBuffers(s),o=new rr(a.vertex,3);if(o.applyMatrix4(n),r.setAttribute("position",o),a.colors.length>0&&r.setAttribute("color",new rr(a.colors,3)),t&&(r.setAttribute("skinIndex",new ir(a.weightsIndices,4)),r.setAttribute("skinWeight",new rr(a.vertexWeights,4)),r.FBX_Deformer=t),a.normal.length>0){const e=(new Wt).getNormalMatrix(n),t=new rr(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 rr(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=~u,g=!0);let f=[],A=[];if(s.push(3*u,3*u+1,3*u+2),e.color){const t=pP(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=pP(p,i,u,e.normal);a.push(t[0],t[1],t[2])}e.material&&"AllSame"!==e.material.mappingType&&(m=pP(p,i,u,e.material)[0],m<0&&(d.negativeMaterialIndices=!0,m=0)),e.uv&&e.uv.forEach((function(e,t){const n=pP(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 wi(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 wi(0,1,0):new wi(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 Ht(e.dot(t),e.dot(i))}genFace(e,t,i,n,r,s,a,o,l,c){let h;if(c>3){const e=[];for(let n=0;n<i.length;n+=3)e.push(new wi(t.vertexPositions[i[n]],t.vertexPositions[i[n+1]],t.vertexPositions[i[n+2]]));const{tangent:n,bitangent:r}=this.getNormalTangentAndBitangent(e),s=[];for(const t of e)s.push(this.flattenVertex(t,n,r));h=Ph.triangulateShape(s,[])}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=$I.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.PolygonVertexIndex?t.PolygonVertexIndex.a:[],a=void 0!==i.Vertices?i.Vertices.a:[],o=void 0!==i.Indexes?i.Indexes.a:[],l=3*e.attributes.position.count,c=new Float32Array(l);for(let e=0;e<o.length;e++){const t=3*o[e];c[t]=a[3*e],c[t+1]=a[3*e+1],c[t+2]=a[3*e+2]}const h={vertexIndices:s,vertexPositions:c},d=this.genBuffers(h),u=new rr(d.vertex,3);u.name=r||i.attrName,u.applyMatrix4(n),e.morphAttributes.position.push(u)}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 Qn;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 ur;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 Ai).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 ZI(i,n,r,a,o).getPoints(12*r.length);return(new ur).setFromPoints(l)}}class sP{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===$I.Objects.AnimationCurve)return;const e=this.parseAnimationCurveNodes();this.parseAnimationCurves(e);const t=this.parseAnimationLayers(e);return this.parseAnimStacks(t)}parseAnimationCurveNodes(){const e=$I.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=$I.Objects.AnimationCurve;for(const i in t){const n={id:t[i].id,times:t[i].KeyTime.a.map(dP),values:t[i].KeyValueFloat.a},r=eP.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=$I.Objects.AnimationLayer,i=new Map;for(const n in t){const t=[],r=eP.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=eP.get(i.ID).parents.filter((function(e){return void 0!==e.relationship}))[0].ID;if(void 0!==e){const r=$I.Objects.Model[e.toString()];if(void 0===r)return void console.warn("THREE.FBXLoader: Encountered a unused curve.",i);const s={modelName:r.attrName?Ou.sanitizeNodeName(r.attrName):"",ID:r.id,initialPosition:[0,0,0],initialRotation:[0,0,0],initialScale:[1,1,1]};tP.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 $i),"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=eP.get(i.ID).parents.filter((function(e){return void 0!==e.relationship}))[0].ID,r=eP.get(e).parents[0].ID,s=eP.get(r).parents[0].ID,a=eP.get(s).parents[0].ID,o=$I.Objects.Model[a],l={modelName:o.attrName?Ou.sanitizeNodeName(o.attrName):"",morphName:$I.Objects.Deformer[e].attrName};t[n]=l}t[n][r.attr]=r}}})),i.set(parseInt(n),t))}return i}parseAnimStacks(e){const t=$I.Objects.AnimationStack,i={};for(const n in t){const r=eP.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 bd(e.name,-1,t)}generateTracks(e){const t=[];let i=new wi,n=new wi;if(e.transform&&e.transform.decompose(i,new xi,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(Vt.degToRad)).push(r),i=(new hn).fromArray(i),i=(new xi).setFromEuler(i)),void 0!==n&&((n=n.map(Vt.degToRad)).push(r),n=(new hn).fromArray(n),n=(new xi).setFromEuler(n).invert());const o=new xi,l=new hn,c=[];if(!a||!s)return new yd(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 xi).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 yd(e+".quaternion",s,c)}generateMorphTrack(e){const t=e.DeformPercent.curves.morph,i=t.values.map((function(e){return e/100})),n=tP.getObjectByName(e.modelName).morphTargetDictionary[e.morphName];return new fd(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(Vt.degToRad(e.values[0])),s.push(Vt.degToRad(t.values[0])),s.push(Vt.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(Vt.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(Vt.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 hn(...l,n),o=new hn(...h,n),c=(new xi).setFromEuler(i),d=(new xi).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 xi,f=new hn;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(Vt.degToRad(e.values[a])),s.push(Vt.degToRad(t.values[a])),s.push(Vt.degToRad(i.values[a]))}return[r,s]}}class aP{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 cP,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=yP(r))}else this.parseNodeSpecialProperty(e,n,r)}parseNodePropertyContinued(e){const t=this.getCurrentNode();t.a+=e,","!==e.slice(-1)&&(t.a=yP(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=yP(l)}this.getPrevNode()[r]={type:s,type2:a,flag:o,value:l},this.setCurrentProp(this.getPrevNode(),r)}}class oP{parse(e){const t=new lP(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 cP;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=vI(new Uint8Array(e.getArrayBuffer(s))),o=new lP(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 lP{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 cP{add(e,t){this[e]=t}}function hP(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 dP(e){return e/46186158e3}const uP=[];function pP(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}(uP,n.buffer,s,a)}const mP=new hn,gP=new wi;function fP(e){const t=new $i,i=new $i,n=new $i,r=new $i,s=new $i,a=new $i,o=new $i,l=new $i,c=new $i,h=new $i,d=new $i,u=new $i,p=e.inheritType?e.inheritType:0;if(e.translation&&t.setPosition(gP.fromArray(e.translation)),e.preRotation){const t=e.preRotation.map(Vt.degToRad);t.push(e.eulerOrder||hn.DEFAULT_ORDER),i.makeRotationFromEuler(mP.fromArray(t))}if(e.rotation){const t=e.rotation.map(Vt.degToRad);t.push(e.eulerOrder||hn.DEFAULT_ORDER),n.makeRotationFromEuler(mP.fromArray(t))}if(e.postRotation){const t=e.postRotation.map(Vt.degToRad);t.push(e.eulerOrder||hn.DEFAULT_ORDER),r.makeRotationFromEuler(mP.fromArray(t)),r.invert()}e.scale&&s.scale(gP.fromArray(e.scale)),e.scalingOffset&&o.setPosition(gP.fromArray(e.scalingOffset)),e.scalingPivot&&a.setPosition(gP.fromArray(e.scalingPivot)),e.rotationOffset&&l.setPosition(gP.fromArray(e.rotationOffset)),e.rotationPivot&&c.setPosition(gP.fromArray(e.rotationPivot)),e.parentMatrixWorld&&(d.copy(e.parentMatrix),h.copy(e.parentMatrixWorld));const m=i.clone().multiply(n).multiply(r),g=new $i;g.extractRotation(h);const f=new $i;f.copyPosition(h);const A=f.clone().invert().multiply(h),y=g.clone().invert().multiply(A),v=s,_=new $i;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 $i).scale((new wi).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 $i).copyPosition(w),S=h.clone().multiply(C);return u.copyPosition(S),w=u.clone().multiply(_),w.premultiply(h.invert()),w}function AP(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 yP(e){return e.split(",").map((function(e){return parseFloat(e)}))}function vP(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=e.byteLength),(new TextDecoder).decode(new Uint8Array(e,t,i))}class _P extends iP{async loadAsync(e,t){const i=mi.DEFAULT_IMAGE;mi.DEFAULT_IMAGE||(mi.DEFAULT_IMAGE=iy);const n=await super.loadAsync(e,t);return mi.DEFAULT_IMAGE=i,n}}class bP extends Id{load(e,t,i,n){return this.setResponseType("arraybuffer"),super.load(e,(e=>{const i=XI(new Uint8Array(e)),n=new Map(Object.entries(i).map((([e,t])=>[e,new File([t],e)])));t?.(n)}),i,n)}}const xP=["hdr","exr","webp","avif","ktx","hdrpng","svg","cube","ico","bmp","gif","tiff"],wP=class e extends mM{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 MP(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=QA()+".drc",a=QA()+".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=xP.map((e=>QA()+"."+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 pM.ImportResources(n,i,t))},afterRoot:async e=>{e._bundledResources=i.bundledResources,await pM.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(uE),mM.ObjectConstructors.DirectionalLight=Qw,mM.ObjectConstructors.PointLight=Kw,mM.ObjectConstructors.SpotLight=nC,mM.ObjectConstructors.MeshStandardMaterial=hw,mM.ObjectConstructors.MeshBasicMaterial=Px,mM.ObjectConstructors.MeshPhysicalMaterial=hw,mM.ObjectConstructors.LineBasicMaterial=mw,mM.ObjectConstructors.PerspectiveCamera=tw,mM.ObjectConstructors.OrthographicCamera=ow}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 Lo,scenes:[],animations:[],cameras:[]}):r&&r(new ErrorEvent("GLTFLoader2: empty file")));const s=mi.DEFAULT_IMAGE;mi.DEFAULT_IMAGE||(mi.DEFAULT_IMAGE=iy);const a=this.importOptions?.useMeshLines??e.UseMeshLines;return mM.ObjectConstructors.LineBasicMaterial=a?yw:mw,t?super.parse(t,i,(e=>{mi.DEFAULT_IMAGE=s,mM.ObjectConstructors.LineBasicMaterial=a?yw:mw;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&&(Xp(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=HC.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]=HC.DummyLineBasicMaterial:t.isLineMaterial?i[e]=HC.DummyLineMaterial:i[e]=HC.DummyMaterial)}Array.isArray(t.material)&&t.material.length?t.material=i:1===i.length&&(t.material=i[0])})),a.forEach((e=>{MP(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)SP(e);return n.importedBundledResources=t._bundledResources,n}register(e){return super.register(e)}setup(t,i){this.register(HS.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}};wP._EmbedResourcePath=!1,wP._UseResourcePath=!0,wP.ImportExtensions=[cM.Import,QS.Import,JS.Import,tM.Import,sM.Import,qS.Import,e=>({name:"_EMBED_RESOURCE_PATH",afterRoot:async t=>{!wP._EmbedResourcePath||!t.scene||(t.userData.resourcePath=e.options.path)}})],wP.UseMeshLines=!0,wP.CreateUniqueNames="auto",wP.BundledResourcesKey="BundledResources",wP.AllowEmptyFiles=!0;let CP=wP;function SP(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 Ew(new Dw,e.material):new Mw(new Iw,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,Xp(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},Xp(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 MP(e,t){if(e&&e.userData){const i=e.userData.gltfExtensions;delete e.userData.gltfExtensions,e.userData=lv.Deserialize(e.userData,{},t),e.userData.gltfExtensions=i}}const EP=new WeakMap;class TP extends Md{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 Id(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,ht).catch(i)}decodeDracoFile(e,t,i,n,r=dt,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(EP.has(e)){const t=EP.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)})),EP.set(e,{key:i,promise:a}),a}_createGeometry(e){const t=new ur;e.index&&t.setIndex(new tr(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 tr(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!==ht)return;const i=new Qn;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 Id(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=IP,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 IP="\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",PP=class e extends TP{constructor(t){super(t),this.encoderPending=null,this.encoderConfig={type:"js"},this.isDRACOLoader2=!0,this.setDecoderPath(e.DRACO_LIBRARY_PATH),this.setDecoderConfig({type:"js"})}transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new Pr(e,new hw({color:new Qn(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((t=>{const i=t[0];return e||(this.encoderConfig.wasmBinary=t[1]),(0,eval)(i+"\nDracoEncoderModule;")?.()})),this.encoderPending}async initDecoder(){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)}));return(0,eval)(e+"\nDracoDecoderModule;")?.()}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}};PP.DRACO_LIBRARY_PATH="https://cdn.jsdelivr.net/gh/google/draco@1.5.6/javascript/",PP.LibraryValueMap={};let DP=PP;class RP extends Rd{constructor(e){super(e),this.type=Ie}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]=Zn.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=vI(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.width*e.scanlineBlockSize*(e.channels*e.type)),r=new Uint8Array(8192);let s=0;const a=new Array(e.channels);for(let t=0;t<e.channels;t++)a[t]={},a[t].start=s,a[t].end=a[t].start,a[t].nx=e.width,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]=N(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.channels;++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.channels;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=vI(e.array.slice(e.offset.value,e.offset.value+e.size)),i=e.lines*e.channels*e.width,n=1==e.type?new Uint16Array(i):new Uint32Array(i);let r=0,s=0;const a=new Array(4);for(let i=0;i<e.lines;i++)for(let i=0;i<e.channels;i++){let i=0;switch(e.type){case 1:a[0]=r,a[1]=a[0]+e.width,r=a[1]+e.width;for(let r=0;r<e.width;++r){i+=t[a[0]++]<<8|t[a[1]++],n[s]=i,s++}break;case 2:a[0]=r,a[1]=a[0]+e.width,a[2]=a[1]+e.width,r=a[2]+e.width;for(let r=0;r<e.width;++r){i+=t[a[0]++]<<24|t[a[1]++]<<16|t[a[2]++]<<8,n[s]=i,s++}}}return new DataView(n.buffer)}function B(e){const t=e.viewer,i={value:e.offset.value},n=new Uint8Array(e.width*e.lines*(e.channels*e.type*2)),r={version:k(t,i),unknownUncompressedSize:k(t,i),unknownCompressedSize:k(t,i),acCompressedSize:k(t,i),dcCompressedSize:k(t,i),rleCompressedSize:k(t,i),rleUncompressedSize:k(t,i),rleRawSize:k(t,i),totalAcUncompressedCount:k(t,i),totalDcUncompressedCount:k(t,i),acCompression:k(t,i)};if(r.version<2)throw new Error("EXRLoader.parse: "+Y.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=N(t,i),r=n>>2&3,o=new Int8Array([(n>>4)-1])[0],l=N(t,i);s.push({name:e,index:o,type:l,compression:r}),a-=e.length+3}const o=Y.channels,l=new Array(e.channels);for(let t=0;t<e.channels;++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.width,i.height=e.lines}const c={idx:new Array(3)};for(let t=0;t<e.channels;++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=vI(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(vI(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 N(e,t){const i=e.getUint8(t.value);return t.value=t.value+1,i}const k=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 Zn.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=N(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"][N(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):"lineOrder"===n?function(e,t){return["INCREASING_Y","DECREASING_Y"][N(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)}const W=new DataView(e),q=new Uint8Array(e),X={value:0},Y=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(-5&r)throw console.error("THREE.EXRHeader:",n),new Error("THREE.EXRLoader: Provided file is currently unsupported.");return n}(W,e,X),K=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,channels:e.channels.length,channelLineOffsets:{},scanOrder:null,bytesPerLine:null,lines:null,inputSize:null,type:null,uncompress:null,getter:null,format:null,colorSpace:dt};switch(e.compression){case"NO_COMPRESSION":s.lines=1,s.uncompress=T;break;case"RLE_COMPRESSION":s.lines=1,s.uncompress=I;break;case"ZIPS_COMPRESSION":s.lines=1,s.uncompress=P;break;case"ZIP_COMPRESSION":s.lines=16,s.uncompress=P;break;case"PIZ_COMPRESSION":s.lines=32,s.uncompress=D;break;case"PXR24_COMPRESSION":s.lines=16,s.uncompress=R;break;case"DWAA_COMPRESSION":s.lines=32,s.uncompress=B;break;case"DWAB_COMPRESSION":s.lines=256,s.uncompress=B;break;default:throw new Error("EXRLoader.parse: "+e.compression+" is unsupported")}s.scanlineBlockSize=s.lines;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 Te:s.getter=V,s.inputSize=2;break;case Ie:s.getter=Q,s.inputSize=2}else{if(2!=s.type)throw new Error("EXRLoader.parse: unsupported pixelType "+s.type+" for "+e.compression+".");switch(r){case Te:s.getter=j,s.inputSize=4;break;case Ie:s.getter=z,s.inputSize=4}}s.blockCount=s.height/s.scanlineBlockSize;for(let e=0;e<s.blockCount;e++)k(t,n);const l=s.width*s.height*s.outputChannels;switch(r){case Te:s.byteArray=new Float32Array(l),o&&s.byteArray.fill(1,0,l);break;case Ie: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.channelLineOffsets[t.name]=c*s.width),c+=2*t.pixelType;return s.bytesPerLine=s.width*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=Be,s.colorSpace=dt):(s.format=Ue,s.colorSpace=ct),s}(Y,W,q,X,this.type),J={value:0};for(let e=0;e<K.height/K.scanlineBlockSize;e++){const t=O(W,X)-Y.dataWindow.yMin;K.size=U(W,X),K.lines=t+K.scanlineBlockSize>K.height?K.height-t:K.scanlineBlockSize;const i=K.size<K.lines*K.bytesPerLine?K.uncompress(K):T(K);X.value+=K.size;for(let t=0;t<K.scanlineBlockSize;t++){const n=e*K.scanlineBlockSize,r=t+K.scanOrder(n);if(r>=K.height)continue;const s=t*K.bytesPerLine,a=(K.height-1-r)*K.outLineWidth;for(let e=0;e<K.channels;e++){const t=Y.channels[e].name,n=K.channelLineOffsets[t],r=K.decodeChannels[t];if(void 0!==r){J.value=s+n;for(let e=0;e<K.width;e++){const t=a+e*K.outputChannels+r;K.byteArray[t]=K.getter(i,J)}}}}}return{header:Y,width:K.width,height:K.height,data:K.byteArray,format:K.format,colorSpace:K.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 BP=new WeakMap;class LP extends Md{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 Id(this.manager);r.setPath(this.path),r.setResponseType("arraybuffer"),r.setRequestHeader(this.requestHeader),this.url=e,r.load(e,(i=>{if(BP.has(i))return BP.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)})),BP.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 Yh({color:new Qn(1,1,1),metalness:.8,name:Md.DEFAULT_MATERIAL_NAME,side:x});const i=new Kh({color:new Qn(e.diffuseColor.r/255,e.diffuseColor.g/255,e.diffuseColor.b/255),emissive:new Qn(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 Qn(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 Bd;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 RP).load(t.image,(function(e){e.mapping=THREE.EquirectangularReflectionMapping,i.envMap=e})),i}_createGeometry(e){const t=new En,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 $i;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 En;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 iu,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 uc({vertexColors:!0,sizeAttenuation:!1,size:2}):(a=n.drawColor,o=new Qn(a.r/255,a.g/255,a.b/255),s=new uc({color:o,sizeAttenuation:!1,size:2})),s=this._compareMaterials(s);const l=new Ac(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 Pr(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 Qn(a.r/255,a.g/255,a.b/255),s=new tc({color:o}),s=this._compareMaterials(s);const h=new oc(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 wc(d.canvas);f.minFilter=be,f.generateMipmaps=!1,f.wrapS=fe,f.wrapT=fe,s=new Ko({map:f,depthTest:!1});const A=new hl(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 Wd,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 zd,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 Kd;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 Xd,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 Qn(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 Id(this.manager);e.setPath(this.libraryPath);const t=new Promise(((t,i)=>{e.load("rhino3dm.js",t,void 0,i)})),i=new Id(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=OP,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 OP="\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",UP=class e extends LP{constructor(t){super(t),this.materials=[],this.setLibraryPath(e.LIBRARY_PATH)}_createMaterial(t){return e.ImportMaterials?super._createMaterial(t):this.materials[0]||new Yh({color:new Qn(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 Nl(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}))}};UP.LIBRARY_PATH=`https://cdn.jsdelivr.net/npm/rhino3dm@${Dm("rhino3dm","8.0.1")}/`,UP.ImportMaterials=!0,UP.ForceLayerMaterials=!1,UP.ReplaceWithInstancedMesh=!1,UP.HideLineMesh=!1,UP.HidePointMesh=!1,UP.LoadUserDataStrings=!0,UP.LoadUserDataWarnings=!0;let FP=UP;const NP=class e extends Md{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 wc(s):new mi,o=new Dd(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.")}};NP.USE_CANVAS_TEXTURE="true"!==Dm("svg-load-disable-canvas");let kP=NP;class jP extends Md{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=wd.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),wd.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 zP extends Md{constructor(e){super(e)}load(e,t,i,n){const r=new jP(this.manager);let s;r.setCrossOrigin(this.crossOrigin),r.setPath(this.path);const a=r.load(e,(function(e){s||(s=new vc(e)),s.format=Be,s.minFilter=be,s.magFilter=be,s.colorSpace=ht,s.needsUpdate=!0,void 0!==t&&t(s)}),i,n);return!s&&a&&(s=new vc(a)),s}}const GP=class e extends XC{constructor(){super(),this.processors=[],this.processors.push(dE)}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 zS)}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=pM.ExportViewerConfig(e,t):(n=Av(t.serializationMeta),pM.BundleExtraResources(t.json,n),pM.BundleArrayBuffers(n,t)),!n||0===Object.values(n).reduce(((e,t)=>e+Object.keys(t).length),0))return;const r=t.json.extras||{};r[CP.BundledResourcesKey]=n,t.json.extras=r}})}};GP.ExportExtensions=[HS.Export,cM.Export,QS.Export,tM.Export,sM.Export,qS.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 QP=GP;class VP{async parseAsync(e,{jsonSpaces:t=2}){return new Blob([JSON.stringify(e,null,t)],{type:"application/json"})}}class HP{async parseAsync(e,t){return new Blob([e],{type:"text/plain"})}}const WP=new TextEncoder;class qP{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!==Te&&e.texture.type!==Ie)throw Error("EXRExporter.parse: Unsupported WebGLRenderTarget texture type.");if(e.texture.format!==Be)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=e.width,r=e.height,s=e.texture.type,a=e.texture.format;texture.colorSpace;const o=void 0!==t.compression?t.compression:3,l=void 0!==t.type?t.type:Ie,c=l===Te?2:1,h=i[o];return{width:n,height:r,type:s,format:a,compression:o,blockLines:h,dataType:c,dataSize:2*c,numBlocks:Math.ceil(r/h),numInputChannels:4,numOutputChannels:4,textureIndex:t.textureIndex||0}}(r,s),o=function(e,t,i){let n;return n=i.type===Te?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 ZP(YP(XP(o,a),a),a)}if(e.isDataTexture){const i=e,n=t;!function(e){if(e.type!==Te&&e.type!==Ie)throw Error("EXRExporter.parse: Unsupported DataTexture texture type.");if(e.format!==Be)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===Te&&"Float32Array"!==e.image.data.constructor.name)throw Error("EXRExporter.parse: DataTexture image data doesn't match type, expected 'Float32Array'.");if(e.type===Ie&&"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:Ie,h=c===Te?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 ZP(YP(XP(i.image.data,r),r),r)}}}function XP(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==Te?oD:aD,l=1==t.dataType?iD:nD,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;$P(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 YP(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=KP;break;case 2:case 3:i=JP}0!==t.compression&&(n=new Uint8Array(a));for(let o=0;o<t.numBlocks;++o){const t=i(e.subarray(a*o,a*(o+1)),n);r+=t.length,s.data.push({dataChunk:t,size:t.length})}return s.totalSize=r,s}function KP(e){return e}function JP(e,t){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 gI(t)}function ZP(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);tD(r,20000630,n),tD(r,2,n),sD(r,"compression",n),sD(r,"compression",n),tD(r,1,n),eD(r,i.compression,n),sD(r,"screenWindowCenter",n),sD(r,"v2f",n),tD(r,8,n),tD(r,0,n),tD(r,0,n),sD(r,"screenWindowWidth",n),sD(r,"float",n),tD(r,4,n),nD(r,1,n),sD(r,"pixelAspectRatio",n),sD(r,"float",n),tD(r,4,n),nD(r,1,n),sD(r,"lineOrder",n),sD(r,"lineOrder",n),tD(r,1,n),eD(r,0,n),sD(r,"dataWindow",n),sD(r,"box2i",n),tD(r,16,n),tD(r,0,n),tD(r,0,n),tD(r,i.width-1,n),tD(r,i.height-1,n),sD(r,"displayWindow",n),sD(r,"box2i",n),tD(r,16,n),tD(r,0,n),tD(r,0,n),tD(r,i.width-1,n),tD(r,i.height-1,n),sD(r,"channels",n),sD(r,"chlist",n),tD(r,18*i.numOutputChannels+1,n),sD(r,"A",n),tD(r,i.dataType,n),n.value+=4,tD(r,1,n),tD(r,1,n),sD(r,"B",n),tD(r,i.dataType,n),n.value+=4,tD(r,1,n),tD(r,1,n),sD(r,"G",n),tD(r,i.dataType,n),n.value+=4,tD(r,1,n),tD(r,1,n),sD(r,"R",n),tD(r,i.dataType,n),n.value+=4,tD(r,1,n),tD(r,1,n),eD(r,0,n),eD(r,0,n);let s=n.value+8*i.numBlocks;for(let e=0;e<t.data.length;++e)rD(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;tD(a,i*t.blockLines,r),tD(a,o,r),s.set(n,r.value),r.value+=o}return s}function $P(e,t,i,n,r){e.r=t,e.g=i,e.b=n,e.a=r}function eD(e,t,i){e.setUint8(i.value,t),i.value+=1}function tD(e,t,i){e.setUint32(i.value,t,!0),i.value+=4}function iD(e,t,i){e.setUint16(i.value,Zn.toHalfFloat(t),!0),i.value+=2}function nD(e,t,i){e.setFloat32(i.value,t,!0),i.value+=4}function rD(e,t,i){e.setBigUint64(i.value,BigInt(t),!0),i.value+=8}function sD(e,t,i){const n=WP.encode(t+"\0");for(let t=0;t<n.length;++t)eD(e,n[t],i)}function aD(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 oD(e,t){return e[t]}class lD extends qP{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 cD=(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?Dx.getMapsForMaterial.call(n):null,i=e&&t.replaceTexture?hD(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=HC.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 ur;s.attributes.position=new tr(n,3),r&&(s.attributes.color=new tr(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,(()=>HC.DummyMaterial));else{const a=r?r(e,t,n,s):null;if(a)c(s,t,a);else{const e=Dx.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 xv(bv(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=kx.getMapsForObject3D.call(e);c.set(e,u)})),t.replaceTexture&&c.forEach(((e,i)=>{const n=hD(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),dD(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),dD(e,i)})),l.clear()}};function hD(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)})),xv(r,t),s}function dD(e,t){e&&xv(e,t)}class uD extends Bt{constructor(){super(),this.exporters=[{ctor:()=>new VP,ext:["json"]},{ctor:()=>new HP,ext:["txt","text"]},{ctor:()=>new lD,ext:["exr"]}],this.exportHooks={},this._cachedWriters=[],this.addEventListener("exportFile",(e=>cD(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:pD(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=GI(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 pD(e){return e.toJSON()}class mD extends Bt{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";ns.bumpmap_pars_fragment=Cv(ns.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&&Xp(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||Ox.call(e),this.findMaterial(e.uuid)&&(Xp(e,"uuid",QA(),!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=Dx.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&&Qp(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||lv.SerializableMaterials.has(e))return;const t=[...lv.SerializableMaterials.values()].find((t=>t.TYPE===e.TYPE));t&&console.warn("Material template with the same type already exists",e,t),lv.SerializableMaterials.add(e)}unregisterMaterialTemplate(e){e&&lv.SerializableMaterials.delete(e)}findTemplate(e){if(e)return[...lv.SerializableMaterials.values()].find((t=>t.TYPE===e))||[...lv.SerializableMaterials.values()].find((t=>t.TypeAlias?.includes(e)))}}class gD extends Rd{constructor(e){super(e),this.type=Ie}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]=Zn.toHalfFloat(Math.min(e[t+0]*s,65504)),i[n+1]=Zn.toHalfFloat(Math.min(e[t+1]*s,65504)),i[n+2]=Zn.toHalfFloat(Math.min(e[t+2]*s,65504)),i[n+3]=Zn.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 Te: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=Te;break;case Ie: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=Ie;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 Te:case Ie:e.colorSpace=dt,e.minFilter=be,e.magFilter=be,e.generateMipmaps=!1,e.flipY=!0}t&&t(e,i)}),i,n)}}class fD extends mM{constructor(e){super(e),mM.ObjectConstructors.MeshStandardMaterial=hw,mM.ObjectConstructors.MeshBasicMaterial=Px,mM.ObjectConstructors.MeshPhysicalMaterial=hw,mM.ObjectConstructors.LineBasicMaterial=mw}transform(e,t){let i;return e.scene.traverse((e=>{if(i)return;const t=e.material;t&&t.isPhysicalMaterial&&(i=t)})),i}}const AD=class extends Bt{constructor(e,t){super(),this._gltfExporter={ext:["gltf","glb"],extensions:[],ctor:(e,t)=>{const i=new QP;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 HC(!!e.getPlugin("debug"),t),this.exporter=new uD,this.materials=new mD,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;if("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),fE.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 kC(class extends mE{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 Yp(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=lv.Deserialize(i,void 0,n);if(n&&(i.resources=n),r)return r}return super.parseAsync(i)}},["json","vjson"],["application/json"],!1),new kC(kP,["svg","data:image/svg"],["image/svg+xml"],!1),new kC(Bd,["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 kC(fE,fE.SupportedJSONExtensions,[],!1,(e=>(e&&(e.viewer=this.viewer),e))),new kC(class extends gD{constructor(t){super(t),this.setDataType(WA(e.renderManager.renderer))}},["hdr"],["image/vnd.radiance"],!1),new kC(class extends RP{constructor(t){super(t),this.setDataType(WA(e.renderManager.renderer))}},["exr"],["image/x-exr"],!1),new kC(_P,["fbx"],["model/fbx"],!0),new kC(bP,["zip","glbz","gltfz"],["application/zip","model/gltf+zip","model/zip"],!0),new kC(DE,["obj"],["model/obj"],!0),new kC(AE,["mtl"],["model/mtl"],!1),new kC(CP,["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 kC(DP,["drc"],["model/mesh+draco","model/drc"],!0),new kC(zP,["mp4","ogg","mov","webm","data:video"],["video/mp4","video/ogg","video/quicktime","video/webm"],!0),new kC(fD,["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=>vD(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)}};AD.PluginType="AssetManager";let yD=AD;const vD=(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=Dx.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,{})):rC.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 ew("",t.viewer.canvas):new aw("",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 Yx.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 Qw:e.isPointLight?new Kw:e.isSpotLight?new nC:e.isAmbientLight?new kw:e.isHemisphereLight?new Ww:e.isRectAreaLight?new $w: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 Uw.upgradeLight.call(e);kx.upgradeObject3D.call(i)}else i.isMaterial?i.assetType||Dx.upgradeMaterial.call(i):i.isTexture&&(rC.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))},_D=class extends Bt{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),Xp(e,"uuid",QA(),!0,!0)}e.assetType||kx.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=kx.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=kx.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=QA()),!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||Dx.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),Xp(e,"uuid",QA(),!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=Dx.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=Dx.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||nx.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),Xp(e,"uuid",QA(),!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||rC.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),Xp(e,"uuid",QA(),!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)}};_D.MaterialTextureProperties=Bx,_D.MaterialTexturePropertiesUserData=Lx,_D.SceneTextureProperties=Qx,_D.Object3DTextureProperties=Vx,new Set([...Px.MapProperties,...mw.MapProperties,...hw.MapProperties,..._w.MapProperties]).forEach((e=>_D.MaterialTextureProperties.add(e)));let bD=_D;var xD=Object.defineProperty,wD=Object.getOwnPropertyDescriptor,CD=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?wD(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&&xD(t,i,s),s};e.RenderManager=class extends NC{constructor({canvas:e,alpha:t=!0,renderScale:i=1,powerPreference:n,targetOptions:r}){super(),this._renderSize=new Ht(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 Ht(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 UC(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=RC(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 Qo({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=ct,s.shadowMap.enabled=!0,s.shadowMap.type=1,s.shadowMap.autoUpdate=!1,sC.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=>Yp(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 useLegacyLights(){return this._renderer.useLegacyLights}set useLegacyLights(e){this._renderer.useLegacyLights=e,this._updated({change:"useLegacyLights",data:e}),this.resetShadows(),this.uiConfig?.uiRefresh?.(!0,"postFrame",1)}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 Ai),A=e?e.scissor.clone():this._renderer.getScissor(new Ai),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 Qn),c=this._renderer.getClearAlpha();this._renderer.setClearColor(new Qn(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 Ai),m=r?r.scissor.clone():this._renderer.getScissor(new Ai),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===Ie||r.type===Te){qA({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:bm(s)).toDataURL(t,i);return s.remove(),a}renderTargetToBuffer(e,t=0){const i=e.textures?.[t]??e.texture,n=i.type===Ie?new Uint16Array(e.width*e.height*4):i.type===Te?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===Ie||s.type===Te;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 lD).parse(this._renderer,r,{textureIndex:i}).buffer;else{const e=this.renderTargetToDataUrl(r,"auto"===t?void 0:t,90,i);a=Pp(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=QA();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=ns,e.RenderManager.ShaderLib=ss,CD([ig("Render Size")],e.RenderManager.prototype,"_renderSize",2),CD([ng("Render Scale",[.1,8],.05)],e.RenderManager.prototype,"renderScale",1),CD([pm(),sg("Shadow Map Type",["BasicShadowMap","PCFShadowMap","PCFSoftShadowMap","VSMShadowMap"].map(((e,t)=>({label:e,value:t}))),{tags:["advanced"]}),LA({obj:"shadowMap",key:"type",onChange:e.RenderManager.prototype._shadowMapTypeChanged})],e.RenderManager.prototype,"shadowMapType",2),CD([LA({obj:"renderer",key:"shadowMap"})],e.RenderManager.prototype,"shadowMap",2),CD([eg(void 0,{label:"Passes",tags:["advanced"],order:1e3})],e.RenderManager.prototype,"_passes",2),CD([dg(),pm()],e.RenderManager.prototype,"stableNoise",2),CD([hm(e.RenderManager.prototype.rebuildPipeline)],e.RenderManager.prototype,"autoBuildPipeline",2),CD([ag("Rebuild Pipeline",{sendArgs:!1,tags:["advanced"]})],e.RenderManager.prototype,"rebuildPipeline",1),CD([pm()],e.RenderManager.prototype,"useLegacyLights",1),e.RenderManager=CD([mm("RenderManager"),pg("Render Manager")],e.RenderManager);var SD=Object.defineProperty,MD=Object.getOwnPropertyDescriptor,ED=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?MD(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&&SD(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?mt:ct,type:t?Ce:Ie,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 wC(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,ED([dm(e.ViewerRenderManager.prototype._gbufferUnpackExtensionChanged)],e.ViewerRenderManager.prototype,"gbufferUnpackExtension",2),e.ViewerRenderManager=ED([pg("Render Manager")],e.ViewerRenderManager);const TD=class extends Jb{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=vp()/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=gb(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):pb(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?bb(e,t):xb(e,t);let s=(n?.duration??1e3)*(t.duration??1);if(n?.normalizeDuration&&s>0){const i=e.getWorldPosition(new wi),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:mb.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=QA();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}=Fb(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?mb[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()))}},vb)),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}};TD.PluginType="PopmotionPlugin";let ID=TD;var PD=Object.defineProperty,DD=Object.getOwnPropertyDescriptor,RD=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?DD(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&&PD(t,i,s),s};e.InteractionPromptPlugin=class extends Jb{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=vp()))},this._startedOnce=!1,this._addSceneObject=()=>{this.autoStartOnObjectLoad&&!this._startedOnce&&(this.lastActionTime=vp()-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 Wu).setFromVector3((new wi).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=vp())},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<vp()&&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);{tm(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",RD([pm(),dg()],e.InteractionPromptPlugin.prototype,"enabled",2),RD([pm(),og()],e.InteractionPromptPlugin.prototype,"animationDuration",2),RD([pm(),og()],e.InteractionPromptPlugin.prototype,"animationDistance",2),RD([pm(),og()],e.InteractionPromptPlugin.prototype,"animationPauseDuration",2),RD([pm(),og()],e.InteractionPromptPlugin.prototype,"rotationDistance",2),RD([pm(),og()],e.InteractionPromptPlugin.prototype,"yOffset",2),RD([pm(),dg()],e.InteractionPromptPlugin.prototype,"autoStart",2),RD([pm(),og()],e.InteractionPromptPlugin.prototype,"autoStartDelay",2),RD([pm(),dg()],e.InteractionPromptPlugin.prototype,"autoStop",2),RD([pm(),dg()],e.InteractionPromptPlugin.prototype,"autoStartOnObjectLoad",2),RD([pm(),dg()],e.InteractionPromptPlugin.prototype,"autoStartOnObjectLoadDelay",2),RD([ig()],e.InteractionPromptPlugin.prototype,"currentTime",2),RD([ig()],e.InteractionPromptPlugin.prototype,"lastActionTime",2),RD([cm(e.InteractionPromptPlugin.prototype._pointerIconChanged)],e.InteractionPromptPlugin.prototype,"pointerIcon",2),RD([pm()],e.InteractionPromptPlugin.prototype,"onlyOnOrbitControls",2),RD([ag()],e.InteractionPromptPlugin.prototype,"startAnimation",2),RD([ag()],e.InteractionPromptPlugin.prototype,"stopAnimation",2),e.InteractionPromptPlugin=RD([pg("Interaction Prompt")],e.InteractionPromptPlugin);var BD=Object.defineProperty,LD=Object.getOwnPropertyDescriptor,OD=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?LD(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&&BD(t,i,s),s};const UD=(r=class extends Jb{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=[ID],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))],...Zm(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 yp(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 yp(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(ID);if(!h)throw new Error("PopmotionPlugin not found");const d="function"==typeof n?n:mb[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 yp(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 yp(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 TA).expandByObject(e||this._viewer.scene.modelRoot,!1,!0),a=s.getCenter(new wi),o=s.getSize(new wi).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 TA).expandByObject(a[0],!1,!0);for(let e=1;e<a.length;e++)o.expandByObject(a[e],!1,!0);const l=sv(this._viewer.scene.mainCamera,o),c=o.getCenter(new wi);o.getSize(new wi).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 wi).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 yp(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}=Xx(this.camViews);return p(u,c,e.position),m(u,c,e.target),e.setDirty(),!0}},r.PluginType="CameraViews",r);OD([pm("cameraViews")],UD.prototype,"_cameraViews",2),OD([cm(UD.prototype._animationLoop),pm(),dg("Loop All Views")],UD.prototype,"viewLooping",2),OD([dm("setDirty"),pm(),og("View Pause Time")],UD.prototype,"viewPauseTime",2),OD([dm("setDirty"),pm(),sg("Ease",Object.keys(mb).map((e=>({label:e}))))],UD.prototype,"animEase",2),OD([dm("setDirty"),pm(),ng("Duration",[10,1e4],10)],UD.prototype,"animDuration",2),OD([dm("setDirty"),pm(),sg("Interpolation",["spherical","linear"].map((e=>({label:e,value:e.split(" ")[0]}))))],UD.prototype,"interpolateMode",2),OD([pm()],UD.prototype,"rotationOffset",2),OD([ag("Reset To First View",{sendArgs:!1})],UD.prototype,"resetToFirstView",1),OD([ag("Add Current View")],UD.prototype,"addCurrentView",1),OD([ag("Focus Next",{sendArgs:!1})],UD.prototype,"focusNext",2),OD([ag("Focus Previous",{sendArgs:!1})],UD.prototype,"focusPrevious",2),OD([ag("Animate All Views")],UD.prototype,"animateAllViews",1),OD([ag("Stop All Animations")],UD.prototype,"stopAllAnimations",1);let FD=UD;var ND=Object.defineProperty,kD=Object.getOwnPropertyDescriptor,jD=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?kD(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&&ND(t,i,s),s};e.DropzonePlugin=class extends Jb{constructor(e){super(),this.enabled=!0,this._allowedExtensions=void 0,this.autoImport=!0,this.autoAdd=!0,this.importOptions={autoImportZipContents:!0,forceImporterReprocess:!1,useMeshLines:CP.UseMeshLines,createUniqueNames:CP.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=Lp(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 Dg(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",jD([dg(),pm()],e.DropzonePlugin.prototype,"enabled",2),jD([pm()],e.DropzonePlugin.prototype,"autoImport",2),jD([dg(),pm()],e.DropzonePlugin.prototype,"autoAdd",2),jD([eg(),pm()],e.DropzonePlugin.prototype,"importOptions",2),jD([eg(),pm()],e.DropzonePlugin.prototype,"addOptions",2),jD([ag("Select Local files")],e.DropzonePlugin.prototype,"promptForFile",1),jD([ag("Import from URL")],e.DropzonePlugin.prototype,"promptForUrl",1),e.DropzonePlugin=jD([pg("Dropzone")],e.DropzonePlugin);var zD=Object.defineProperty,GD=(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&&zD(t,i,s),s};const QD=class extends Jb{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=$p(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)}};GD([pm(),dg("Enabled"),cm(QD.prototype.setDirty)],QD.prototype,"enabled"),GD([pm("pass")],QD.prototype,"_pass");let VD=QD;const HD="#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(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 WD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,XD=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?qD(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&&WD(t,i,s),s};e.GBufferPlugin=class extends VD{constructor(e=Ce,t=!0,i=!0,n=!0,r=!1,s=Ee){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=Cv(e.fragmentShader,`#include <${t}>`,"\n"+HD+"\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}createMaterial(){const e=this._viewer?.renderManager.isWebGL2&&this.renderFlagsBuffer;return new Nx(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 Qn(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 HD}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",XD([hg(void 0,{readOnly:!0})],e.GBufferPlugin.prototype,"normalDepthTexture",1),XD([hg(void 0,{readOnly:!0})],e.GBufferPlugin.prototype,"flagsTexture",1),XD([hg(void 0,{readOnly:!0})],e.GBufferPlugin.prototype,"depthTexture",1),e.GBufferPlugin=XD([pg("G-Buffer Plugin")],e.GBufferPlugin);class YD extends Jb{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=Cv(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 KD=Object.defineProperty,JD=Object.getOwnPropertyDescriptor,ZD=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?JD(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&&KD(t,i,s),s};const $D=5;e.TonemapPlugin=class extends YD{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()?"":Np`
            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=Im(e.w,1,i),super.updateGBufferFlags(e,t)}},e.TonemapPlugin.PluginType="Tonemap",ns.tonemapping_pars_fragment=ns.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);}"),ZD([pm(),cm(e.TonemapPlugin.prototype.setDirty),dg("Enabled")],e.TonemapPlugin.prototype,"enabled",2),ZD([sg("Mode",[["Linear",ne],["Reinhard",re],["Cineon",se],["ACESFilmic",ae],["Uncharted2",$D],["AgX",oe]].map((e=>({label:e[0],value:e[1]})))),cm(e.TonemapPlugin.prototype.setDirty),pm()],e.TonemapPlugin.prototype,"toneMapping",2),ZD([cm(e.TonemapPlugin.prototype.setDirty),pm()],e.TonemapPlugin.prototype,"tonemapBackground",2),ZD([cm(e.TonemapPlugin.prototype.setDirty),ng("Exposure",[0,2*Math.PI],.01),pm()],e.TonemapPlugin.prototype,"exposure",2),ZD([ng("Saturation",[0,2],.01),DA({propKey:"toneMappingSaturation"}),pm()],e.TonemapPlugin.prototype,"saturation",2),ZD([ng("Contrast",[0,2],.01),DA({propKey:"toneMappingContrast"}),pm()],e.TonemapPlugin.prototype,"contrast",2),e.TonemapPlugin=ZD([pg("Tonemapping")],e.TonemapPlugin);var eR=Object.defineProperty,tR=Object.getOwnPropertyDescriptor,iR=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?tR(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&&eR(t,i,s),s};function nR(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 Bt{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 wi,this._lastCameraQuat=new xi,this._lastCameraTarget=new wi,this._tempVec=new wi,this._tempQuat=new xi,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=yv(e,this);return await fv.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 Ht,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||Cp();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 Eg(this._container),this.renderStats.show()),window.threeViewers||(window.threeViewers=[]),window.threeViewers.push(this),i.camera?.isCamera)r=i.camera,r.assetType||Yx.upgradeCamera.call(r);else{r="orthographic"===i.camera?.type?new aw(i.camera?.controlsMode??"orbit",this._canvas):new ew(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 bD,this._scene=i.rootScene??new e.RootScene(r,Nb(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 yD(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?vv(e.exportConfig()):e.constructor?.PluginType?vv(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)nR(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=gv(),i=e.toJSON?.(t);return i?(i.resources=Av(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=gv(),i=this.serializePlugins(t,e);return pv(t),{...this._defaultConfig,plugins:i,resources:Av(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||gv();const n=Object.assign({...this._defaultConfig,metadata:{...this._defaultConfig.metadata},plugins:this.serializePlugins(i,t)},lv.Serialize(this,i,!0));return e||pv(i),n.resources=Av(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&&void 0===i.renderManager?.useLegacyLights&&(this.console.warn("old file format, useLegacyLights moved to RenderManager"),this.renderManager.useLegacyLights=i.useLegacyLights,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 Qn).setHex(i.background,dt):"string"==typeof i.background?i.background=(new Qn).setStyle(i.background,dt):i.background?.isColor&&(i.background=new Qn(i.background)),i.background?.isColor?(this._scene.backgroundColor=i.background,this._scene.background=null):i.background?(this._scene.backgroundColor=new Qn("#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),lv.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):zp(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(FD)?.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 wc(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=nR(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=nR(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.5.1",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=Rm,e.ThreeViewer.ViewerDebugging=!1,iR([pm()],e.ThreeViewer.prototype,"type",2),iR([cm(e.ThreeViewer.prototype._renderEnabledChanged),dg("Enable Rendering",{tags:["advanced"]})],e.ThreeViewer.prototype,"renderEnabled",2),iR([eg(void 0,{label:"Rendering",expanded:!0}),pm("renderManager")],e.ThreeViewer.prototype,"renderManager",2),iR([eg(void 0,{label:"Scene",expanded:!0}),pm("scene")],e.ThreeViewer.prototype,"_scene",2),iR([eg(void 0,{label:"Timeline",expanded:!0,tags:["advanced"]}),pm("timeline")],e.ThreeViewer.prototype,"timeline",2),e.ThreeViewer=iR([ug("Viewer")],e.ThreeViewer);const rR=new wi,sR=new wi;class aR extends Pr{constructor(e=new fy,t=new Ay({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)rR.fromBufferAttribute(t,e),sR.fromBufferAttribute(i,e),n[r]=0===r?0:n[r-1],n[r+1]=n[r]+rR.distanceTo(sR);const r=new zu(n,2,1);return e.setAttribute("instanceDistanceStart",new Yo(r,1,0)),e.setAttribute("instanceDistanceEnd",new Yo(r,1,1)),this}}function oR(e,t=1024){const i=new Ht,n=new Ht,r=[new Ht,new Ht,new Ht],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 lR{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 cR=9,hR=15,dR=16,uR=22,pR=37,mR=43,gR=76,fR=83,AR=97,yR=100,vR=103,_R=109,bR=165,xR=166;class wR{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 CR{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 SR=[171,75,84,88,32,50,48,187,13,10,26,10];function MR(e){return typeof TextDecoder<"u"?(new TextDecoder).decode(e):Buffer.from(e).toString("utf8")}let ER,TR,IR;const PR={env:{emscripten_notify_memory_growth:function(e){IR=new Uint8Array(TR.exports.memory.buffer)}}};class DR{init(){return ER||(ER=typeof fetch<"u"?fetch("data:application/wasm;base64,"+RR).then((e=>e.arrayBuffer())).then((e=>WebAssembly.instantiate(e,PR))).then(this._init):WebAssembly.instantiate(Buffer.from(RR,"base64"),PR).then(this._init),ER)}_init(e){TR=e.instance,PR.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!TR)throw new Error("ZSTDDecoder: Await .init() before decoding.");const i=e.byteLength,n=TR.exports.malloc(i);IR.set(e,n),t=t||Number(TR.exports.ZSTD_findDecompressedSize(n,i));const r=TR.exports.malloc(t),s=TR.exports.ZSTD_decompress(r,t,n,i),a=IR.slice(r,r+s);return TR.exports.free(n),TR.exports.free(r),a}}const RR="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",BR=new WeakMap;let LR,OR=0;class UR extends Md{constructor(e){super(e),this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new lR,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.workerConfig.etc1Supported=!1),this}init(){if(!this.transcoderPending){const e=new Id(this.manager);e.setPath(this.transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new Id(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=UR.BasisWorker,n=["/* constants */","let _EngineFormat = "+JSON.stringify(UR.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(UR.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(UR.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}))})),OR>0&&console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."),OR++}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 Id(this.manager);r.setResponseType("arraybuffer"),r.setCrossOrigin(this.crossOrigin),r.setWithCredentials(this.withCredentials),r.load(e,(e=>{if(BR.has(e))return BR.get(e).promise.then(t).catch(n);this.createTexture(e).then((e=>t?t(e):null)).catch(n)}),i,n)}_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 xc(i,s,Ce);else{const e=i[0].mipmaps;c=t.layerCount>1?new bc(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=jR(t),c.premultiplyAlpha=!!(1&l),c}async createTexture(e,t={}){const i=function(e){const t=new Uint8Array(e.buffer,e.byteOffset,SR.length);if(t[0]!==SR[0]||t[1]!==SR[1]||t[2]!==SR[2]||t[3]!==SR[3]||t[4]!==SR[4]||t[5]!==SR[5]||t[6]!==SR[6]||t[7]!==SR[7]||t[8]!==SR[8]||t[9]!==SR[9]||t[10]!==SR[10]||t[11]!==SR[11])throw new Error("Missing KTX 2.0 identifier.");const i=new wR,n=17*Uint32Array.BYTES_PER_ELEMENT,r=new CR(e,SR.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 CR(e,SR.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 CR(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 CR(e,l,c,!0);for(;f._offset<c;){const e=f._nextUint32(),t=f._scan(e),n=MR(t),r=f._scan(e-t.byteLength);i.keyValue[n]=n.match(/^ktx/i)?MR(r):r,f._offset%4&&f._skip(4-f._offset%4)}if(d<=0)return i;const A=new CR(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===NR[t])throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");let i;2===e.supercompressionScheme&&(LR||(LR=new Promise((async e=>{const t=new DR;await t.init(),e(t)}))),i=await LR);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=kR[t]===Te?new Float32Array(c.buffer,c.byteOffset,c.byteLength/Float32Array.BYTES_PER_ELEMENT):kR[t]===Ie?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(FR.has(NR[t]))r=0===e.pixelDepth?new Ml(n[0].data,e.pixelWidth,e.pixelHeight):new bi(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=kR[t],r.format=NR[t],r.colorSpace=jR(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 BR.set(e,{promise:r}),r}dispose(){return this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),OR--,this}}UR.BasisFormat={ETC1S:0,UASTC_4x4:1},UR.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},UR.EngineFormat={RGBAFormat:Be,RGBA_ASTC_4x4_Format:qe,RGBA_BPTC_Format:Ye,RGBA_ETC2_EAC_Format:We,RGBA_PVRTC_4BPPV1_Format:Qe,RGBA_S3TC_DXT5_Format:ze,RGB_ETC1_Format:Ve,RGB_ETC2_Format:He,RGB_PVRTC_4BPPV1_Format:Ge,RGB_S3TC_DXT1_Format:Ne},UR.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.RGB_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 FR=new Set([Be,Fe,Ue]),NR={[_R]:Be,[AR]:Be,[pR]:Be,[mR]:Be,[vR]:Fe,[fR]:Fe,[dR]:Fe,[uR]:Fe,[yR]:Ue,[gR]:Ue,[hR]:Ue,[cR]:Ue,[xR]:Xe,[bR]:Xe},kR={[_R]:Te,[AR]:Ie,[pR]:Ce,[mR]:Ce,[vR]:Te,[fR]:Ie,[dR]:Ce,[uR]:Ce,[yR]:Te,[gR]:Ie,[hR]:Ce,[cR]:Ce,[xR]:Ce,[bR]:Ce};function jR(e){const t=e.dataFormatDescriptor[0];return 1===t.colorPrimaries?2===t.transferFunction?ht:dt:10===t.colorPrimaries?2===t.transferFunction?ut:pt:(0===t.colorPrimaries||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${t.colorPrimaries}"`),ct)}class zR extends Pd{constructor(e){super(e)}parse(e,t){const i=new GR(e,1);return{mipmaps:i.mipmaps(t),width:i.pixelWidth,height:i.pixelHeight,format:i.glInternalFormat,isCubemap:6===i.numberOfFaces,mipmapCount:i.numberOfMipmapLevels}}}class GR{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 QR{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 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 VR extends Md{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new Id(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 QR;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=XI(new Uint8Array(e)),r=function(e){const n={};(new Id).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])){console.warn("THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.");continue}const s=PI(e[r]);n[r]=t.parse(s)}}return n}(n),s=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}n&&console.warn("THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.")}(n);if(void 0===s)return console.warn("THREE.USDZLoader: No usda file found."),new Lo;const a=PI(s),o=t.parse(a);function l(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"point3f[] points"in e&&(i["point3f[] points"]=e["point3f[] points"]),"texCoord2f[] primvars:st"in e&&(i["texCoord2f[] primvars:st"]=e["texCoord2f[] primvars:st"]),"int[] primvars:st:indices"in e&&(i["int[] primvars:st:indices"]=e["int[] primvars:st:indices"]),i;if("object"==typeof i){const e=l(i);if(e)return e}}}}function c(e){if(!e)return;let t=new ur;if("int[] faceVertexIndices"in e){const i=JSON.parse(e["int[] faceVertexIndices"]);t.setIndex(i)}if("point3f[] points"in e){const i=JSON.parse(e["point3f[] points"].replace(/[()]*/g,"")),n=new tr(new Float32Array(i),3);t.setAttribute("position",n)}if("normal3f[] normals"in e){const i=JSON.parse(e["normal3f[] normals"].replace(/[()]*/g,"")),n=new tr(new Float32Array(i),3);t.setAttribute("normal",n)}else t.computeVertexNormals();if("float2[] primvars:st"in e&&(e["texCoord2f[] primvars:st"]=e["float2[] primvars:st"]),"texCoord2f[] primvars:st"in e){const i=JSON.parse(e["texCoord2f[] primvars:st"].replace(/[()]*/g,"")),n=new tr(new Float32Array(i),2);if("int[] primvars:st:indices"in e){t=t.toNonIndexed();const i=JSON.parse(e["int[] primvars:st:indices"]);t.setAttribute("uv",function(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 tr(r,n)}(n,i))}else t.setAttribute("uv",n)}return t}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 Ht).fromArray(JSON.parse("["+t["float2 inputs:scale"].replace(/[()]*/g,"")+"]"))),t["float2 inputs:translation"]&&(e.offset=(new Ht).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,""),i=(new Bd).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=c(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 l(r[i],n)}return l(e)}}(e)),i=function(e){const t=new Kh;if(void 0!==e){if('def Shader "PreviewSurface"'in e){const i=e['def Shader "PreviewSurface"'];if("color3f inputs:diffuseColor.connect"in i){const n=i["color3f inputs:diffuseColor.connect"],r=u(o,/(\w+).output/.exec(n)[1]);t.map=p(r),t.map.colorSpace=ht,'def Shader "Transform2d_diffuse"'in e&&d(t.map,e['def Shader "Transform2d_diffuse"'])}else if("color3f inputs:diffuseColor"in i){const e=i["color3f inputs:diffuseColor"].replace(/[()]*/g,"");t.color.fromArray(JSON.parse("["+e+"]"))}if("color3f inputs:emissiveColor.connect"in i){const n=i["color3f inputs:emissiveColor.connect"],r=u(o,/(\w+).output/.exec(n)[1]);t.emissiveMap=p(r),t.emissiveMap.colorSpace=ht,t.emissive.set(16777215),'def Shader "Transform2d_emissive"'in e&&d(t.emissiveMap,e['def Shader "Transform2d_emissive"'])}else if("color3f inputs:emissiveColor"in i){const e=i["color3f inputs:emissiveColor"].replace(/[()]*/g,"");t.emissive.fromArray(JSON.parse("["+e+"]"))}if("normal3f inputs:normal.connect"in i){const n=i["normal3f inputs:normal.connect"],r=u(o,/(\w+).output/.exec(n)[1]);t.normalMap=p(r),t.normalMap.colorSpace=ct,'def Shader "Transform2d_normal"'in e&&d(t.normalMap,e['def Shader "Transform2d_normal"'])}if("float inputs:roughness.connect"in i){const n=i["float inputs:roughness.connect"],r=u(o,/(\w+).output/.exec(n)[1]);t.roughness=1,t.roughnessMap=p(r),t.roughnessMap.colorSpace=ct,'def Shader "Transform2d_roughness"'in e&&d(t.roughnessMap,e['def Shader "Transform2d_roughness"'])}else"float inputs:roughness"in i&&(t.roughness=parseFloat(i["float inputs:roughness"]));if("float inputs:metallic.connect"in i){const n=i["float inputs:metallic.connect"],r=u(o,/(\w+).output/.exec(n)[1]);t.metalness=1,t.metalnessMap=p(r),t.metalnessMap.colorSpace=ct,'def Shader "Transform2d_metallic"'in e&&d(t.metalnessMap,e['def Shader "Transform2d_metallic"'])}else"float inputs:metallic"in i&&(t.metalness=parseFloat(i["float inputs:metallic"]));if("float inputs:clearcoat.connect"in i){const n=i["float inputs:clearcoat.connect"],r=u(o,/(\w+).output/.exec(n)[1]);t.clearcoat=1,t.clearcoatMap=p(r),t.clearcoatMap.colorSpace=ct,'def Shader "Transform2d_clearcoat"'in e&&d(t.clearcoatMap,e['def Shader "Transform2d_clearcoat"'])}else"float inputs:clearcoat"in i&&(t.clearcoat=parseFloat(i["float inputs:clearcoat"]));if("float inputs:clearcoatRoughness.connect"in i){const n=i["float inputs:clearcoatRoughness.connect"],r=u(o,/(\w+).output/.exec(n)[1]);t.clearcoatRoughness=1,t.clearcoatRoughnessMap=p(r),t.clearcoatRoughnessMap.colorSpace=ct,'def Shader "Transform2d_clearcoatRoughness"'in e&&d(t.clearcoatRoughnessMap,e['def Shader "Transform2d_clearcoatRoughness"'])}else"float inputs:clearcoatRoughness"in i&&(t.clearcoatRoughness=parseFloat(i["float inputs:clearcoatRoughness"]));if("float inputs:ior"in i&&(t.ior=parseFloat(i["float inputs:ior"])),"float inputs:occlusion.connect"in i){const n=i["float inputs:occlusion.connect"],r=u(o,/(\w+).output/.exec(n)[1]);t.aoMap=p(r),t.aoMap.colorSpace=ct,'def Shader "Transform2d_occlusion"'in e&&d(t.aoMap,e['def Shader "Transform2d_occlusion"'])}}if('def Shader "diffuseColor_texture"'in e){const i=e['def Shader "diffuseColor_texture"'];t.map=p(i),t.map.colorSpace=ht}if('def Shader "normal_texture"'in e){const i=e['def Shader "normal_texture"'];t.normalMap=p(i),t.normalMap.colorSpace=ct}}return t}(function(e){if(e){if("rel material:binding"in e){const t=e["rel material:binding"].replace(/^<\//,"").replace(/>$/,"").split("/");return h(o,` "${t[1]}"`)}return h(e)}}(e)),n=t?new Pr(t,i):new En;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 Lo;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)}}(o,g),g}}const HR=new Qn;class WR extends Md{constructor(e){super(e),this.propertyNameMapping={},this.customPropertyMapping={}}load(e,t,i,n){const r=this,s=new Id(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 qR(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 ur;e.indices.length>0&&t.setIndex(e.indices),t.setAttribute("position",new rr(e.vertices,3)),e.normals.length>0&&t.setAttribute("normal",new rr(e.normals,3)),e.uvs.length>0&&t.setAttribute("uv",new rr(e.uvs,2)),e.colors.length>0&&t.setAttribute("color",new rr(e.colors,3)),(e.faceVertexUvs.length>0||e.faceVertexColors.length>0)&&(t=t.toNonIndexed(),e.faceVertexUvs.length>0&&t.setAttribute("uv",new rr(e.faceVertexUvs,2)),e.faceVertexColors.length>0&&t.setAttribute("color",new rr(e.faceVertexColors,3)));for(const i of Object.keys(u.customPropertyMapping))e[i].length>0&&t.setAttribute(i,new rr(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&&(HR.setRGB(i[n.attrR]/255,i[n.attrG]/255,i[n.attrB]/255).convertSRGBToLinear(),e.colors.push(HR.r,HR.g,HR.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&&(HR.setRGB(i[n.attrR]/255,i[n.attrG]/255,i[n.attrB]/255).convertSRGBToLinear(),e.faceVertexColors.push(HR.r,HR.g,HR.b),e.faceVertexColors.push(HR.r,HR.g,HR.b),e.faceVertexColors.push(HR.r,HR.g,HR.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 qR{constructor(e){this.arr=e,this.i=0}empty(){return this.i>=this.arr.length}next(){return this.arr[this.i++]}}class XR extends Md{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new Id(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 ur,p=new Float32Array(3*i*3),m=new Float32Array(3*i*3),g=new Qn;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 tr(p,3)),u.setAttribute("normal",new tr(m,3)),d&&(u.setAttribute("color",new tr(a,3)),u.hasColors=!0,u.alpha=h),u}(i):function(e){const t=new ur,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 wi;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 rr(c,3)),t.setAttribute("normal",new rr(h,3)),t}("string"!=typeof(n=e)?(new TextDecoder).decode(n):n);var n}}const YR=new Nn,KR=new wi,JR=new Ht,ZR=new Ht,$R=new Ht;const eB=new wi,tB=new Zu,iB=new Kr,nB=new wi,rB=new Nn;class sB{constructor(){this.normal=new wi,this.midpoint=new wi,this.area=0,this.constant=0,this.outside=null,this.mark=0,this.edge=null}static create(e,t,i){const n=new sB,r=new aB(e,n),s=new aB(t,n),a=new aB(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 rB.set(e.point,t.point,i.point),rB.getNormal(this.normal),rB.getMidpoint(this.midpoint),this.area=rB.getArea(),this.constant=this.normal.dot(this.midpoint),this}distanceToPoint(e){return this.normal.dot(e)-this.constant}}class aB{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 oB{constructor(e){this.point=e,this.prev=null,this.next=null,this.face=null}}class lB{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 cB{constructor(){this.toJSON=null}onAdded(e){e.assetManager.importer.addImporter(this._importer)}onRemove(e){e.assetManager.importer.removeImporter(this._importer)}dispose(){}}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};e.BaseGroundPlugin=class extends Jb{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=nx.upgradeGeometry.call(new is(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 wi).sub(new wi(0,e.getSize(new wi).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 hn(-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 ww(this._geometry,this._createMaterial()),e}setGeometry(e){e?this._geometry&&this._geometry.dispose():e=this._geometry,e&&(this._geometry=e,nx.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 hw({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",uB([dg("Visible"),cm(e.BaseGroundPlugin.prototype.refreshTransform),pm()],e.BaseGroundPlugin.prototype,"visible",2),uB([lg("Size"),hm(e.BaseGroundPlugin.prototype._onSceneUpdate),pm()],e.BaseGroundPlugin.prototype,"size",2),uB([lg("Height (yOffset)"),hm(e.BaseGroundPlugin.prototype._onSceneUpdate),pm()],e.BaseGroundPlugin.prototype,"yOffset",2),uB([dg("Render to Depth"),cm(e.BaseGroundPlugin.prototype._refresh2),pm()],e.BaseGroundPlugin.prototype,"renderToDepth",2),uB([dg("Tonemap Ground"),cm(e.BaseGroundPlugin.prototype._refresh2),pm()],e.BaseGroundPlugin.prototype,"tonemapGround",2),uB([dg("Limit Camera Above Ground"),cm(e.BaseGroundPlugin.prototype._refreshCameraLimits),pm()],e.BaseGroundPlugin.prototype,"limitCameraAboveGround",2),uB([dg("Auto Adjust Transform"),cm(e.BaseGroundPlugin.prototype.refreshTransform),pm()],e.BaseGroundPlugin.prototype,"autoAdjustTransform",2),uB([pm("material"),eg(),LA({obj:"mesh",key:"material",allowUndefined:!0})],e.BaseGroundPlugin.prototype,"_material",2),e.BaseGroundPlugin=uB([pg("Ground Plane")],e.BaseGroundPlugin);class pB extends Jb{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 mB=Object.defineProperty;const gB=class extends Jb{constructor(e,t){super(),this.container=t,this.enabled=!0,this._mainDiv=Sp({id:"assetManager"+e,addToBody:!1,innerHTML:""}),this._contentDiv=Sp({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&&mB(t,i,r)})([dg("Enabled"),cm(gB.prototype._onEnabledChange),pm()],gB.prototype,"enabled");let fB=gB;class AB extends _C{constructor(e,t=120){super({vertexShader:fC.vertexShader,fragmentShader:Np`
                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 Ai(1,1,1,1)},weight2:{value:new Ai(1,1,1,1)}},defines:{MAX_INTENSITY:t}},"tDiffuse","tDiffuse2"),this.clear=!1,this.needsSwap=!0}}var yB=Object.defineProperty,vB=Object.getOwnPropertyDescriptor,_B=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?vB(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&&yB(t,i,s),s};e.SSAAPlugin=class extends Jb{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&&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&&(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",_B([pm(),dg("Enabled"),cm(e.SSAAPlugin.prototype.setDirty)],e.SSAAPlugin.prototype,"enabled",2),_B([pm(),ng("Renders/Frame",[1,32],1),cm(e.SSAAPlugin.prototype.setDirty)],e.SSAAPlugin.prototype,"rendersPerFrame",2),_B([pm(),dg("Render Camera"),cm(e.SSAAPlugin.prototype.setDirty)],e.SSAAPlugin.prototype,"jitterRenderCamera",2),_B([pm(),dg("Light Cameras"),cm(e.SSAAPlugin.prototype.setDirty)],e.SSAAPlugin.prototype,"jitterLightCameras",2),e.SSAAPlugin=_B([pg("SSAA Plugin")],e.SSAAPlugin);var bB=Object.defineProperty,xB=Object.getOwnPropertyDescriptor,wB=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?xB(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&&bB(t,i,s),s};e.ProgressivePlugin=class extends VD{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 CB(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",wB([pm(),og("Frame count")],e.ProgressivePlugin.prototype,"maxFrameCount",2),wB([hg("Last Texture",{readOnly:!0})],e.ProgressivePlugin.prototype,"mainTexture",1),e.ProgressivePlugin=wB([pg("Progressive Plugin")],e.ProgressivePlugin);class CB extends AB{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=Yp(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=Yp(this.target)?.texture,this.material.uniformsNeedUpdate=!0}}var SB=Object.defineProperty,MB=Object.getOwnPropertyDescriptor,EB=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?MB(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&&SB(t,i,s),s};e.DepthBufferPlugin=class extends VD{constructor(e=Ce,t=!1,i=!0,n=at){super(),this.passId="depth",this.material=new TB({depthPacking:at,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=Cv(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#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:at,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}_depthPackingChanged(){this.material.depthPacking=this.depthPacking,this.material.needsUpdate=!0,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,new Qn(0,0,0),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",EB([hg("Depth Buffer",{readOnly:!0})],e.DepthBufferPlugin.prototype,"texture",2),EB([cm(e.DepthBufferPlugin.prototype._depthPackingChanged),sg("Depth Packing",ty.DepthPackingStrategies.uiConfig)],e.DepthBufferPlugin.prototype,"depthPacking",2),e.DepthBufferPlugin=EB([pg("Depth Buffer Plugin")],e.DepthBufferPlugin);class TB extends Eo{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 IB=Object.defineProperty,PB=Object.getOwnPropertyDescriptor,DB=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?PB(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.NormalBufferPlugin=class extends VD{constructor(e=Ie,t=!0){super(),this.passId="normal",this.material=new RB({blending:w}),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:dt})),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 Qn(0,0,0),1),i=t.preprocessMaterial;return t.preprocessMaterial=e=>i(e,!0),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",DB([hg("Normal Buffer",{readOnly:!0})],e.NormalBufferPlugin.prototype,"texture",2),e.NormalBufferPlugin=DB([pg("Normal Buffer Plugin")],e.NormalBufferPlugin);class RB extends $h{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=ot,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.flatShading=!1,this.side=x,this.wireframe=!1,this.wireframeLinewidth=1}}var BB=Object.defineProperty,LB=Object.getOwnPropertyDescriptor,OB=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?LB(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&&BB(t,i,s),s};e.FrameFadePlugin=class extends VD{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 yp(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 UB(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",OB([pm(),dg()],e.FrameFadePlugin.prototype,"fadeOnActiveCameraChange",2),OB([pm(),dg()],e.FrameFadePlugin.prototype,"fadeOnMaterialUpdate",2),OB([pm(),dg()],e.FrameFadePlugin.prototype,"fadeOnSceneUpdate",2),e.FrameFadePlugin=OB([pg("FrameFade Plugin")],e.FrameFadePlugin);class UB extends AB{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=vp();this._lastTime<10&&(this._lastTime=l-10);const c=l-this._lastTime;this._lastTime=l,this.fadeTimeState-=c}}var FB=Object.defineProperty,NB=Object.getOwnPropertyDescriptor,kB=(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&&FB(t,i,s),s};e.SSAOPlugin=class extends VD{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:dt})),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=Im(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",kB([hg("SSAO Buffer",{readOnly:!0,tags:["debug"]})],e.SSAOPlugin.prototype,"texture",2),kB([eg(void 0,{unwrapContents:!0})],e.SSAOPlugin.prototype,"_pass",2),e.SSAOPlugin=kB([pg("SSAO Plugin")],e.SSAOPlugin),e.SSAOPluginPass=class extends _C{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 Ht(0,0)},saoData:{value:new Ai},frameCount:{value:0},cameraNearFar:{value:new Ht(.1,1e3)},projection:{value:new $i},saoBiasEpsilon:{value:new Ai(1,1,1,1)},sceneBoundingRadius:{value:0},ssaoSplitX:{value:.5}},vertexShader:Xm.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:Yp(this.target)?.texture??null}),ssaoSplitX:this.material.uniforms.ssaoSplitX},shaderExtender:(e,t,i)=>{e.defines?.SSAO_ENABLED&&(e.fragmentShader=Cv(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:()=>Np`
             uniform sampler2D tSSAOMap;
            #if defined(SSAO_ENABLED) && SSAO_ENABLED == 2
            uniform float ssaoSplitX;
            #endif
             ${UA("tSSAOMap",Yp(this.target)?.texture.colorSpace)}
             #include <simpleCameraHelpers>
        `,computeCacheKey:()=>(this.enabled?"1":"0")+Yp(this.target)?.texture?.colorSpace,uuid:e.SSAOPlugin.PluginType,...ux(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=Yp(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*Vt.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}]}}},kB([pm(),ng("Intensity",[0,4],1e-4),hm(e.SSAOPluginPass.prototype.setDirty)],e.SSAOPluginPass.prototype,"intensity",2),kB([pm(),ng("Occlusion World Radius",[.1,8],.01),hm(e.SSAOPluginPass.prototype.setDirty)],e.SSAOPluginPass.prototype,"occlusionWorldRadius",2),kB([pm(),hm(e.SSAOPluginPass.prototype.setDirty),dg()],e.SSAOPluginPass.prototype,"autoRadius",2),kB([pm(),ng("Bias",[1e-5,.01],1e-5),hm(e.SSAOPluginPass.prototype.setDirty)],e.SSAOPluginPass.prototype,"bias",2),kB([pm(),ng("Falloff",[.01,3],.01),hm(e.SSAOPluginPass.prototype.setDirty)],e.SSAOPluginPass.prototype,"falloff",2),kB([pm(),ng("Num Samples",[1,11],1,{tags:["performance"]}),RA("NUM_SAMPLES",void 0,void 0,e.SSAOPluginPass.prototype.setDirty)],e.SSAOPluginPass.prototype,"numSamples",2),kB([BA("CHECK_GBUFFER_FLAG")],e.SSAOPluginPass.prototype,"checkGBufferFlag",2),kB([ng("Split",[0,1],.01,{tags:["debug"]}),pm(),DA({propKey:"ssaoSplitX",onChange:e.SSAOPluginPass.prototype.setDirty})],e.SSAOPluginPass.prototype,"split",2),e.SSAOPluginPass=kB([pg("SSAO Pass")],e.SSAOPluginPass);var jB=Object.defineProperty,zB=Object.getOwnPropertyDescriptor,GB=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?zB(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&&jB(t,i,s),s};e.RenderTargetPreviewPlugin=class extends Jb{constructor(e=!0){super(),this.enabled=!0,this.toJSON=null,this.mainDiv=Sp({id:"RenderTargetPreviewPluginContainer",addToBody:!1}),this.targetBlocks=[],this._postRender=()=>{if(this._viewer)for(const e of this.targetBlocks){if(!e.visible)continue;const t=Yp(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=ht),this._viewer.renderManager.blit(null,{source:n,clear:!e.transparent,respectColorSpace:!e.originalColorSpace,viewport:new Ai(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=Ep('#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 CC(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(),Ig.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=Yp(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",GB([dg("Enabled"),cm(e.RenderTargetPreviewPlugin.prototype.refreshUi)],e.RenderTargetPreviewPlugin.prototype,"enabled",2),e.RenderTargetPreviewPlugin=GB([pg("Render Target Preview Plugin")],e.RenderTargetPreviewPlugin);var QB=Object.defineProperty,VB=Object.getOwnPropertyDescriptor,HB=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?VB(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&&QB(t,i,s),s};e.GeometryUVPreviewPlugin=class extends Jb{constructor(e=!0){super(),this.enabled=!0,this.toJSON=null,this.mainDiv=Sp({id:"GeometryUVPreviewPluginContainer",addToBody:!1}),this.targetBlocks=[],this._postRender=()=>{if(this._viewer)for(const e of this.targetBlocks){if(!e.visible)continue;const t=Yp(e.target);t?.attributes?.uv&&(e.uvCanvas||(e.uvCanvas=oR(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=Ep('#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(),Ig.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",HB([dg("Enabled"),cm(e.GeometryUVPreviewPlugin.prototype.refreshUi)],e.GeometryUVPreviewPlugin.prototype,"enabled",2),e.GeometryUVPreviewPlugin=HB([pg("Render Target Preview Plugin")],e.GeometryUVPreviewPlugin);var WB=Object.defineProperty;const qB=class extends Jb{constructor(){super(),this.enabled=!0,this.serializeWithViewer=!1,this.uiConfig={}}onAdded(e){super.onAdded(e),this.uiConfig=e.uiConfig,this.uiConfig.expanded=!0}};qB.PluginType="ViewerUiConfigPlugin";let XB=qB;((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&&WB(t,i,r)})([pm("viewer")],XB.prototype,"_viewer");var YB=Object.defineProperty;const KB=class extends Jb{constructor(){super(),this.enabled=!0,this.serializeWithViewer=!1,this.uiConfig={}}onAdded(e){super.onAdded(e),this.uiConfig=e.scene.uiConfig,this._scene=e.scene}};KB.PluginType="SceneUiConfigPlugin";let JB=KB;((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&&YB(t,i,r)})([pm("scene")],JB.prototype,"_scene");var ZB=Object.defineProperty,$B=Object.getOwnPropertyDescriptor,eL=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?$B(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&&ZB(t,i,s),s};e.FullScreenPlugin=class extends Jb{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",eL([ag("Enter FullScreen",{sendArgs:!1})],e.FullScreenPlugin.prototype,"enter",1),eL([ag("Exit FullScreen",{sendArgs:!1})],e.FullScreenPlugin.prototype,"exit",1),eL([ag("Toggle FullScreen",{sendArgs:!1})],e.FullScreenPlugin.prototype,"toggle",1),e.FullScreenPlugin=eL([pg("Full Screen")],e.FullScreenPlugin);var tL=Object.defineProperty,iL=Object.getOwnPropertyDescriptor,nL=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?iL(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&&tL(t,i,s),s};e.LoadingScreenPlugin=class extends fB{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=Sp({classList:["loadingScreenLoadingElement"],addToBody:!1}),this.filesElement=Sp({classList:["loadingScreenFilesElement"],addToBody:!1}),this.logoElement=Sp({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&&yp(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 yp(502),this._isHidden&&(this._mainDiv.style.display="none",this._showMainDiv())}async hideWithDelay(){if(this._isHidden=!0,await yp(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">${Fp(e.state)}</span>: `:"")+Fp((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,Fp(this.errorTextHeader)):this._setHTML(this._contentDiv,Fp(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=Ep(this.styles,e.container),this.stylesheetLoader=this.spinners.map((t=>Ep(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",nL([sg("Loader",["Spinner 1"].map(((e,t)=>({value:t,label:e})))),pm()],e.LoadingScreenPlugin.prototype,"loader",2),nL([og("Loading text header"),cm(e.LoadingScreenPlugin.prototype.refresh),pm()],e.LoadingScreenPlugin.prototype,"loadingTextHeader",2),nL([og("Error text header"),pm()],e.LoadingScreenPlugin.prototype,"errorTextHeader",2),nL([dg("Show file names"),cm(e.LoadingScreenPlugin.prototype.refresh),pm()],e.LoadingScreenPlugin.prototype,"showFileNames",2),nL([dg("Show process states"),cm(e.LoadingScreenPlugin.prototype.refresh),pm()],e.LoadingScreenPlugin.prototype,"showProcessStates",2),nL([dg("Show progress"),cm(e.LoadingScreenPlugin.prototype.refresh),pm()],e.LoadingScreenPlugin.prototype,"showProgress",2),nL([dg("Hide on only errors"),pm()],e.LoadingScreenPlugin.prototype,"hideOnOnlyErrors",2),nL([dg("Hide on files load"),pm()],e.LoadingScreenPlugin.prototype,"hideOnFilesLoad",2),nL([dg("Hide on scene object load"),pm()],e.LoadingScreenPlugin.prototype,"hideOnSceneObjectLoad",2),nL([dg("Minimize on scene object load"),pm()],e.LoadingScreenPlugin.prototype,"minimizeOnSceneObjectLoad",2),nL([dg("Show when files start loading"),pm()],e.LoadingScreenPlugin.prototype,"showOnFilesLoading",2),nL([dg("Show when scene empty"),pm()],e.LoadingScreenPlugin.prototype,"showOnSceneEmpty",2),nL([og("Hide delay (ms)"),pm()],e.LoadingScreenPlugin.prototype,"hideDelay",2),nL([ng("Background Opacity",[0,1]),cm(e.LoadingScreenPlugin.prototype.refresh),pm()],e.LoadingScreenPlugin.prototype,"backgroundOpacity",2),nL([ng("Background Blur",[0,100]),cm(e.LoadingScreenPlugin.prototype.refresh),pm()],e.LoadingScreenPlugin.prototype,"backgroundBlur",2),nL([og("Background Color"),cm(e.LoadingScreenPlugin.prototype.refresh),pm()],e.LoadingScreenPlugin.prototype,"background",2),nL([og("Text Color"),cm(e.LoadingScreenPlugin.prototype.refresh),pm()],e.LoadingScreenPlugin.prototype,"textColor",2),nL([og("Logo Image"),cm(e.LoadingScreenPlugin.prototype.refresh),pm()],e.LoadingScreenPlugin.prototype,"logoImage",2),nL([ag("Toggle preview")],e.LoadingScreenPlugin.prototype,"togglePreview",1),nL([ag("Minimize")],e.LoadingScreenPlugin.prototype,"minimize",1),nL([ag("Maximize")],e.LoadingScreenPlugin.prototype,"maximize",1),e.LoadingScreenPlugin=nL([pg("Loading Screen")],e.LoadingScreenPlugin);class rL extends xw{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 TA).expandByObject(e,!1);t.getCenter(this.position);let i=t.getBoundingSphere(new Vi).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 sL=Object.defineProperty;const aL=class extends xw{constructor(e,t=!0){super(),this.isWidget=!0,this.assetType="widget",this.visible=!0,this._objectUpdated=!1,this.uiConfig=$m("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&&kx.setDirty.call(this)}_objectUpdate(){this._objectUpdated=!0}_objectBeforeRender(){this.visible&&this._objectUpdated&&(this._objectUpdated=!1,this.object&&this.update())}attach(e){return this.object&&this.detach(),this.object=e,this.object&&(this.update(),this.object.addEventListener("beforeRender",this._objectBeforeRender),this.object.addEventListener("objectUpdate",this._objectUpdate),this.object.addEventListener("geometryUpdate",this._objectUpdate),this.uiConfig&&this.object.uiConfig?.children?.push(this.uiConfig),this.visible=!0),this}detach(){if(!this.object)return this;if(this.object.removeEventListener("beforeRender",this._objectBeforeRender),this.object.removeEventListener("objectUpdate",this._objectUpdate),this.object.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&&sL(t,i,r)})([dg(),hm(aL.prototype.update)],aL.prototype,"visible");let oL=aL;class lL extends oL{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 cL extends oL{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 hL=Object.defineProperty,dL=(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&&hL(t,i,s),s};const uL=class e extends oL{constructor(e,t,i){super(e),this._vector=new wi,this._boneMatrix=new $i,this._matrixWorldInv=new $i,this.lineWidth=5,this.color1=new Qn(0,0,1),this.color2=new Qn(0,1,0),this.autoUpdate=!0,t&&this.color1.set(t),i&&this.color2.set(i);const n=new fy;this.hMaterial=new yw({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 By(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)}};dL([hm(uL.prototype.update)],uL.prototype,"hMaterial"),dL([hm(uL.prototype.update),ng(void 0,[.1,20],.01)],uL.prototype,"lineWidth"),dL([hm(uL.prototype.update),cg()],uL.prototype,"color1"),dL([hm(uL.prototype.update),cg()],uL.prototype,"color2"),dL([dg(),hm(uL.prototype.update)],uL.prototype,"autoUpdate");let pL=uL;class mL extends rL{constructor(){super();const e=new yw({color:"#ff2222",transparent:!0,opacity:.9,linewidth:5,resolution:new Ht(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 fy;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 By(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 TA).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 gL=Object.defineProperty;const fL=class e extends lL{constructor(e){super(e),this._vector=new wi,this._camera=new Nr,this._colorFrustum=new Qn(16755200),this._colorCone=new Qn(16711680),this._colorUp=new Qn(43775),this._colorTarget=new Qn(16777215),this._colorCross=new Qn(3355443),this.showFar=!1;const t=new fy,i=new yw({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 By(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),yL("c",t,e,i,0,0,-1,n),yL("t",t,e,i,0,0,1,n),yL("n1",t,e,i,-1,-1,-1,n),yL("n2",t,e,i,1,-1,-1,n),yL("n3",t,e,i,-1,1,-1,n),yL("n4",t,e,i,1,1,-1,n),yL("f1",t,e,i,-1,-1,1,n),yL("f2",t,e,i,1,-1,1,n),yL("f3",t,e,i,-1,1,1,n),yL("f4",t,e,i,1,1,1,n),yL("u1",t,e,i,.7,1.1,-1,n),yL("u2",t,e,i,-.7,1.1,-1,n),yL("u3",t,e,i,0,2,-1,n),yL("cf1",t,e,i,-1,0,1,n),yL("cf2",t,e,i,1,0,1,n),yL("cf3",t,e,i,0,-1,1,n),yL("cf4",t,e,i,0,1,1,n),yL("cn1",t,e,i,-1,0,-1,n),yL("cn2",t,e,i,1,0,-1,n),yL("cn3",t,e,i,0,-1,-1,n),yL("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&&gL(t,i,r)})([dg(),hm(fL.prototype.update)],fL.prototype,"showFar");let AL=fL;function yL(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 vL=Object.defineProperty,_L=(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&&vL(t,i,s),s};const bL=class e extends cL{constructor(e,t,i){super(e),this.lineWidth=5,this.size=.5,this._v1=new wi,this._v2=new wi,this._v3=new wi,this.color=i,void 0!==t&&(this.size=t);let n=new Cw;this.hMaterial=new yw({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 Sw(n,this.hMaterial),this.add(this.lightPlane),n=new Cw,n.setPositions([0,0,0,0,0,1]),this.targetLine=new Sw(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)}};_L([cm(bL.prototype.update)],bL.prototype,"hMaterial"),_L([cm(bL.prototype.update),ng(void 0,[.1,20],.01)],bL.prototype,"lineWidth"),_L([cm(bL.prototype.update),ng(void 0,[.01,10],.01)],bL.prototype,"size");let xL=bL;var wL=Object.defineProperty,CL=(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&&wL(t,i,s),s};const SL=class e extends oL{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 Rr(1,1,1,2,2,2),nx.upgradeGeometry.call(this._cubeGeometry),this._cubeMaterial=new Xn({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=EL(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 Pr(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 Pr(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)}};CL([cm(SL.prototype.update),ng(void 0,[.001,.2],.001)],SL.prototype,"handleSize"),CL([cm(SL.prototype.update),ng(void 0,[.001,.5],.001)],SL.prototype,"editableHandleSize"),CL([cm(SL.prototype.update),cg()],SL.prototype,"handleColor"),CL([cm(SL.prototype.update),cg()],SL.prototype,"editableHandleColor");let ML=SL;function EL(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=EL(e);n.forEach((e=>{e[1]="curves."+i+"."+e[1]})),t.push(...n)})),t}var TL=Object.defineProperty,IL=(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&&TL(t,i,s),s};const PL=class e extends cL{constructor(e,t,i){super(e),this.lineWidth=5,this.size=.5,this.color=i,void 0!==t&&(this.size=t);const n=new Rw(new kh(.5,4,2));this.hMaterial=new yw({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 aR(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)}};IL([cm(PL.prototype.update)],PL.prototype,"hMaterial"),IL([cm(PL.prototype.update),ng(void 0,[.1,20],.01)],PL.prototype,"lineWidth"),IL([cm(PL.prototype.update),ng(void 0,[.01,10],.01)],PL.prototype,"size");let DL=PL;var RL=Object.defineProperty,BL=(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&&RL(t,i,s),s};const LL=class e extends oL{constructor(e,t,i){super(e),this._vector=new wi,this._boneMatrix=new $i,this._matrixWorldInv=new $i,this.lineWidth=5,this.color1=new Qn(0,0,1),this.color2=new Qn(0,1,0),this.autoUpdate=!0,t&&this.color1.set(t),i&&this.color2.set(i),this.bones=UL(e);const n=new fy;this.hMaterial=new yw({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 By(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&&UL(e).length>0}static Create(t){const i=new e(t);return t._hasSkeletonHelper=!0,i}};BL([hm(LL.prototype.update)],LL.prototype,"hMaterial"),BL([hm(LL.prototype.update),ng(void 0,[.1,20],.01)],LL.prototype,"lineWidth"),BL([hm(LL.prototype.update),cg()],LL.prototype,"color1"),BL([hm(LL.prototype.update),cg()],LL.prototype,"color2"),BL([dg(),hm(LL.prototype.update)],LL.prototype,"autoUpdate");let OL=LL;function UL(e){const t=[];!0===e.isBone&&t.push(e);for(const i of e.children)t.push(...UL(i));return t}var FL=Object.defineProperty,NL=(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&&FL(t,i,s),s};const kL=class e extends cL{constructor(e,t,i){super(e),this.lineWidth=5,this._v1=new wi,this.color=i;const n=new fy,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 yw({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 By(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)}};NL([cm(kL.prototype.update)],kL.prototype,"hMaterial"),NL([cm(kL.prototype.update),ng(void 0,[.1,20],.01)],kL.prototype,"lineWidth");let jL=kL;const zL=class e{constructor(){this._initialMatrix=new $i,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}};zL._iP=new wi,zL._iQ=new xi,zL._iS=new wi,zL._rel=new wi;let GL=zL;class QL{constructor(){this._state=null}get state(){return this._state}get isEmpty(){return!this._state}copy(e){const t=jx(e);t.length&&(this._state={objects:t,mode:"copy",sourceParents:this._parentMap(t)})}cut(e){const t=jx(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);tx(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 VL=Object.defineProperty,HL=(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&&VL(t,i,s),s};function WL(e){for(;e.parent&&"widget"!==e.assetType&&!e.userData.allowPicking;)e=e.parent;return e}const qL=(s=class extends Jb{constructor(t=mL,i=!0,n=!1){super(),this.enabled=!0,this._extraWidgets=[],this._clipboard=new QL,this._duplicateTracker=new GL,this.duplicateMode="simple",this.dependencies=[FD],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=WL(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:Px,def:HC.DummyMaterial,name:"Unlit"},{cls:mw,def:HC.DummyLineBasicMaterial,line:!0,name:"Basic Line"},{cls:yw,def:HC.DummyLineMaterial,line:!0,name:"Line"},{cls:hw,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 zx(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}=Gx(i);if(!n.length)return;const a=this._duplicateTracker.saveState(),o=(new $i).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 oy(e.scene.modelRoot,e.canvas,e.scene.mainCamera,(e=>{if(!e.material&&!e.userData.userSelectable)return!1;let t=e;t=WL(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&&Xp(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&&Xp(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===yw))?.def:e.isLine||e.isLineSegments?this.materialTypes.find((e=>e.cls===mw))?.def:null)||t[0]}},s.PluginType="Picking",s.OldPluginType="PickingPlugin",s);HL([pm(),cm(qL.prototype.setDirty)],qL.prototype,"enabled"),HL([LA({obj:"_picker",key:"selectionMode"})],qL.prototype,"selectionMode"),HL([pm()],qL.prototype,"autoFocus"),HL([cm(qL.prototype._widgetEnabledChange)],qL.prototype,"widgetEnabled"),HL([LA({obj:"_picker",key:"multiSelectEnabled"})],qL.prototype,"multiSelectEnabled");let XL=qL;class YL{constructor(){this.multiObjects=[],this._dummy=null,this._dummyStart=new $i,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 En,this._dummy.userData.isMultiSelectDummy=!0,t.scene.addObject(this._dummy,{addToRoot:!0}));const i=new wi;for(const t of e)t.updateWorldMatrix(!0,!1),i.add((new wi).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 $i;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 wi;for(const t of this.multiObjects)t.updateWorldMatrix(!0,!1),e.add((new wi).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 KL=Object.defineProperty,JL=Object.getOwnPropertyDescriptor,ZL=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?JL(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&&KL(t,i,s),s};e.TransformControlsPlugin=class extends Jb{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.dependencies=[XL],this._isInteracting=!1,this._viewerListeners={postFrame:()=>{!this.transformControls||this._viewer}},this._transformState={obj:null,position:new wi,rotation:new hn,scale:new wi},this.selectionFilterTest=void 0,this._multi=new YL,this._mainCameraChange=()=>{!this.transformControls||!this._viewer||(this.transformControls.camera=this._viewer.scene.mainCamera)},Jg.ObjectConstructors.MeshBasicMaterial=Px,Jg.ObjectConstructors.LineBasicMaterial=mw,this.enabled=e}setDirty(){if(!this._viewer)return;const e=this._viewer.getPlugin(XL),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(XL).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",ZL([dg(),cm(e.TransformControlsPlugin.prototype.setDirty)],e.TransformControlsPlugin.prototype,"enabled",2),ZL([eg(void 0,{expanded:!0})],e.TransformControlsPlugin.prototype,"transformControls",2),ZL([ag("Center All Meshes")],e.TransformControlsPlugin.prototype,"centerAllMeshes",1),e.TransformControlsPlugin=ZL([pg("Transform Controls")],e.TransformControlsPlugin),e.TransformControls2=class extends Jg{constructor(e,t){super(e,t),this.isWidget=!0,this.assetType="widget",this.setDirty=kx.setDirty.bind(this),this.refreshUi=kx.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(!bf(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=Vt.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}},ZL([sg("Mode",["translate","rotate","scale"].map((e=>({label:e}))))],e.TransformControls2.prototype,"mode",2),ZL([sg("Space",["world","local"].map((e=>({label:e}))))],e.TransformControls2.prototype,"space",2),ZL([ng("Size",[.1,10],.01)],e.TransformControls2.prototype,"size",2),ZL([dg("Show X")],e.TransformControls2.prototype,"showX",2),ZL([dg("Show Y")],e.TransformControls2.prototype,"showY",2),ZL([dg("Show Z")],e.TransformControls2.prototype,"showZ",2),e.TransformControls2=ZL([pg("Transform Controls")],e.TransformControls2);var $L=Object.defineProperty,eO=Object.getOwnPropertyDescriptor,tO=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?eO(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&&$L(t,i,s),s};e.PivotControlsPlugin=class extends Jb{constructor(e=!0){super(),this.enabled=!0,this.toJSON=void 0,this.dependencies=[XL],this._isInteracting=!1,this._viewerListeners={preFrame:()=>{!this.pivotControls||!this._viewer||this.pivotControls.updateGizmoScale()}},this._transformState={obj:null,position:new wi,rotation:new hn,scale:new wi},this.selectionFilterTest=void 0,this._multi=new YL,this._mainCameraChange=()=>{!this.pivotControls||!this._viewer||(this.pivotControls.camera=this._viewer.scene.mainCamera)},qf.ObjectConstructors.MeshBasicMaterial=Px,qf.ObjectConstructors.LineBasicMaterial=mw,this.enabled=e}setDirty(){if(!this._viewer)return;const e=this._viewer.getPlugin(XL),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(XL).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",tO([dg(),cm(e.PivotControlsPlugin.prototype.setDirty)],e.PivotControlsPlugin.prototype,"enabled",2),tO([eg(void 0,{expanded:!0})],e.PivotControlsPlugin.prototype,"pivotControls",2),e.PivotControlsPlugin=tO([pg("Pivot Controls")],e.PivotControlsPlugin),e.PivotControls2=class extends qf{constructor(e,t){super(e,t),this.isWidget=!0,this.assetType="widget",this.setDirty=kx.setDirty.bind(this),this.refreshUi=kx.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}},tO([sg("Space",["world","local"].map((e=>({label:e})))),cm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"space",2),tO([ng("Gizmo Scale",[.1,10],.01),cm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"gizmoScale",2),tO([dg("Fixed Size"),cm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"fixed",2),tO([dg("Depth Test"),cm(e.PivotControls2.prototype._onRebuild)],e.PivotControls2.prototype,"depthTest",2),tO([dg("Annotations")],e.PivotControls2.prototype,"annotations",2),tO([ng("Translation Snap",[.01,5],.01)],e.PivotControls2.prototype,"translationSnap",2),tO([ng("Rotation Snap (deg)",[1,90],1)],e.PivotControls2.prototype,"rotationSnap",2),tO([ng("Scale Snap",[.01,1],.01)],e.PivotControls2.prototype,"scaleSnap",2),tO([dg("Uniform Scale (Alt)")],e.PivotControls2.prototype,"uniformScaleEnabled",2),tO([dg("Disable Axes"),cm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"disableAxes",2),tO([dg("Disable Sliders"),cm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"disableSliders",2),tO([dg("Disable Rotations"),cm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"disableRotations",2),tO([dg("Disable Scaling"),cm(e.PivotControls2.prototype._onVisibilityChange)],e.PivotControls2.prototype,"disableScaling",2),e.PivotControls2=tO([pg("Pivot Controls")],e.PivotControls2);var iO=Object.defineProperty,nO=Object.getOwnPropertyDescriptor,rO=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?nO(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&&iO(t,i,s),s};const sO=new wi,aO=new wi;e.PivotEditPlugin=class extends Jb{constructor(e=!0){super(),this.dependencies=[XL],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(XL);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 Xn({color:this.markerColor,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0,opacity:.9});this._pivotMarker=new Pr(new kh(1,8,8),i),this._pivotMarker.renderOrder=1e3,this._pivotMarker.userData.isWidgetHandle=!0,this._pivotMarker.userData.isPivotMarker=!0;const n=new xw;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 xw,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 TA).expandByObject(this._selectedObject,!0,!0),t=e.getCenter(new wi);this._applyPivot(new wi(t.x,e.min.y,t.z))}pivotToOrigin(){this._applyPivot(new wi(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),sO.setFromMatrixPosition(this._selectedObject.matrixWorld),this._markerRoot.position.copy(sO),this._markerRoot.visible=!0;const e=this._viewer.scene.mainCamera;let t;e.isOrthographicCamera?t=(e.top-e.bottom)/e.zoom:(aO.setFromMatrixPosition(e.matrixWorld),t=sO.distanceTo(aO)*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||(Jg.ObjectConstructors.MeshBasicMaterial=Px,Jg.ObjectConstructors.LineBasicMaterial=mw,this._pivotGizmo=new Jg(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 wi).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 wi).setFromMatrixPosition(this._selectedObject.matrixWorld);if(this._pivotGizmo.object)this._pivotGizmo.object.position.copy(t),this._pivotGizmo.object.updateMatrixWorld(!0);else{const e=new En;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 wi).setFromMatrixPosition(t.matrixWorld);this.undoManager.record({undo:()=>{e(),this._refreshAfterPivotChange()},redo:()=>{t.pivotToPoint&&(t.pivotToPoint(i,!0),this._refreshAfterPivotChange())}})}},e.PivotEditPlugin.PluginType="PivotEditPlugin",rO([dg(),cm(e.PivotEditPlugin.prototype._onEnabledChange)],e.PivotEditPlugin.prototype,"enabled",2),rO([dg("Edit Pivot"),cm(e.PivotEditPlugin.prototype._onEditPivotChange)],e.PivotEditPlugin.prototype,"editPivot",2),rO([dg("Show Pivot Marker"),cm(e.PivotEditPlugin.prototype._onDirty)],e.PivotEditPlugin.prototype,"showPivotMarker",2),rO([ng("Marker Scale",[.1,5],.1),cm(e.PivotEditPlugin.prototype._onDirty)],e.PivotEditPlugin.prototype,"markerScale",2),rO([cg("Marker Color"),cm(e.PivotEditPlugin.prototype._onMarkerColorChange)],e.PivotEditPlugin.prototype,"markerColor",2),rO([ag("Pivot to Center")],e.PivotEditPlugin.prototype,"pivotToCenter",1),rO([ag("Pivot to Bottom")],e.PivotEditPlugin.prototype,"pivotToBottom",1),rO([ag("Pivot to Origin")],e.PivotEditPlugin.prototype,"pivotToOrigin",1),e.PivotEditPlugin=rO([pg("Pivot Edit")],e.PivotEditPlugin);var oO=Object.defineProperty,lO=Object.getOwnPropertyDescriptor,cO=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?lO(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&&oO(t,i,s),s};e.EditorViewWidgetPlugin=class extends Jb{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 $y(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",cO([dg(),cm(e.EditorViewWidgetPlugin.prototype.setDirty)],e.EditorViewWidgetPlugin.prototype,"enabled",2),e.EditorViewWidgetPlugin=cO([pg("Editor View Widget")],e.EditorViewWidgetPlugin);const hO=class extends pB{constructor(){super(...arguments),this.controlsKey="deviceOrientation",this._controlsCtor=(t,i)=>new e.DeviceOrientationControls2(t)}};hO.PluginType="DeviceOrientationControlsPlugin";let dO=hO;const uO=class extends pB{constructor(){super(...arguments),this.controlsKey="pointerLock",this._controlsCtor=(t,i)=>new e.PointerLockControls2(t,i?.ownerDocument?i:(i||document).documentElement)}};uO.PluginType="PointerLockControlsPlugin";let pO=uO;const mO=class extends pB{constructor(){super(...arguments),this.controlsKey="threeFirstPerson",this._controlsCtor=(t,i)=>new e.FirstPersonControls2(t,i||document.documentElement)}};mO.PluginType="ThreeFirstPersonControlsPlugin";let gO=mO;var fO=Object.defineProperty,AO=(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&&fO(t,i,s),s};const yO=(a=class extends Jb{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 bp({bindHotKeys:!0,limit:this.limit,debug:e.debug||null!==Dm("debugUndo"),hotKeyRoot:document}),this._refresh()}onRemove(e){this.undoManager?.dispose(),this.undoManager=void 0,super.onRemove(e)}recordUndo(e){return Vm(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!(!Hm(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=_O(e,t);return this.setValue([l,"value"],i,n,r,s,a,o)}},a.PluginType="UndoManagerPlugin",a);AO([cm(yO.prototype._refresh)],yO.prototype,"enabled"),AO([cm(yO.prototype._refresh)],yO.prototype,"limit");let vO=yO;function _O(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 bO=Object.defineProperty,xO=Object.getOwnPropertyDescriptor,wO=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?xO(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&&bO(t,i,s),s};e.Rhino3dmLoadPlugin=class extends cB{constructor(){super(...arguments),this._importer=new kC(FP,["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(){FP.ImportMaterials=this.importMaterials,FP.ForceLayerMaterials=this.forceLayerMaterials,FP.ReplaceWithInstancedMesh=this.replaceWithInstancedMesh,FP.HideLineMesh=this.hideLineMesh,FP.HidePointMesh=this.hidePointMesh,FP.LoadUserDataStrings=this.loadUserDataStrings,FP.LoadUserDataWarnings=!1}onAdded(e){if(!window.WebAssembly)throw new Error("Rhino3dmLoadPlugin requires WebAssembly support");super.onAdded(e),this._refresh()}},e.Rhino3dmLoadPlugin.PluginType="Rhino3dmLoadPlugin",wO([cm(e.Rhino3dmLoadPlugin.prototype._refresh),dg()],e.Rhino3dmLoadPlugin.prototype,"importMaterials",2),wO([cm(e.Rhino3dmLoadPlugin.prototype._refresh),dg()],e.Rhino3dmLoadPlugin.prototype,"forceLayerMaterials",2),wO([cm(e.Rhino3dmLoadPlugin.prototype._refresh),dg()],e.Rhino3dmLoadPlugin.prototype,"replaceWithInstancedMesh",2),wO([cm(e.Rhino3dmLoadPlugin.prototype._refresh),dg()],e.Rhino3dmLoadPlugin.prototype,"hideLineMesh",2),wO([cm(e.Rhino3dmLoadPlugin.prototype._refresh),dg()],e.Rhino3dmLoadPlugin.prototype,"hidePointMesh",2),wO([cm(e.Rhino3dmLoadPlugin.prototype._refresh),dg()],e.Rhino3dmLoadPlugin.prototype,"loadUserDataStrings",2),e.Rhino3dmLoadPlugin=wO([pg("Rhino 3dm Loader")],e.Rhino3dmLoadPlugin);const CO=class extends cB{constructor(){super(...arguments),this._importer=new kC(class extends VR{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=GI(i).buffer}}return super.parse(e)}},["usdz","usda"],["model/vnd.usd+zip","model/vnd.usdz+zip","model/vnd.usda"],!1)}};CO.PluginType="USDZLoadPlugin";let SO=CO;const MO=class extends cB{constructor(){super(...arguments),this._importer=new kC(class extends WR{transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new Pr(e,new hw({color:new Qn(1,1,1),vertexColors:e.hasAttribute("color")})):void 0}},["ply"],["text/plain+ply"],!1)}};MO.PluginType="PLYLoadPlugin";let EO=MO;const TO=class extends cB{constructor(){super(...arguments),this._importer=new kC(class extends XR{transform(e,t){return e.attributes?.normal||e.computeVertexNormals(),e?new Pr(e,new hw({color:new Qn(1,1,1),vertexColors:e.hasAttribute("color")})):void 0}},["stl"],["model/stl","model/x.stl-binary","model/x.stl-ascii"],!1)}};TO.PluginType="STLLoadPlugin";let IO=TO;const PO=class extends cB{constructor(){super(...arguments),this._importer=new kC(zR,["ktx"],["image/ktx"],!1)}};PO.PluginType="KTXLoadPlugin";let DO=PO;const RO=class e extends cB{constructor(){super(...arguments),this._importer=new kC(LO,["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(UO)}onRemove(e){const t=e.assetManager.exporter.getExporter("gltf","glb"),i=t?.extensions?.indexOf(UO);void 0!==i&&-1!==i&&t?.extensions?.splice(i,1),super.onRemove(e)}};RO.PluginType="KTX2LoadPlugin",RO.TRANSCODER_LIBRARY_PATH="https://cdn.jsdelivr.net/gh/BinomialLLC/basis_universal@1.16.4/webgl/transcoder/build/",RO.SAVE_SOURCE_BLOBS=!1;let BO=RO;class LO extends UR{_initTexture(e){rC.call(e),e.userData.mimeType="image/ktx2",e.toJSON=t=>_v(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=BO.SAVE_SOURCE_BLOBS?new Uint8Array(e.slice(0)):void 0,n=await super.createTexture(e,t);return BO.SAVE_SOURCE_BLOBS&&i&&(n.source._sourceImgBuffer=i,n.source._canSerialize=!0),this._initTexture(n),n}}const OO="KHR_texture_basisu",UO=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[OO]=r,e.extensionsUsed[OO]=!0}}),FO=class e extends Ap{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(){}};FO.PluginType="GLTFMeshOptDecodePlugin",FO.DECODER_URL="https://unpkg.com/meshoptimizer@0.20.0/meshopt_decoder.module.js";let NO=FO;var kO=Object.defineProperty;const jO=class extends Jb{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}};jO.PluginType="AssetExporterPlugin";let zO=jO;((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&&kO(t,i,r)})([pm()],zO.prototype,"exportOptions");var GO=Object.defineProperty,QO=Object.getOwnPropertyDescriptor,VO=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?QO(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&&GO(t,i,s),s};e.CanvasSnapshotPlugin=class extends Jb{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 yp(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 Rb.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=GI(i);c=new File([n],t+".zip",{type:"application/zip",lastModified:Date.now()})}else c=e}else c=await Rb.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 yp(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",VO([og("Filename"),pm()],e.CanvasSnapshotPlugin.prototype,"filename",2),VO([eg(void 0,{label:"Options"}),pm()],e.CanvasSnapshotPlugin.prototype,"defaultOptions",2),VO([ag("Download .png")],e.CanvasSnapshotPlugin.prototype,"_downloadPng",1),VO([ag("Download .jpeg")],e.CanvasSnapshotPlugin.prototype,"_downloadJpeg",1),VO([ag("Download .webp")],e.CanvasSnapshotPlugin.prototype,"_downloadWebp",1),e.CanvasSnapshotPlugin=VO([pg("Image Export (Canvas Snapshot)")],e.CanvasSnapshotPlugin);const HO=class extends e.CanvasSnapshotPlugin{constructor(){super(),console.warn("CanvasSnipperPlugin is deprecated, use CanvasSnapshotPlugin")}};HO.PluginType="CanvasSnipper";let WO=HO;const qO=class extends Jb{constructor(){super(),this.enabled=!0,this.toJSON=void 0,this.defaultActions={exportFile:async(e,t,i)=>{zp(e,t)}},this.actions={...this.defaultActions},this._updateProcessState=this._updateProcessState.bind(this)}async exportFile(e,t){t=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)}};qO.PluginType="FileTransferPlugin";let XO=qO;var YO=Object.defineProperty,KO=Object.getOwnPropertyDescriptor,JO=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?KO(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&&YO(t,i,s),s};e.VignettePlugin=class extends YD{constructor(e=!0){super(),this.extraUniforms={power:{value:1},bgcolor:{value:new Qn}},this.power=.5,this.color=new Qn(0),this.priority=-50,this.parsFragmentSnippet=()=>this.isDisabled()?"":Np`
            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",JO([cm(e.VignettePlugin.prototype.setDirty),dg("Enable"),pm()],e.VignettePlugin.prototype,"enabled",2),JO([ng("Power",[.1,4],.01),DA({propKey:"power"}),pm()],e.VignettePlugin.prototype,"power",2),JO([cg("Color",(e=>({onChange:()=>e?.setDirty()}))),DA({propKey:"bgcolor"}),pm("bgcolor")],e.VignettePlugin.prototype,"color",2),e.VignettePlugin=JO([pg("Vignette")],e.VignettePlugin);var ZO=Object.defineProperty,$O=Object.getOwnPropertyDescriptor,eU=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?$O(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&&ZO(t,i,s),s};e.ChromaticAberrationPlugin=class extends YD{constructor(e=!0){super(),this.extraUniforms={aberrationIntensity:{value:1}},this.intensity=.5,this.priority=-50,this.parsFragmentSnippet=()=>this.isDisabled()?"":Np`
            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",eU([cm(e.ChromaticAberrationPlugin.prototype.setDirty),dg("Enable"),pm()],e.ChromaticAberrationPlugin.prototype,"enabled",2),eU([ng("Intensity",[0,.3],.001),DA({propKey:"aberrationIntensity"}),pm("aberrationIntensity")],e.ChromaticAberrationPlugin.prototype,"intensity",2),e.ChromaticAberrationPlugin=eU([pg("ChromaticAberration")],e.ChromaticAberrationPlugin);var tU=Object.defineProperty,iU=Object.getOwnPropertyDescriptor,nU=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?iU(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&&tU(t,i,s),s};e.FilmicGrainPlugin=class extends YD{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()?"":Np`
            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",nU([cm(e.FilmicGrainPlugin.prototype.setDirty),dg("Enable"),pm()],e.FilmicGrainPlugin.prototype,"enabled",2),nU([ng("Intensity",[0,20],.01),DA({propKey:"grainIntensity"}),pm("grainIntensity")],e.FilmicGrainPlugin.prototype,"intensity",2),nU([dg("Multiply"),DA({propKey:"grainMultiply"}),pm("grainMultiply")],e.FilmicGrainPlugin.prototype,"multiply",2),e.FilmicGrainPlugin=nU([pg("FilmicGrain")],e.FilmicGrainPlugin);var rU=Object.defineProperty,sU=Object.getOwnPropertyDescriptor,aU=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?sU(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};const oU=(o=class extends Jb{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 _p,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:[...Zm(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=QA();this._lastAnimId=s;for(const e of t)e.setLoop(this.loopAnimations?Je:Ke,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=vp()/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*=Tm(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=vp()/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;let n=this._animations.find((t=>t.object===e));n=n||{object:e,mixer:new Nu(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:QA(),active:!0,name:t.name,startTime:0,timeScale:1},r.setLoop(this.loopAnimations?Je:Ke,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);aU([hm(oU.prototype._onPropertyChange),dg("Loop"),pm()],oU.prototype,"loopAnimations",2),aU([hm(oU.prototype._onPropertyChange),pm()],oU.prototype,"loopRepetitions",2),aU([ng("Timescale",[-2,2],.01),pm()],oU.prototype,"timeScale",2),aU([ng("Speed",[.1,4],.1),pm()],oU.prototype,"animationSpeed",2),aU([dg(),pm()],oU.prototype,"animateOnScroll",2),aU([ng("Scroll Damping",[0,1]),pm()],oU.prototype,"scrollAnimationDamping",2),aU([dg(),pm()],oU.prototype,"animateOnPageScroll",2),aU([ng("Page Scroll Damping",[0,1]),pm()],oU.prototype,"pageScrollAnimationDamping",2),aU([dg(),pm()],oU.prototype,"animateOnDrag",2),aU([sg("Drag Axis",[{label:"x"},{label:"y"}]),pm()],oU.prototype,"dragAxis",2),aU([ng("Drag Damping",[0,1]),pm()],oU.prototype,"dragAnimationDamping",2),aU([dg(),pm()],oU.prototype,"autoplayOnLoad",2),aU([dg("syncMaxDuration(dev)"),pm()],oU.prototype,"syncMaxDuration",2),aU([ig()],oU.prototype,"animationState",1),aU([ig()],oU.prototype,"animationTime",1),aU([ig()],oU.prototype,"animationDuration",1),aU([ag("Play/Pause",(e=>({label:()=>"playing"===e.animationState?"Pause":"Play"})))],oU.prototype,"playPauseAnimation",1),aU([cm(oU.prototype.onStateChange)],oU.prototype,"_animationState",2),aU([dg()],oU.prototype,"autoUnpauseActions",2),aU([dg()],oU.prototype,"autoEnableActions",2),aU([ag("Stop",{sendArgs:!1})],oU.prototype,"stopAnimation",1),aU([ag("Reset",{sendArgs:!1})],oU.prototype,"resetAnimation",1);let lU=oU;const cU=class e extends Jb{constructor(){super(),this.toJSON=void 0,this.enabled=!0,this.dependencies=[ID],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(ID);n||this._viewer?.console.error("PopmotionPlugin required for animation");const r=this.getSavedTransform(t,e);if(!r)return;const s=new wi,a=new xi,o=new wi,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?.()}})}};cU.PluginType="TransformAnimationPlugin";let hU=cU;var dU=Object.defineProperty;const uU=(l=class extends Jb{constructor(){super(),this.enabled=!0,this.dependencies=[ID],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(ID);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=mU(t,e.key);if(!i)return;this._refreshTriggerBtn(i,e.btn)}},this.uiConfig={label:"Viewer Animations",type:"folder",children:[Zm(this.animation).filter((e=>{const t=Yp(e?.label)??"";return["Animate","Stop","Animate Reverse"].includes(t)}))??[],()=>Zm(this.animation.animSet).map((e=>Yp(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}),Ep("\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=Yp(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=Sp({innerHTML:"◆",classList:["anim-object-uic-trigger"],addToBody:!1});l.parentElement&&l.remove(),l.dataset.isAnimObjectTrigger="1",l.title="Add Animation for "+Yp(i.label,a),l.addEventListener("click",(()=>{const n=this._viewer?.getPlugin("UndoManagerPlugin");let r=mU(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+" "+(Yp(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=mU(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=mU(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&&dU(t,i,r)})([pm()],uU.prototype,"animation");let pU=uU;const mU=(e,t)=>e?.userData.animationObjects?.find((e=>e.access===t));var gU=Object.defineProperty,fU=Object.getOwnPropertyDescriptor,AU=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?fU(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&&gU(t,i,s),s};e.ClearcoatTintPlugin=class extends Jb{constructor(){super(),this.enabled=!0,this._uniforms={ccTintColor:{value:new Qn},ccThickness:{value:0},ccIor:{value:0}},this.materialExtension={parsFragmentSnippet:(e,t)=>!this.isDisabled()&&t?.userData._clearcoatTint?.enableTint&&t.clearcoat>0?Np`
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=Cv(e.fragmentShader,"float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );","float dotNVcc = saturate( dot( geometryClearcoatNormal, -refract(geometryViewDir, geometryClearcoatNormal, 1./ccIor) ) );"),e.fragmentShader=Cv(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,ax({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(vU)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(vU.name),super.onRemove(e)}},e.ClearcoatTintPlugin.PluginType="ClearcoatTintPlugin",e.ClearcoatTintPlugin.CLEARCOAT_TINT_GLTF_EXTENSION="WEBGI_materials_clearcoat_tint",AU([dg("Enabled",(e=>({onChange:e.setDirty}))),pm()],e.ClearcoatTintPlugin.prototype,"enabled",2),e.ClearcoatTintPlugin=AU([pg("Clearcoat Tint (MatExt)")],e.ClearcoatTintPlugin);class yU{constructor(e){this.parser=e,this.name=vU.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),lv.Deserialize(r,i.userData._clearcoatTint)}}const vU={name:"WEBGI_materials_clearcoat_tint",import:e=>new yU(e),export:e=>({writeMaterial:(t,i)=>{if(!t.isMeshStandardMaterial||!t.userData._clearcoatTint?.enableTint)return;i.extensions=i.extensions||{};const n=lv.Serialize(t.userData._clearcoatTint);i.extensions[vU.name]=n,e.extensionsUsed[vU.name]=!0}}),textures:void 0};var _U=Object.defineProperty,bU=Object.getOwnPropertyDescriptor,xU=(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&&_U(t,i,s),s};e.NoiseBumpMaterialPlugin=class extends Jb{constructor(){super(),this.enabled=!0,this._uniforms={noiseBumpParams:{value:new Ht},noiseBumpScale:{value:.05},noiseBumpFlakeScale:{value:1e3},noiseFlakeClamp:{value:1},noiseFlakeRadius:{value:.5},flakeParams:{value:new Ai(0,1,3,0)},flakeFallOffParams:{value:new wi(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=Cv(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,ax({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 Ht(.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 Ai(0,1,3,0)),void 0===n.flakeFallOffParams&&(n.flakeFallOffParams=new wi(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(CU)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(CU.name),super.onRemove(e)}},e.NoiseBumpMaterialPlugin.PluginType="NoiseBumpMaterialPlugin",e.NoiseBumpMaterialPlugin.NOISE_BUMP_MATERIAL_GLTF_EXTENSION="WEBGI_materials_noise_bump",xU([dg("Enabled",(e=>({onChange:e.setDirty}))),pm()],e.NoiseBumpMaterialPlugin.prototype,"enabled",2),e.NoiseBumpMaterialPlugin=xU([pg("Noise/Sparkle Bump (MatExt)")],e.NoiseBumpMaterialPlugin);class wU{constructor(e){this.parser=e,this.name=CU.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),lv.Deserialize(r,i.userData._noiseBumpMat)}}const CU={name:"WEBGI_materials_noise_bump",import:e=>new wU(e),export:e=>({writeMaterial:(t,i)=>{if(!t.isMeshStandardMaterial||!t.userData._noiseBumpMat?.hasBump)return;i.extensions=i.extensions||{};const n=lv.Serialize(t.userData._noiseBumpMat);i.extensions[CU.name]=n,e.extensionsUsed[CU.name]=!0}}),textures:void 0};var SU=Object.defineProperty,MU=Object.getOwnPropertyDescriptor,EU=(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&&SU(t,i,s),s};e.CustomBumpMapPlugin=class extends Jb{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 Wt},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=Cv(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=Cv(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=Cv(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)),ax({...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()}},px(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(IU)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(IU.name),super.onRemove(e)}},e.CustomBumpMapPlugin.PluginType="CustomBumpMapPlugin",e.CustomBumpMapPlugin.CUSTOM_BUMP_MAP_GLTF_EXTENSION="WEBGI_materials_custom_bump_map",EU([dg("Enabled",(e=>({onChange:e.setDirty}))),pm()],e.CustomBumpMapPlugin.prototype,"enabled",2),EU([dg("Bicubic",(e=>({onChange:e.setDirty}))),RA("CUSTOM_BUMP_MAP_BICUBIC",void 0,!0,e.CustomBumpMapPlugin.prototype.setDirty),pm()],e.CustomBumpMapPlugin.prototype,"bicubicFiltering",2),e.CustomBumpMapPlugin=EU([pg("Custom BumpMap (MatExt)")],e.CustomBumpMapPlugin);class TU{constructor(e,t){this._viewer=t,this.parser=e,this.name=IU.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=lv.Deserialize(o,null,s,!1):o&&void 0!==o.index?a.push(i.assignTexture(t.userData,"_customBumpMap",o).then((e=>{e.colorSpace=ht}))):(console.warn("CustomBumpMapPlugin: Invalid Texture Map in extension",o,n.name),t.userData._customBumpMap=null)),Promise.all(a)}}const IU={name:"WEBGI_materials_custom_bump_map",import:(e,t)=>new TU(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&&qm(s)&&(r.customBumpMap=lv.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[IU.name]=r,e.extensionsUsed[IU.name]=!0}}),textures:{customBumpMap:"RGB"}};var PU=Object.defineProperty,DU=Object.getOwnPropertyDescriptor,RU=(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&&PU(t,i,s),s};e.ParallaxMappingPlugin=class extends Jb{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=Cv(e.fragmentShader,`#include <${t}>`,ns[t].replace(/\bv\w+Uv\b/g,"parallaxUv.xy",{replaceAll:!0}));(this.debugNormals||this.debugHitHeight)&&(e.fragmentShader=Cv(e.fragmentShader,"texture2D( map, parallaxUv.xy )",this.debugNormals?"vec4(normal, 1.); normal = nonPerturbedNormal":"vec4(parallaxUv.z,0., 0., 1.)")),e.fragmentShader=Cv(e.fragmentShader,"#include <normal_fragment_maps>",Cv(Cv(ns.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()||ax({...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",RU([cm(e.ParallaxMappingPlugin.prototype._updateExtension),pm(),dg("Enabled")],e.ParallaxMappingPlugin.prototype,"enabled",2),RU([ng("Step count",[1,32],1),cm(e.ParallaxMappingPlugin.prototype._updateExtension),pm()],e.ParallaxMappingPlugin.prototype,"stepCount",2),RU([ng("Binary search steps",[1,8],1),cm(e.ParallaxMappingPlugin.prototype._updateExtension),pm()],e.ParallaxMappingPlugin.prototype,"binaryStepCount",2),RU([cm(e.ParallaxMappingPlugin.prototype._updateExtension),dg("Debug Normals")],e.ParallaxMappingPlugin.prototype,"debugNormals",2),RU([cm(e.ParallaxMappingPlugin.prototype._updateExtension),dg("Debug Hit Height")],e.ParallaxMappingPlugin.prototype,"debugHitHeight",2),e.ParallaxMappingPlugin=RU([pg("Parallax Bump Mapping (MatExt)")],e.ParallaxMappingPlugin);var BU=Object.defineProperty,LU=Object.getOwnPropertyDescriptor,OU=(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&&BU(t,i,s),s};e.FragmentClippingExtensionPlugin=class extends Jb{constructor(){super(),this.enabled=!0,this._defines={FRAG_CLIPPING_DEBUG:0},this._uniforms={fragClippingPosition:{value:new Ai},fragClippingParams:{value:new Ai},fragClippingCamAspect:{value:1}},this._plane=new Kr,this._viewNormalMatrix=new Wt,this._v4=new Ai,this.materialExtension={parsFragmentSnippet:(e,t)=>this.enabled&&t?.userData._fragmentClippingExt?.clipEnabled?Object.entries(UU).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=Cv(e.fragmentShader,"#glMarker mainStart",Object.entries(UU).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,ax({...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(UU).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(NU)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(NU.name),super.onRemove(e)}},e.FragmentClippingExtensionPlugin.PluginType="FragmentClippingExtensionPlugin1",e.FragmentClippingExtensionPlugin.FRAGMENT_CLIPPING_EXTENSION_GLTF_EXTENSION="WEBGI_materials_fragment_clipping_extension",OU([dg("Enabled",(e=>({onChange:e.setDirty}))),pm()],e.FragmentClippingExtensionPlugin.prototype,"enabled",2),e.FragmentClippingExtensionPlugin=OU([pg("Fragment Clipping (MatExt)")],e.FragmentClippingExtensionPlugin);var UU=(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))(UU||{});class FU{constructor(e){this.parser=e,this.name=NU.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),lv.Deserialize(r,i.userData._fragmentClippingExt)}}const NU={name:"WEBGI_materials_fragment_clipping",import:e=>new FU(e),export:e=>({writeMaterial:(t,i)=>{if(!t.isMeshStandardMaterial||!t.userData._fragmentClippingExt?.clipEnabled)return;i.extensions=i.extensions||{};const n=lv.Serialize(t.userData._fragmentClippingExt);i.extensions[NU.name]=n,e.extensionsUsed[NU.name]=!0}}),textures:void 0};var kU=Object.defineProperty,jU=Object.getOwnPropertyDescriptor,zU=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?jU(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&&kU(t,i,s),s};e.VirtualCamerasPlugin=class extends Jb{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",zU([dg()],e.VirtualCamerasPlugin.prototype,"enabled",2),e.VirtualCamerasPlugin=zU([pg("Virtual Cameras")],e.VirtualCamerasPlugin);var GU=Object.defineProperty,QU=(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&&GU(t,i,s),s};const VU={cascades:3,shadowMapSize:2048,shadowBias:void 0,lightNear:void 0,lightFar:void 0,lightMargin:200},HU=(c=class extends Jb{constructor(e=!0){super(),this.enabled=!0,this.parent=new Lo,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.refreshLights=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={...VU,...t};for(let e=0;e<i.cascades;e++){if(!this.lights[e]){const t=new Xd(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.light=t,void(this._lightAutoAttached=!0)}},this._sversion=0,this._updateFrustums=()=>{if(!this.light)return;const{cascades:e=VU.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 Ht(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)=>{t.extraUniformsToUpload.CSM_cascades&&(t.extraUniformsToUpload.CSM_cascades.needsUpdate=!1),t.extraUniformsToUpload.cameraNear&&(t.extraUniformsToUpload.cameraNear.needsUpdate=!1),t.extraUniformsToUpload.shadowFar&&(t.extraUniformsToUpload.shadowFar.needsUpdate=!1),!this.isDisabled()&&this.light&&(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.__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,t.extraUniformsToUpload.cameraNear.needsUpdate=!0,t.extraUniformsToUpload.shadowFar.needsUpdate=!0,t.extraUniformsToUpload.CSM_cascades.needsUpdate=!0))},isCompatible:e=>e.isMeshStandardMaterial||e.isMeshPhysicalMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial},this.uiConfig={type:"folder",label:"Cascaded Shadows (CSM)",children:[...Zm(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 wi,this._cameraToLightMatrix=new $i,this._lightSpaceFrustum=new qU,this._center=new wi,this._bbox=new Mi,this._uniformArray=[],this._logArray=[],this._lightOrientationMatrix=new $i,this._lightOrientationMatrixInverse=new $i,this._up=new wi(0,1,0),this.injectInclude(),this._lastEnabled=e,this.enabled=e,this.mainFrustum=new qU}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(Vt.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=VU.shadowMapSize,lightMargin:n=VU.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(){ns.lights_fragment_begin.includes("defined( USE_CSM ) && defined( CSM_CASCADES )")||(ns.lights_fragment_begin=Cv(ns.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.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.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.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.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"),ns.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"+ns.lights_pars_begin)}},c.PluginType="CascadedShadowsPlugin",c);QU([dg(),pm(),cm("setDirty")],HU.prototype,"enabled"),QU([cm("cameraNeedsUpdate"),pm(),og()],HU.prototype,"maxFar"),QU([cm("cameraNeedsUpdate"),pm(),sg(void 0,["uniform","logarithmic","practical"])],HU.prototype,"mode"),QU([dg(),pm()],HU.prototype,"attachToFirstLight"),QU([cm("cameraNeedsUpdate"),pm(),dg()],HU.prototype,"fade"),QU([cm("refreshLights")],HU.prototype,"light"),QU([cm("cameraNeedsUpdate")],HU.prototype,"customSplitsCallback"),QU([ag()],HU.prototype,"refreshAttachedLight");let WU=HU;class qU{constructor(e={}){this._inverseProjectionMatrix=new $i,this.vertices={near:[new wi,new wi,new wi,new wi],far:[new wi,new wi,new wi,new wi]},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 qU);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 XU=Object.defineProperty,YU=(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&&XU(t,i,s),s};const KU=(h=class extends Jb{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(XL,(e=>{this._picking=e,this._picking?.addEventListener("selectedObjectChanged",this._refreshUiConfig)}),(()=>{this._picking?.removeEventListener("selectedObjectChanged",this._refreshUiConfig),this._picking=void 0}),this),this._previewGenerator=new py,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(ID);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?ym(e.image,100):"",r.length||(r=xm(e.isColor?e.getHexString():e))}return i&&this._viewer.setDirty(),r}refreshUi(){this.isDisabled()||!this._viewer||Yp(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(hw.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?Op(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);YU([pm()],KU.prototype,"applyOnLoad"),YU([pm()],KU.prototype,"variations");let JU=KU;var ZU=Object.defineProperty,$U=(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&&ZU(t,i,s),s};const eF=class extends Jb{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(XL,(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 wi((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=uy(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)}}};eF.PluginType="SwitchNodePlugin";let tF=eF;function iF(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 rr(n,i):n),s}function nF(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"))}$U([pm()],tF.prototype,"refreshScene"),$U([pm()],tF.prototype,"variations");class rF{constructor(e){this.type=e,this.defaultMeshClass=()=>ww,this.defaultMaterialClass=()=>hw,this.defaultGeometryClass=()=>Tw}createUiConfig(e){if(!e.userData.generationParams)return[];const t=Zm(e.userData.generationParams)?.flatMap((e=>Yp(e))).filter((e=>"type"!==Yp(e.property)?.[1]))||[];return t.forEach((t=>{t.onChange=()=>this.generate(e)})),t}generate(e,t={}){const i=e??new Tw;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&&iF(i,"position",3,s),a&&iF(i,"normal",3,a),o&&iF(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),nF(i,(()=>this.createUiConfig(i))),i.setDirty(),i}setDefaultParams(e){return Object.assign(this.defaultParams,e),this}}class sF extends rF{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 wi,d=new wi,u=new wi;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 aF extends rF{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 wi,h=new Ht;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 oF extends rF{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 wi;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 lF extends rF{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 wi,u=new wi,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 cF extends rF{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 hF extends rF{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 wi,A=new wi;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 Ht,f=new wi;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 dF={};function uF(e,t,i=dF){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 wi:new Ht,t=o.type.endsWith("3")?new wi(1,1,1):new Ht(1,1);o.points.push(e,t)}if(Array.isArray(o.curves)&&0===o.curves.length){const e=o.type.endsWith("3")?new kc(new wi(0,0,0),new wi(1,1,0)):new Nc(new Ht(0,0),new Ht(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 pF(e,t=dF){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]}dF.LineCurve={ctor:Nc,vals:{start:"v1",end:"v2"},getUiConfig:e=>[Jm(e,"v1","Start Point"),Jm(e,"v2","End Point")]},dF.CubicBezierCurve={ctor:Uc,vals:{start:"v0",end:"v3",control1:"v1",control2:"v2"},getUiConfig:e=>[Jm(e,"v0","Start Point"),Jm(e,"v1","Control Point 1"),Jm(e,"v2","Control Point 2"),Jm(e,"v3","End Point")]},dF.QuadraticBezierCurve={ctor:jc,vals:{start:"v0",end:"v2",control1:"v1"},getUiConfig:e=>[Jm(e,"v0","Start Point"),Jm(e,"v1","Control Point"),Jm(e,"v2","End Point")]},dF.EllipseCurve={ctor:Sc,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise",rotation:"aRotation"},getUiConfig:e=>[Jm(e,"aX","X Center"),Jm(e,"aY","Y Center"),Jm(e,"xRadius","X Radius"),Jm(e,"yRadius","Y Radius"),Jm(e,"aStartAngle","Start Angle"),Jm(e,"aEndAngle","End Angle"),Jm(e,"aClockwise","Clockwise"),Jm(e,"aRotation","Rotation")]},dF.ArcCurve={ctor:Mc,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise"},getUiConfig:e=>{const t=Jm(e,"xRadius","Radius");if(t){const i=t.onChange;t.onChange=(...t)=>{e.yRadius=e.xRadius,i?.(...t)}}return[Jm(e,"aX","X Center"),Jm(e,"aY","Y Center"),t,Jm(e,"aStartAngle","Start Angle"),Jm(e,"aEndAngle","End Angle"),Jm(e,"aClockwise","Clockwise")]}},dF.SplineCurve={ctor:Gc,vals:{points:"points"},getUiConfig:e=>[()=>e.points.map(((t,i)=>Jm(e.points,i.toString(),`Point ${i}`))),{type:"button",label:"Add Point",value:()=>{const t=e.points,i=t[t.length-1]||new Ht(0,0),n=t[t.length-2]||new Ht(1,1);t.push(i.clone().add(i.clone().sub(n))),e.points=t,e.updateArcLengths(),e.uiConfig?.uiRefresh?.(!0,"postFrame")}}]},dF.LineCurve3={...dF.LineCurve,ctor:kc},dF.CubicBezierCurve3={...dF.CubicBezierCurve,ctor:Fc},dF.QuadraticBezierCurve3={...dF.QuadraticBezierCurve,ctor:zc},dF.CatmullRomCurve3={ctor:Rc,vals:{points:"points",closed:"closed",curveType:"curveType",tension:"tension"},getUiConfig:e=>[()=>e.points.map(((t,i)=>Jm(e.points,i.toString(),`Point ${i}`))),{type:"button",label:"Add Point",value:()=>{const t=e.points,i=t[t.length-1]||new wi(0,0,0),n=t[t.length-2]||new wi(1,1,0);t.push(i.clone().add(i.clone().sub(n))),e.points=t,e.updateArcLengths(),e.uiConfig?.uiRefresh?.(!0,"postFrame")}},Jm(e,"closed","Closed Loop"),{type:"dropdown",property:[e,"curveType"],label:"Curve Type",children:["centripetal","chordal","catmullrom"].map((e=>({label:e,value:e})))},Jm(e,"tension","Tension")]},dF.EllipseCurve3D={ctor:Ow,vals:{centerX:"aX",centerY:"aY",radiusX:"xRadius",radiusY:"yRadius",startAngle:"aStartAngle",endAngle:"aEndAngle",clockwise:"aClockwise",rotation:"aRotation"},getUiConfig:dF.EllipseCurve.getUiConfig},dF.CurvePath={ctor:Vc,vals:{},getUiConfig:e=>[()=>e.curves.map(((t,i)=>{if(t.uiConfig)return t.uiConfig;const n=t.type,r=dF[n];if(r){const s=r.getUiConfig(t)||[],a={type:"folder",label:n.replace(/([A-Z])/g," $1").trim(),children:[uF(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 kc(new wi(0,0,0),new wi(1,1,0)):new Nc(new Ht(0,0),new Ht(1,1));return e.add(t),e.updateArcLengths(),e.uiConfig?.uiRefresh?.(!0,"postFrame"),!0}}]},dF.CurvePath3={...dF.CurvePath,ctor:rv};class mF extends rF{constructor(e="tube",t){super(e),this.defaultParams={path:new Ow(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 Qh(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[uF(t.path,(i=>{t.path=i,e.userData.__generationParamsUiType="",this.generate(e)})),...pF(t.path),...i]}}function gF(e,t){const i=new rh;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 fF(e){const t=e.getPoints();return t.reverse(),new rh(t)}class AF extends rF{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=gF(e.shapeType,e),i=new Nh(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 yF extends rF{constructor(e="tubeShape",t){super(e),this.defaultParams={path:new Ow(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=fF("custom"===e.shapeType&&e.shape?e.shape:gF(e.shapeType,e)),i=new Bw(t,e.path,e.shapeSegments,e.tubularSegments,e.closed,new Ht(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[uF(t.path,(i=>{t.path=i,e.userData.__generationParamsUiType="",this.generate(e)})),...pF(t.path),...i]}}const vF=class e extends rF{constructor(t="line",i){super(t),this.defaultParams={curve:new kc(new wi(0,0,0),new wi(1,1,0)),segments:50,closePath:!1},this.defaultMeshClass=()=>e.UseMeshLines?Mw:oc,this.defaultMaterialClass=()=>e.UseMeshLines?yw:mw,this.defaultGeometryClass=()=>e.UseMeshLines?Iw:Tw,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=pF(n);if(e.length>0){const n=t.indexOf(i);t.splice(n,1,...e)}}return[uF(n,(t=>{e.userData.generationParams.curve=t,e.userData.__generationParamsUiType="",this.generate(e)})),...t]}};vF.UseMeshLines=!0;let _F=vF;const bF=class extends Jb{constructor(){super(...arguments),this.enabled=!0,this.toJSON=void 0,this.generators={plane:new cF("plane"),sphere:new lF("sphere"),box:new oF("box"),circle:new aF("circle"),torus:new sF("torus"),cylinder:new hF("cylinder"),tube:new mF("tube"),shape:new AF("shape"),tubeShape:new yF("tubeShape"),line:new _F("line")},this.defaultMeshClass=ww,this.defaultMaterialClass=hw,this.defaultGeometryClass=Tw,this._objectAdd=e=>{const t=e.object,i=t?.geometry?.userData?.generationParams?.type;i&&nF(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 "+Bp(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)}};bF.PluginType="GeometryGeneratorPlugin";let xF=bF;var wF=Object.defineProperty,CF=Object.getOwnPropertyDescriptor,SF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?CF(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.ShapeTubeExtrudePlugin=class extends Jb{constructor(){super(...arguments),this.dependencies=[XL,xF],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(XL)?.getSelectedObject();if(!e||!e.geometry)return;const t=new Ow(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(xF);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(xF);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 wi),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 Ht;"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 rh(s);return e.userData.__planarShape=a,a}},e.ShapeTubeExtrudePlugin.PluginType="ShapeTubeExtrudePlugin",SF([ng("Shape Segments",[1,100],1)],e.ShapeTubeExtrudePlugin.prototype,"shapeSegments",2),SF([ng("Tube Segments",[1,100],1)],e.ShapeTubeExtrudePlugin.prototype,"tubularSegments",2),SF([ng("Shape Scale X",[.01,10],.01)],e.ShapeTubeExtrudePlugin.prototype,"shapeScaleX",2),SF([ng("Shape Scale Y",[.01,10],.01)],e.ShapeTubeExtrudePlugin.prototype,"shapeScaleY",2),SF([og("Material Splits")],e.ShapeTubeExtrudePlugin.prototype,"materialSplits",2),SF([dg("Horizontal Splits")],e.ShapeTubeExtrudePlugin.prototype,"horizontalSplits",2),SF([ag("Extrude Circle Tube")],e.ShapeTubeExtrudePlugin.prototype,"extrudeCircleTube",2),e.ShapeTubeExtrudePlugin=SF([pg("Extrude Tube Shapes")],e.ShapeTubeExtrudePlugin);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.HDRiGroundPlugin=class extends Jb{constructor(e=!1,t=!0){super(),this.enabled=!1,this.worldRadius=100,this.tripodHeight=10,this.originPosition=new wi(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??ss.backgroundCube.uniforms;i.tripodHeight||(i.tripodHeight={value:1}),i.worldRadius||(i.worldRadius={value:1}),i.originPosition||(i.originPosition={value:new wi}),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"),!ss.backgroundCube.fragmentShader.includes("#ifdef HDRi_GROUND_PROJ")){const t="void main() {",i=ss.backgroundCube.fragmentShader.split(t);2!==i.length?e.console.error("HDRi Ground Plugin: Could not parse backgroundCube shader"):ss.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${Cv(i[1],"vWorldDirection","worldDirection",{replaceAll:!0})}\n`}e.scene.addEventListener("environmentChanged",this.setDirty)}},e.HDRiGroundPlugin.PluginType="HDRiGroundPlugin",TF([pm(),cm(e.HDRiGroundPlugin.prototype.setDirty),dg("Enabled")],e.HDRiGroundPlugin.prototype,"enabled",2),TF([pm(),cm(e.HDRiGroundPlugin.prototype.setDirty),ng("World Radius",[1,1e3],.01)],e.HDRiGroundPlugin.prototype,"worldRadius",2),TF([pm(),cm(e.HDRiGroundPlugin.prototype.setDirty),ng("Tripod height",[0,50],.01)],e.HDRiGroundPlugin.prototype,"tripodHeight",2),TF([pm(),cm(e.HDRiGroundPlugin.prototype.setDirty),rg("Origin Position",void 0,.001,(e=>({onChange:e.setDirty})))],e.HDRiGroundPlugin.prototype,"originPosition",2),TF([pm(),cm(e.HDRiGroundPlugin.prototype.setDirty)],e.HDRiGroundPlugin.prototype,"promptOnBackgroundMismatch",2),e.HDRiGroundPlugin=TF([pg("HDRi Ground")],e.HDRiGroundPlugin);var IF=Object.defineProperty;const PF=(d=class extends Jb{constructor(e=!0,t=!1){super(),this.enabled=!0,this.helpers=[xL,jL,DL,AL,ML,OL],this.toJSON=null,this.inSceneRoot=!1,this._widgetRoot=new xw,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&&IF(t,i,r)})([cm(PF.prototype.setDirty)],PF.prototype,"enabled");let DF=PF;var RF=Object.defineProperty,BF=Object.getOwnPropertyDescriptor,LF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?BF(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&&RF(t,i,s),s};e.Object3DGeneratorPlugin=class extends Jb{constructor(){super(),this.enabled=!0,this.toJSON=void 0,this._selectedType="",this.generators={"object-empty":(e={})=>{const t=new bw;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 xw;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 ew(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 aw(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 Qw(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 wi(0,0,0)),t.name="Directional Light",t},"light-ambient":(e={})=>{const t=new kw(e.color??16777215,e.intensity??1);return t.name="Ambient Light",t},"light-point":(e={})=>{const t=new Kw(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 nC(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 wi(0,0,0)),t.name="Spot Light",t},"light-hemisphere":(e={})=>{const t=new Ww(e.color??11184895,5592131,e.intensity??1);return t.name="Hemisphere Light",t},"light-rect-area":(e={})=>{const t=new $w(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 wi(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",LF([sg("Type",void 0,(e=>({children:[()=>Object.keys(e.generators).map((e=>({label:e})))]})))],e.Object3DGeneratorPlugin.prototype,"_selectedType",2),LF([ag("Generate",{sendArgs:!1})],e.Object3DGeneratorPlugin.prototype,"generate",1),e.Object3DGeneratorPlugin=LF([ug("Generate Scene Objects")],e.Object3DGeneratorPlugin);var OF=Object.defineProperty,UF=Object.getOwnPropertyDescriptor,FF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?UF(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&&OF(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 fs(-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:Be,colorSpace:ct,size:{width:512,height:512},generateMipmaps:!1,depthBuffer:!0,minFilter:be,magFilter:be});i.texture.name="groundContactDepthTexture";const n=new Eo({depthPacking:st,transparent:!1,blending:w});n.opacity=-1,n.onBeforeCompile=e=>{e.fragmentShader=Cv(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 Qn(1,1,1),1),this._blurHelper=new dy(t),super.onAdded(t)}onRemove(e){const t=Yp(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=Yp(this._depthPass.target);if(!e)return;const t=this._viewer.renderManager.getTempTarget({type:Ce,format:Be,colorSpace:ct,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 wi)),this.shadowCamera.setRotationFromEuler(new hn(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=Yp(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 Qn(1,1,1):new Qn(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",FF([dg("Contact Shadows"),cm(e.ContactShadowGroundPlugin.prototype.refresh),pm()],e.ContactShadowGroundPlugin.prototype,"contactShadows",2),FF([ng("Shadow Scale",[0,2]),pm(),cm(e.ContactShadowGroundPlugin.prototype._refreshShadowCameraFrustum)],e.ContactShadowGroundPlugin.prototype,"shadowScale",2),FF([ng("Shadow Height",[0,20]),pm(),cm(e.ContactShadowGroundPlugin.prototype._refreshShadowCameraFrustum)],e.ContactShadowGroundPlugin.prototype,"shadowHeight",2),FF([ng("Blur Amount",[0,10]),pm(),cm(e.ContactShadowGroundPlugin.prototype._setDirty)],e.ContactShadowGroundPlugin.prototype,"blurAmount",2),FF([cm(e.ContactShadowGroundPlugin.prototype._refreshMaterial),sg("Map Mode",["aoMap","map","alphaMap"]),pm()],e.ContactShadowGroundPlugin.prototype,"mapMode",2),e.ContactShadowGroundPlugin=FF([ug("Ground Plane (Contact Shadows)")],e.ContactShadowGroundPlugin);var NF=Object.defineProperty,kF=Object.getOwnPropertyDescriptor,jF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?kF(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&&NF(t,i,s),s};const zF=class extends Jb{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(XL)}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 wi);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 wi),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)}};zF.PluginType="SimplifyModifierPlugin";let GF=zF;jF([ng("Simplify Factor",[0,1])],GF.prototype,"simplifyFactor",2),jF([ag("Simplify All",{sendArgs:!1})],GF.prototype,"simplifyAll",1),jF([ag("Simplify Selected")],GF.prototype,"simplifySelected",1);var QF=Object.defineProperty,VF=Object.getOwnPropertyDescriptor,HF=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?VF(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&&QF(t,i,s),s};e.MeshOptSimplifyModifierPlugin=class extends GF{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():GA(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 tr(new Uint32Array(a),1)),nx.upgradeGeometry.call(e.toNonIndexed())}},e.MeshOptSimplifyModifierPlugin.PluginType="MeshOptSimplifyModifierPlugin",e.MeshOptSimplifyModifierPlugin.SIMPLIFIER_URL="https://unpkg.com/meshoptimizer@0.20.0/meshopt_simplifier.module.js",HF([lg()],e.MeshOptSimplifyModifierPlugin.prototype,"errorThreshold",2),HF([dg()],e.MeshOptSimplifyModifierPlugin.prototype,"lockBorder",2),e.MeshOptSimplifyModifierPlugin=HF([pg("Simplify Modifier (meshopt)")],e.MeshOptSimplifyModifierPlugin);const WF=(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},qF="KHR_materials_variants";class XF{constructor(e){this.parser=e,this.name=qF}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=WF(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[qF]={names:n},Promise.all(i)})))}}const YF=e=>void 0!==e.material&&e.userData&&e.userData._variantMaterials&&!!Object.values(e.userData._variantMaterials).filter((e=>KF(e?.material))),KF=e=>e&&e.isMaterial&&!Array.isArray(e);class JF{constructor(e){this.writer=e,this.name=qF,this.variantNames=[]}beforeParse(e){const t=new Set;for(const i of e)i.traverse((e=>{if(!YF(e))return;const i=e.userData._variantMaterials;for(const e in i){const n=i[e];KF(n.material)&&t.add(e)}}));t.forEach((e=>this.variantNames.push(e)))}writeMesh(e,t){if(!YF(e))return;const i=e.userData,n=i._variantMaterials,r={};for(const e in n){const t=n[e].material;if(!KF(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=KF(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 ZF=Object.defineProperty,$F=(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&&ZF(t,i,s),s};const eN=(u=class extends Jb{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?.[qF];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[qF]})),!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(iN)}onRemove(e){return e.scene.removeEventListener("addSceneObject",this._objectAdded),e.assetManager.unregisterGltfExtension(iN.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);$F([cm(eN.prototype._variantChanged),pm()],eN.prototype,"selectedVariant"),$F([pm()],eN.prototype,"applyFirstVariantOnLoad");let tN=eN;const iN={name:qF,import:e=>new XF(e),export:function(e){return new JF(e)}};var nN=Object.getOwnPropertyDescriptor;e.TailwindCSSCDNPlugin=class extends Jb{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?nN(t,i):t,a=e.length-1;a>=0;a--)(r=e[a])&&(s=r(s)||s);return s})([pg("Tailwind CSS")],e.TailwindCSSCDNPlugin);const rN=class extends Jb{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 Kb))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)}};rN.PluginType="DynamicImportPlugin";let sN=rN;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`}}},oN={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 wi);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 hn).copy(e.rotation);a||(a=o.order),o.order=a;const l=new xi;t.getWorldQuaternion(l);const c=(new hn).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 wi;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 $i;t.updateMatrixWorld(),r.copy(t.matrixWorld);const s=(new wi).copy(e.position),a=(new xi).copy(e.quaternion),o=(new wi).copy(e.scale),l=new wi,c=new xi,h=new wi;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 wi(d+(m-d)*l,u+(g-u)*l,p+(f-p)*l),y=new wi(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 wi).copy(e.position),p=(new xi).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 wi).clone().sub(e.position).normalize(),a=new wi(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 wi).crossVectors(a,s).normalize();a.crossVectors(s,o).normalize();const l=new $i;l.makeBasis(o,a,s);const c=(new xi).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 lN=Object.defineProperty,cN=Object.getOwnPropertyDescriptor,hN=(e,t,i,n)=>{for(var r,s=n>1?void 0:n?cN(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&&lN(t,i,s),s};e.ObjectConstraintsPlugin=class extends Jb{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),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||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=>Yp(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=oN,hN([dg(),pm()],e.ObjectConstraintsPlugin.prototype,"enabled",2),e.ObjectConstraintsPlugin=hN([pg("Object Constraints")],e.ObjectConstraintsPlugin),e.ObjectConstraint=class{constructor(t){this.uuid=QA(),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=oN[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:[...Zm(this),()=>{if(this._propsUi.length)return this._propsUi.forEach((e=>e.uiRefresh?.(!0))),this._propsUi;const e=Zm(this.props).map((e=>Yp(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=oN[this.type]?.defaultProps||{},this.props||(this.props={})}update(e){const t=oN[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=oN[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)}},hN([pm(),dg()],e.ObjectConstraint.prototype,"enabled",2),hN([pm(),cm("typeChanged"),sg(void 0,Object.keys(oN).map((e=>({label:e}))))],e.ObjectConstraint.prototype,"type",2),hN([pm(),cm("refresh2"),og()],e.ObjectConstraint.prototype,"target",2),hN([pm(),ng(void 0,[0,1],.01)],e.ObjectConstraint.prototype,"influence",2),hN([pm()],e.ObjectConstraint.prototype,"props",2),e.ObjectConstraint=hN([mm("ObjectConstraint")],e.ObjectConstraint);const dN=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&&am.SerializableClasses.has(e.type))return e.type;if(e.serializableClassId&&am.SerializableClasses.has(e.serializableClassId))return e.serializableClassId;const t=am.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}};dN.Classes=new Map;let uN=dN;class pN{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=gN.Get(this);t&&(t.__rootPath?e.typed[this.id]={external:!0,rootPath:t.__rootPath,rootPathOptions:t.__rootPathOptions}:e.typed[this.id]=lv.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:lv.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 mN=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 pN(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}}};lv.MakeSerializable(pN,"ItemRef"),mN.Objects=new Map;let gN=mN;function fN(e){const t=new Set;let i=e;for(;i&&i!==CN&&i!==Function.prototype;)i.ComponentType&&t.add(i.ComponentType),i=Object.getPrototypeOf(i);return t}function AN(e,t){if(!e.isObject3DComponent)throw new Error("EntityComponentPlugin: invalid component instance");e.ctx=t;const i=function(e){const t=vN.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})}else i.set(t,["string"==typeof e?{key:e}:e,n,r]),r+=.001}if(n===CN)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:Zm(e)},r=n.children,s=[];i.forEach((t=>{const i=t.key;if(!tm(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=uN.GetType(n);if(!a)return void console.error("Object3DComponent: unsupported type for state property",t,n);const o=t.type??uN.NonLiteral(a);if(!uN.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:()=>_N(e,i,n),set:t=>{bN(t,e,i,o,n)},enumerable:!0,configurable:!0}),xN(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=>uN.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=Jm(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)}})),vN.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 yN=class{};yN.TypeProperties=new Map,yN.InstanceProperties=new Map;let vN=yN;function _N(e,t,i,n,r=!0){if(void 0===(n=n??e.stateRef[t]))return i;const s=gN.GetOp(n,r);return void 0!==s?s:n}function bN(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?_N(t,i,r,s):t[i];if(a===e)return;const o=uN.GetType(e);o?uN.CanAssign(o,n)?(void 0===s&&(s=t.stateRef[i]),gN.RemoveOp(s,t),xN(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 xN(e,t,i,n,r){let s;const a=uN.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=gN.Add(e,t,n)}else s=t===i?void 0:t;void 0===s?delete n.stateRef[r]:n.stateRef[r]=s}const wN=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=vN.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=gN.GetCached(a);o=void 0!==l?l:_N(e,n,r,a,!1),bN(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?PN.GetComponent(i,e):PN.GetComponentInParent(i,e)||this.ctx.ecp.getComponentOfType(e):t?null:this.ctx.ecp.getComponentOfType(e)}};wN.StateProperties=[],wN.ComponentType="Object3DComponent";let CN=wN;var SN=Object.defineProperty,MN=(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&&SN(t,i,s),s};const EN=class extends CN{constructor(){super(...arguments),this.running=!0,this.mass=1,this.damping=.98,this.velocity=new wi,this.acceleration=new wi,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 yp(32)},this.PushBackward=async()=>{for(let e=0;e<200;e++)this.addForce({z:-10}),await yp(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)}};EN.StateProperties=["running","mass","damping"],EN.ComponentType="SampleBodyComponent";let TN=EN;MN([ag()],TN.prototype,"MoveLeft"),MN([ag()],TN.prototype,"MoveRight"),MN([ag()],TN.prototype,"PushForward"),MN([ag()],TN.prototype,"PushBackward");const IN=class e extends Jb{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(CN.ComponentType,CN),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]:[...fN(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]:[...fN(i)];return n.filter((e=>{const t=fN(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]:[...fN(i)];for(const e of n){const t=fN(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 CN,r||(console.error("EntityComponentPlugin: unknown component type "+i.type,t),a._sType=i.type),n&&(a.uuid=n),AN(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");gN.Delete(e),vN.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}};IN.PluginType="EntityComponentPlugin",IN.ObjectToComponents=new Map,IN.UserDataKey=IN.PluginType,IN.AddObjectUiConfig=!0;let PN=IN;const DN=PN;e.AAssetManagerProcessStatePlugin=fB,e.ACESFilmicToneMapping=4,e.ACameraControlsPlugin=pB,e.ACameraHelperWidget=lL,e.AGeometryGenerator=rF,e.AHelperWidget=oL,e.ALightHelperWidget=cL,e.AScreenPassExtensionPlugin=YD,e.AViewerPlugin=Kb,e.AViewerPluginAsync=class extends Kb{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=Jb,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=Yd,e.AmbientLight2=kw,e.AnimationAction=Uu,e.AnimationClip=bd,e.AnimationLoader=class extends Md{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new Id(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=bd.parse(e[i]);t.push(n)}return t}},e.AnimationMixer=Nu,e.AnimationObjectGroup=class{constructor(){this.isAnimationObjectGroup=!0,this.uuid=Nt(),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 Ou(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 Ou(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 Ou(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=pU,e.AnimationUtils=ld,e.ArcCurve=Mc,e.ArrayCamera=Bo,e.ArrowHelper=class extends En{constructor(e=new wi(0,0,1),t=new wi(0,0,0),i=1,n=16776960,r=.2*i,s=.2*r){super(),this.type="ArrowHelper",void 0===gp&&(gp=new ur,gp.setAttribute("position",new rr([0,0,0,0,1,0],3)),fp=new Yc(0,.5,1,5,1),fp.translate(0,-.5,0)),this.position.copy(t),this.line=new oc(gp,new tc({color:n,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new Pr(fp,new Xn({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{mp.set(e.z,0,-e.x).normalize();const t=Math.acos(e.y);this.quaternion.setFromAxisAngle(mp,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=uD,e.AssetExporterPlugin=zO,e.AssetImporter=HC,e.AssetManager=yD,e.AsyncCompress=aI,e.AsyncDecompress=bI,e.AsyncDeflate=ZT,e.AsyncGunzip=hI,e.AsyncGzip=aI,e.AsyncInflate=iI,e.AsyncUnzipInflate=HI,e.AsyncUnzlib=AI,e.AsyncZipDeflate=jI,e.AsyncZlib=mI,e.AttachedBindMode="attached",e.Audio=vu,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=cu,e.AudioListener=class extends En{constructor(){super(),this.type="AudioListener",this.context=cu.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new pu}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(gu,fu,Au),yu.set(0,0,-1).applyQuaternion(fu),t.positionX){const e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(gu.x,e),t.positionY.linearRampToValueAtTime(gu.y,e),t.positionZ.linearRampToValueAtTime(gu.z,e),t.forwardX.linearRampToValueAtTime(yu.x,e),t.forwardY.linearRampToValueAtTime(yu.y,e),t.forwardZ.linearRampToValueAtTime(yu.z,e),t.upX.linearRampToValueAtTime(i.x,e),t.upY.linearRampToValueAtTime(i.y,e),t.upZ.linearRampToValueAtTime(i.z,e)}else t.setPosition(gu.x,gu.y,gu.z),t.setOrientation(yu.x,yu.y,yu.z,i.x,i.y,i.z)}},e.AudioLoader=class extends Md{constructor(e){super(e)}load(e,t,i,n){const r=this,s=new Id(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);cu.getContext().decodeAudioData(i,(function(e){t(e)})).catch(a)}catch(e){a(e)}}),i,n)}},e.AxesHelper=class extends hc{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 ur;i.setAttribute("position",new rr(t,3)),i.setAttribute("color",new rr([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(i,new tc({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(e,t,i){const n=new Qn,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=cB,e.BasicDepthPacking=3200,e.BasicShadowMap=0,e.BatchedMesh=ec,e.Bone=Sl,e.BoneHelper=pL,e.BooleanKeyframeTrack=md,e.Box2=Yu,e.Box3=Mi,e.Box3B=TA,e.Box3Helper=class extends hc{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 ur;n.setIndex(new tr(i,1)),n.setAttribute("position",new rr([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 tc({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=Rr,e.BoxGeometryGenerator=oF,e.BoxHelper=class extends hc{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 ur;r.setIndex(new tr(i,1)),r.setAttribute("position",new tr(n,3)),super(r,new tc({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&&pp.setFromObject(this.object),pp.isEmpty())return;const t=pp.min,i=pp.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=mL,e.BufferAttribute=tr,e.BufferGeometry=ur,e.BufferGeometry2=Tw,e.BufferGeometryLoader=iu,e.ByteType=1010,e.CSMFrustum=qU,e.Cache=wd,e.Camera=Nr,e.CameraHelper=class extends hc{constructor(e){const t=new ur,i=new tc({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 rr(n,3)),t.setAttribute("color",new rr(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 Qn(16755200),c=new Qn(16711680),h=new Qn(43775),d=new Qn(16777215),u=new Qn(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;dp.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),up("c",t,e,dp,0,0,-1),up("t",t,e,dp,0,0,1),up("n1",t,e,dp,-1,-1,-1),up("n2",t,e,dp,1,-1,-1),up("n3",t,e,dp,-1,1,-1),up("n4",t,e,dp,1,1,-1),up("f1",t,e,dp,-1,-1,1),up("f2",t,e,dp,1,-1,1),up("f3",t,e,dp,-1,1,1),up("f4",t,e,dp,1,1,1),up("u1",t,e,dp,.7,1.1,-1),up("u2",t,e,dp,-.7,1.1,-1),up("u3",t,e,dp,0,2,-1),up("cf1",t,e,dp,-1,0,1),up("cf2",t,e,dp,1,0,1),up("cf3",t,e,dp,0,-1,1),up("cf4",t,e,dp,0,1,1),up("cn1",t,e,dp,-1,0,-1),up("cn2",t,e,dp,1,0,-1),up("cn3",t,e,dp,0,-1,-1),up("cn4",t,e,dp,0,1,-1),e.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}},e.CameraHelper2=AL,e.CameraViewPlugin=FD,e.CanvasSnapshot=Rb,e.CanvasSnipperPlugin=WO,e.CanvasTexture=wc,e.CapsuleGeometry=qc,e.CascadedShadowsPlugin=WU,e.CatmullRomCurve3=Rc,e.CineonToneMapping=3,e.CircleGeometry=Xc,e.CircleGeometryGenerator=aF,e.ClampToEdgeWrapping=1001,e.Clock=pu,e.Color=Qn,e.ColorKeyframeTrack=gd,e.ColorManagement=si,e.Compress=sI,e.CompressedArrayTexture=bc,e.CompressedCubeTexture=xc,e.CompressedTexture=_c,e.CompressedTextureLoader=Pd,e.ConeGeometry=Kc,e.ConstantAlphaFactor=213,e.ConstantColorFactor=211,e.ConvexHull=class{constructor(){this.tolerance=-1,this.faces=[],this.newFaces=[],this.assigned=new lB,this.unassigned=new lB,this.vertices=[]}setFromPoints(e){if(e.length>=4){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.vertices.push(new oB(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 wi;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,eB)}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 wi,t=new wi,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,tB.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){tB.closestPointToPoint(i.point,!0,nB);const e=nB.distanceToSquared(i.point);e>r&&(r=e,l=i)}}r=-1,iB.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(iB.distanceToPoint(i.point));e>r&&(r=e,c=i)}}const h=[];if(iB.distanceToPoint(c.point)<0){h.push(sB.create(a,o,l),sB.create(c,o,a),sB.create(c,l,o),sB.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(sB.create(a,l,o),sB.create(c,a,o),sB.create(c,o,l),sB.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=sB.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=fC,e.CubeCamera=Vr,e.CubeReflectionMapping=301,e.CubeRefractionMapping=302,e.CubeTexture=Hr,e.CubeTextureLoader=class extends Md{constructor(e){super(e)}load(e,t,i,n){const r=new Hr;r.colorSpace=ht;const s=new Dd(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=Uc,e.CubicBezierCurve3=Fc,e.CubicInterpolant=hd,e.CullFaceBack=1,e.CullFaceFront=2,e.CullFaceFrontBack=3,e.CullFaceNone=0,e.Curve=Cc,e.CurvePath=Vc,e.CurvePath3=rv,e.CustomBlending=5,e.CustomContextMenu=Ig,e.CustomToneMapping=5,e.CylinderGeometry=Yc,e.CylinderGeometryGenerator=hF,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=TP,e.DRACOLoader2=DP,e.Damper=wp,e.Data3DTexture=bi,e.DataArrayTexture=_i,e.DataTexture=Ml,e.DataTextureLoader=Rd,e.DataUtils=Zn,e.DecodeUTF8=EI,e.Decompress=_I,e.DecrementStencilOp=7683,e.DecrementWrapStencilOp=34056,e.DefaultLoadingManager=Sd,e.Deflate=JT,e.DepthFormat=1026,e.DepthNormalMaterial=class extends Nx{constructor(e,t){super(e,t),console.warn("DepthNormalMaterial is deprecated, use GBufferMaterial instead")}},e.DepthStencilFormat=1027,e.DepthTexture=zs,e.DetachedBindMode="detached",e.DeviceOrientationControlsPlugin=dO,e.DirectionalLight=Xd,e.DirectionalLight2=Qw,e.DirectionalLightHelper=class extends En{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 ur;n.setAttribute("position",new rr([-t,t,0,t,t,0,t,-t,0,-t,-t,0,-t,t,0],3));const r=new tc({fog:!1,toneMapped:!1});this.lightPlane=new oc(n,r),this.add(this.lightPlane),n=new ur,n.setAttribute("position",new rr([0,0,0,0,0,1],3)),this.targetLine=new oc(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),op.setFromMatrixPosition(this.light.matrixWorld),lp.setFromMatrixPosition(this.light.target.matrixWorld),cp.subVectors(lp,op),this.lightPlane.lookAt(lp),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(lp),this.targetLine.scale.z=cp.length()}},e.DirectionalLightHelper2=xL,e.DiscreteInterpolant=ud,e.DisplayP3ColorSpace="display-p3",e.DodecahedronGeometry=Zc,e.DoubleSide=2,e.Dropzone=Dg,e.DstAlphaFactor=206,e.DstColorFactor=208,e.DuplicateTracker=GL,e.DynamicCopyUsage=35050,e.DynamicDrawUsage=35048,e.DynamicImportPlugin=sN,e.DynamicReadUsage=35049,e.ECS=DN,e.EXRExporter=qP,e.EXRExporter2=lD,e.EXRLoader=RP,e.EasingFunctions=mb,e.EdgesGeometry=nh,e.EffectComposer=OC,e.EffectComposer2=UC,e.EllipseCurve=Sc,e.EllipseCurve3D=Ow,e.EncodeUTF8=TI,e.EntityComponentPlugin=PN,e.EqualCompare=514,e.EqualDepth=4,e.EqualStencilFunc=514,e.EquirectangularReflectionMapping=303,e.EquirectangularRefractionMapping=304,e.Euler=hn,e.EventDispatcher=Bt,e.ExtendedCopyPass=CC,e.ExtendedRenderPass=wC,e.ExtendedShaderMaterial=lw,e.ExtendedShaderPass=_C,e.ExtrudeGeometry=Bh,e.FBXLoader=iP,e.FBXLoader2=_P,e.Face=sB,e.FileLoader=Id,e.FileTransferPlugin=XO,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 tr{constructor(e,t,i){super(new Uint16Array(e),t,i),this.isFloat16BufferAttribute=!0}getX(e){let t=Jn(this.array[e*this.itemSize]);return this.normalized&&(t=Gt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Qt(t,this.array)),this.array[e*this.itemSize]=Kn(t),this}getY(e){let t=Jn(this.array[e*this.itemSize+1]);return this.normalized&&(t=Gt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Qt(t,this.array)),this.array[e*this.itemSize+1]=Kn(t),this}getZ(e){let t=Jn(this.array[e*this.itemSize+2]);return this.normalized&&(t=Gt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Qt(t,this.array)),this.array[e*this.itemSize+2]=Kn(t),this}getW(e){let t=Jn(this.array[e*this.itemSize+3]);return this.normalized&&(t=Gt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Qt(t,this.array)),this.array[e*this.itemSize+3]=Kn(t),this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=Qt(t,this.array),i=Qt(i,this.array)),this.array[e+0]=Kn(t),this.array[e+1]=Kn(i),this}setXYZ(e,t,i,n){return e*=this.itemSize,this.normalized&&(t=Qt(t,this.array),i=Qt(i,this.array),n=Qt(n,this.array)),this.array[e+0]=Kn(t),this.array[e+1]=Kn(i),this.array[e+2]=Kn(n),this}setXYZW(e,t,i,n,r){return e*=this.itemSize,this.normalized&&(t=Qt(t,this.array),i=Qt(i,this.array),n=Qt(n,this.array),r=Qt(r,this.array)),this.array[e+0]=Kn(t),this.array[e+1]=Kn(i),this.array[e+2]=Kn(n),this.array[e+3]=Kn(r),this}},e.Float32BufferAttribute=rr,e.FloatType=1015,e.FnCaller=lm,e.Fog=Ho,e.FogExp2=Vo,e.FragmentClippingMode=UU,e.FrameFadeBlendPass=UB,e.FramebufferTexture=class extends mi{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=$r,e.FullScreenQuad=mC,e.GBufferMaterial=Nx,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=Eg,e.GLTFAnimationPlugin=lU,e.GLTFBinaryExtension=FM,e.GLTFExporter=XC,e.GLTFExporter2=QP,e.GLTFKHRMaterialVariantsPlugin=tN,e.GLTFLightExtrasExtension=QS,e.GLTFLoader=mM,e.GLTFLoader2=CP,e.GLTFMaterialExtrasExtension=HS,e.GLTFMaterialsAlphaMapExtension=qS,e.GLTFMaterialsBumpMapExtension=JS,e.GLTFMaterialsDisplacementMapExtension=tM,e.GLTFMaterialsLightMapExtension=sM,e.GLTFMeshOptDecodePlugin=NO,e.GLTFObject3DExtrasExtension=cM,e.GLTFParser=cE,e.GLTFViewerConfigExtension=pM,e.GLTFWriter2=zS,e.GPUComputationRenderer=class{constructor(e,t,i){this.variables=[],this.currentTextureIndex=0;let n=Te;const r=new Wo,s=new Nr;s.position.z=1;const a={passThruTexture:{value:null}},o=h("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",a),l=new Pr(new is(2,2),o);function c(i){i.defines.resolution="vec2( "+e.toFixed(1)+", "+t.toFixed(1)+" )"}function h(e,t){const i=new Fr({name:"GPUComputationShader",uniforms:t=t||{},vertexShader:"void main()\t{\n\n\tgl_Position = vec4( position, 1.0 );\n\n}\n",fragmentShader:e});return c(i),i}r.add(l),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(){l.geometry.dispose(),l.material.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=c,this.createShaderMaterial=h,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:Be,type:n,depthBuffer:!1})},this.createTexture=function(){const i=new Float32Array(e*t*4),n=new Ml(i,e,t,Be,Te);return n.needsUpdate=!0,n},this.renderTexture=function(e,t){a.passThruTexture.value=e,this.doRenderTarget(o,t),a.passThruTexture.value=null},this.doRenderTarget=function(e,t){const n=i.getRenderTarget(),a=i.xr.enabled,c=i.shadowMap.autoUpdate;i.xr.enabled=!1,i.shadowMap.autoUpdate=!1,l.material=e,i.setRenderTarget(t),i.render(r,s),l.material=o,i.xr.enabled=a,i.shadowMap.autoUpdate=c,i.setRenderTarget(n)}}},e.GenericBlendTexturePass=bC,e.GeometryGeneratorPlugin=xF,e.GreaterCompare=516,e.GreaterDepth=6,e.GreaterEqualCompare=518,e.GreaterEqualDepth=5,e.GreaterEqualStencilFunc=518,e.GreaterStencilFunc=516,e.GridHelper=class extends hc{constructor(e=10,t=10,i=4473924,n=8947848){i=new Qn(i),n=new Qn(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 ur;c.setAttribute("position",new rr(o,3)),c.setAttribute("color",new rr(l,3));super(c,new tc({vertexColors:!0,toneMapped:!1})),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}},e.Group=Lo,e.Group2=xw,e.Gunzip=cI,e.Gzip=sI,e.HVBlurHelper=dy,e.HalfEdge=aB,e.HalfFloatType=1016,e.HemisphereLight=Od,e.HemisphereLight2=Ww,e.HemisphereLightHelper=class extends En{constructor(e,t,i){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=i,this.type="HemisphereLightHelper";const n=new Uh(t);n.rotateY(.5*Math.PI),this.material=new Xn({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 tr(s,3)),this.add(new Pr(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");sp.copy(this.light.color),ap.copy(this.light.groundColor);for(let e=0,i=t.count;e<i;e++){const n=e<i/2?sp:ap;t.setXYZ(e,n.r,n.g,n.b)}t.needsUpdate=!0}this.light.updateWorldMatrix(!0,!1),e.lookAt(rp.setFromMatrixPosition(this.light.matrixWorld).negate())}},e.HorizontalBlurShader=cy,e.IcosahedronGeometry=Oh,e.ImageBitmapLoader=ou,e.ImageLoader=Dd,e.ImageUtils=ci,e.Importer=kC,e.IncrementStencilOp=7682,e.IncrementWrapStencilOp=34055,e.Inflate=tI,e.InstancedBufferAttribute=Pl,e.InstancedBufferGeometry=tu,e.InstancedInterleavedBuffer=zu,e.InstancedMesh=Nl,e.InstancedMesh2=class extends Nl{constructor(e,t,i=1){super(e,t,i),this.assetType="model",this.setDirty=kx.setDirty,this.refreshUi=kx.refreshUi,kx.upgradeObject3D.call(this)}get modelObject(){return this}},e.Int16BufferAttribute=class extends tr{constructor(e,t,i){super(new Int16Array(e),t,i)}},e.Int32BufferAttribute=class extends tr{constructor(e,t,i){super(new Int32Array(e),t,i)}},e.Int8BufferAttribute=class extends tr{constructor(e,t,i){super(new Int8Array(e),t,i)}},e.IntType=1013,e.InterleavedBuffer=qo,e.InterleavedBufferAttribute=Yo,e.Interpolant=cd,e.InterpolateDiscrete=2300,e.InterpolateLinear=2301,e.InterpolateSmooth=2302,e.InvertStencilOp=5386,e.JSONMaterialLoader=fE,e.JSUndoManager=bp,e.KHR_TEXTURE_BASISU=OO,e.KTX2LoadPlugin=BO,e.KTX2Loader=UR,e.KTX2Loader2=LO,e.KTXLoadPlugin=DO,e.KTXLoader=zR,e.KeepStencilOp=7680,e.KeyframeTrack=pd,e.LOD=ml,e.LatheGeometry=Wc,e.Layers=dn,e.LegacyPhongMaterial=_w,e.LessCompare=513,e.LessDepth=2,e.LessEqualCompare=515,e.LessEqualDepth=3,e.LessEqualStencilFunc=515,e.LessStencilFunc=513,e.Light=Ld,e.LightProbe=Zd,e.Line=oc,e.Line2=Sw,e.Line3=Zu,e.LineBasicMaterial=tc,e.LineBasicMaterial2=class extends mw{constructor(e){super(e),console.error("LineBasicMaterial2 is deprecated, use UnlitLineMaterial instead")}},e.LineCurve=Nc,e.LineCurve3=kc,e.LineDashedMaterial=id,e.LineGeometry=Cw,e.LineGeometry2=Iw,e.LineGeometryGenerator=_F,e.LineHelper=ML,e.LineLoop=dc,e.LineMaterial=Ay,e.LineMaterial2=yw,e.LineSegments=hc,e.LineSegments2=By,e.LineSegmentsGeometry=fy,e.LineSegmentsGeometry2=Dw,e.LinearDisplayP3ColorSpace="display-p3-linear",e.LinearEncoding=3e3,e.LinearFilter=1006,e.LinearInterpolant=dd,e.LinearMipMapLinearFilter=1008,e.LinearMipMapNearestFilter=1007,e.LinearMipmapLinearFilter=1008,e.LinearMipmapNearestFilter=1007,e.LinearSRGBColorSpace="srgb-linear",e.LinearToSRGB=Hp,e.LinearToneMapping=1,e.LinearTransfer="linear",e.Loader=Md,e.LoaderUtils=eu,e.LoadingManager=Cd,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=AE,e.Material=Wn,e.MaterialConfiguratorBasePlugin=JU,e.MaterialExtender=sx,e.MaterialLoader=$d,e.MaterialManager=mD,e.MaterialPreviewGenerator=py,e.MathUtils=Vt,e.Matrix2=qu,e.Matrix3=Wt,e.Matrix4=$i,e.MaxEquation=104,e.Mesh=Pr,e.Mesh2=ww,e.MeshBasicMaterial=Xn,e.MeshBasicMaterial2=class extends Px{constructor(e){super(e),console.error("MeshBasicMaterial2 is deprecated, use UnlitMaterial instead")}},e.MeshDepthMaterial=Eo,e.MeshDepthMaterialOverride=TB,e.MeshDistanceMaterial=To,e.MeshLambertMaterial=ed,e.MeshLine=Mw,e.MeshLineMaterial=class extends yw{},e.MeshLineSegments=Ew,e.MeshMatcapMaterial=td,e.MeshNormalMaterial=$h,e.MeshNormalMaterialOverride=RB,e.MeshPhongMaterial=Jh,e.MeshPhysicalMaterial=Kh,e.MeshStandardMaterial=Yh,e.MeshStandardMaterial2=class extends hw{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)),YR.a.fromBufferAttribute(t,a),YR.b.fromBufferAttribute(t,o),YR.c.fromBufferAttribute(t,l),n*=YR.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)),YR.a.fromBufferAttribute(this.positionAttribute,l),YR.b.fromBufferAttribute(this.positionAttribute,c),YR.c.fromBufferAttribute(this.positionAttribute,h),t.set(0,0,0).addScaledVector(YR.a,s).addScaledVector(YR.b,a).addScaledVector(YR.c,1-(s+a)),void 0!==i&&(void 0!==this.normalAttribute?(YR.a.fromBufferAttribute(this.normalAttribute,l),YR.b.fromBufferAttribute(this.normalAttribute,c),YR.c.fromBufferAttribute(this.normalAttribute,h),i.set(0,0,0).addScaledVector(YR.a,s).addScaledVector(YR.b,a).addScaledVector(YR.c,1-(s+a)).normalize()):YR.getNormal(i)),void 0!==n&&void 0!==this.colorAttribute&&(YR.a.fromBufferAttribute(this.colorAttribute,l),YR.b.fromBufferAttribute(this.colorAttribute,c),YR.c.fromBufferAttribute(this.colorAttribute,h),KR.set(0,0,0).addScaledVector(YR.a,s).addScaledVector(YR.b,a).addScaledVector(YR.c,1-(s+a)),n.r=KR.x,n.g=KR.y,n.b=KR.z),void 0!==r&&void 0!==this.uvAttribute&&(JR.fromBufferAttribute(this.uvAttribute,l),ZR.fromBufferAttribute(this.uvAttribute,c),$R.fromBufferAttribute(this.uvAttribute,h),r.set(0,0).addScaledVector(JR,s).addScaledVector(ZR,a).addScaledVector($R,1-(s+a))),this}},e.MeshToonMaterial=Zh,e.MetaImporter=fv,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=fd,e.OBJLoader2=DE,e.Object3D=En,e.Object3D2=bw,e.Object3DComponent=CN,e.Object3DManager=bD,e.Object3DWidgetsPlugin=DF,e.ObjectClipboard=QL,e.ObjectLoader=nu,e.ObjectPicker=oy,e.ObjectShaderMaterial=uw,e.ObjectSpaceNormalMap=1,e.OctahedronGeometry=Uh,e.OneFactor=201,e.OneMinusConstantAlphaFactor=214,e.OneMinusConstantColorFactor=212,e.OneMinusDstAlphaFactor=207,e.OneMinusDstColorFactor=209,e.OneMinusSrcAlphaFactor=205,e.OneMinusSrcColorFactor=203,e.OrbitControls=Ng,e.OrbitControls2=class extends Ng{constructor(e,t){super(e,t),this.throttleUpdate=60,this.targetOffset=new wi(0,0,0);const i=this.update;this.update=()=>this._update(i)}_update(e){this.target.add(this.targetOffset),vA.copy(this.object.position).sub(this.target),SA=vA.length(),CA.copy(this.target);const t=e();return CA.sub(this.target),vA.copy(this.object.position).sub(this.target),SA/=vA.length(),this.target.add(CA),this.object.position.copy(this.target).add(vA),vA.normalize(),_A.crossVectors(MA,vA).normalize(),bA.crossVectors(vA,_A).normalize(),xA.crossVectors(_A,bA).normalize().negate(),_A.length()>.1&&this.object.up.crossVectors(vA.clone().normalize(),_A),this.enablePan&&(wA.set(0,0,0).addScaledVector(_A,CA.x).addScaledVector(bA,CA.y).addScaledVector(xA,CA.z),this.targetOffset.add(wA),this.targetOffset.multiplyScalar(1/SA)),wA.set(0,0,0).addScaledVector(_A,-this.targetOffset.x).addScaledVector(bA,-this.targetOffset.y).addScaledVector(xA,-this.targetOffset.z),this.object.lookAt(wA.add(this.target)),this.object.updateMatrixWorld(),this.object.isCamera&&this.object.updateProjectionMatrix(),this.target.sub(this.targetOffset),t}},e.OrthographicCamera=fs,e.OrthographicCamera0=ow,e.OrthographicCamera2=aw,e.P3Primaries="p3",e.PCFShadowMap=1,e.PCFSoftShadowMap=2,e.PLYLoadPlugin=EO,e.PLYLoader=WR,e.PMREMGenerator=Ts,e.Pass=dC,e.Path=Hc,e.PerspectiveCamera=Gr,e.PerspectiveCamera0=tw,e.PerspectiveCamera2=ew,e.PhysicalMaterial=hw,e.PickingPlugin=XL,e.PipelinePassPlugin=VD,e.PivotControls=qf,e.Plane=Kr,e.PlaneGeometry=is,e.PlaneGeometryGenerator=cF,e.PlaneHelper=class extends oc{constructor(e,t=1,i=16776960){const n=i,r=new ur;r.setAttribute("position",new rr([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 tc({color:n,toneMapped:!1})),this.type="PlaneHelper",this.plane=e,this.size=t;const s=new ur;s.setAttribute("position",new rr([1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],3)),s.computeBoundingSphere(),this.add(new Pr(s,new Xn({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=Wd,e.PointLight2=Kw,e.PointLightHelper=class extends Pr{constructor(e,t,i){super(new kh(t,4,2),new Xn({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=DL,e.PointerDragHelper=_p,e.PointerLockControlsPlugin=pO,e.Points=Ac,e.PointsMaterial=uc,e.PolarGridHelper=class extends hc{constructor(e=10,t=16,i=8,n=64,r=4473924,s=8947848){r=new Qn(r),s=new Qn(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 ur;l.setAttribute("position",new rr(a,3)),l.setAttribute("color",new rr(o,3));super(l,new tc({vertexColors:!0,toneMapped:!1})),this.type="PolarGridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}},e.PolyhedronGeometry=Jc,e.PopmotionPlugin=ID,e.PositionalAudio=class extends vu{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,bu,xu),wu.set(0,0,1).applyQuaternion(bu);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(wu.x,e),t.orientationY.linearRampToValueAtTime(wu.y,e),t.orientationZ.linearRampToValueAtTime(wu.z,e)}else t.setPosition(_u.x,_u.y,_u.z),t.setOrientation(wu.x,wu.y,wu.z)}},e.ProgressiveBlendPass=CB,e.PropertyBinding=Ou,e.PropertyMixer=Cu,e.QuadraticBezierCurve=jc,e.QuadraticBezierCurve3=zc,e.Quaternion=xi,e.QuaternionKeyframeTrack=yd,e.QuaternionLinearInterpolant=Ad,e.RED_GREEN_RGTC2_Format=36285,e.RED_RGTC1_Format=36283,e.REVISION="163",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.RGBELoader=gD,e.RGBEPNGLoader=hM,e.RGBFormat=1022,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.RGFormat=1030,e.RGIntegerFormat=1031,e.RawShaderMaterial=Xh,e.Ray=Zi,e.Raycaster=Qu,e.Rec709Primaries="rec709",e.RectAreaLight=Kd,e.RectAreaLight2=$w,e.RedFormat=1028,e.RedIntegerFormat=1029,e.ReferenceManager=gN,e.ReinhardToneMapping=2,e.RenderPass=gC,e.RenderTarget=yi,e.RenderTargetManager=NC,e.RepeatWrapping=1e3,e.ReplaceStencilOp=7681,e.ReverseSubtractEquation=102,e.Rhino3dmLoader=LP,e.Rhino3dmLoader2=FP,e.RingGeometry=Fh,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=IO,e.STLLoader=XR,e.SVGTextureLoader=kP,e.SampleBodyComponent=TN,e.Scene=Wo,e.SceneUiConfigPlugin=JB,e.SelectionWidget=rL,e.Serialization=am,e.ShaderChunk=ns,e.ShaderLib=ss,e.ShaderMaterial=Fr,e.ShaderMaterial2=Fx,e.ShaderPass=AC,e.ShadowMaterial=qh,e.Shape=rh,e.ShapeGeometry=Nh,e.ShapeGeometryGenerator=AF,e.ShapePath=class{constructor(){this.type="ShapePath",this.color=new Qn,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Hc,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=Ph.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 rh,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 rh,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 rh;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=Ph,e.ShortType=1011,e.SimpleEventDispatcher=Ap,e.SimpleJSONExporter=VP,e.SimpleJSONLoader=mE,e.SimpleTextExporter=HP,e.SimplifyModifierPlugin=GF,e.Skeleton=Il,e.SkeletonHelper=class extends hc{constructor(e){const t=np(e),i=new ur,n=[],r=[],s=new Qn(0,0,1),a=new Qn(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 rr(n,3)),i.setAttribute("color",new rr(r,3));super(i,new tc({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");ip.copy(this.root.matrixWorld).invert();for(let e=0,i=0;e<t.length;e++){const r=t[e];r.parent&&r.parent.isBone&&(tp.multiplyMatrices(ip,r.matrixWorld),ep.setFromMatrixPosition(tp),n.setXYZ(i,ep.x,ep.y,ep.z),tp.multiplyMatrices(ip,r.parent.matrixWorld),ep.setFromMatrixPosition(tp),n.setXYZ(i+1,ep.x,ep.y,ep.z),i+=2)}i.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose()}},e.SkeletonHelper2=OL,e.SkinnedMesh=Cl,e.Source=di,e.Sphere=Vi,e.SphereGeometry=kh,e.SphereGeometryGenerator=lF,e.Spherical=Wu,e.SphericalHarmonics3=Jd,e.SplineCurve=Gc,e.SpotLight=zd,e.SpotLight2=nC,e.SpotLightHelper=class extends En{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";const i=new ur,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 rr(n,3));const r=new tc({fog:!1,toneMapped:!1});this.cone=new hc(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),$u.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt($u),void 0!==this.color?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}},e.SpotLightHelper2=jL,e.Sprite=hl,e.SpriteMaterial=Ko,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 Gr,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Gr,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,uu.copy(e.projectionMatrix);const i=t.eyeSep/2,n=i*t.near/t.focus,r=t.near*Math.tan(Ut*t.fov*.5)/t.zoom;let s,a;du.elements[12]=-i,hu.elements[12]=i,s=-r*t.aspect+n,a=r*t.aspect+n,uu.elements[0]=2*t.near/(a-s),uu.elements[8]=(a+s)/(a-s),this.cameraL.projectionMatrix.copy(uu),s=-r*t.aspect-n,a=r*t.aspect-n,uu.elements[0]=2*t.near/(a-s),uu.elements[8]=(a+s)/(a-s),this.cameraR.projectionMatrix.copy(uu)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(du),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(hu)}},e.StreamCopyUsage=35042,e.StreamDrawUsage=35040,e.StreamReadUsage=35041,e.StringKeyframeTrack=vd,e.SubtractEquation=101,e.SubtractiveBlending=3,e.SwitchNodeBasePlugin=tF,e.TOUCH={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},e.TYPED_ARRAYS=Dp,e.TangentSpaceNormalMap=0,e.TetrahedronGeometry=jh,e.Texture=mi,e.TextureLoader=Bd,e.ThreeFirstPersonControlsPlugin=gO,e.ThreeSerialization=lv,e.TorusGeometry=zh,e.TorusGeometryGenerator=sF,e.TorusKnotGeometry=Gh,e.TransformAnimationPlugin=hU,e.TransformControls=Jg,e.TransformControlsGizmo=vf,e.TransformControlsPlane=_f,e.Triangle=Nn,e.TriangleFanDrawMode=2,e.TriangleStripDrawMode=1,e.TrianglesDrawMode=0,e.TubeGeometry=Qh,e.TubeGeometryGenerator=mF,e.TubeShapeGeometry=Bw,e.TubeShapeGeometryGenerator=yF,e.TypeSystem=uN,e.USDZLoadPlugin=SO,e.USDZLoader=VR,e.UVMapping=300,e.UVsDebug=oR,e.UiConfigMethods=fg,e.UiConfigRenderer=class extends Ag{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){var n,r;null==(r=(n=this.config).uiRefresh)||r.call(n,e,t,i)}_createUiContainer(){return Sp({id:"uiConfigContainer",addToBody:!1})}},e.UiConfigRendererBase=Ag,e.UiConfigTypeMap=Km,e.Uint16BufferAttribute=ir,e.Uint32BufferAttribute=nr,e.Uint8BufferAttribute=class extends tr{constructor(e,t,i){super(new Uint8Array(e),t,i)}},e.Uint8ClampedBufferAttribute=class extends tr{constructor(e,t,i){super(new Uint8ClampedArray(e),t,i)}},e.UndoManagerPlugin=vO,e.Uniform=ku,e.UniformsGroup=class extends Bt{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:ju++}),this.name="",this.usage=Tt,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=rs,e.UniformsUtils=Ur,e.UnlitLineMaterial=mw,e.UnlitMaterial=Px,e.UnsignedByteType=1009,e.UnsignedInt248Type=1020,e.UnsignedInt5999Type=35902,e.UnsignedIntType=1014,e.UnsignedShort4444Type=1017,e.UnsignedShort5551Type=1018,e.UnsignedShortType=1012,e.Unzip=WI,e.UnzipInflate=VI,e.UnzipPassThrough=QI,e.Unzlib=fI,e.VSMShadowMap=3,e.Vector2=Ht,e.Vector3=wi,e.Vector4=Ai,e.VectorKeyframeTrack=_d,e.VertexList=lB,e.VertexNode=oB,e.VerticalBlurShader=hy,e.VideoLoader=jP,e.VideoTexture=vc,e.VideoTextureLoader=zP,e.ViewHelper2=$y,e.ViewerUiConfigPlugin=XB,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 bi(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 _i(null,e,t,i),this.texture.isRenderTargetTexture=!0}},e.WebGLCoordinateSystem=2e3,e.WebGLCubeRenderTarget=Wr,e.WebGLRenderTarget=vi,e.WebGLRenderer=Qo,e.WebGLUtils=Ro,e.WebGPUCoordinateSystem=2001,e.Wireframe=aR,e.WireframeGeometry=Vh,e.WireframeGeometry2=Rw,e.WireframeGeometry3=class extends Rw{constructor(e){super(e),this.center2=nx.center2,this.setDirty=nx.setDirty,this.refreshUi=nx.refreshUi,this.appliedMeshes=new Set,nx.upgradeGeometry.call(this)}},e.WrapAroundEnding=2402,e.ZeroCurvatureEnding=2400,e.ZeroFactor=200,e.ZeroSlopeEnding=2401,e.ZeroStencilOp=0,e.Zip=zI,e.ZipDeflate=kI,e.ZipLoader=bP,e.ZipPassThrough=NI,e.Zlib=pI,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=Tm,e.addModelProcess=kb,e.aesGcmDecrypt=fm,e.aesGcmEncrypt=gm,e.animate=pb,e.animateAsync=fb,e.animateCameraToViewLinear=xb,e.animateCameraToViewSpherical=bb,e.animateTarget=async function(e,t,i,n,r=!1){t in e||console.error("invalid key",t,e);const s=gb(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 yp(e??0).then((()=>o(i.to)))}return"function"==typeof i.to&&(i={...i,to:i.to(a,e)}),fb({...i,from:a,onUpdate:o},n)},e.arrayBufferToBase64=Ip,e.assetExportHook=cD,e.autoCenterObject3D=function(e){return kx.autoCenter.call(e)},e.autoGPUInstanceMeshes=ly,e.autoScaleObject3D=function(e,t,i,n){return kx.autoScale.call(e,t,i,n)},e.base64ToArrayBuffer=Pp,e.basicObjectConstraints=oN,e.bindToValue=LA,e.blobToDataURL=Gp,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=qb,e.cLinearToRGBM=function(e,t){return Ib(new Ai(e.r,e.g,e.b,1),t)},e.cRGBMToLinear=function(e,t){return Tb(e,t),new Qn(e.x,e.y,e.z)},e.canvasFlipY=bm,e.centerAllGeometries=jb,e.checkTexMapReference=HA,e.clearBit=function(e,t){return e&~(1<<t)},e.clearCoatTintGLTFExtension=vU,e.clonePrimitive=zm,e.cloneScriptTag=Tp,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=oI,e.compressSync=lI,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 tr(s,4)),e!==r&&e.copy(r),e},e.computeMorphedAttributes=function(e){const t=new wi,i=new wi,n=new wi,r=new wi,s=new wi,a=new wi,o=new wi,l=new wi,c=new wi;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 rr(D,3),morphedNormalAttribute:new rr(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 wi,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 Ht(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 Ht(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 Yu(n,r)},e.convertArrayBufferToStringsInMeta=pv,e.convertStringsToArrayBuffersInMeta=mv,e.copyMaterialUserData=dv,e.copyObject3DUserData=uv,e.copyPrimitive=Qm,e.copyProps=Kp,e.copyTextureUserData=hv,e.copyUserData=cv,e.createBindingsProxy=_O,e.createCameraPath=Xx,e.createCanvasElement=Cp,e.createCurvePropertyUi=pF,e.createCurveTypeDropdown=uF,e.createDiv=Sp,e.createImage=Mp,e.createRenderTargetKey=FC,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=gF,e.createStyles=Ep,e.css=kp,e.curveUiConfigs=dF,e.customBumpMapGLTFExtension=IU,e.dataTextureFromColor=function(e){const t=new Ml(new Uint8Array([Math.floor(255*e.r),Math.floor(255*e.g),Math.floor(255*e.b),255]),1,1,Be,Ce);return t.needsUpdate=!0,t.colorSpace=dt,t},e.dataTextureFromVec4=function(e){const t=new Ml(new Uint8Array([Math.floor(255*e.x),Math.floor(255*e.y),Math.floor(255*e.z),Math.floor(255*e.w)]),1,1,Be,Ce);return t.needsUpdate=!0,t.colorSpace=dt,t},e.decompress=function(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&lT(7),31==e[0]&&139==e[1]&&8==e[2]?dI(e,t,i):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?nI(e,t,i):yI(e,t,i)},e.decompressSync=function(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?uI(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?rI(e,t):vI(e,t)},e.deepAccessObject=em,e.deepCloneAttribute=function(e){return e.isInstancedInterleavedBufferAttribute||e.isInterleavedBufferAttribute?kA(e):e.isInstancedBufferAttribute?(new Pl).copy(e):(new tr).copy(e)},e.defaultObjectProcessor=Nb,e.deflate=$T,e.deflateSync=eI,e.deinterleaveAttribute=kA,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,kA(i)),t[e]=n.get(i))}for(const e in i){const t=i[e];t.isInterleavedBufferAttribute&&(n.has(t)||n.set(t,kA(t)),i[e]=n.get(t))}},e.deleteObjects=zx,e.downloadBlob=zp,e.downloadFile=Qp,e.duplicateObjects=Gx,e.embedUrlRefs=Mm,e.equalsPrimitive=Gm,e.escapeRegExp=Op,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=Fb,e.filterTopmostAncestors=jx,e.findLastIndex=Zp,e.fontFormatExtensionMap=Wb,e.fragmentClippingGLTFExtension=NU,e.generateUUID=QA,e.generateUiConfig=Zm,e.generateUiFolder=$m,e.generateValueConfig=Jm,e.getComponentTypes=fN,e.getEmptyMeta=gv,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=sv,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=Yp,e.getPartialProps=bv,e.getPropDesc=Wm,e.getPropertyDescriptor=Wp,e.getTexelDecoding=UA,e.getTexelDecodingFunction=OA,e.getTextureDataType=WA,e.getTypedArray=Rp,e.getUrlQueryParam=Dm,e.glbEncryptionPreparser=uE,e.glbEncryptionProcessor=dE,e.glsl=Np,e.gunzip=dI,e.gunzipSync=uI,e.gzip=oI,e.gzipSync=lI,e.halfFloatToRgbe=PA,e.html=(e,...t)=>String.raw({raw:e},...t),e.htmlDialogWrapper=jm,e.htmlToCanvas=async function(e,t,i){const n=Em(e,t,i);return await wm(n,i)},e.htmlToPng=async function(e,t,i){const n=Em(e,t,i);return await Cm(n,i)},e.htmlToSvg=Em,e.iCameraCommons=Yx,e.iGeometryCommons=nx,e.iLightCommons=Uw,e.iMaterialCommons=Dx,e.iObjectCommons=kx,e.imageBitmapToBase64=ym,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=Am(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=Am,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=_m,e.imageUrlToImageData=vm,e.includesAll=Jp,e.incrementObjectCloneName=tx,e.inflate=nI,e.inflateSync=rI,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 qo(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 Yo(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=qm,e.isPropertyWritable=qp,e.isWebpExportSupported=function(){const e=document.createElement("canvas");return!(!e.getContext||!e.getContext("2d"))&&e.toDataURL("image/webp").startsWith("data:image/webp")},e.jsonToBlob=vv,e.lerp=yb,e.lerpAngle=Ab,e.lerpNumber=Cb,e.lerpParams=Eb,e.lerpTexture=Mb,e.lerpVal=wb,e.lerpVector=Sb,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 xi){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=xm,e.makeGLBFile=Mv,e.makeICameraCommonUiConfig=Zb,e.makeIObject3DUiConfig=$b,e.makeSamplerUi=px,e.makeSetterFor=gb,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||Xb[i]||"",r=e.style||"";if(n.length>0){!qm(n)&&!n.startsWith("blob:")&&!n.startsWith("ftp:")&&globalThis.window&&(n=new URL(n,window.location.href).href);const e=Lp(n)||"woff";r+="\n"+(n.length>0?`\n            @font-face {\n                font-family: ${JSON.stringify(i)};\n                src: url(${n}) format(${Wb[e]||e});\n            }`:"")}let s=qb({...e,fontFamily:i,style:r});s=await Mm(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 zb(t.loadingManager),processRaw:!1};try{return await t.importSingle(e,i)}catch(e){return console.error(e),""}}(e,t))),s=jp(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=RA,e.matDefineBool=BA,e.mergeAttributes=NA,e.mergeBufferAttributes=function(e){return console.warn("THREE.BufferGeometryUtils: mergeBufferAttributes() has been renamed to mergeAttributes()."),NA(e)},e.mergeBufferGeometries=function(e,t=!1){return console.warn("THREE.BufferGeometryUtils: mergeBufferGeometries() has been renamed to mergeGeometries()."),FA(e,t)},e.mergeGeometries=FA,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=jA,e.metaFromResources=yv,e.metaToResources=Av,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=CU,e.now=vp,e.objectActionsUiConfig=ix,e.objectExtensionsUiConfig=ex,e.objectHasOwn=tm,e.objectMap=im,e.objectMap2=nm,e.onChange=cm,e.onChange2=hm,e.onChange3=dm,e.onChangeDispatchEvent=um,e.overrideThreeCache=IA,e.parseFileExtension=Lp,e.pathJoin=function(e,t="/"){return e.join(t)},e.prettyScrollbar=function(e=document.head){return Ep(kp`
      ::-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=Vm,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=Up,e.reverseShapeWinding=fF,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=Xp,e.sampleThreepipeViteHmrPlugin=aN,e.serializable=mm,e.serialize=pm,e.serializeTextureInExtras=_v,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=Tp(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=xv,e.setThreeRendererMode=oC,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=Hm,e.setupComponent=AN,e.shaderReplaceString=Cv,e.shaderUtils=Xm,e.snapObject=uy,e.sortPasses=RC,e.sphericalFromCameraView=_b,e.strFromU8=PI,e.strToU8=II,e.svgToCanvas=wm,e.svgToPng=Cm,e.svgUrl=jp,e.texImageToCanvas=YA,e.textureDataToImageData=qA,e.textureToBlob=async function(e,t,i,n,r){const s=XA(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=XA,e.textureToDataUrl=function(e,t,i,n,r){return XA(e,t,i).toDataURL(n,r)},e.threeConstMappings=ty,e.threeMaterialInterpolateProps=Tx,e.threeMaterialPropList=Ex,e.timeout=yp,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 wi,new wi,new wi],s=new wi,a=new wi,o=new wi,l=new wi;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 wi).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 tr(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=GA,e.toTitleCase=Bp,e.toTrianglesDrawMode=zA,e.uiButton=ag,e.uiColor=cg,e.uiConfig=eg,e.uiConfigMaterialExtension=ux,e.uiContainer=tg,e.uiDropdown=sg,e.uiFolderContainer=pg,e.uiImage=hg,e.uiInput=og,e.uiMonitor=ig,e.uiNumber=lg,e.uiPanelContainer=ug,e.uiSlider=ng,e.uiToggle=dg,e.uiVector=rg,e.uniform=DA,e.unzip=function(e,t,i){i||(i=t,t={}),"function"!=typeof i&&lT(7);var n=[],r=function(){for(var e=0;e<n.length;++e)n[e]()},s={},a=function(e,t){qI((function(){i(e,t)}))};qI((function(){a=i}));for(var o=e.length-22;101010256!=zT(e,o);--o)if(!o||e.length-o>65558)return a(lT(13,0,1),null),r;var l=jT(e,o+8);if(l){var c=l,h=zT(e,o+16),d=4294967295==h||65535==c;if(d){var u=zT(e,o-12);(d=101075792==zT(e,u))&&(c=l=zT(e,u+32),h=zT(e,u+48))}for(var p=t&&t.filter,m=function(t){var i=BI(e,h,d),o=i[0],c=i[1],u=i[2],m=i[3],g=i[4],f=i[5],A=RI(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,rI(v,{out:new BE(u)}))}catch(e){y(e,null)}else n.push(nI(v,{size:u},y))}else y(lT(14,"unknown compression type "+o,1),null);else y(null,aT(e,A,A+c));else y(null,null)},g=0;g<c;++g)m()}else a(null,{});return r},e.unzipSync=XI,e.unzlib=yI,e.unzlibSync=vI,e.updateBit=Im,e.updateMaterialDefines=ax,e.updateUi=nF,e.upgradeTexture=rC,e.upgradeWebGLRenderer=sC,e.uploadFile=Vp,e.uuidV4=Pm,e.vLinearToRGBM=Ib,e.vRGBMToLinear=Tb,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=iy,e.whiteTexture=ny,e.windowDialogWrapper=Rm,e.worldToLocalQuaternion=VA,e.wrapThisFunction=function(e,t){return function(...i){return e(),t&&t.call(this,...i)}},e.wrapThisFunction2=$p,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&&lT(7);var n={};xI(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){qI((function(){i(e,t)}))};qI((function(){u=i}));var p=function(){var e=new BE(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;UI(e,o,r,r.f,r.u,s);var h=30+r.f.length+OI(r.extra),d=o+h;e.set(r.c,d),UI(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)}}FI(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=xT(),f=l.length;g.p(l);var A=II(t),y=A.length,v=m.comment,_=v&&II(v),b=_&&_.length,x=OI(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]=ST(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(lT(11,0,1),null),w)if(f<16e4)try{C(null,eI(l,m))}catch(e){C(e,null)}else h.push($T(l,m,C));else C(null,l)},g=0;g<l;++g)m(g);return d},e.zipSync=GI,e.zlib=function(e,t,i){return i||(i=t,t={}),"function"!=typeof i&&lT(7),FT(e,t,[PT,BT,function(){return[gI]}],(function(e){return OT(gI(e.data[0],e.data[1]))}),4,i)},e.zlibSync=gI,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}));
//# sourceMappingURL=/sm/32b018617fdbbd6e1df25311d9a666807c8b7d556e99b7da7f3f15adc10883ff.map