toolnet-memory 0.3.5 → 0.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/toolnet-memory +44 -111
- package/bundle/full-index.js +23 -22
- package/bundle/graph-cli.js +1 -0
- package/bundle/graph-index.js +1 -1
- package/bundle/graph-ui.js +3 -0
- package/bundle/help-cli.js +4 -0
- package/bundle/impact.js +2 -2
- package/bundle/mcp.js +20 -20
- package/bundle/model-cli.js +2 -0
- package/bundle/public/index.html +2987 -0
- package/bundle/public/vendor/3d-force-graph.min.js +5 -0
- package/bundle/runtime.js +6 -6
- package/bundle/semantic.js +6 -6
- package/bundle/shimmer-worker.js +1 -0
- package/bundle/status-cli.js +4 -0
- package/package.json +1 -1
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// Version 1.80.0 3d-force-graph - https://github.com/vasturiano/3d-force-graph
|
|
2
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).ForceGraph3D=t()}(this,function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function t(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,i)}return n}function i(e){for(var i=1;i<arguments.length;i++){var r=null!=arguments[i]?arguments[i]:{};i%2?n(Object(r),!0).forEach(function(n){t(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function r(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||function(t,n){if(t){if("string"==typeof t)return e(t,n);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?e(t,n):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===n&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".graph-info-msg {\n top: 50%;\n width: 100%;\n text-align: center;\n color: lavender;\n opacity: 0.7;\n font-size: 22px;\n position: absolute;\n font-family: Sans-serif;\n}\n\n.scene-container .clickable {\n cursor: pointer;\n}\n\n.scene-container .grabbable {\n cursor: move;\n cursor: grab;\n cursor: -moz-grab;\n cursor: -webkit-grab;\n}\n\n.scene-container .grabbable:active {\n cursor: grabbing;\n cursor: -moz-grabbing;\n cursor: -webkit-grabbing;\n}");const s="183",a=0,o=1,l=2,u=0,c=1,h=2,d=3,p=1,f=3,m=0,g=1,_=2,v=100,y=101,b=102,x=200,T=201,S=202,M=203,E=204,w=205,A=206,R=207,C=208,N=209,P=210,L=211,D=212,I=213,U=214,F=0,O=1,B=2,k=3,z=4,V=5,G=6,H=7,j=0,W=1,$=2,X=1,q=2,Y=3,K=4,Z=5,Q=6,J=7,ee=301,te=302,ne=303,ie=304,re=306,se=1e3,ae=1001,oe=1002,le=1003,ue=1004,ce=1005,he=1006,de=1007,pe=1008,fe=1009,me=1010,ge=1011,_e=1012,ve=1013,ye=1014,be=1015,xe=1016,Te=1017,Se=1018,Me=1020,Ee=35902,we=35899,Ae=1021,Re=1022,Ce=1023,Ne=1026,Pe=1027,Le=1028,De=1029,Ie=1030,Ue=1031,Fe=1033,Oe=33776,Be=33777,ke=33778,ze=33779,Ve=35840,Ge=35841,He=35842,je=35843,We=36196,$e=37492,Xe=37496,qe=37488,Ye=37489,Ke=37490,Ze=37491,Qe=37808,Je=37809,et=37810,tt=37811,nt=37812,it=37813,rt=37814,st=37815,at=37816,ot=37817,lt=37818,ut=37819,ct=37820,ht=37821,dt=36492,pt=36494,ft=36495,mt=36283,gt=36284,_t=36285,vt=36286,yt="",bt="srgb",xt="srgb-linear",Tt="linear",St="srgb",Mt=7680,Et=512,wt=513,At=514,Rt=515,Ct=516,Nt=517,Pt=518,Lt=519,Dt=35044,It=35048,Ut="300 es",Ft=2e3,Ot=2001,Bt="compute",kt="render",zt="depthTextureCompare";function Vt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Gt(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function Ht(){const e=Gt("canvas");return e.style.display="block",e}const jt={};function Wt(...e){const t="THREE."+e.shift();console.log(t,...e)}function $t(e){const t=e[0];if("string"==typeof t&&t.startsWith("TSL:")){const t=e[1];t&&t.isStackTrace?e[0]+=" "+t.getLocation():e[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return e}function Xt(...e){const t="THREE."+(e=$t(e)).shift();{const n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function qt(...e){const t="THREE."+(e=$t(e)).shift();{const n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function Yt(...e){const t=e.join(" ");t in jt||(jt[t]=!0,Xt(...e))}const Kt={[F]:1,[B]:6,[z]:7,[k]:5,[O]:0,[G]:2,[H]:4,[V]:3};class Zt{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[e]&&(n[e]=[]),-1===n[e].indexOf(t)&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return void 0!==n&&(void 0!==n[e]&&-1!==n[e].indexOf(t))}removeEventListener(e,t){const n=this._listeners;if(void 0===n)return;const i=n[e];if(void 0!==i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}dispatchEvent(e){const t=this._listeners;if(void 0===t)return;const n=t[e.type];if(void 0!==n){e.target=this;const t=n.slice(0);for(let n=0,i=t.length;n<i;n++)t[n].call(this,e);e.target=null}}}const Qt=["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 Jt=1234567;const en=Math.PI/180,tn=180/Math.PI;function nn(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(Qt[255&e]+Qt[e>>8&255]+Qt[e>>16&255]+Qt[e>>24&255]+"-"+Qt[255&t]+Qt[t>>8&255]+"-"+Qt[t>>16&15|64]+Qt[t>>24&255]+"-"+Qt[63&n|128]+Qt[n>>8&255]+"-"+Qt[n>>16&255]+Qt[n>>24&255]+Qt[255&i]+Qt[i>>8&255]+Qt[i>>16&255]+Qt[i>>24&255]).toLowerCase()}function rn(e,t,n){return Math.max(t,Math.min(n,e))}function sn(e,t){return(e%t+t)%t}function an(e,t,n){return(1-n)*e+n*t}function on(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 ln(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 un={DEG2RAD:en,RAD2DEG:tn,generateUUID:nn,clamp:rn,euclideanModulo:sn,mapLinear:function(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)},inverseLerp:function(e,t,n){return e!==t?(n-e)/(t-e):0},lerp:an,damp:function(e,t,n,i){return an(e,t,1-Math.exp(-n*i))},pingpong:function(e,t=1){return t-Math.abs(sn(e,2*t)-t)},smoothstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*(3-2*e)},smootherstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-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&&(Jt=e);let t=Jt+=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*en},radToDeg:function(e){return e*tn},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,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),u=s((t+i)/2),c=a((t+i)/2),h=s((t-i)/2),d=a((t-i)/2),p=s((i-t)/2),f=a((i-t)/2);switch(r){case"XYX":e.set(o*c,l*h,l*d,o*u);break;case"YZY":e.set(l*d,o*c,l*h,o*u);break;case"ZXZ":e.set(l*h,l*d,o*c,o*u);break;case"XZX":e.set(o*c,l*f,l*p,o*u);break;case"YXY":e.set(l*p,o*c,l*f,o*u);break;case"ZYZ":e.set(l*f,l*p,o*c,o*u);break;default:Xt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:ln,denormalize:on};class cn{constructor(e=0,t=0){cn.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,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=rn(this.x,e.x,t.x),this.y=rn(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=rn(this.x,e,t),this.y=rn(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(rn(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(rn(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*n-s*i+e.x,this.y=r*i+s*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class hn{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,r,s,a){let o=n[i+0],l=n[i+1],u=n[i+2],c=n[i+3],h=r[s+0],d=r[s+1],p=r[s+2],f=r[s+3];if(c!==f||o!==h||l!==d||u!==p){let e=o*h+l*d+u*p+c*f;e<0&&(h=-h,d=-d,p=-p,f=-f,e=-e);let t=1-a;if(e<.9995){const n=Math.acos(e),i=Math.sin(n);t=Math.sin(t*n)/i,o=o*t+h*(a=Math.sin(a*n)/i),l=l*t+d*a,u=u*t+p*a,c=c*t+f*a}else{o=o*t+h*a,l=l*t+d*a,u=u*t+p*a,c=c*t+f*a;const e=1/Math.sqrt(o*o+l*l+u*u+c*c);o*=e,l*=e,u*=e,c*=e}}e[t]=o,e[t+1]=l,e[t+2]=u,e[t+3]=c}static multiplyQuaternionsFlat(e,t,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],u=n[i+3],c=r[s],h=r[s+1],d=r[s+2],p=r[s+3];return e[t]=a*p+u*c+o*d-l*h,e[t+1]=o*p+u*h+l*c-a*d,e[t+2]=l*p+u*d+a*h-o*c,e[t+3]=u*p-a*c-o*h-l*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,i=e._y,r=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(n/2),u=a(i/2),c=a(r/2),h=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"YXZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"ZXY":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"ZYX":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"YZX":this._x=h*u*c+l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c-h*d*p;break;case"XZY":this._x=h*u*c-l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c+h*d*p;break;default:Xt("Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],i=t[4],r=t[8],s=t[1],a=t[5],o=t[9],l=t[2],u=t[6],c=t[10],h=n+a+c;if(h>0){const e=.5/Math.sqrt(h+1);this._w=.25/e,this._x=(u-o)*e,this._y=(r-l)*e,this._z=(s-i)*e}else if(n>a&&n>c){const e=2*Math.sqrt(1+n-a-c);this._w=(u-o)/e,this._x=.25*e,this._y=(i+s)/e,this._z=(r+l)/e}else if(a>c){const e=2*Math.sqrt(1+a-n-c);this._w=(r-l)/e,this._x=(i+s)/e,this._y=.25*e,this._z=(o+u)/e}else{const e=2*Math.sqrt(1+c-n-a);this._w=(s-i)/e,this._x=(r+l)/e,this._y=(o+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(rn(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(0===n)return this;const i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 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 n=e._x,i=e._y,r=e._z,s=e._w,a=t._x,o=t._y,l=t._z,u=t._w;return this._x=n*u+s*a+i*l-r*o,this._y=i*u+s*o+r*a-n*l,this._z=r*u+s*l+n*o-i*a,this._w=s*u-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(e,t){let n=e._x,i=e._y,r=e._z,s=e._w,a=this.dot(e);a<0&&(n=-n,i=-i,r=-r,s=-s,a=-a);let o=1-t;if(a<.9995){const e=Math.acos(a),l=Math.sin(e);o=Math.sin(o*e)/l,t=Math.sin(t*e)/l,this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+s*t,this._onChangeCallback()}else this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+s*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(e),i*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 dn{constructor(e=0,t=0,n=0){dn.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return void 0===n&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(fn.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(fn.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=e.elements,s=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,r=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*i-a*n),u=2*(a*t-r*i),c=2*(r*n-s*t);return this.x=t+o*l+s*c-a*u,this.y=n+o*u+a*l-r*c,this.z=i+o*c+r*u-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,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=rn(this.x,e.x,t.x),this.y=rn(this.y,e.y,t.y),this.z=rn(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=rn(this.x,e,t),this.y=rn(this.y,e,t),this.z=rn(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(rn(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,i=e.y,r=e.z,s=t.x,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return pn.copy(this).projectOnVector(e),this.sub(pn)}reflect(e){return this.sub(pn.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 n=this.dot(e)/t;return Math.acos(rn(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,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,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const pn=new dn,fn=new hn;class mn{constructor(e,t,n,i,r,s,a,o,l){mn.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l)}set(e,t,n,i,r,s,a,o,l){const u=this.elements;return u[0]=e,u[1]=i,u[2]=a,u[3]=t,u[4]=r,u[5]=o,u[6]=n,u[7]=s,u[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],u=n[4],c=n[7],h=n[2],d=n[5],p=n[8],f=i[0],m=i[3],g=i[6],_=i[1],v=i[4],y=i[7],b=i[2],x=i[5],T=i[8];return r[0]=s*f+a*_+o*b,r[3]=s*m+a*v+o*x,r[6]=s*g+a*y+o*T,r[1]=l*f+u*_+c*b,r[4]=l*m+u*v+c*x,r[7]=l*g+u*y+c*T,r[2]=h*f+d*_+p*b,r[5]=h*m+d*v+p*x,r[8]=h*g+d*y+p*T,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8];return t*s*u-t*a*l-n*r*u+n*a*o+i*r*l-i*s*o}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=u*s-a*l,h=a*o-u*r,d=l*r-s*o,p=t*c+n*h+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const f=1/p;return e[0]=c*f,e[1]=(i*l-u*n)*f,e[2]=(a*n-i*s)*f,e[3]=h*f,e[4]=(u*t-i*o)*f,e[5]=(i*r-a*t)*f,e[6]=d*f,e[7]=(n*o-l*t)*f,e[8]=(s*t-n*r)*f,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+e,-i*l,i*o,-i*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(gn.makeScale(e,t)),this}rotate(e){return this.premultiply(gn.makeRotation(-e)),this}translate(e,t){return this.premultiply(gn.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const gn=new mn,_n=(new mn).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),vn=(new mn).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function yn(){const e={enabled:!0,workingColorSpace:xt,spaces:{},convert:function(e,t,n){return!1!==this.enabled&&t!==n&&t&&n?(this.spaces[t].transfer===St&&(e.r=xn(e.r),e.g=xn(e.g),e.b=xn(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===St&&(e.r=Tn(e.r),e.g=Tn(e.g),e.b=Tn(e.b)),e):e},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===yt?Tt:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return Yt("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return Yt("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[xt]:{primaries:t,whitePoint:i,transfer:Tt,toXYZ:_n,fromXYZ:vn,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:bt},outputColorSpaceConfig:{drawingBufferColorSpace:bt}},[bt]:{primaries:t,whitePoint:i,transfer:St,toXYZ:_n,fromXYZ:vn,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:bt}}}),e}const bn=yn();function xn(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function Tn(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Sn;class Mn{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{void 0===Sn&&(Sn=Gt("canvas")),Sn.width=e.width,Sn.height=e.height;const t=Sn.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Sn}return n.toDataURL(t)}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=Gt("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e<r.length;e++)r[e]=255*xn(r[e]/255);return n.putImageData(i,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*xn(t[e]/255)):t[e]=xn(t[e]);return{data:t,width:e.width,height:e.height}}return Xt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let En=0;class wn{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:En++}),this.uuid=nn(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):null!==t?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}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 n={uuid:this.uuid,url:""},i=this.data;if(null!==i){let e;if(Array.isArray(i)){e=[];for(let t=0,n=i.length;t<n;t++)i[t].isDataTexture?e.push(An(i[t].image)):e.push(An(i[t]))}else e=An(i);n.url=e}return t||(e.images[this.uuid]=n),n}}function An(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?Mn.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(Xt("Texture: Unable to serialize Texture."),{})}let Rn=0;const Cn=new dn;class Nn extends Zt{constructor(e=Nn.DEFAULT_IMAGE,t=Nn.DEFAULT_MAPPING,n=1001,i=1001,r=1006,s=1008,a=1023,o=fe,l=Nn.DEFAULT_ANISOTROPY,u=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Rn++}),this.uuid=nn(),this.name="",this.source=new wn(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=i,this.magFilter=r,this.minFilter=s,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=o,this.offset=new cn(0,0),this.repeat=new cn(1,1),this.center=new cn(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new mn,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Cn).x}get height(){return this.source.getSize(Cn).y}get depth(){return this.source.getSize(Cn).z}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)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return(new this.constructor).copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(void 0===n){Xt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&n&&i.isVector2&&n.isVector2||i&&n&&i.isVector3&&n.isVector3||i&&n&&i.isMatrix3&&n.isMatrix3?i.copy(n):this[t]=n:Xt(`Texture.setValues(): property '${t}' does not exist.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.textures[this.uuid])return e.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(300!==this.mapping)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case se:e.x=e.x-Math.floor(e.x);break;case ae:e.x=e.x<0?0:1;break;case oe: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 se:e.y=e.y-Math.floor(e.y);break;case ae:e.y=e.y<0?0:1;break;case oe: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)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}Nn.DEFAULT_IMAGE=null,Nn.DEFAULT_MAPPING=300,Nn.DEFAULT_ANISOTROPY=1;class Pn{constructor(e=0,t=0,n=0,i=1){Pn.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=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,n=this.y,i=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*t+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*t+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*t+s[7]*n+s[11]*i+s[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,r;const s=.01,a=.1,o=e.elements,l=o[0],u=o[4],c=o[8],h=o[1],d=o[5],p=o[9],f=o[2],m=o[6],g=o[10];if(Math.abs(u-h)<s&&Math.abs(c-f)<s&&Math.abs(p-m)<s){if(Math.abs(u+h)<a&&Math.abs(c+f)<a&&Math.abs(p+m)<a&&Math.abs(l+d+g-3)<a)return this.set(1,0,0,0),this;t=Math.PI;const e=(l+1)/2,o=(d+1)/2,_=(g+1)/2,v=(u+h)/4,y=(c+f)/4,b=(p+m)/4;return e>o&&e>_?e<s?(n=0,i=.707106781,r=.707106781):(n=Math.sqrt(e),i=v/n,r=y/n):o>_?o<s?(n=.707106781,i=0,r=.707106781):(i=Math.sqrt(o),n=v/i,r=b/i):_<s?(n=.707106781,i=.707106781,r=0):(r=Math.sqrt(_),n=y/r,i=b/r),this.set(n,i,r,t),this}let _=Math.sqrt((m-p)*(m-p)+(c-f)*(c-f)+(h-u)*(h-u));return Math.abs(_)<.001&&(_=1),this.x=(m-p)/_,this.y=(c-f)/_,this.z=(h-u)/_,this.w=Math.acos((l+d+g-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=rn(this.x,e.x,t.x),this.y=rn(this.y,e.y,t.y),this.z=rn(this.z,e.z,t.z),this.w=rn(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=rn(this.x,e,t),this.y=rn(this.y,e,t),this.z=rn(this.z,e,t),this.w=rn(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(rn(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Ln extends Zt{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:he,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Pn(0,0,e,t),this.scissorTest=!1,this.viewport=new Pn(0,0,e,t),this.textures=[];const i={width:e,height:t,depth:n.depth},r=new Nn(i),s=n.count;for(let e=0;e<s;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){const t={minFilter:he,generateMipmaps:!1,flipY:!1,internalFormat:null};void 0!==e.mapping&&(t.mapping=e.mapping),void 0!==e.wrapS&&(t.wrapS=e.wrapS),void 0!==e.wrapT&&(t.wrapT=e.wrapT),void 0!==e.wrapR&&(t.wrapR=e.wrapR),void 0!==e.magFilter&&(t.magFilter=e.magFilter),void 0!==e.minFilter&&(t.minFilter=e.minFilter),void 0!==e.format&&(t.format=e.format),void 0!==e.type&&(t.type=e.type),void 0!==e.anisotropy&&(t.anisotropy=e.anisotropy),void 0!==e.colorSpace&&(t.colorSpace=e.colorSpace),void 0!==e.flipY&&(t.flipY=e.flipY),void 0!==e.generateMipmaps&&(t.generateMipmaps=e.generateMipmaps),void 0!==e.internalFormat&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++){this.textures[e].setValues(t)}}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){null!==this._depthTexture&&(this._depthTexture.renderTarget=null),null!==e&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let i=0,r=this.textures.length;i<r;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=n,!0!==this.textures[i].isData3DTexture&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return(new this.constructor).copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const n=Object.assign({},e.textures[t].image);this.textures[t].source=new wn(n)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,null!==e.depthTexture&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Dn extends Ln{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class In extends Nn{constructor(e=null,t=1,n=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=le,this.minFilter=le,this.wrapR=ae,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class Un extends Nn{constructor(e=null,t=1,n=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=le,this.minFilter=le,this.wrapR=ae,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Fn{constructor(e,t,n,i,r,s,a,o,l,u,c,h,d,p,f,m){Fn.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,n,i,r,s,a,o,l,u,c,h,d,p,f,m)}set(e,t,n,i,r,s,a,o,l,u,c,h,d,p,f,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=u,g[10]=c,g[14]=h,g[3]=d,g[7]=p,g[11]=f,g[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new Fn).fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return 0===this.determinant()?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(0===e.determinant())return this.identity();const t=this.elements,n=e.elements,i=1/On.setFromMatrixColumn(e,0).length(),r=1/On.setFromMatrixColumn(e,1).length(),s=1/On.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*s,t[9]=n[9]*s,t[10]=n[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,i=e.y,r=e.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),u=Math.cos(r),c=Math.sin(r);if("XYZ"===e.order){const e=s*u,n=s*c,i=a*u,r=a*c;t[0]=o*u,t[4]=-o*c,t[8]=l,t[1]=n+i*l,t[5]=e-r*l,t[9]=-a*o,t[2]=r-e*l,t[6]=i+n*l,t[10]=s*o}else if("YXZ"===e.order){const e=o*u,n=o*c,i=l*u,r=l*c;t[0]=e+r*a,t[4]=i*a-n,t[8]=s*l,t[1]=s*c,t[5]=s*u,t[9]=-a,t[2]=n*a-i,t[6]=r+e*a,t[10]=s*o}else if("ZXY"===e.order){const e=o*u,n=o*c,i=l*u,r=l*c;t[0]=e-r*a,t[4]=-s*c,t[8]=i+n*a,t[1]=n+i*a,t[5]=s*u,t[9]=r-e*a,t[2]=-s*l,t[6]=a,t[10]=s*o}else if("ZYX"===e.order){const e=s*u,n=s*c,i=a*u,r=a*c;t[0]=o*u,t[4]=i*l-n,t[8]=e*l+r,t[1]=o*c,t[5]=r*l+e,t[9]=n*l-i,t[2]=-l,t[6]=a*o,t[10]=s*o}else if("YZX"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*u,t[4]=r-e*c,t[8]=i*c+n,t[1]=c,t[5]=s*u,t[9]=-a*u,t[2]=-l*u,t[6]=n*c+i,t[10]=e-r*c}else if("XZY"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*u,t[4]=-c,t[8]=l*u,t[1]=e*c+r,t[5]=s*u,t[9]=n*c-i,t[2]=i*c-n,t[6]=a*u,t[10]=r*c+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(kn,e,zn)}lookAt(e,t,n){const i=this.elements;return Hn.subVectors(e,t),0===Hn.lengthSq()&&(Hn.z=1),Hn.normalize(),Vn.crossVectors(n,Hn),0===Vn.lengthSq()&&(1===Math.abs(n.z)?Hn.x+=1e-4:Hn.z+=1e-4,Hn.normalize(),Vn.crossVectors(n,Hn)),Vn.normalize(),Gn.crossVectors(Hn,Vn),i[0]=Vn.x,i[4]=Gn.x,i[8]=Hn.x,i[1]=Vn.y,i[5]=Gn.y,i[9]=Hn.y,i[2]=Vn.z,i[6]=Gn.z,i[10]=Hn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],u=n[1],c=n[5],h=n[9],d=n[13],p=n[2],f=n[6],m=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=i[0],T=i[4],S=i[8],M=i[12],E=i[1],w=i[5],A=i[9],R=i[13],C=i[2],N=i[6],P=i[10],L=i[14],D=i[3],I=i[7],U=i[11],F=i[15];return r[0]=s*x+a*E+o*C+l*D,r[4]=s*T+a*w+o*N+l*I,r[8]=s*S+a*A+o*P+l*U,r[12]=s*M+a*R+o*L+l*F,r[1]=u*x+c*E+h*C+d*D,r[5]=u*T+c*w+h*N+d*I,r[9]=u*S+c*A+h*P+d*U,r[13]=u*M+c*R+h*L+d*F,r[2]=p*x+f*E+m*C+g*D,r[6]=p*T+f*w+m*N+g*I,r[10]=p*S+f*A+m*P+g*U,r[14]=p*M+f*R+m*L+g*F,r[3]=_*x+v*E+y*C+b*D,r[7]=_*T+v*w+y*N+b*I,r[11]=_*S+v*A+y*P+b*U,r[15]=_*M+v*R+y*L+b*F,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],i=e[8],r=e[12],s=e[1],a=e[5],o=e[9],l=e[13],u=e[2],c=e[6],h=e[10],d=e[14],p=e[3],f=e[7],m=e[11],g=e[15],_=o*d-l*h,v=a*d-l*c,y=a*h-o*c,b=s*d-l*u,x=s*h-o*u,T=s*c-a*u;return t*(f*_-m*v+g*y)-n*(p*_-m*b+g*x)+i*(p*v-f*b+g*T)-r*(p*y-f*x+m*T)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],d=e[11],p=e[12],f=e[13],m=e[14],g=e[15],_=t*a-n*s,v=t*o-i*s,y=t*l-r*s,b=n*o-i*a,x=n*l-r*a,T=i*l-r*o,S=u*f-c*p,M=u*m-h*p,E=u*g-d*p,w=c*m-h*f,A=c*g-d*f,R=h*g-d*m,C=_*R-v*A+y*w+b*E-x*M+T*S;if(0===C)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const N=1/C;return e[0]=(a*R-o*A+l*w)*N,e[1]=(i*A-n*R-r*w)*N,e[2]=(f*T-m*x+g*b)*N,e[3]=(h*x-c*T-d*b)*N,e[4]=(o*E-s*R-l*M)*N,e[5]=(t*R-i*E+r*M)*N,e[6]=(m*y-p*T-g*v)*N,e[7]=(u*T-h*y+d*v)*N,e[8]=(s*A-a*E+l*S)*N,e[9]=(n*E-t*A-r*S)*N,e[10]=(p*x-f*y+g*_)*N,e[11]=(c*y-u*x-d*_)*N,e[12]=(a*M-s*w-o*S)*N,e[13]=(t*w-n*M+i*S)*N,e[14]=(f*v-p*b-m*_)*N,e[15]=(u*b-c*v+h*_)*N,this}scale(e){const t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),i=Math.sin(t),r=1-n,s=e.x,a=e.y,o=e.z,l=r*s,u=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,u*a+n,u*o-i*s,0,l*o-i*a,u*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,r,s){return this.set(1,n,r,0,e,1,s,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,r=t._x,s=t._y,a=t._z,o=t._w,l=r+r,u=s+s,c=a+a,h=r*l,d=r*u,p=r*c,f=s*u,m=s*c,g=a*c,_=o*l,v=o*u,y=o*c,b=n.x,x=n.y,T=n.z;return i[0]=(1-(f+g))*b,i[1]=(d+y)*b,i[2]=(p-v)*b,i[3]=0,i[4]=(d-y)*x,i[5]=(1-(h+g))*x,i[6]=(m+_)*x,i[7]=0,i[8]=(p+v)*T,i[9]=(m-_)*T,i[10]=(1-(h+f))*T,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){const i=this.elements;e.x=i[12],e.y=i[13],e.z=i[14];const r=this.determinant();if(0===r)return n.set(1,1,1),t.identity(),this;let s=On.set(i[0],i[1],i[2]).length();const a=On.set(i[4],i[5],i[6]).length(),o=On.set(i[8],i[9],i[10]).length();r<0&&(s=-s),Bn.copy(this);const l=1/s,u=1/a,c=1/o;return Bn.elements[0]*=l,Bn.elements[1]*=l,Bn.elements[2]*=l,Bn.elements[4]*=u,Bn.elements[5]*=u,Bn.elements[6]*=u,Bn.elements[8]*=c,Bn.elements[9]*=c,Bn.elements[10]*=c,t.setFromRotationMatrix(Bn),n.x=s,n.y=a,n.z=o,this}makePerspective(e,t,n,i,r,s,a=2e3,o=!1){const l=this.elements,u=2*r/(t-e),c=2*r/(n-i),h=(t+e)/(t-e),d=(n+i)/(n-i);let p,f;if(o)p=r/(s-r),f=s*r/(s-r);else if(a===Ft)p=-(s+r)/(s-r),f=-2*s*r/(s-r);else{if(a!==Ot)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);p=-s/(s-r),f=-s*r/(s-r)}return l[0]=u,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=c,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,i,r,s,a=2e3,o=!1){const l=this.elements,u=2/(t-e),c=2/(n-i),h=-(t+e)/(t-e),d=-(n+i)/(n-i);let p,f;if(o)p=1/(s-r),f=s/(s-r);else if(a===Ft)p=-2/(s-r),f=-(s+r)/(s-r);else{if(a!==Ot)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=-1/(s-r),f=-r/(s-r)}return l[0]=u,l[4]=0,l[8]=0,l[12]=h,l[1]=0,l[5]=c,l[9]=0,l[13]=d,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const On=new dn,Bn=new Fn,kn=new dn(0,0,0),zn=new dn(1,1,1),Vn=new dn,Gn=new dn,Hn=new dn,jn=new Fn,Wn=new hn;class $n{constructor(e=0,t=0,n=0,i=$n.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const i=e.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],u=i[9],c=i[2],h=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(rn(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-rn(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-c,r),this._z=0);break;case"ZXY":this._x=Math.asin(rn(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-rn(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(h,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(rn(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,l),this._y=Math.atan2(-c,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-rn(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-u,d),this._y=0);break;default:Xt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return jn.makeRotationFromQuaternion(e),this.setFromRotationMatrix(jn,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Wn.setFromEuler(this),this.setFromQuaternion(Wn,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}}$n.DEFAULT_ORDER="XYZ";class Xn{constructor(){this.mask=1}set(e){this.mask=1<<e>>>0}enable(e){this.mask|=1<<e}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e}disable(e){this.mask&=~(1<<e)}disableAll(){this.mask=0}test(e){return 0!==(this.mask&e.mask)}isEnabled(e){return!!(this.mask&1<<e)}}let qn=0;const Yn=new dn,Kn=new hn,Zn=new Fn,Qn=new dn,Jn=new dn,ei=new dn,ti=new hn,ni=new dn(1,0,0),ii=new dn(0,1,0),ri=new dn(0,0,1),si={type:"added"},ai={type:"removed"},oi={type:"childadded",child:null},li={type:"childremoved",child:null};class ui extends Zt{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:qn++}),this.uuid=nn(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=ui.DEFAULT_UP.clone();const e=new dn,t=new $n,n=new hn,i=new dn(1,1,1);t._onChange(function(){n.setFromEuler(t,!1)}),n._onChange(function(){t.setFromQuaternion(n,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:n},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new Fn},normalMatrix:{value:new mn}}),this.matrix=new Fn,this.matrixWorld=new Fn,this.matrixAutoUpdate=ui.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=ui.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Xn,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Kn.setFromAxisAngle(e,t),this.quaternion.multiply(Kn),this}rotateOnWorldAxis(e,t){return Kn.setFromAxisAngle(e,t),this.quaternion.premultiply(Kn),this}rotateX(e){return this.rotateOnAxis(ni,e)}rotateY(e){return this.rotateOnAxis(ii,e)}rotateZ(e){return this.rotateOnAxis(ri,e)}translateOnAxis(e,t){return Yn.copy(e).applyQuaternion(this.quaternion),this.position.add(Yn.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(ni,e)}translateY(e){return this.translateOnAxis(ii,e)}translateZ(e){return this.translateOnAxis(ri,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Zn.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Qn.copy(e):Qn.set(e,t,n);const i=this.parent;this.updateWorldMatrix(!0,!1),Jn.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Zn.lookAt(Jn,Qn,this.up):Zn.lookAt(Qn,Jn,this.up),this.quaternion.setFromRotationMatrix(Zn),i&&(Zn.extractRotation(i.matrixWorld),Kn.setFromRotationMatrix(Zn),this.quaternion.premultiply(Kn.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(qt("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(si),oi.child=e,this.dispatchEvent(oi),oi.child=null):qt("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(ai),li.child=e,this.dispatchEvent(li),li.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),Zn.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),Zn.multiply(e.parent.matrixWorld)),e.applyMatrix4(Zn),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(si),oi.child=e,this.dispatchEvent(oi),oi.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,i=this.children.length;n<i;n++){const i=this.children[n].getObjectByProperty(e,t);if(void 0!==i)return i}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const i=this.children;for(let r=0,s=i.length;r<s;r++)i[r].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Jn,e,ei),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Jn,ti,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverse(e)}traverseVisible(e){if(!1===this.visible)return;e(this);const t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;null!==t&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(null!==e){const t=e.x,n=e.y,i=e.z,r=this.matrix.elements;r[12]+=t-r[0]*t-r[4]*n-r[8]*i,r[13]+=n-r[1]*t-r[5]*n-r[9]*i,r[14]+=i-r[2]*t-r[6]*n-r[10]*i}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,i=t.length;n<i;n++){t[n].updateMatrixWorld(e)}}updateWorldMatrix(e,t){const n=this.parent;if(!0===e&&null!==n&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),!0===t){const e=this.children;for(let t=0,n=e.length;t<n;t++){e[t].updateWorldMatrix(!1,!0)}}}toJSON(e){const t=void 0===e||"string"==typeof e,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};function r(t,n){return void 0===t[n.uuid]&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),!0===this.castShadow&&(i.castShadow=!0),!0===this.receiveShadow&&(i.receiveShadow=!0),!1===this.visible&&(i.visible=!1),!1===this.frustumCulled&&(i.frustumCulled=!1),0!==this.renderOrder&&(i.renderOrder=this.renderOrder),!1!==this.static&&(i.static=this.static),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),null!==this.pivot&&(i.pivot=this.pivot.toArray()),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),void 0!==this.morphTargetDictionary&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),void 0!==this.morphTargetInfluences&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(e=>({...e})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(i.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const n=t.shapes;if(Array.isArray(n))for(let t=0,i=n.length;t<i;t++){const i=n[t];r(e.shapes,i)}else r(e.shapes,n)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const t=[];for(let n=0,i=this.material.length;n<i;n++)t.push(r(e.materials,this.material[n]));i.material=t}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let t=0;t<this.children.length;t++)i.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let t=0;t<this.animations.length;t++){const n=this.animations[t];i.animations.push(r(e.animations,n))}}if(t){const t=s(e.geometries),i=s(e.materials),r=s(e.textures),a=s(e.images),o=s(e.shapes),l=s(e.skeletons),u=s(e.animations),c=s(e.nodes);t.length>0&&(n.geometries=t),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),u.length>0&&(n.animations=u),c.length>0&&(n.nodes=c)}return n.object=i,n;function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),null!==e.pivot&&(this.pivot=e.pivot.clone()),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t<e.children.length;t++){const n=e.children[t];this.add(n.clone())}return this}}ui.DEFAULT_UP=new dn(0,1,0),ui.DEFAULT_MATRIX_AUTO_UPDATE=!0,ui.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;let ci=class extends ui{constructor(){super(),this.isGroup=!0,this.type="Group"}};const hi={type:"move"};class di{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new ci,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 ci,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new dn,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new dn),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new ci,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new dn,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new dn),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 n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),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,n){let i=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 i of e.hand.values()){const e=t.getJointPose(i,n),r=this._getHandJoint(l,i);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 i=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],a=i.position.distanceTo(r.position),o=.02,u=.005;l.inputState.pinching&&a>o+u?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-u&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),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&&(i=t.getPose(e.targetRaySpace,n),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(hi)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const n=new ci;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}const pi={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},fi={h:0,s:0,l:0},mi={h:0,s:0,l:0};function gi(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}class _i{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(void 0===t&&void 0===n){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,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=bt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,bn.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=bn.workingColorSpace){return this.r=e,this.g=t,this.b=n,bn.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=bn.workingColorSpace){if(e=sn(e,1),t=rn(t,0,1),n=rn(n,0,1),0===t)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+t):n+t-n*t,r=2*n-i;this.r=gi(r,i,e+1/3),this.g=gi(r,i,e),this.b=gi(r,i,e-1/3)}return bn.colorSpaceToWorking(this,i),this}setStyle(e,t=bt){function n(t){void 0!==t&&parseFloat(t)<1&&Xt("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=i[1],a=i[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 n(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 n(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 n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Xt("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(n,16),t);Xt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=bt){const n=pi[e.toLowerCase()];return void 0!==n?this.setHex(n,t):Xt("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=xn(e.r),this.g=xn(e.g),this.b=xn(e.b),this}copyLinearToSRGB(e){return this.r=Tn(e.r),this.g=Tn(e.g),this.b=Tn(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=bt){return bn.workingToColorSpace(vi.copy(this),e),65536*Math.round(rn(255*vi.r,0,255))+256*Math.round(rn(255*vi.g,0,255))+Math.round(rn(255*vi.b,0,255))}getHexString(e=bt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=bn.workingColorSpace){bn.workingToColorSpace(vi.copy(this),t);const n=vi.r,i=vi.g,r=vi.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const u=(a+s)/2;if(a===s)o=0,l=0;else{const e=s-a;switch(l=u<=.5?e/(s+a):e/(2-s-a),s){case n:o=(i-r)/e+(i<r?6:0);break;case i:o=(r-n)/e+2;break;case r:o=(n-i)/e+4}o/=6}return e.h=o,e.s=l,e.l=u,e}getRGB(e,t=bn.workingColorSpace){return bn.workingToColorSpace(vi.copy(this),t),e.r=vi.r,e.g=vi.g,e.b=vi.b,e}getStyle(e=bt){bn.workingToColorSpace(vi.copy(this),e);const t=vi.r,n=vi.g,i=vi.b;return e!==bt?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(255*t)},${Math.round(255*n)},${Math.round(255*i)})`}offsetHSL(e,t,n){return this.getHSL(fi),this.setHSL(fi.h+e,fi.s+t,fi.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(fi),e.getHSL(mi);const n=an(fi.h,mi.h,t),i=an(fi.s,mi.s,t),r=an(fi.l,mi.l,t);return this.setHSL(n,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*i,this.g=r[1]*t+r[4]*n+r[7]*i,this.b=r[2]*t+r[5]*n+r[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const vi=new _i;_i.NAMES=pi;class yi extends ui{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 $n,this.environmentIntensity=1,this.environmentRotation=new $n,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__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}}const bi=new dn,xi=new dn,Ti=new dn,Si=new dn,Mi=new dn,Ei=new dn,wi=new dn,Ai=new dn,Ri=new dn,Ci=new dn,Ni=new Pn,Pi=new Pn,Li=new Pn;class Di{constructor(e=new dn,t=new dn,n=new dn){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),bi.subVectors(e,t),i.cross(bi);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){bi.subVectors(i,t),xi.subVectors(n,t),Ti.subVectors(e,t);const s=bi.dot(bi),a=bi.dot(xi),o=bi.dot(Ti),l=xi.dot(xi),u=xi.dot(Ti),c=s*l-a*a;if(0===c)return r.set(0,0,0),null;const h=1/c,d=(l*o-a*u)*h,p=(s*u-a*o)*h;return r.set(1-d-p,p,d)}static containsPoint(e,t,n,i){return null!==this.getBarycoord(e,t,n,i,Si)&&(Si.x>=0&&Si.y>=0&&Si.x+Si.y<=1)}static getInterpolation(e,t,n,i,r,s,a,o){return null===this.getBarycoord(e,t,n,i,Si)?(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,Si.x),o.addScaledVector(s,Si.y),o.addScaledVector(a,Si.z),o)}static getInterpolatedAttribute(e,t,n,i,r,s){return Ni.setScalar(0),Pi.setScalar(0),Li.setScalar(0),Ni.fromBufferAttribute(e,t),Pi.fromBufferAttribute(e,n),Li.fromBufferAttribute(e,i),s.setScalar(0),s.addScaledVector(Ni,r.x),s.addScaledVector(Pi,r.y),s.addScaledVector(Li,r.z),s}static isFrontFacing(e,t,n,i){return bi.subVectors(n,t),xi.subVectors(e,t),bi.cross(xi).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return bi.subVectors(this.c,this.b),xi.subVectors(this.a,this.b),.5*bi.cross(xi).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Di.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Di.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return Di.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return Di.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Di.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,r=this.c;let s,a;Mi.subVectors(i,n),Ei.subVectors(r,n),Ai.subVectors(e,n);const o=Mi.dot(Ai),l=Ei.dot(Ai);if(o<=0&&l<=0)return t.copy(n);Ri.subVectors(e,i);const u=Mi.dot(Ri),c=Ei.dot(Ri);if(u>=0&&c<=u)return t.copy(i);const h=o*c-u*l;if(h<=0&&o>=0&&u<=0)return s=o/(o-u),t.copy(n).addScaledVector(Mi,s);Ci.subVectors(e,r);const d=Mi.dot(Ci),p=Ei.dot(Ci);if(p>=0&&d<=p)return t.copy(r);const f=d*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(n).addScaledVector(Ei,a);const m=u*p-d*c;if(m<=0&&c-u>=0&&d-p>=0)return wi.subVectors(r,i),a=(c-u)/(c-u+(d-p)),t.copy(i).addScaledVector(wi,a);const g=1/(m+f+h);return s=f*g,a=h*g,t.copy(n).addScaledVector(Mi,s).addScaledVector(Ei,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class Ii{constructor(e=new dn(1/0,1/0,1/0),t=new dn(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Fi.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Fi.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=Fi.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return(new this.constructor).copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(void 0!==n){const i=n.getAttribute("position");if(!0===t&&void 0!==i&&!0!==e.isInstancedMesh)for(let t=0,n=i.count;t<n;t++)!0===e.isMesh?e.getVertexPosition(t,Fi):Fi.fromBufferAttribute(i,t),Fi.applyMatrix4(e.matrixWorld),this.expandByPoint(Fi);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),Oi.copy(e.boundingBox)):(null===n.boundingBox&&n.computeBoundingBox(),Oi.copy(n.boundingBox)),Oi.applyMatrix4(e.matrixWorld),this.union(Oi)}const i=e.children;for(let e=0,n=i.length;e<n;e++)this.expandByObject(i[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,Fi),Fi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(ji),Wi.subVectors(this.max,ji),Bi.subVectors(e.a,ji),ki.subVectors(e.b,ji),zi.subVectors(e.c,ji),Vi.subVectors(ki,Bi),Gi.subVectors(zi,ki),Hi.subVectors(Bi,zi);let t=[0,-Vi.z,Vi.y,0,-Gi.z,Gi.y,0,-Hi.z,Hi.y,Vi.z,0,-Vi.x,Gi.z,0,-Gi.x,Hi.z,0,-Hi.x,-Vi.y,Vi.x,0,-Gi.y,Gi.x,0,-Hi.y,Hi.x,0];return!!qi(t,Bi,ki,zi,Wi)&&(t=[1,0,0,0,1,0,0,0,1],!!qi(t,Bi,ki,zi,Wi)&&($i.crossVectors(Vi,Gi),t=[$i.x,$i.y,$i.z],qi(t,Bi,ki,zi,Wi)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Fi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Fi).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()||(Ui[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ui[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ui[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ui[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ui[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ui[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ui[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ui[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ui)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Ui=[new dn,new dn,new dn,new dn,new dn,new dn,new dn,new dn],Fi=new dn,Oi=new Ii,Bi=new dn,ki=new dn,zi=new dn,Vi=new dn,Gi=new dn,Hi=new dn,ji=new dn,Wi=new dn,$i=new dn,Xi=new dn;function qi(e,t,n,i,r){for(let s=0,a=e.length-3;s<=a;s+=3){Xi.fromArray(e,s);const a=r.x*Math.abs(Xi.x)+r.y*Math.abs(Xi.y)+r.z*Math.abs(Xi.z),o=t.dot(Xi),l=n.dot(Xi),u=i.dot(Xi);if(Math.max(-Math.max(o,l,u),Math.min(o,l,u))>a)return!1}return!0}const Yi=Ki();function Ki(){const e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[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,n=0;for(;!(8388608&t);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,s[e]=t|n}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:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function Zi(e){Math.abs(e)>65504&&Xt("DataUtils.toHalfFloat(): Value out of range."),e=rn(e,-65504,65504),Yi.floatView[0]=e;const t=Yi.uint32View[0],n=t>>23&511;return Yi.baseTable[n]+((8388607&t)>>Yi.shiftTable[n])}function Qi(e){const t=e>>10;return Yi.uint32View[0]=Yi.mantissaTable[Yi.offsetTable[t]+(1023&e)]+Yi.exponentTable[t],Yi.floatView[0]}const Ji=new dn,er=new cn;let tr=0;class nr{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:tr++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=n,this.usage=Dt,this.updateRanges=[],this.gpuType=be,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,r=this.itemSize;i<r;i++)this.array[e+i]=t.array[n+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(2===this.itemSize)for(let t=0,n=this.count;t<n;t++)er.fromBufferAttribute(this,t),er.applyMatrix3(e),this.setXY(t,er.x,er.y);else if(3===this.itemSize)for(let t=0,n=this.count;t<n;t++)Ji.fromBufferAttribute(this,t),Ji.applyMatrix3(e),this.setXYZ(t,Ji.x,Ji.y,Ji.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Ji.fromBufferAttribute(this,t),Ji.applyMatrix4(e),this.setXYZ(t,Ji.x,Ji.y,Ji.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Ji.fromBufferAttribute(this,t),Ji.applyNormalMatrix(e),this.setXYZ(t,Ji.x,Ji.y,Ji.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Ji.fromBufferAttribute(this,t),Ji.transformDirection(e),this.setXYZ(t,Ji.x,Ji.y,Ji.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=on(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ln(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=on(t,this.array)),t}setX(e,t){return this.normalized&&(t=ln(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=on(t,this.array)),t}setY(e,t){return this.normalized&&(t=ln(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=on(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ln(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=on(t,this.array)),t}setW(e,t){return this.normalized&&(t=ln(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=ln(t,this.array),n=ln(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=ln(t,this.array),n=ln(n,this.array),i=ln(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this}setXYZW(e,t,n,i,r){return e*=this.itemSize,this.normalized&&(t=ln(t,this.array),n=ln(n,this.array),i=ln(i,this.array),r=ln(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,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!==Dt&&(e.usage=this.usage),e}}class ir extends nr{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class rr extends nr{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class sr extends nr{constructor(e,t,n){super(new Uint16Array(e),t,n),this.isFloat16BufferAttribute=!0}getX(e){let t=Qi(this.array[e*this.itemSize]);return this.normalized&&(t=on(t,this.array)),t}setX(e,t){return this.normalized&&(t=ln(t,this.array)),this.array[e*this.itemSize]=Zi(t),this}getY(e){let t=Qi(this.array[e*this.itemSize+1]);return this.normalized&&(t=on(t,this.array)),t}setY(e,t){return this.normalized&&(t=ln(t,this.array)),this.array[e*this.itemSize+1]=Zi(t),this}getZ(e){let t=Qi(this.array[e*this.itemSize+2]);return this.normalized&&(t=on(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ln(t,this.array)),this.array[e*this.itemSize+2]=Zi(t),this}getW(e){let t=Qi(this.array[e*this.itemSize+3]);return this.normalized&&(t=on(t,this.array)),t}setW(e,t){return this.normalized&&(t=ln(t,this.array)),this.array[e*this.itemSize+3]=Zi(t),this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=ln(t,this.array),n=ln(n,this.array)),this.array[e+0]=Zi(t),this.array[e+1]=Zi(n),this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=ln(t,this.array),n=ln(n,this.array),i=ln(i,this.array)),this.array[e+0]=Zi(t),this.array[e+1]=Zi(n),this.array[e+2]=Zi(i),this}setXYZW(e,t,n,i,r){return e*=this.itemSize,this.normalized&&(t=ln(t,this.array),n=ln(n,this.array),i=ln(i,this.array),r=ln(r,this.array)),this.array[e+0]=Zi(t),this.array[e+1]=Zi(n),this.array[e+2]=Zi(i),this.array[e+3]=Zi(r),this}}class ar extends nr{constructor(e,t,n){super(new Float32Array(e),t,n)}}const or=new Ii,lr=new dn,ur=new dn;class cr{constructor(e=new dn,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;void 0!==t?n.copy(t):or.setFromPoints(e).getCenter(n);let i=0;for(let t=0,r=e.length;t<r;t++)i=Math.max(i,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;lr.subVectors(e,this.center);const t=lr.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector(lr,n/e),this.radius+=n}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):(ur.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(lr.copy(e.center).add(ur)),this.expandByPoint(lr.copy(e.center).sub(ur))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}let hr=0;const dr=new Fn,pr=new ui,fr=new dn,mr=new Ii,gr=new Ii,_r=new dn;class vr extends Zt{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:hr++}),this.uuid=nn(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(function(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}(e)?rr:ir)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return void 0!==this.attributes[e]}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(void 0!==n){const t=(new mn).getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(e),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return dr.makeRotationFromQuaternion(e),this.applyMatrix4(dr),this}rotateX(e){return dr.makeRotationX(e),this.applyMatrix4(dr),this}rotateY(e){return dr.makeRotationY(e),this.applyMatrix4(dr),this}rotateZ(e){return dr.makeRotationZ(e),this.applyMatrix4(dr),this}translate(e,t,n){return dr.makeTranslation(e,t,n),this.applyMatrix4(dr),this}scale(e,t,n){return dr.makeScale(e,t,n),this.applyMatrix4(dr),this}lookAt(e){return pr.lookAt(e),pr.updateMatrix(),this.applyMatrix4(pr.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(fr).negate(),this.translate(fr.x,fr.y,fr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(void 0===t){const t=[];for(let n=0,i=e.length;n<i;n++){const i=e[n];t.push(i.x,i.y,i.z||0)}this.setAttribute("position",new ar(t,3))}else{const n=Math.min(e.length,t.count);for(let i=0;i<n;i++){const n=e[i];t.setXYZ(i,n.x,n.y,n.z||0)}e.length>t.count&&Xt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Ii);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return qt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new dn(-1/0,-1/0,-1/0),new dn(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){const n=t[e];mr.setFromBufferAttribute(n),this.morphTargetsRelative?(_r.addVectors(this.boundingBox.min,mr.min),this.boundingBox.expandByPoint(_r),_r.addVectors(this.boundingBox.max,mr.max),this.boundingBox.expandByPoint(_r)):(this.boundingBox.expandByPoint(mr.min),this.boundingBox.expandByPoint(mr.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&qt('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 cr);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return qt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new dn,1/0);if(e){const n=this.boundingSphere.center;if(mr.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){const n=t[e];gr.setFromBufferAttribute(n),this.morphTargetsRelative?(_r.addVectors(mr.min,gr.min),mr.expandByPoint(_r),_r.addVectors(mr.max,gr.max),mr.expandByPoint(_r)):(mr.expandByPoint(gr.min),mr.expandByPoint(gr.max))}mr.getCenter(n);let i=0;for(let t=0,r=e.count;t<r;t++)_r.fromBufferAttribute(e,t),i=Math.max(i,n.distanceToSquared(_r));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++)_r.fromBufferAttribute(s,t),a&&(fr.fromBufferAttribute(e,t),_r.add(fr)),i=Math.max(i,n.distanceToSquared(_r))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&qt('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 qt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const n=t.position,i=t.normal,r=t.uv;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new nr(new Float32Array(4*n.count),4));const s=this.getAttribute("tangent"),a=[],o=[];for(let e=0;e<n.count;e++)a[e]=new dn,o[e]=new dn;const l=new dn,u=new dn,c=new dn,h=new cn,d=new cn,p=new cn,f=new dn,m=new dn;function g(e,t,i){l.fromBufferAttribute(n,e),u.fromBufferAttribute(n,t),c.fromBufferAttribute(n,i),h.fromBufferAttribute(r,e),d.fromBufferAttribute(r,t),p.fromBufferAttribute(r,i),u.sub(l),c.sub(l),d.sub(h),p.sub(h);const s=1/(d.x*p.y-p.x*d.y);isFinite(s)&&(f.copy(u).multiplyScalar(p.y).addScaledVector(c,-d.y).multiplyScalar(s),m.copy(c).multiplyScalar(d.x).addScaledVector(u,-p.x).multiplyScalar(s),a[e].add(f),a[t].add(f),a[i].add(f),o[e].add(m),o[t].add(m),o[i].add(m))}let _=this.groups;0===_.length&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){const n=_[t],i=n.start;for(let t=i,r=i+n.count;t<r;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}const v=new dn,y=new dn,b=new dn,x=new dn;function T(e){b.fromBufferAttribute(i,e),x.copy(b);const t=a[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);const n=y.dot(o[e])<0?-1:1;s.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){const n=_[t],i=n.start;for(let t=i,r=i+n.count;t<r;t+=3)T(e.getX(t+0)),T(e.getX(t+1)),T(e.getX(t+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(void 0!==t){let n=this.getAttribute("normal");if(void 0===n)n=new nr(new Float32Array(3*t.count),3),this.setAttribute("normal",n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);const i=new dn,r=new dn,s=new dn,a=new dn,o=new dn,l=new dn,u=new dn,c=new dn;if(e)for(let h=0,d=e.count;h<d;h+=3){const d=e.getX(h+0),p=e.getX(h+1),f=e.getX(h+2);i.fromBufferAttribute(t,d),r.fromBufferAttribute(t,p),s.fromBufferAttribute(t,f),u.subVectors(s,r),c.subVectors(i,r),u.cross(c),a.fromBufferAttribute(n,d),o.fromBufferAttribute(n,p),l.fromBufferAttribute(n,f),a.add(u),o.add(u),l.add(u),n.setXYZ(d,a.x,a.y,a.z),n.setXYZ(p,o.x,o.y,o.z),n.setXYZ(f,l.x,l.y,l.z)}else for(let e=0,a=t.count;e<a;e+=3)i.fromBufferAttribute(t,e+0),r.fromBufferAttribute(t,e+1),s.fromBufferAttribute(t,e+2),u.subVectors(s,r),c.subVectors(i,r),u.cross(c),n.setXYZ(e+0,u.x,u.y,u.z),n.setXYZ(e+1,u.x,u.y,u.z),n.setXYZ(e+2,u.x,u.y,u.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)_r.fromBufferAttribute(e,t),_r.normalize(),e.setXYZ(t,_r.x,_r.y,_r.z)}toNonIndexed(){function e(e,t){const n=e.array,i=e.itemSize,r=e.normalized,s=new n.constructor(t.length*i);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]*i;for(let e=0;e<i;e++)s[o++]=n[a++]}return new nr(s,i,r)}if(null===this.index)return Xt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new vr,n=this.index.array,i=this.attributes;for(const r in i){const s=e(i[r],n);t.setAttribute(r,s)}const r=this.morphAttributes;for(const i in r){const s=[],a=r[i];for(let t=0,i=a.length;t<i;t++){const i=e(a[t],n);s.push(i)}t.morphAttributes[i]=s}t.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let e=0,n=s.length;e<n;e++){const n=s[e];t.addGroup(n.start,n.count,n.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,""!==this.name&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const n in t)void 0!==t[n]&&(e[n]=t[n]);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 n=this.attributes;for(const t in n){const i=n[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const n=this.morphAttributes[t],s=[];for(let t=0,i=n.length;t<i;t++){const i=n[t];s.push(i.toJSON(e.data))}s.length>0&&(i[t]=s,r=!0)}r&&(e.data.morphAttributes=i,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=a.toJSON()),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;null!==n&&this.setIndex(n.clone());const i=e.attributes;for(const e in i){const n=i[e];this.setAttribute(e,n.clone(t))}const r=e.morphAttributes;for(const e in r){const n=[],i=r[e];for(let e=0,r=i.length;e<r;e++)n.push(i[e].clone(t));this.morphAttributes[e]=n}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"})}}class yr{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Dt,this.updateRanges=[],this.version=0,this.uuid=nn()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,r=this.stride;i<r;i++)this.array[e+i]=t.array[n+i];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=nn()),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]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}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=nn()),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 br=new dn;class xr{constructor(e,t,n,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)br.fromBufferAttribute(this,t),br.applyMatrix4(e),this.setXYZ(t,br.x,br.y,br.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)br.fromBufferAttribute(this,t),br.applyNormalMatrix(e),this.setXYZ(t,br.x,br.y,br.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)br.fromBufferAttribute(this,t),br.transformDirection(e),this.setXYZ(t,br.x,br.y,br.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=on(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ln(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=ln(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=ln(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=ln(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=ln(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=on(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=on(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=on(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=on(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=ln(t,this.array),n=ln(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=ln(t,this.array),n=ln(n,this.array),i=ln(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this}setXYZW(e,t,n,i,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=ln(t,this.array),n=ln(n,this.array),i=ln(i,this.array),r=ln(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this.data.array[e+3]=r,this}clone(e){if(void 0===e){Wt("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return new nr(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 xr(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){Wt("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}return 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}}}let Tr=0;class Sr extends Zt{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Tr++}),this.uuid=nn(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=E,this.blendDst=w,this.blendEquation=v,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new _i(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Mt,this.stencilZFail=Mt,this.stencilZPass=Mt,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const n=e[t];if(void 0===n){Xt(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n:Xt(`Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),void 0!==this.dispersion&&(n.dispersion=this.dispersion),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==E&&(n.blendSrc=this.blendSrc),this.blendDst!==w&&(n.blendDst=this.blendDst),this.blendEquation!==v&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Mt&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Mt&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Mt&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!1===this.allowOverride&&(n.allowOverride=!1),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(n.textures=t),r.length>0&&(n.images=r)}return n}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(null!==t){const e=t.length;n=new Array(e);for(let i=0;i!==e;++i)n[i]=t[i].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}class Mr extends Sr{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new _i(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const Er=new dn,wr=new dn,Ar=new dn,Rr=new dn,Cr=new dn,Nr=new dn,Pr=new dn;class Lr{constructor(e=new dn,t=new dn(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,Er)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Er.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Er.copy(this.origin).addScaledVector(this.direction,t),Er.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){wr.copy(e).add(t).multiplyScalar(.5),Ar.copy(t).sub(e).normalize(),Rr.copy(this.origin).sub(wr);const r=.5*e.distanceTo(t),s=-this.direction.dot(Ar),a=Rr.dot(this.direction),o=-Rr.dot(Ar),l=Rr.lengthSq(),u=Math.abs(1-s*s);let c,h,d,p;if(u>0)if(c=s*o-a,h=s*a-o,p=r*u,c>=0)if(h>=-p)if(h<=p){const e=1/u;c*=e,h*=e,d=c*(c+s*h+2*a)+h*(s*c+h+2*o)+l}else h=r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h=-r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h<=-p?(c=Math.max(0,-(-s*r+a)),h=c>0?-r:Math.min(Math.max(-r,-o),r),d=-c*c+h*(h+2*o)+l):h<=p?(c=0,h=Math.min(Math.max(-r,-o),r),d=h*(h+2*o)+l):(c=Math.max(0,-(s*r+a)),h=c>0?r:Math.min(Math.max(-r,-o),r),d=-c*c+h*(h+2*o)+l);else h=s>0?-r:r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,c),i&&i.copy(wr).addScaledVector(Ar,h),d}intersectSphere(e,t){Er.subVectors(e.center,this.origin);const n=Er.dot(this.direction),i=Er.dot(Er)-n*n,r=e.radius*e.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return!(e.radius<0)&&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 n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return null===n?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,s,a,o;const l=1/this.direction.x,u=1/this.direction.y,c=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,i=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,i=(e.min.x-h.x)*l),u>=0?(r=(e.min.y-h.y)*u,s=(e.max.y-h.y)*u):(r=(e.max.y-h.y)*u,s=(e.min.y-h.y)*u),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s<i||isNaN(i))&&(i=s),c>=0?(a=(e.min.z-h.z)*c,o=(e.max.z-h.z)*c):(a=(e.max.z-h.z)*c,o=(e.min.z-h.z)*c),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o<i||i!=i)&&(i=o),i<0?null:this.at(n>=0?n:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Er)}intersectTriangle(e,t,n,i,r){Cr.subVectors(t,e),Nr.subVectors(n,e),Pr.crossVectors(Cr,Nr);let s,a=this.direction.dot(Pr);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}Rr.subVectors(this.origin,e);const o=s*this.direction.dot(Nr.crossVectors(Rr,Nr));if(o<0)return null;const l=s*this.direction.dot(Cr.cross(Rr));if(l<0)return null;if(o+l>a)return null;const u=-s*Rr.dot(Pr);return u<0?null:this.at(u/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 Dr extends Sr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new _i(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 $n,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 Ir=new Fn,Ur=new Lr,Fr=new cr,Or=new dn,Br=new dn,kr=new dn,zr=new dn,Vr=new dn,Gr=new dn,Hr=new dn,jr=new dn;class Wr extends ui{constructor(e=new vr,t=new Dr){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),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}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){const t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){const n=this.geometry,i=n.attributes.position,r=n.morphAttributes.position,s=n.morphTargetsRelative;t.fromBufferAttribute(i,e);const a=this.morphTargetInfluences;if(r&&a){Gr.set(0,0,0);for(let n=0,i=r.length;n<i;n++){const i=a[n],o=r[n];0!==i&&(Vr.fromBufferAttribute(o,e),s?Gr.addScaledVector(Vr,i):Gr.addScaledVector(Vr.sub(t),i))}t.add(Gr)}return t}raycast(e,t){const n=this.geometry,i=this.material,r=this.matrixWorld;if(void 0!==i){if(null===n.boundingSphere&&n.computeBoundingSphere(),Fr.copy(n.boundingSphere),Fr.applyMatrix4(r),Ur.copy(e.ray).recast(e.near),!1===Fr.containsPoint(Ur.origin)){if(null===Ur.intersectSphere(Fr,Or))return;if(Ur.origin.distanceToSquared(Or)>(e.far-e.near)**2)return}Ir.copy(r).invert(),Ur.copy(e.ray).applyMatrix4(Ir),null!==n.boundingBox&&!1===Ur.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,Ur)}}_computeIntersections(e,t,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,u=r.attributes.uv1,c=r.attributes.normal,h=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=h.length;r<o;r++){const o=h[r],p=s[o.materialIndex];for(let r=Math.max(o.start,d.start),s=Math.min(a.count,Math.min(o.start+o.count,d.start+d.count));r<s;r+=3){i=$r(this,p,e,n,l,u,c,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=o.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);r<o;r+=3){i=$r(this,s,e,n,l,u,c,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}else if(void 0!==o)if(Array.isArray(s))for(let r=0,a=h.length;r<a;r++){const a=h[r],p=s[a.materialIndex];for(let r=Math.max(a.start,d.start),s=Math.min(o.count,Math.min(a.start+a.count,d.start+d.count));r<s;r+=3){i=$r(this,p,e,n,l,u,c,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=a.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);r<a;r+=3){i=$r(this,s,e,n,l,u,c,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function $r(e,t,n,i,r,s,a,o,l,u){e.getVertexPosition(o,Br),e.getVertexPosition(l,kr),e.getVertexPosition(u,zr);const c=function(e,t,n,i,r,s,a,o){let l;if(l=1===t.side?i.intersectTriangle(a,s,r,!0,o):i.intersectTriangle(r,s,a,0===t.side,o),null===l)return null;jr.copy(o),jr.applyMatrix4(e.matrixWorld);const u=n.ray.origin.distanceTo(jr);return u<n.near||u>n.far?null:{distance:u,point:jr.clone(),object:e}}(e,t,n,i,Br,kr,zr,Hr);if(c){const e=new dn;Di.getBarycoord(Hr,Br,kr,zr,e),r&&(c.uv=Di.getInterpolatedAttribute(r,o,l,u,e,new cn)),s&&(c.uv1=Di.getInterpolatedAttribute(s,o,l,u,e,new cn)),a&&(c.normal=Di.getInterpolatedAttribute(a,o,l,u,e,new dn),c.normal.dot(i.direction)>0&&c.normal.multiplyScalar(-1));const t={a:o,b:l,c:u,normal:new dn,materialIndex:0};Di.getNormal(Br,kr,zr,t.normal),c.face=t,c.barycoord=e}return c}class Xr extends Nn{constructor(e=null,t=1,n=1,i,r,s,a,o,l=1003,u=1003,c,h){super(null,s,a,o,l,u,i,r,c,h),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class qr extends nr{constructor(e,t,n,i=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const Yr=new dn,Kr=new dn,Zr=new mn;class Qr{constructor(e=new dn(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const i=Yr.subVectors(n,t).cross(Kr.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(Yr),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||Zr.getNormalMatrix(e),i=this.coplanarPoint(Yr).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.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 cr,es=new cn(.5,.5),ts=new dn;class ns{constructor(e=new Qr,t=new Qr,n=new Qr,i=new Qr,r=new Qr,s=new Qr){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3,n=!1){const i=this.planes,r=e.elements,s=r[0],a=r[1],o=r[2],l=r[3],u=r[4],c=r[5],h=r[6],d=r[7],p=r[8],f=r[9],m=r[10],g=r[11],_=r[12],v=r[13],y=r[14],b=r[15];if(i[0].setComponents(l-s,d-u,g-p,b-_).normalize(),i[1].setComponents(l+s,d+u,g+p,b+_).normalize(),i[2].setComponents(l+a,d+c,g+f,b+v).normalize(),i[3].setComponents(l-a,d-c,g-f,b-v).normalize(),n)i[4].setComponents(o,h,m,y).normalize(),i[5].setComponents(l-o,d-h,g-m,b-y).normalize();else if(i[4].setComponents(l-o,d-h,g-m,b-y).normalize(),t===Ft)i[5].setComponents(l+o,d+h,g+m,b+y).normalize();else{if(t!==Ot)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(o,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){Jr.center.set(0,0,0);const t=es.distanceTo(e.center);return Jr.radius=.7071067811865476+t,Jr.applyMatrix4(e.matrixWorld),this.intersectsSphere(Jr)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(n)<i)return!1}return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const i=t[n];if(ts.x=i.normal.x>0?e.max.x:e.min.x,ts.y=i.normal.y>0?e.max.y:e.min.y,ts.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(ts)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}const is=new Fn,rs=new ns;class ss{constructor(){this.coordinateSystem=Ft}intersectsObject(e,t){if(!t.isArrayCamera||0===t.cameras.length)return!1;for(let n=0;n<t.cameras.length;n++){const i=t.cameras[n];if(is.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),rs.setFromProjectionMatrix(is,i.coordinateSystem,i.reversedDepth),rs.intersectsObject(e))return!0}return!1}intersectsSprite(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let n=0;n<t.cameras.length;n++){const i=t.cameras[n];if(is.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),rs.setFromProjectionMatrix(is,i.coordinateSystem,i.reversedDepth),rs.intersectsSprite(e))return!0}return!1}intersectsSphere(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let n=0;n<t.cameras.length;n++){const i=t.cameras[n];if(is.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),rs.setFromProjectionMatrix(is,i.coordinateSystem,i.reversedDepth),rs.intersectsSphere(e))return!0}return!1}intersectsBox(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let n=0;n<t.cameras.length;n++){const i=t.cameras[n];if(is.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),rs.setFromProjectionMatrix(is,i.coordinateSystem,i.reversedDepth),rs.intersectsBox(e))return!0}return!1}containsPoint(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let n=0;n<t.cameras.length;n++){const i=t.cameras[n];if(is.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),rs.setFromProjectionMatrix(is,i.coordinateSystem,i.reversedDepth),rs.containsPoint(e))return!0}return!1}clone(){return new ss}}class as extends Sr{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new _i(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 os=new dn,ls=new dn,us=new Fn,cs=new Lr,hs=new cr,ds=new dn,ps=new dn;function fs(e,t,n,i,r,s,a){const o=e.geometry.attributes.position;os.fromBufferAttribute(o,r),ls.fromBufferAttribute(o,s);if(n.distanceSqToSegment(os,ls,ds,ps)>i)return;ds.applyMatrix4(e.matrixWorld);const l=t.ray.origin.distanceTo(ds);return l<t.near||l>t.far?void 0:{distance:l,point:ps.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}class ms extends Sr{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new _i(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class gs extends Nn{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=le,this.minFilter=le,this.generateMipmaps=!1,this.needsUpdate=!0}}class _s extends Nn{constructor(e=[],t=301,n,i,r,s,a,o,l,u){super(e,t,n,i,r,s,a,o,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class vs extends Nn{constructor(e,t,n=1014,i,r,s,a=1003,o=1003,l,u=1026,c=1){if(u!==Ne&&u!==Pe)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:c},i,r,s,a,o,u,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new wn(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class ys extends vs{constructor(e,t=1014,n=301,i,r,s=1003,a=1003,o,l=1026){const u={width:e,height:e,depth:1},c=[u,u,u,u,u,u];super(e,e,t,n,i,r,s,a,o,l),this.image=c,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class bs extends Nn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class xs extends vr{constructor(e=1,t=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],u=[],c=[];let h=0,d=0;function p(e,t,n,i,r,s,p,f,m,g,_){const v=s/m,y=p/g,b=s/2,x=p/2,T=f/2,S=m+1,M=g+1;let E=0,w=0;const A=new dn;for(let s=0;s<M;s++){const a=s*y-x;for(let o=0;o<S;o++){const h=o*v-b;A[e]=h*i,A[t]=a*r,A[n]=T,l.push(A.x,A.y,A.z),A[e]=0,A[t]=0,A[n]=f>0?1:-1,u.push(A.x,A.y,A.z),c.push(o/m),c.push(1-s/g),E+=1}}for(let e=0;e<g;e++)for(let t=0;t<m;t++){const n=h+t+S*e,i=h+t+S*(e+1),r=h+(t+1)+S*(e+1),s=h+(t+1)+S*e;o.push(n,i,s),o.push(i,r,s),w+=6}a.addGroup(d,w,_),d+=w,h+=E}p("z","y","x",-1,-1,n,t,e,s,r,0),p("z","y","x",1,-1,n,t,-e,s,r,1),p("x","z","y",1,1,e,n,t,i,s,2),p("x","z","y",1,-1,e,n,-t,i,s,3),p("x","y","z",1,-1,e,t,n,i,r,4),p("x","y","z",-1,-1,e,t,-n,i,r,5),this.setIndex(o),this.setAttribute("position",new ar(l,3)),this.setAttribute("normal",new ar(u,3)),this.setAttribute("uv",new ar(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new xs(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class Ts extends vr{constructor(e=1,t=1,n=1,i=32,r=1,s=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:i,heightSegments:r,openEnded:s,thetaStart:a,thetaLength:o};const l=this;i=Math.floor(i),r=Math.floor(r);const u=[],c=[],h=[],d=[];let p=0;const f=[],m=n/2;let g=0;function _(n){const r=p,s=new cn,f=new dn;let _=0;const v=!0===n?e:t,y=!0===n?1:-1;for(let e=1;e<=i;e++)c.push(0,m*y,0),h.push(0,y,0),d.push(.5,.5),p++;const b=p;for(let e=0;e<=i;e++){const t=e/i*o+a,n=Math.cos(t),r=Math.sin(t);f.x=v*r,f.y=m*y,f.z=v*n,c.push(f.x,f.y,f.z),h.push(0,y,0),s.x=.5*n+.5,s.y=.5*r*y+.5,d.push(s.x,s.y),p++}for(let e=0;e<i;e++){const t=r+e,i=b+e;!0===n?u.push(i,i+1,t):u.push(i+1,i,t),_+=3}l.addGroup(g,_,!0===n?1:2),g+=_}!function(){const s=new dn,_=new dn;let v=0;const y=(t-e)/n;for(let l=0;l<=r;l++){const u=[],g=l/r,v=g*(t-e)+e;for(let e=0;e<=i;e++){const t=e/i,r=t*o+a,l=Math.sin(r),f=Math.cos(r);_.x=v*l,_.y=-g*n+m,_.z=v*f,c.push(_.x,_.y,_.z),s.set(l,y,f).normalize(),h.push(s.x,s.y,s.z),d.push(t,1-g),u.push(p++)}f.push(u)}for(let n=0;n<i;n++)for(let i=0;i<r;i++){const s=f[i][n],a=f[i+1][n],o=f[i+1][n+1],l=f[i][n+1];(e>0||0!==i)&&(u.push(s,a,l),v+=3),(t>0||i!==r-1)&&(u.push(a,o,l),v+=3)}l.addGroup(g,v,0),g+=v}(),!1===s&&(e>0&&_(!0),t>0&&_(!1)),this.setIndex(u),this.setAttribute("position",new ar(c,3)),this.setAttribute("normal",new ar(h,3)),this.setAttribute("uv",new ar(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ts(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Ss extends Ts{constructor(e=1,t=1,n=32,i=1,r=!1,s=0,a=2*Math.PI){super(0,e,t,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(e){return new Ss(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Ms{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){Xt("Curve: .getPoint() not implemented.")}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,i=this.getPoint(0),r=0;t.push(0);for(let s=1;s<=e;s++)n=this.getPoint(s/e),r+=n.distanceTo(i),t.push(r),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const n=this.getLengths();let i=0;const r=n.length;let s;s=t||e*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const u=n[i];return(i+(s-u)/(n[i+1]-u))/(r-1)}getTangent(e,t){const n=1e-4;let i=e-n,r=e+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=t||(s.isVector2?new cn:new dn);return o.copy(a).sub(s).normalize(),o}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){const n=new dn,i=[],r=[],s=[],a=new dn,o=new Fn;for(let t=0;t<=e;t++){const n=t/e;i[t]=this.getTangentAt(n,new dn)}r[0]=new dn,s[0]=new dn;let l=Number.MAX_VALUE;const u=Math.abs(i[0].x),c=Math.abs(i[0].y),h=Math.abs(i[0].z);u<=l&&(l=u,n.set(1,0,0)),c<=l&&(l=c,n.set(0,1,0)),h<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[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(i[t-1],i[t]),a.length()>Number.EPSILON){a.normalize();const e=Math.acos(rn(i[t-1].dot(i[t]),-1,1));r[t].applyMatrix4(o.makeRotationAxis(a,e))}s[t].crossVectors(i[t],r[t])}if(!0===t){let t=Math.acos(rn(r[0].dot(r[e]),-1,1));t/=e,i[0].dot(a.crossVectors(r[0],r[e]))>0&&(t=-t);for(let n=1;n<=e;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],t*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,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.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class Es extends Ms{constructor(e=0,t=0,n=1,i=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=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(e,t=new cn){const n=t,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)<Number.EPSILON;for(;r<0;)r+=i;for(;r>i;)r-=i;r<Number.EPSILON&&(r=s?0:i),!0!==this.aClockwise||s||(r===i?r=-i:r-=i);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),n=o-this.aX,i=l-this.aY;o=n*e-i*t+this.aX,l=n*t+i*e+this.aY}return n.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}}function ws(){let e=0,t=0,n=0,i=0;function r(r,s,a,o){e=r,t=a,n=-3*r+3*s-2*a-o,i=2*r-2*s+a+o}return{initCatmullRom:function(e,t,n,i,s){r(t,n,s*(n-e),s*(i-t))},initNonuniformCatmullRom:function(e,t,n,i,s,a,o){let l=(t-e)/s-(n-e)/(s+a)+(n-t)/a,u=(n-t)/a-(i-t)/(a+o)+(i-n)/o;l*=a,u*=a,r(t,n,l,u)},calc:function(r){const s=r*r;return e+t*r+n*s+i*(s*r)}}}const As=new dn,Rs=new ws,Cs=new ws,Ns=new ws;function Ps(e,t,n,i,r){const s=.5*(i-t),a=.5*(r-n),o=e*e;return(2*n-2*i+s+a)*(e*o)+(-3*n+3*i-2*s-a)*o+s*e+n}function Ls(e,t,n,i){return function(e,t){const n=1-e;return n*n*t}(e,t)+function(e,t){return 2*(1-e)*e*t}(e,n)+function(e,t){return e*e*t}(e,i)}function Ds(e,t,n,i,r){return function(e,t){const n=1-e;return n*n*n*t}(e,t)+function(e,t){const n=1-e;return 3*n*n*e*t}(e,n)+function(e,t){return 3*(1-e)*e*e*t}(e,i)+function(e,t){return e*e*e*t}(e,r)}class Is extends Ms{constructor(e=new dn,t=new dn,n=new dn,i=new dn){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=n,this.v3=i}getPoint(e,t=new dn){const n=t,i=this.v0,r=this.v1,s=this.v2,a=this.v3;return n.set(Ds(e,i.x,r.x,s.x,a.x),Ds(e,i.y,r.y,s.y,a.y),Ds(e,i.z,r.z,s.z,a.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}}class Us extends Ms{constructor(e=new dn,t=new dn,n=new dn){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new dn){const n=t,i=this.v0,r=this.v1,s=this.v2;return n.set(Ls(e,i.x,r.x,s.x),Ls(e,i.y,r.y,s.y),Ls(e,i.z,r.z,s.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}var Fs=Object.freeze({__proto__:null,ArcCurve:class extends Es{constructor(e,t,n,i,r,s){super(e,t,n,n,i,r,s),this.isArcCurve=!0,this.type="ArcCurve"}},CatmullRomCurve3:class extends Ms{constructor(e=[],t=!1,n="centripetal",i=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=e,this.closed=t,this.curveType=n,this.tension=i}getPoint(e,t=new dn){const n=t,i=this.points,r=i.length,s=(r-(this.closed?0:1))*e;let a,o,l=Math.floor(s),u=s-l;this.closed?l+=l>0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===u&&l===r-1&&(l=r-2,u=1),this.closed||l>0?a=i[(l-1)%r]:(As.subVectors(i[0],i[1]).add(i[0]),a=As);const c=i[l%r],h=i[(l+1)%r];if(this.closed||l+2<r?o=i[(l+2)%r]:(As.subVectors(i[r-1],i[r-2]).add(i[r-1]),o=As),"centripetal"===this.curveType||"chordal"===this.curveType){const e="chordal"===this.curveType?.5:.25;let t=Math.pow(a.distanceToSquared(c),e),n=Math.pow(c.distanceToSquared(h),e),i=Math.pow(h.distanceToSquared(o),e);n<1e-4&&(n=1),t<1e-4&&(t=n),i<1e-4&&(i=n),Rs.initNonuniformCatmullRom(a.x,c.x,h.x,o.x,t,n,i),Cs.initNonuniformCatmullRom(a.y,c.y,h.y,o.y,t,n,i),Ns.initNonuniformCatmullRom(a.z,c.z,h.z,o.z,t,n,i)}else"catmullrom"===this.curveType&&(Rs.initCatmullRom(a.x,c.x,h.x,o.x,this.tension),Cs.initCatmullRom(a.y,c.y,h.y,o.y,this.tension),Ns.initCatmullRom(a.z,c.z,h.z,o.z,this.tension));return n.set(Rs.calc(u),Cs.calc(u),Ns.calc(u)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const n=e.points[t];this.points.push(n.clone())}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){const n=this.points[t];e.points.push(n.toArray())}return e.closed=this.closed,e.curveType=this.curveType,e.tension=this.tension,e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const n=e.points[t];this.points.push((new dn).fromArray(n))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}},CubicBezierCurve:class extends Ms{constructor(e=new cn,t=new cn,n=new cn,i=new cn){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=n,this.v3=i}getPoint(e,t=new cn){const n=t,i=this.v0,r=this.v1,s=this.v2,a=this.v3;return n.set(Ds(e,i.x,r.x,s.x,a.x),Ds(e,i.y,r.y,s.y,a.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}},CubicBezierCurve3:Is,EllipseCurve:Es,LineCurve:class extends Ms{constructor(e=new cn,t=new cn){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new cn){const n=t;return 1===e?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new cn){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}},LineCurve3:class extends Ms{constructor(e=new dn,t=new dn){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new dn){const n=t;return 1===e?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new dn){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}},QuadraticBezierCurve:class extends Ms{constructor(e=new cn,t=new cn,n=new cn){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new cn){const n=t,i=this.v0,r=this.v1,s=this.v2;return n.set(Ls(e,i.x,r.x,s.x),Ls(e,i.y,r.y,s.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},QuadraticBezierCurve3:Us,SplineCurve:class extends Ms{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new cn){const n=t,i=this.points,r=(i.length-1)*e,s=Math.floor(r),a=r-s,o=i[0===s?s:s-1],l=i[s],u=i[s>i.length-2?i.length-1:s+1],c=i[s>i.length-3?i.length-1:s+2];return n.set(Ps(a,o.x,l.x,u.x,c.x),Ps(a,o.y,l.y,u.y,c.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const n=e.points[t];this.points.push(n.clone())}return this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){const n=this.points[t];e.points.push(n.toArray())}return e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const n=e.points[t];this.points.push((new cn).fromArray(n))}return this}}});class Os extends vr{constructor(e=1,t=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};const r=e/2,s=t/2,a=Math.floor(n),o=Math.floor(i),l=a+1,u=o+1,c=e/a,h=t/o,d=[],p=[],f=[],m=[];for(let e=0;e<u;e++){const t=e*h-s;for(let n=0;n<l;n++){const i=n*c-r;p.push(i,-t,0),f.push(0,0,1),m.push(n/a),m.push(1-e/o)}}for(let e=0;e<o;e++)for(let t=0;t<a;t++){const n=t+l*e,i=t+l*(e+1),r=t+1+l*(e+1),s=t+1+l*e;d.push(n,i,s),d.push(i,r,s)}this.setIndex(d),this.setAttribute("position",new ar(p,3)),this.setAttribute("normal",new ar(f,3)),this.setAttribute("uv",new ar(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Os(e.width,e.height,e.widthSegments,e.heightSegments)}}class Bs extends vr{constructor(e=1,t=32,n=16,i=0,r=2*Math.PI,s=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:i,phiLength:r,thetaStart:s,thetaLength:a},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));const o=Math.min(s+a,Math.PI);let l=0;const u=[],c=new dn,h=new dn,d=[],p=[],f=[],m=[];for(let d=0;d<=n;d++){const g=[],_=d/n;let v=0;0===d&&0===s?v=.5/t:d===n&&o===Math.PI&&(v=-.5/t);for(let n=0;n<=t;n++){const o=n/t;c.x=-e*Math.cos(i+o*r)*Math.sin(s+_*a),c.y=e*Math.cos(s+_*a),c.z=e*Math.sin(i+o*r)*Math.sin(s+_*a),p.push(c.x,c.y,c.z),h.copy(c).normalize(),f.push(h.x,h.y,h.z),m.push(o+v,1-_),g.push(l++)}u.push(g)}for(let e=0;e<n;e++)for(let i=0;i<t;i++){const t=u[e][i+1],r=u[e][i],a=u[e+1][i],l=u[e+1][i+1];(0!==e||s>0)&&d.push(t,r,l),(e!==n-1||o<Math.PI)&&d.push(r,a,l)}this.setIndex(d),this.setAttribute("position",new ar(p,3)),this.setAttribute("normal",new ar(f,3)),this.setAttribute("uv",new ar(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Bs(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class ks extends vr{constructor(e=new Us(new dn(-1,-1,0),new dn(-1,1,0),new dn(1,1,0)),t=64,n=1,i=8,r=!1){super(),this.type="TubeGeometry",this.parameters={path:e,tubularSegments:t,radius:n,radialSegments:i,closed:r};const s=e.computeFrenetFrames(t,r);this.tangents=s.tangents,this.normals=s.normals,this.binormals=s.binormals;const a=new dn,o=new dn,l=new cn;let u=new dn;const c=[],h=[],d=[],p=[];function f(r){u=e.getPointAt(r/t,u);const l=s.normals[r],d=s.binormals[r];for(let e=0;e<=i;e++){const t=e/i*Math.PI*2,r=Math.sin(t),s=-Math.cos(t);o.x=s*l.x+r*d.x,o.y=s*l.y+r*d.y,o.z=s*l.z+r*d.z,o.normalize(),h.push(o.x,o.y,o.z),a.x=u.x+n*o.x,a.y=u.y+n*o.y,a.z=u.z+n*o.z,c.push(a.x,a.y,a.z)}}!function(){for(let e=0;e<t;e++)f(e);f(!1===r?t:0),function(){for(let e=0;e<=t;e++)for(let n=0;n<=i;n++)l.x=e/t,l.y=n/i,d.push(l.x,l.y)}(),function(){for(let e=1;e<=t;e++)for(let t=1;t<=i;t++){const n=(i+1)*(e-1)+(t-1),r=(i+1)*e+(t-1),s=(i+1)*e+t,a=(i+1)*(e-1)+t;p.push(n,r,a),p.push(r,s,a)}}()}(),this.setIndex(p),this.setAttribute("position",new ar(c,3)),this.setAttribute("normal",new ar(h,3)),this.setAttribute("uv",new ar(d,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 ks((new Fs[e.path.type]).fromJSON(e.path),e.tubularSegments,e.radius,e.radialSegments,e.closed)}}class zs extends Sr{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new _i(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}function Vs(e){const t={};for(const n in e){t[n]={};for(const i in e[n]){const r=e[n][i];r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)?r.isRenderTargetTexture?(Xt("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[n][i]=null):t[n][i]=r.clone():Array.isArray(r)?t[n][i]=r.slice():t[n][i]=r}}return t}function Gs(e){const t={};for(let n=0;n<e.length;n++){const i=Vs(e[n]);for(const e in i)t[e]=i[e]}return t}function Hs(e){const t=e.getRenderTarget();return null===t?e.outputColorSpace:!0===t.isXRRenderTarget?t.texture.colorSpace:bn.workingColorSpace}const js={clone:Vs,merge:Gs};class Ws extends Sr{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=Vs(e.uniforms),this.uniformsGroups=function(e){const t=[];for(let n=0;n<e.length;n++)t.push(e[n].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.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const n in this.uniforms){const i=this.uniforms[n].value;i&&i.isTexture?t.uniforms[n]={type:"t",value:i.toJSON(e).uuid}:i&&i.isColor?t.uniforms[n]={type:"c",value:i.getHex()}:i&&i.isVector2?t.uniforms[n]={type:"v2",value:i.toArray()}:i&&i.isVector3?t.uniforms[n]={type:"v3",value:i.toArray()}:i&&i.isVector4?t.uniforms[n]={type:"v4",value:i.toArray()}:i&&i.isMatrix3?t.uniforms[n]={type:"m3",value:i.toArray()}:i&&i.isMatrix4?t.uniforms[n]={type:"m4",value:i.toArray()}:t.uniforms[n]={value:i}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const e in this.extensions)!0===this.extensions[e]&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class $s extends Ws{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Xs extends Sr{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new _i(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 _i(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(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 $n,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 qs extends Xs{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 cn(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return rn(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new _i(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 _i(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new _i(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class Ys extends Sr{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new _i(16777215),this.specular=new _i(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new _i(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new $n,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Ks extends Sr{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new _i(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new _i(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(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 Zs extends Sr{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(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 Qs extends Sr{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new _i(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new _i(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new $n,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Js extends Sr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,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 ea extends Sr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class ta extends Sr{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new _i(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}}class na extends as{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}const ia={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(ra(e)||(this.files[e]=t))},get:function(e){if(!1!==this.enabled&&!ra(e))return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function ra(e){try{const t=e.slice(e.indexOf(":")+1);return"blob:"===new URL(t).protocol}catch(e){return!1}}class sa{constructor(e,t,n){const i=this;let r,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(e){o++,!1===s&&void 0!==i.onStart&&i.onStart(e,a,o),s=!0},this.itemEnd=function(e){a++,void 0!==i.onProgress&&i.onProgress(e,a,o),a===o&&(s=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(e){void 0!==i.onError&&i.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,n=l.length;t<n;t+=2){const n=l[t],i=l[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return i}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}}const aa=new sa;class oa{constructor(e){this.manager=void 0!==e?e:aa,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}load(){}loadAsync(e,t){const n=this;return new Promise(function(i,r){n.load(e,i,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}abort(){return this}}oa.DEFAULT_MATERIAL_NAME="__DEFAULT";const la=new WeakMap;class ua extends oa{constructor(e){super(e)}load(e,t,n,i){void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=this,s=ia.get(`image:${e}`);if(void 0!==s){if(!0===s.complete)r.manager.itemStart(e),setTimeout(function(){t&&t(s),r.manager.itemEnd(e)},0);else{let e=la.get(s);void 0===e&&(e=[],la.set(s,e)),e.push({onLoad:t,onError:i})}return s}const a=Gt("img");function o(){u(),t&&t(this);const n=la.get(this)||[];for(let e=0;e<n.length;e++){const t=n[e];t.onLoad&&t.onLoad(this)}la.delete(this),r.manager.itemEnd(e)}function l(t){u(),i&&i(t),ia.remove(`image:${e}`);const n=la.get(this)||[];for(let e=0;e<n.length;e++){const i=n[e];i.onError&&i.onError(t)}la.delete(this),r.manager.itemError(e),r.manager.itemEnd(e)}function u(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),"data:"!==e.slice(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),ia.add(`image:${e}`,a),r.manager.itemStart(e),a.src=e,a}}class ca extends ui{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new _i(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}class ha extends ca{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(ui.DEFAULT_UP),this.updateMatrix(),this.groundColor=new _i(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){const t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}}const da=new Fn,pa=new dn,fa=new dn;class ma{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new cn(512,512),this.mapType=fe,this.map=null,this.mapPass=null,this.matrix=new Fn,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new ns,this._frameExtents=new cn(1,1),this._viewportCount=1,this._viewports=[new Pn(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,n=this.matrix;pa.setFromMatrixPosition(e.matrixWorld),t.position.copy(pa),fa.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(fa),t.updateMatrixWorld(),da.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(da,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===Ot||t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(da)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return(new this.constructor).copy(this)}toJSON(){const e={};return 1!==this.intensity&&(e.intensity=this.intensity),0!==this.bias&&(e.bias=this.bias),0!==this.normalBias&&(e.normalBias=this.normalBias),1!==this.radius&&(e.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const ga=new dn,_a=new hn,va=new dn;class ya extends ui{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Fn,this.projectionMatrix=new Fn,this.projectionMatrixInverse=new Fn,this.coordinateSystem=Ft,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(ga,_a,va),1===va.x&&1===va.y&&1===va.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(ga,_a,va.set(1,1,1)).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorld.decompose(ga,_a,va),1===va.x&&1===va.y&&1===va.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(ga,_a,va.set(1,1,1)).invert()}clone(){return(new this.constructor).copy(this)}}const ba=new dn,xa=new cn,Ta=new cn;class Sa extends ya{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=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*tn*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*en*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*tn*Math.atan(Math.tan(.5*en*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){ba.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ba.x,ba.y).multiplyScalar(-e/ba.z),ba.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(ba.x,ba.y).multiplyScalar(-e/ba.z)}getViewSize(e,t){return this.getViewBounds(e,xa,Ta),t.subVectors(Ta,xa)}setViewOffset(e,t,n,i,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=n,this.view.offsetY=i,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*en*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const e=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/e,t-=s.offsetY*n/a,i*=s.width/e,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}class Ma extends ma{constructor(){super(new Sa(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,n=2*tn*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,r=e.distance||t.far;n===t.fov&&i===t.aspect&&r===t.far||(t.fov=n,t.aspect=i,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class Ea extends ca{constructor(e,t,n=0,i=Math.PI/3,r=0,s=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(ui.DEFAULT_UP),this.updateMatrix(),this.target=new ui,this.distance=n,this.angle=i,this.penumbra=r,this.decay=s,this.map=null,this.shadow=new Ma}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}}class wa extends ma{constructor(){super(new Sa(90,1,.5,500)),this.isPointLightShadow=!0}}class Aa extends ca{constructor(e,t,n=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new wa}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}}class Ra extends ya{constructor(e=-1,t=1,n=1,i=-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=n,this.bottom=i,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,n,i,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=n,this.view.offsetY=i,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),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-e,s=n+e,a=i+t,o=i-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.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,null!==this.view&&(t.object.view=Object.assign({},this.view)),t}}class Ca extends ma{constructor(){super(new Ra(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Na extends ca{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(ui.DEFAULT_UP),this.updateMatrix(),this.target=new ui,this.shadow=new Ca}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}}class Pa extends ca{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class La extends ca{constructor(e,t,n=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=n,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class Da{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new dn)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const n=e.x,i=e.y,r=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.282095),t.addScaledVector(s[1],.488603*i),t.addScaledVector(s[2],.488603*r),t.addScaledVector(s[3],.488603*n),t.addScaledVector(s[4],n*i*1.092548),t.addScaledVector(s[5],i*r*1.092548),t.addScaledVector(s[6],.315392*(3*r*r-1)),t.addScaledVector(s[7],n*r*1.092548),t.addScaledVector(s[8],.546274*(n*n-i*i)),t}getIrradianceAt(e,t){const n=e.x,i=e.y,r=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.886227),t.addScaledVector(s[1],1.023328*i),t.addScaledVector(s[2],1.023328*r),t.addScaledVector(s[3],1.023328*n),t.addScaledVector(s[4],.858086*n*i),t.addScaledVector(s[5],.858086*i*r),t.addScaledVector(s[6],.743125*r*r-.247708),t.addScaledVector(s[7],.858086*n*r),t.addScaledVector(s[8],.429043*(n*n-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(e.coefficients[n],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let n=0;n<9;n++)this.coefficients[n].lerp(e.coefficients[n],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(e,t=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].fromArray(e,t+3*i);return this}toArray(e=[],t=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].toArray(e,t+3*i);return e}static getBasisAt(e,t){const n=e.x,i=e.y,r=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*r,t[3]=.488603*n,t[4]=1.092548*n*i,t[5]=1.092548*i*r,t[6]=.315392*(3*r*r-1),t[7]=1.092548*n*r,t[8]=.546274*(n*n-i*i)}}class Ia extends ca{constructor(e=new Da,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}const Ua=-90;class Fa extends ui{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Sa(Ua,1,e,t);i.layers=this.layers,this.add(i);const r=new Sa(Ua,1,e,t);r.layers=this.layers,this.add(r);const s=new Sa(Ua,1,e,t);s.layers=this.layers,this.add(s);const a=new Sa(Ua,1,e,t);a.layers=this.layers,this.add(a);const o=new Sa(Ua,1,e,t);o.layers=this.layers,this.add(o);const l=new Sa(Ua,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,i,r,s,a,o]=t;for(const e of t)this.remove(e);if(e===Ft)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.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!==Ot)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.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:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,u]=this.children,c=e.getRenderTarget(),h=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const f=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let m=!1;m=!0===e.isWebGLRenderer?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,r),e.setRenderTarget(n,1,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,2,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,3,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,4,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,l),n.texture.generateMipmaps=f,e.setRenderTarget(n,5,i),m&&!1===e.autoClear&&e.clearDepth(),e.render(t,u),e.setRenderTarget(c,h,d),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class Oa extends Sa{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}let Ba=class{constructor(){this._previousTime=0,this._currentTime=0,this._startTime=performance.now(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,void 0!==e.hidden&&(this._pageVisibilityHandler=ka.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){null!==this._pageVisibilityHandler&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(e){return null!==this._pageVisibilityHandler&&!0===this._document.hidden?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(void 0!==e?e:performance.now())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function ka(){!1===this._document.hidden&&this.reset()}class za extends yr{constructor(e,t,n=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}const Va=new Fn;class Ga{constructor(e,t,n=0,i=1/0){this.ray=new Lr(e,t),this.near=n,this.far=i,this.camera=null,this.layers=new Xn,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):qt("Raycaster: Unsupported camera type: "+t.type)}setFromXRController(e){return Va.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(Va),this}intersectObject(e,t=!0,n=[]){return ja(e,this,n,t),n.sort(Ha),n}intersectObjects(e,t=!0,n=[]){for(let i=0,r=e.length;i<r;i++)ja(e[i],this,n,t);return n.sort(Ha),n}}function Ha(e,t){return e.distance-t.distance}function ja(e,t,n,i){let r=!0;if(e.layers.test(t.layers)){!1===e.raycast(t,n)&&(r=!1)}if(!0===r&&!0===i){const i=e.children;for(let e=0,r=i.length;e<r;e++)ja(i[e],t,n,!0)}}class Wa{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){const e=1e-6;return this.phi=rn(this.phi,e,Math.PI-e),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(rn(t/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}}class $a{constructor(e,t,n,i){$a.prototype.isMatrix2=!0,this.elements=[1,0,0,1],void 0!==e&&this.set(e,t,n,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,i){const r=this.elements;return r[0]=e,r[2]=t,r[1]=n,r[3]=i,this}}class Xa extends Zt{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){void 0!==e?(null!==this.domElement&&this.disconnect(),this.domElement=e):Xt("Controls: connect() now requires an element.")}disconnect(){}dispose(){}update(){}}function qa(e,t,n,i){const r=function(e){switch(e){case fe:case me:return{byteLength:1,components:1};case _e:case ge:case xe:return{byteLength:2,components:1};case Te:case Se:return{byteLength:2,components:4};case ye:case ve:case be:return{byteLength:4,components:1};case Ee:case we:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}(i);switch(n){case Ae:return e*t;case Le:case De:return e*t/r.components*r.byteLength;case Ie:case Ue:return e*t*2/r.components*r.byteLength;case Re:return e*t*3/r.components*r.byteLength;case Ce:case Fe:return e*t*4/r.components*r.byteLength;case Oe:case Be:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case ke:case ze:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ge:case je:return Math.max(e,16)*Math.max(t,8)/4;case Ve:case He:return Math.max(e,8)*Math.max(t,8)/2;case We:case $e:case qe:case Ye:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Xe:case Ke:case Ze:case Qe:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Je:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case et:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case tt:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case nt:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case it:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case rt:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case st:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case at:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case ot:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case lt:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case ut:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case ct:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case ht:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case dt:case pt:case ft:return Math.ceil(e/4)*Math.ceil(t/4)*16;case mt:case gt:return Math.ceil(e/4)*Math.ceil(t/4)*8;case _t:case vt:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${n} format.`)}function Ya(){let e=null,t=!1,n=null,i=null;function r(t,s){n(t,s),i=e.requestAnimationFrame(r)}return{start:function(){!0!==t&&null!==n&&(i=e.requestAnimationFrame(r),t=!0)},stop:function(){e.cancelAnimationFrame(i),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function Ka(e){const t=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)},remove:function(n){n.isInterleavedBufferAttribute&&(n=n.data);const i=t.get(n);i&&(e.deleteBuffer(i.buffer),t.delete(n))},update:function(n,i){if(n.isInterleavedBufferAttribute&&(n=n.data),n.isGLBufferAttribute){const e=t.get(n);return void((!e||e.version<n.version)&&t.set(n,{buffer:n.buffer,type:n.type,bytesPerElement:n.elementSize,version:n.version}))}const r=t.get(n);if(void 0===r)t.set(n,function(t,n){const i=t.array,r=t.usage,s=i.byteLength,a=e.createBuffer();let o;if(e.bindBuffer(n,a),e.bufferData(n,i,r),t.onUploadCallback(),i instanceof Float32Array)o=e.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)o=e.HALF_FLOAT;else if(i instanceof Uint16Array)o=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(i instanceof Int16Array)o=e.SHORT;else if(i instanceof Uint32Array)o=e.UNSIGNED_INT;else if(i instanceof Int32Array)o=e.INT;else if(i instanceof Int8Array)o=e.BYTE;else if(i instanceof Uint8Array)o=e.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+i);o=e.UNSIGNED_BYTE}return{buffer:a,type:o,bytesPerElement:i.BYTES_PER_ELEMENT,version:t.version,size:s}}(n,i));else if(r.version<n.version){if(r.size!==n.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,n,i){const r=n.array,s=n.updateRanges;if(e.bindBuffer(i,t),0===s.length)e.bufferSubData(i,0,r);else{s.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<s.length;e++){const n=s[t],i=s[e];i.start<=n.start+n.count+1?n.count=Math.max(n.count,i.start+i.count-n.start):(++t,s[t]=i)}s.length=t+1;for(let t=0,n=s.length;t<n;t++){const n=s[t];e.bufferSubData(i,n.start*r.BYTES_PER_ELEMENT,r,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}(r.buffer,n,i),r.version=n.version}}}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:s}})),"undefined"!=typeof window&&(window.__THREE__?Xt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=s);const Za={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\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",alphatest_fragment:"#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif",alphatest_pars_fragment:"#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",batching_pars_vertex:"#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec4 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 );\n\t}\n#endif",batching_vertex:"#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif",begin_vertex:"vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif",beginnormal_vertex:"vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif",bsdfs:"float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated",iridescence_fragment:"#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec4 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec4( 1.0 );\n#endif\n#ifdef USE_COLOR_ALPHA\n\tvColor *= color;\n#elif defined( USE_COLOR )\n\tvColor.rgb *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.rgb *= instanceColor.rgb;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );\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}\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\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\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:"vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( 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 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}",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\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t\t#endif\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\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\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, pow4( roughness ) ) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = 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 = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.0001, 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:"uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t\tvec3 iridescenceFresnelDielectric;\n\t\tvec3 iridescenceFresnelMetallic;\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#ifdef USE_ANISOTROPY\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 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.specularColorBlended;\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 * transpose( 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 rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\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\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\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}\nvec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;\n\tvec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;\n\tvec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;\n\tvec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;\n\tfloat Ess_V = dfgV.x + dfgV.y;\n\tfloat Ess_L = dfgL.x + dfgL.y;\n\tfloat Ems_V = 1.0 - Ess_V;\n\tfloat Ems_L = 1.0 - Ess_L;\n\tvec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;\n\tvec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );\n\tfloat compensationFactor = Ems_V * Ems_L;\n\tvec3 multiScatter = Fms * compensationFactor;\n\treturn singleScatter + multiScatter;\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.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t\t#ifdef USE_CLEARCOAT\n\t\t\tvec3 Ncc = geometryClearcoatNormal;\n\t\t\tvec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );\n\t\t\tvec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );\n\t\t\tvec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );\n\t\t\tmat3 mInvClearcoat = mat3(\n\t\t\t\tvec3( t1Clearcoat.x, 0, t1Clearcoat.y ),\n\t\t\t\tvec3( 0, 1, 0 ),\n\t\t\t\tvec3( t1Clearcoat.z, 0, t1Clearcoat.w )\n\t\t\t);\n\t\t\tvec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;\n\t\t\tclearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );\n\t\t#endif\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 \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\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\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\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 ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\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.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );\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 ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\t#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )\n\t\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t\t#endif\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\t#if defined( LAMBERT ) || defined( PHONG )\n\t\tirradiance += iblIrradiance;\n\t#endif\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_LOGARITHMIC_DEPTH_BUFFER )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\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 = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\n\t\treturn depth * ( far - near ) - far;\n\t#else\n\t\treturn depth * ( near - far ) - near;\n\t#endif\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\t\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\treturn ( near * far ) / ( ( near - far ) * depth - near );\n\t#else\n\t\treturn ( near * far ) / ( ( far - near ) * depth - far );\n\t#endif\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\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\t\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tfloat dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp -= shadowBias;\n\t\t\t#else\n\t\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp += shadowBias;\n\t\t\t#endif\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\tvec2 sample0 = vogelDiskSample( 0, 5, phi );\n\t\t\tvec2 sample1 = vogelDiskSample( 1, 5, phi );\n\t\t\tvec2 sample2 = vogelDiskSample( 2, 5, phi );\n\t\t\tvec2 sample3 = vogelDiskSample( 3, 5, phi );\n\t\t\tvec2 sample4 = vogelDiskSample( 4, 5, phi );\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tdepth = 1.0 - depth;\n\t\t\t#endif\n\t\t\tshadow = step( dp, depth );\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\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\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn 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 ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\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\ttexColor.rgb *= 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\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distance_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}",distance_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\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 <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 = vec4( dist, 0.0, 0.0, 1.0 );\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 <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 <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <envmap_physical_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 <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( normalize( normal ) * 0.5 + 0.5, 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 <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 <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <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 \n\t\toutgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \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 <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 <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\t#include <premultiplied_alpha_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[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\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}"},Qa={common:{diffuse:{value:new _i(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new mn},alphaMap:{value:null},alphaMapTransform:{value:new mn},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new mn}},envmap:{envMap:{value:null},envMapRotation:{value:new mn},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new mn}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new mn}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new mn},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new mn},normalScale:{value:new cn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new mn},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new mn}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new mn}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new mn}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new _i(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new _i(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new mn},alphaTest:{value:0},uvTransform:{value:new mn}},sprite:{diffuse:{value:new _i(16777215)},opacity:{value:1},center:{value:new cn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new mn},alphaMap:{value:null},alphaMapTransform:{value:new mn},alphaTest:{value:0}}},Ja={basic:{uniforms:Gs([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.fog]),vertexShader:Za.meshbasic_vert,fragmentShader:Za.meshbasic_frag},lambert:{uniforms:Gs([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,Qa.lights,{emissive:{value:new _i(0)},envMapIntensity:{value:1}}]),vertexShader:Za.meshlambert_vert,fragmentShader:Za.meshlambert_frag},phong:{uniforms:Gs([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,Qa.lights,{emissive:{value:new _i(0)},specular:{value:new _i(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Za.meshphong_vert,fragmentShader:Za.meshphong_frag},standard:{uniforms:Gs([Qa.common,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.roughnessmap,Qa.metalnessmap,Qa.fog,Qa.lights,{emissive:{value:new _i(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Za.meshphysical_vert,fragmentShader:Za.meshphysical_frag},toon:{uniforms:Gs([Qa.common,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.gradientmap,Qa.fog,Qa.lights,{emissive:{value:new _i(0)}}]),vertexShader:Za.meshtoon_vert,fragmentShader:Za.meshtoon_frag},matcap:{uniforms:Gs([Qa.common,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,{matcap:{value:null}}]),vertexShader:Za.meshmatcap_vert,fragmentShader:Za.meshmatcap_frag},points:{uniforms:Gs([Qa.points,Qa.fog]),vertexShader:Za.points_vert,fragmentShader:Za.points_frag},dashed:{uniforms:Gs([Qa.common,Qa.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Za.linedashed_vert,fragmentShader:Za.linedashed_frag},depth:{uniforms:Gs([Qa.common,Qa.displacementmap]),vertexShader:Za.depth_vert,fragmentShader:Za.depth_frag},normal:{uniforms:Gs([Qa.common,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,{opacity:{value:1}}]),vertexShader:Za.meshnormal_vert,fragmentShader:Za.meshnormal_frag},sprite:{uniforms:Gs([Qa.sprite,Qa.fog]),vertexShader:Za.sprite_vert,fragmentShader:Za.sprite_frag},background:{uniforms:{uvTransform:{value:new mn},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Za.background_vert,fragmentShader:Za.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new mn}},vertexShader:Za.backgroundCube_vert,fragmentShader:Za.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Za.cube_vert,fragmentShader:Za.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Za.equirect_vert,fragmentShader:Za.equirect_frag},distance:{uniforms:Gs([Qa.common,Qa.displacementmap,{referencePosition:{value:new dn},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Za.distance_vert,fragmentShader:Za.distance_frag},shadow:{uniforms:Gs([Qa.lights,Qa.fog,{color:{value:new _i(0)},opacity:{value:1}}]),vertexShader:Za.shadow_vert,fragmentShader:Za.shadow_frag}};Ja.physical={uniforms:Gs([Ja.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new mn},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new mn},clearcoatNormalScale:{value:new cn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new mn},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new mn},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new mn},sheen:{value:0},sheenColor:{value:new _i(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new mn},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new mn},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new mn},transmissionSamplerSize:{value:new cn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new mn},attenuationDistance:{value:0},attenuationColor:{value:new _i(0)},specularColor:{value:new _i(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new mn},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new mn},anisotropyVector:{value:new cn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new mn}}]),vertexShader:Za.meshphysical_vert,fragmentShader:Za.meshphysical_frag};const eo={r:0,b:0,g:0},to=new $n,no=new Fn;function io(e,t,n,i,r,s){const a=new _i(0);let o,l,u=!0===r?0:1,c=null,h=0,d=null;function p(e){let n=!0===e.isScene?e.background:null;if(n&&n.isTexture){const i=e.backgroundBlurriness>0;n=t.get(n,i)}return n}function f(t,i){t.getRGB(eo,Hs(e)),n.buffers.color.setClear(eo.r,eo.g,eo.b,i,s)}return{getClearColor:function(){return a},setClearColor:function(e,t=1){a.set(e),u=t,f(a,u)},getClearAlpha:function(){return u},setClearAlpha:function(e){u=e,f(a,u)},render:function(t){let i=!1;const r=p(t);null===r?f(a,u):r&&r.isColor&&(f(r,1),i=!0);const o=e.xr.getEnvironmentBlendMode();"additive"===o?n.buffers.color.setClear(0,0,0,1,s):"alpha-blend"===o&&n.buffers.color.setClear(0,0,0,0,s),(e.autoClear||i)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,n){const r=p(n);r&&(r.isCubeTexture||r.mapping===re)?(void 0===l&&(l=new Wr(new xs(1,1,1),new Ws({name:"BackgroundCubeMaterial",uniforms:Vs(Ja.backgroundCube.uniforms),vertexShader:Ja.backgroundCube.vertexShader,fragmentShader:Ja.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(l)),to.copy(n.backgroundRotation),to.x*=-1,to.y*=-1,to.z*=-1,r.isCubeTexture&&!1===r.isRenderTargetTexture&&(to.y*=-1,to.z*=-1),l.material.uniforms.envMap.value=r,l.material.uniforms.flipEnvMap.value=r.isCubeTexture&&!1===r.isRenderTargetTexture?-1:1,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(no.makeRotationFromEuler(to)),l.material.toneMapped=bn.getTransfer(r.colorSpace)!==St,c===r&&h===r.version&&d===e.toneMapping||(l.material.needsUpdate=!0,c=r,h=r.version,d=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):r&&r.isTexture&&(void 0===o&&(o=new Wr(new Os(2,2),new Ws({name:"BackgroundMaterial",uniforms:Vs(Ja.background.uniforms),vertexShader:Ja.background.vertexShader,fragmentShader:Ja.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),o.geometry.deleteAttribute("normal"),Object.defineProperty(o.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(o)),o.material.uniforms.t2D.value=r,o.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,o.material.toneMapped=bn.getTransfer(r.colorSpace)!==St,!0===r.matrixAutoUpdate&&r.updateMatrix(),o.material.uniforms.uvTransform.value.copy(r.matrix),c===r&&h===r.version&&d===e.toneMapping||(o.material.needsUpdate=!0,c=r,h=r.version,d=e.toneMapping),o.layers.enableAll(),t.unshift(o,o.geometry,o.material,0,0,null))},dispose:function(){void 0!==l&&(l.geometry.dispose(),l.material.dispose(),l=void 0),void 0!==o&&(o.geometry.dispose(),o.material.dispose(),o=void 0)}}}function ro(e,t){const n=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},r=u(null);let s=r,a=!1;function o(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function u(e){const t=[],i=[],r=[];for(let e=0;e<n;e++)t[e]=0,i[e]=0,r[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:i,attributeDivisors:r,object:e,attributes:{},index:null}}function c(){const e=s.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function h(e){d(e,0)}function d(t,n){const i=s.newAttributes,r=s.enabledAttributes,a=s.attributeDivisors;i[t]=1,0===r[t]&&(e.enableVertexAttribArray(t),r[t]=1),a[t]!==n&&(e.vertexAttribDivisor(t,n),a[t]=n)}function p(){const t=s.newAttributes,n=s.enabledAttributes;for(let i=0,r=n.length;i<r;i++)n[i]!==t[i]&&(e.disableVertexAttribArray(i),n[i]=0)}function f(t,n,i,r,s,a,o){!0===o?e.vertexAttribIPointer(t,n,i,s,a):e.vertexAttribPointer(t,n,i,r,s,a)}function m(){g(),a=!0,s!==r&&(s=r,o(s.object))}function g(){r.geometry=null,r.program=null,r.wireframe=!1}return{setup:function(n,r,l,m,g){let _=!1;const v=function(t,n,r,s){const a=!0===s.wireframe;let o=i[n.id];void 0===o&&(o={},i[n.id]=o);const l=!0===t.isInstancedMesh?t.id:0;let c=o[l];void 0===c&&(c={},o[l]=c);let h=c[r.id];void 0===h&&(h={},c[r.id]=h);let d=h[a];void 0===d&&(d=u(e.createVertexArray()),h[a]=d);return d}(n,m,l,r);s!==v&&(s=v,o(s.object)),_=function(e,t,n,i){const r=s.attributes,a=t.attributes;let o=0;const l=n.getAttributes();for(const t in l){if(l[t].location>=0){const n=r[t];let i=a[t];if(void 0===i&&("instanceMatrix"===t&&e.instanceMatrix&&(i=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(i=e.instanceColor)),void 0===n)return!0;if(n.attribute!==i)return!0;if(i&&n.data!==i.data)return!0;o++}}return s.attributesNum!==o||s.index!==i}(n,m,l,g),_&&function(e,t,n,i){const r={},a=t.attributes;let o=0;const l=n.getAttributes();for(const t in l){if(l[t].location>=0){let n=a[t];void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor));const i={};i.attribute=n,n&&n.data&&(i.data=n.data),r[t]=i,o++}}s.attributes=r,s.attributesNum=o,s.index=i}(n,m,l,g),null!==g&&t.update(g,e.ELEMENT_ARRAY_BUFFER),(_||a)&&(a=!1,function(n,i,r,s){c();const a=s.attributes,o=r.getAttributes(),l=i.defaultAttributeValues;for(const i in o){const r=o[i];if(r.location>=0){let o=a[i];if(void 0===o&&("instanceMatrix"===i&&n.instanceMatrix&&(o=n.instanceMatrix),"instanceColor"===i&&n.instanceColor&&(o=n.instanceColor)),void 0!==o){const i=o.normalized,a=o.itemSize,l=t.get(o);if(void 0===l)continue;const u=l.buffer,c=l.type,p=l.bytesPerElement,m=c===e.INT||c===e.UNSIGNED_INT||o.gpuType===ve;if(o.isInterleavedBufferAttribute){const t=o.data,l=t.stride,g=o.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<r.locationSize;e++)d(r.location+e,t.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<r.locationSize;e++)h(r.location+e);e.bindBuffer(e.ARRAY_BUFFER,u);for(let e=0;e<r.locationSize;e++)f(r.location+e,a/r.locationSize,c,i,l*p,(g+a/r.locationSize*e)*p,m)}else{if(o.isInstancedBufferAttribute){for(let e=0;e<r.locationSize;e++)d(r.location+e,o.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=o.meshPerAttribute*o.count)}else for(let e=0;e<r.locationSize;e++)h(r.location+e);e.bindBuffer(e.ARRAY_BUFFER,u);for(let e=0;e<r.locationSize;e++)f(r.location+e,a/r.locationSize,c,i,a*p,a/r.locationSize*e*p,m)}}else if(void 0!==l){const t=l[i];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()}(n,r,l,m),null!==g&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(g).buffer))},reset:m,resetDefaultState:g,dispose:function(){m();for(const e in i){const t=i[e];for(const e in t){const n=t[e];for(const e in n){const t=n[e];for(const e in t)l(t[e].object),delete t[e];delete n[e]}}delete i[e]}},releaseStatesOfGeometry:function(e){if(void 0===i[e.id])return;const t=i[e.id];for(const e in t){const n=t[e];for(const e in n){const t=n[e];for(const e in t)l(t[e].object),delete t[e];delete n[e]}}delete i[e.id]},releaseStatesOfObject:function(e){for(const t in i){const n=i[t],r=!0===e.isInstancedMesh?e.id:0,s=n[r];if(void 0!==s){for(const e in s){const t=s[e];for(const e in t)l(t[e].object),delete t[e];delete s[e]}delete n[r],0===Object.keys(n).length&&delete i[t]}}},releaseStatesOfProgram:function(e){for(const t in i){const n=i[t];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:c,enableAttribute:h,disableUnusedAttributes:p}}function so(e,t,n){let i;function r(t,r,s){0!==s&&(e.drawArraysInstanced(i,t,r,s),n.update(r,i,s))}this.setMode=function(e){i=e},this.render=function(t,r){e.drawArrays(i,t,r),n.update(r,i,1)},this.renderInstances=r,this.renderMultiDraw=function(e,r,s){if(0===s)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,e,0,r,0,s);let a=0;for(let e=0;e<s;e++)a+=r[e];n.update(a,i,1)},this.renderMultiDrawInstances=function(e,s,a,o){if(0===a)return;const l=t.get("WEBGL_multi_draw");if(null===l)for(let t=0;t<e.length;t++)r(e[t],s[t],o[t]);else{l.multiDrawArraysInstancedWEBGL(i,e,0,s,0,o,0,a);let t=0;for(let e=0;e<a;e++)t+=s[e]*o[e];n.update(t,i,1)}}}function ao(e,t,n,i){let r;function s(t){if("highp"===t){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==n.precision?n.precision:"highp";const o=s(a);o!==a&&(Xt("WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(t){return t===Ce||i.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const r=n===xe&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(n!==fe&&i.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==be&&!r)},precision:a,logarithmicDepthBuffer:!0===n.logarithmicDepthBuffer,reversedDepthBuffer:!0===n.reversedDepthBuffer&&t.has("EXT_clip_control"),maxTextures:e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),maxVertexTextures:e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),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),maxSamples:e.getParameter(e.MAX_SAMPLES),samples:e.getParameter(e.SAMPLES)}}function oo(e){const t=this;let n=null,i=0,r=!1,s=!1;const a=new Qr,o=new mn,l={value:null,needsUpdate:!1};function u(e,n,i,r){const s=null!==e?e.length:0;let u=null;if(0!==s){if(u=l.value,!0!==r||null===u){const t=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===u||u.length<t)&&(u=new Float32Array(t));for(let t=0,n=i;t!==s;++t,n+=4)a.copy(e[t]).applyMatrix4(r,o),a.normal.toArray(u,n),u[n+3]=a.constant}l.value=u,l.needsUpdate=!0}return t.numPlanes=s,t.numIntersection=0,u}this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){const n=0!==e.length||t||0!==i||r;return r=t,i=e.length,n},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(a,o,c){const h=a.clippingPlanes,d=a.clipIntersection,p=a.clipShadows,f=e.get(a);if(!r||null===h||0===h.length||s&&!p)s?u(null):function(){l.value!==n&&(l.value=n,l.needsUpdate=i>0);t.numPlanes=i,t.numIntersection=0}();else{const e=s?0:i,t=4*e;let r=f.clippingState||null;l.value=r,r=u(h,o,t,c);for(let e=0;e!==t;++e)r[e]=n[e];f.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}const lo=[.125,.215,.35,.446,.526,.582],uo=20,co=new Ra,ho=new _i;let po=null,fo=0,mo=0,go=!1;const _o=new dn;let vo=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,i=100,r={}){const{size:s=256,position:a=_o}=r;po=this._renderer.getRenderTarget(),fo=this._renderer.getActiveCubeFace(),mo=this._renderer.getActiveMipmapLevel(),go=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);const o=this._allocateTargets();return o.depthBuffer=!0,this._sceneToCubeUV(e,n,i,o,a),t>0&&this._blur(o,0,0,t),this._applyPMREM(o),this._cleanup(o),o}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=To(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=xo(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(po,fo,mo),this._renderer.xr.enabled=go,e.scissorTest=!1,bo(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===ee||e.mapping===te?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),po=this._renderer.getRenderTarget(),fo=this._renderer.getActiveCubeFace(),mo=this._renderer.getActiveMipmapLevel(),go=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:he,minFilter:he,generateMipmaps:!1,type:xe,format:Ce,colorSpace:xt,depthBuffer:!1},i=yo(e,t,n);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=yo(e,t,n);const{_lodMax:i}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=function(e){const t=[],n=[],i=[];let r=e;const s=e-4+1+lo.length;for(let a=0;a<s;a++){const s=Math.pow(2,r);t.push(s);let o=1/s;a>e-4?o=lo[a-e+4-1]:0===a&&(o=0),n.push(o);const l=1/(s-2),u=-l,c=1+l,h=[u,u,c,u,c,c,u,u,c,c,u,c],d=6,p=6,f=3,m=2,g=1,_=new Float32Array(f*p*d),v=new Float32Array(m*p*d),y=new Float32Array(g*p*d);for(let e=0;e<d;e++){const t=e%3*2/3-1,n=e>2?0:-1,i=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];_.set(i,f*p*e),v.set(h,m*p*e);const r=[e,e,e,e,e,e];y.set(r,g*p*e)}const b=new vr;b.setAttribute("position",new nr(_,f)),b.setAttribute("uv",new nr(v,m)),b.setAttribute("faceIndex",new nr(y,g)),i.push(new Wr(b,null)),r>4&&r--}return{lodMeshes:i,sizeLods:t,sigmas:n}}(i)),this._blurMaterial=function(e,t,n){const i=new Float32Array(uo),r=new dn(0,1,0),s=new Ws({name:"SphericalGaussianBlur",defines:{n:uo,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:So(),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:0,depthTest:!1,depthWrite:!1});return s}(i,e,t),this._ggxMaterial=function(e,t,n){const i=new Ws({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:256,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:So(),fragmentShader:'\n\n\t\t\tprecision highp float;\n\t\t\tprecision highp int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform float roughness;\n\t\t\tuniform float mipInt;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\t#define PI 3.14159265359\n\n\t\t\t// Van der Corput radical inverse\n\t\t\tfloat radicalInverse_VdC(uint bits) {\n\t\t\t\tbits = (bits << 16u) | (bits >> 16u);\n\t\t\t\tbits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);\n\t\t\t\tbits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);\n\t\t\t\tbits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);\n\t\t\t\tbits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);\n\t\t\t\treturn float(bits) * 2.3283064365386963e-10; // / 0x100000000\n\t\t\t}\n\n\t\t\t// Hammersley sequence\n\t\t\tvec2 hammersley(uint i, uint N) {\n\t\t\t\treturn vec2(float(i) / float(N), radicalInverse_VdC(i));\n\t\t\t}\n\n\t\t\t// GGX VNDF importance sampling (Eric Heitz 2018)\n\t\t\t// "Sampling the GGX Distribution of Visible Normals"\n\t\t\t// https://jcgt.org/published/0007/04/01/\n\t\t\tvec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {\n\t\t\t\tfloat alpha = roughness * roughness;\n\n\t\t\t\t// Section 4.1: Orthonormal basis\n\t\t\t\tvec3 T1 = vec3(1.0, 0.0, 0.0);\n\t\t\t\tvec3 T2 = cross(V, T1);\n\n\t\t\t\t// Section 4.2: Parameterization of projected area\n\t\t\t\tfloat r = sqrt(Xi.x);\n\t\t\t\tfloat phi = 2.0 * PI * Xi.y;\n\t\t\t\tfloat t1 = r * cos(phi);\n\t\t\t\tfloat t2 = r * sin(phi);\n\t\t\t\tfloat s = 0.5 * (1.0 + V.z);\n\t\t\t\tt2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;\n\n\t\t\t\t// Section 4.3: Reprojection onto hemisphere\n\t\t\t\tvec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V;\n\n\t\t\t\t// Section 3.4: Transform back to ellipsoid configuration\n\t\t\t\treturn normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));\n\t\t\t}\n\n\t\t\tvoid main() {\n\t\t\t\tvec3 N = normalize(vOutputDirection);\n\t\t\t\tvec3 V = N; // Assume view direction equals normal for pre-filtering\n\n\t\t\t\tvec3 prefilteredColor = vec3(0.0);\n\t\t\t\tfloat totalWeight = 0.0;\n\n\t\t\t\t// For very low roughness, just sample the environment directly\n\t\t\t\tif (roughness < 0.001) {\n\t\t\t\t\tgl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Tangent space basis for VNDF sampling\n\t\t\t\tvec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\n\t\t\t\tvec3 tangent = normalize(cross(up, N));\n\t\t\t\tvec3 bitangent = cross(N, tangent);\n\n\t\t\t\tfor(uint i = 0u; i < uint(GGX_SAMPLES); i++) {\n\t\t\t\t\tvec2 Xi = hammersley(i, uint(GGX_SAMPLES));\n\n\t\t\t\t\t// For PMREM, V = N, so in tangent space V is always (0, 0, 1)\n\t\t\t\t\tvec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);\n\n\t\t\t\t\t// Transform H back to world space\n\t\t\t\t\tvec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);\n\t\t\t\t\tvec3 L = normalize(2.0 * dot(V, H) * H - V);\n\n\t\t\t\t\tfloat NdotL = max(dot(N, L), 0.0);\n\n\t\t\t\t\tif(NdotL > 0.0) {\n\t\t\t\t\t\t// Sample environment at fixed mip level\n\t\t\t\t\t\t// VNDF importance sampling handles the distribution filtering\n\t\t\t\t\t\tvec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);\n\n\t\t\t\t\t\t// Weight by NdotL for the split-sum approximation\n\t\t\t\t\t\t// VNDF PDF naturally accounts for the visible microfacet distribution\n\t\t\t\t\t\tprefilteredColor += sampleColor * NdotL;\n\t\t\t\t\t\ttotalWeight += NdotL;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (totalWeight > 0.0) {\n\t\t\t\t\tprefilteredColor = prefilteredColor / totalWeight;\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = vec4(prefilteredColor, 1.0);\n\t\t\t}\n\t\t',blending:0,depthTest:!1,depthWrite:!1});return i}(i,e,t)}return i}_compileMaterial(e){const t=new Wr(new vr,e);this._renderer.compile(t,co)}_sceneToCubeUV(e,t,n,i,r){const s=new Sa(90,1,t,n),a=[1,-1,1,1,1,1],o=[1,1,1,-1,-1,-1],l=this._renderer,u=l.autoClear,c=l.toneMapping;l.getClearColor(ho),l.toneMapping=0,l.autoClear=!1;l.state.buffers.depth.getReversed()&&(l.setRenderTarget(i),l.clearDepth(),l.setRenderTarget(null)),null===this._backgroundBox&&(this._backgroundBox=new Wr(new xs,new Dr({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const h=this._backgroundBox,d=h.material;let p=!1;const f=e.background;f?f.isColor&&(d.color.copy(f),e.background=null,p=!0):(d.color.copy(ho),p=!0);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x+o[t],r.y,r.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y+o[t],r.z)):(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y,r.z+o[t]));const u=this._cubeSize;bo(i,n*u,t>2?u:0,u,u),l.setRenderTarget(i),p&&l.render(h,s),l.render(e,s)}l.toneMapping=c,l.autoClear=u,e.background=f}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===ee||e.mapping===te;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=To()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=xo());const r=i?this._cubemapMaterial:this._equirectMaterial,s=this._lodMeshes[0];s.material=r;r.uniforms.envMap.value=e;const a=this._cubeSize;bo(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,co)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let t=1;t<i;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){const i=this._renderer,r=this._pingPongRenderTarget,s=this._ggxMaterial,a=this._lodMeshes[n];a.material=s;const o=s.uniforms,l=n/(this._lodMeshes.length-1),u=t/(this._lodMeshes.length-1),c=Math.sqrt(l*l-u*u)*(0+1.25*l),{_lodMax:h}=this,d=this._sizeLods[n],p=3*d*(n>h-4?n-h+4:0),f=4*(this._cubeSize-d);o.envMap.value=e.texture,o.roughness.value=c,o.mipInt.value=h-t,bo(r,p,f,3*d,2*d),i.setRenderTarget(r),i.render(a,co),o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=h-n,bo(e,p,f,3*d,2*d),i.setRenderTarget(e),i.render(a,co)}_blur(e,t,n,i,r){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,n,i,"latitudinal",r),this._halfBlur(s,e,n,n,i,"longitudinal",r)}_halfBlur(e,t,n,i,r,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&qt("blur direction must be either latitudinal or longitudinal!");const u=this._lodMeshes[i];u.material=l;const c=l.uniforms,h=this._sizeLods[n]-1,d=isFinite(r)?Math.PI/(2*h):2*Math.PI/39,p=r/d,f=isFinite(r)?1+Math.floor(3*p):uo;f>uo&&Xt(`sigmaRadians, ${r}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let e=0;e<uo;++e){const t=e/p,n=Math.exp(-t*t/2);m.push(n),0===e?g+=n:e<f&&(g+=2*n)}for(let e=0;e<m.length;e++)m[e]=m[e]/g;c.envMap.value=e.texture,c.samples.value=f,c.weights.value=m,c.latitudinal.value="latitudinal"===s,a&&(c.poleAxis.value=a);const{_lodMax:_}=this;c.dTheta.value=d,c.mipInt.value=_-n;const v=this._sizeLods[i];bo(t,3*v*(i>_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,co)}};function yo(e,t,n){const i=new Dn(e,t,n);return i.texture.mapping=re,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function bo(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function xo(){return new Ws({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:So(),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:0,depthTest:!1,depthWrite:!1})}function To(){return new Ws({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:So(),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:0,depthTest:!1,depthWrite:!1})}function So(){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"}class Mo extends Dn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new _s(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\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"},i=new xs(5,5,5),r=new Ws({name:"CubemapFromEquirect",uniforms:Vs(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const s=new Wr(i,r),a=t.minFilter;t.minFilter===pe&&(t.minFilter=he);return new Fa(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(r)}}function Eo(e){let t=new WeakMap,n=new WeakMap,i=null;function r(e,t){return t===ne?e.mapping=ee:t===ie&&(e.mapping=te),e}function s(e){const n=e.target;n.removeEventListener("dispose",s);const i=t.get(n);void 0!==i&&(t.delete(n),i.dispose())}function a(e){const t=e.target;t.removeEventListener("dispose",a);const i=n.get(t);void 0!==i&&(n.delete(t),i.dispose())}return{get:function(o,l=!1){return null==o?null:l?function(t){if(t&&t.isTexture){const r=t.mapping,s=r===ne||r===ie,o=r===ee||r===te;if(s||o){let r=n.get(t);const l=void 0!==r?r.texture.pmremVersion:0;if(t.isRenderTargetTexture&&t.pmremVersion!==l)return null===i&&(i=new vo(e)),r=s?i.fromEquirectangular(t,r):i.fromCubemap(t,r),r.texture.pmremVersion=t.pmremVersion,n.set(t,r),r.texture;if(void 0!==r)return r.texture;{const l=t.image;return s&&l&&l.height>0||o&&l&&function(e){let t=0;const n=6;for(let i=0;i<n;i++)void 0!==e[i]&&t++;return t===n}(l)?(null===i&&(i=new vo(e)),r=s?i.fromEquirectangular(t):i.fromCubemap(t),r.texture.pmremVersion=t.pmremVersion,n.set(t,r),t.addEventListener("dispose",a),r.texture):null}}}return t}(o):function(n){if(n&&n.isTexture){const i=n.mapping;if(i===ne||i===ie){if(t.has(n)){return r(t.get(n).texture,n.mapping)}{const i=n.image;if(i&&i.height>0){const a=new Mo(i.height);return a.fromEquirectangularTexture(e,n),t.set(n,a),n.addEventListener("dispose",s),r(a.texture,n.mapping)}return null}}}return n}(o)},dispose:function(){t=new WeakMap,n=new WeakMap,null!==i&&(i.dispose(),i=null)}}}function wo(e){const t={};function n(n){if(void 0!==t[n])return t[n];const i=e.getExtension(n);return t[n]=i,i}return{has:function(e){return null!==n(e)},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(e){const t=n(e);return null===t&&Yt("WebGLRenderer: "+e+" extension not supported."),t}}}function Ao(e,t,n,i){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]);o.removeEventListener("dispose",a),delete r[o.id];const l=s.get(o);l&&(t.remove(l),s.delete(o)),i.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,n.memory.geometries--}function o(e){const n=[],i=e.index,r=e.attributes.position;let a=0;if(void 0===r)return;if(null!==i){const e=i.array;a=i.version;for(let t=0,i=e.length;t<i;t+=3){const i=e[t+0],r=e[t+1],s=e[t+2];n.push(i,r,r,s,s,i)}}else{const e=r.array;a=r.version;for(let t=0,i=e.length/3-1;t<i;t+=3){const e=t+0,i=t+1,r=t+2;n.push(e,i,i,r,r,e)}}const o=new(r.count>=65535?rr:ir)(n,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,n.memory.geometries++),t},update:function(n){const i=n.attributes;for(const n in i)t.update(i[n],e.ARRAY_BUFFER)},getWireframeAttribute:function(e){const t=s.get(e);if(t){const n=e.index;null!==n&&t.version<n.version&&o(e)}else o(e);return s.get(e)}}}function Ro(e,t,n){let i,r,s;function a(t,a,o){0!==o&&(e.drawElementsInstanced(i,a,r,t*s,o),n.update(a,i,o))}this.setMode=function(e){i=e},this.setIndex=function(e){r=e.type,s=e.bytesPerElement},this.render=function(t,a){e.drawElements(i,a,r,t*s),n.update(a,i,1)},this.renderInstances=a,this.renderMultiDraw=function(e,s,a){if(0===a)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,s,0,r,e,0,a);let o=0;for(let e=0;e<a;e++)o+=s[e];n.update(o,i,1)},this.renderMultiDrawInstances=function(e,o,l,u){if(0===l)return;const c=t.get("WEBGL_multi_draw");if(null===c)for(let t=0;t<e.length;t++)a(e[t]/s,o[t],u[t]);else{c.multiDrawElementsInstancedWEBGL(i,o,0,r,e,0,u,0,l);let t=0;for(let e=0;e<l;e++)t+=o[e]*u[e];n.update(t,i,1)}}}function Co(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(n,i,r){switch(t.calls++,i){case e.TRIANGLES:t.triangles+=r*(n/3);break;case e.LINES:t.lines+=r*(n/2);break;case e.LINE_STRIP:t.lines+=r*(n-1);break;case e.LINE_LOOP:t.lines+=r*n;break;case e.POINTS:t.points+=r*n;break;default:qt("WebGLInfo: Unknown draw mode:",i)}}}}function No(e,t,n){const i=new WeakMap,r=new Pn;return{update:function(s,a,o){const l=s.morphTargetInfluences,u=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,c=void 0!==u?u.length:0;let h=i.get(a);if(void 0===h||h.count!==c){void 0!==h&&h.texture.dispose();const d=void 0!==a.morphAttributes.position,p=void 0!==a.morphAttributes.normal,f=void 0!==a.morphAttributes.color,m=a.morphAttributes.position||[],g=a.morphAttributes.normal||[],_=a.morphAttributes.color||[];let v=0;!0===d&&(v=1),!0===p&&(v=2),!0===f&&(v=3);let y=a.attributes.position.count*v,b=1;y>t.maxTextureSize&&(b=Math.ceil(y/t.maxTextureSize),y=t.maxTextureSize);const x=new Float32Array(y*b*4*c),T=new In(x,y,b,c);T.type=be,T.needsUpdate=!0;const S=4*v;for(let E=0;E<c;E++){const w=m[E],A=g[E],R=_[E],C=y*b*4*E;for(let N=0;N<w.count;N++){const P=N*S;!0===d&&(r.fromBufferAttribute(w,N),x[C+P+0]=r.x,x[C+P+1]=r.y,x[C+P+2]=r.z,x[C+P+3]=0),!0===p&&(r.fromBufferAttribute(A,N),x[C+P+4]=r.x,x[C+P+5]=r.y,x[C+P+6]=r.z,x[C+P+7]=0),!0===f&&(r.fromBufferAttribute(R,N),x[C+P+8]=r.x,x[C+P+9]=r.y,x[C+P+10]=r.z,x[C+P+11]=4===R.itemSize?r.w:1)}}function M(){T.dispose(),i.delete(a),a.removeEventListener("dispose",M)}h={count:c,texture:T,size:new cn(y,b)},i.set(a,h),a.addEventListener("dispose",M)}if(!0===s.isInstancedMesh&&null!==s.morphTexture)o.getUniforms().setValue(e,"morphTexture",s.morphTexture,n);else{let L=0;for(let I=0;I<l.length;I++)L+=l[I];const D=a.morphTargetsRelative?1:1-L;o.getUniforms().setValue(e,"morphTargetBaseInfluence",D),o.getUniforms().setValue(e,"morphTargetInfluences",l)}o.getUniforms().setValue(e,"morphTargetsTexture",h.texture,n),o.getUniforms().setValue(e,"morphTargetsTextureSize",h.size)}}}function Po(e,t,n,i,r){let s=new WeakMap;function a(e){const t=e.target;t.removeEventListener("dispose",a),i.releaseStatesOfObject(t),n.remove(t.instanceMatrix),null!==t.instanceColor&&n.remove(t.instanceColor)}return{update:function(i){const o=r.render.frame,l=i.geometry,u=t.get(i,l);if(s.get(u)!==o&&(t.update(u),s.set(u,o)),i.isInstancedMesh&&(!1===i.hasEventListener("dispose",a)&&i.addEventListener("dispose",a),s.get(i)!==o&&(n.update(i.instanceMatrix,e.ARRAY_BUFFER),null!==i.instanceColor&&n.update(i.instanceColor,e.ARRAY_BUFFER),s.set(i,o))),i.isSkinnedMesh){const e=i.skeleton;s.get(e)!==o&&(e.update(),s.set(e,o))}return u},dispose:function(){s=new WeakMap}}}const Lo={[X]:"LINEAR_TONE_MAPPING",[q]:"REINHARD_TONE_MAPPING",[Y]:"CINEON_TONE_MAPPING",[K]:"ACES_FILMIC_TONE_MAPPING",[Q]:"AGX_TONE_MAPPING",[J]:"NEUTRAL_TONE_MAPPING",[Z]:"CUSTOM_TONE_MAPPING"};function Do(e,t,n,i,r){const s=new Dn(t,n,{type:e,depthBuffer:i,stencilBuffer:r}),a=new Dn(t,n,{type:xe,depthBuffer:!1,stencilBuffer:!1}),o=new vr;o.setAttribute("position",new ar([-1,3,0,-1,-1,0,3,-1,0],3)),o.setAttribute("uv",new ar([0,2,0,0,2,0],2));const l=new $s({uniforms:{tDiffuse:{value:null}},vertexShader:"\n\t\t\tprecision highp float;\n\n\t\t\tuniform mat4 modelViewMatrix;\n\t\t\tuniform mat4 projectionMatrix;\n\n\t\t\tattribute vec3 position;\n\t\t\tattribute vec2 uv;\n\n\t\t\tvarying vec2 vUv;\n\n\t\t\tvoid main() {\n\t\t\t\tvUv = uv;\n\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\t\t\t}",fragmentShader:"\n\t\t\tprecision highp float;\n\n\t\t\tuniform sampler2D tDiffuse;\n\n\t\t\tvarying vec2 vUv;\n\n\t\t\t#include <tonemapping_pars_fragment>\n\t\t\t#include <colorspace_pars_fragment>\n\n\t\t\tvoid main() {\n\t\t\t\tgl_FragColor = texture2D( tDiffuse, vUv );\n\n\t\t\t\t#ifdef LINEAR_TONE_MAPPING\n\t\t\t\t\tgl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( REINHARD_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( CINEON_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( ACES_FILMIC_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( AGX_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( NEUTRAL_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( CUSTOM_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );\n\t\t\t\t#endif\n\n\t\t\t\t#ifdef SRGB_TRANSFER\n\t\t\t\t\tgl_FragColor = sRGBTransferOETF( gl_FragColor );\n\t\t\t\t#endif\n\t\t\t}",depthTest:!1,depthWrite:!1}),u=new Wr(o,l),c=new Ra(-1,1,1,-1,0,1);let h,d=null,p=null,f=!1,m=null,g=[],_=!1;this.setSize=function(e,t){s.setSize(e,t),a.setSize(e,t);for(let n=0;n<g.length;n++){const i=g[n];i.setSize&&i.setSize(e,t)}},this.setEffects=function(e){g=e,_=g.length>0&&!0===g[0].isRenderPass;const t=s.width,n=s.height;for(let e=0;e<g.length;e++){const i=g[e];i.setSize&&i.setSize(t,n)}},this.begin=function(e,t){if(f)return!1;if(0===e.toneMapping&&0===g.length)return!1;if(m=t,null!==t){const e=t.width,n=t.height;s.width===e&&s.height===n||this.setSize(e,n)}return!1===_&&e.setRenderTarget(s),h=e.toneMapping,e.toneMapping=0,!0},this.hasRenderPass=function(){return _},this.end=function(e,t){e.toneMapping=h,f=!0;let n=s,i=a;for(let r=0;r<g.length;r++){const s=g[r];if(!1!==s.enabled&&(s.render(e,i,n,t),!1!==s.needsSwap)){const e=n;n=i,i=e}}if(d!==e.outputColorSpace||p!==e.toneMapping){d=e.outputColorSpace,p=e.toneMapping,l.defines={},bn.getTransfer(d)===St&&(l.defines.SRGB_TRANSFER="");const t=Lo[p];t&&(l.defines[t]=""),l.needsUpdate=!0}l.uniforms.tDiffuse.value=n.texture,e.setRenderTarget(m),e.render(u,c),m=null,f=!1},this.isCompositing=function(){return f},this.dispose=function(){s.dispose(),a.dispose(),o.dispose(),l.dispose()}}const Io=new Nn,Uo=new vs(1,1),Fo=new In,Oo=new Un,Bo=new _s,ko=[],zo=[],Vo=new Float32Array(16),Go=new Float32Array(9),Ho=new Float32Array(4);function jo(e,t,n){const i=e[0];if(i<=0||i>0)return e;const r=t*n;let s=ko[r];if(void 0===s&&(s=new Float32Array(r),ko[r]=s),0!==t){i.toArray(s,0);for(let i=1,r=0;i!==t;++i)r+=n,e[i].toArray(s,r)}return s}function Wo(e,t){if(e.length!==t.length)return!1;for(let n=0,i=e.length;n<i;n++)if(e[n]!==t[n])return!1;return!0}function $o(e,t){for(let n=0,i=t.length;n<i;n++)e[n]=t[n]}function Xo(e,t){let n=zo[t];void 0===n&&(n=new Int32Array(t),zo[t]=n);for(let i=0;i!==t;++i)n[i]=e.allocateTextureUnit();return n}function qo(e,t){const n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function Yo(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Wo(n,t))return;e.uniform2fv(this.addr,t),$o(n,t)}}function Ko(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else if(void 0!==t.r)n[0]===t.r&&n[1]===t.g&&n[2]===t.b||(e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b);else{if(Wo(n,t))return;e.uniform3fv(this.addr,t),$o(n,t)}}function Zo(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Wo(n,t))return;e.uniform4fv(this.addr,t),$o(n,t)}}function Qo(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(Wo(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),$o(n,t)}else{if(Wo(n,i))return;Ho.set(i),e.uniformMatrix2fv(this.addr,!1,Ho),$o(n,i)}}function Jo(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(Wo(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),$o(n,t)}else{if(Wo(n,i))return;Go.set(i),e.uniformMatrix3fv(this.addr,!1,Go),$o(n,i)}}function el(e,t){const n=this.cache,i=t.elements;if(void 0===i){if(Wo(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),$o(n,t)}else{if(Wo(n,i))return;Vo.set(i),e.uniformMatrix4fv(this.addr,!1,Vo),$o(n,i)}}function tl(e,t){const n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function nl(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Wo(n,t))return;e.uniform2iv(this.addr,t),$o(n,t)}}function il(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(Wo(n,t))return;e.uniform3iv(this.addr,t),$o(n,t)}}function rl(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Wo(n,t))return;e.uniform4iv(this.addr,t),$o(n,t)}}function sl(e,t){const n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function al(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Wo(n,t))return;e.uniform2uiv(this.addr,t),$o(n,t)}}function ol(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(Wo(n,t))return;e.uniform3uiv(this.addr,t),$o(n,t)}}function ll(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Wo(n,t))return;e.uniform4uiv(this.addr,t),$o(n,t)}}function ul(e,t,n){const i=this.cache,r=n.allocateTextureUnit();let s;i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),this.type===e.SAMPLER_2D_SHADOW?(Uo.compareFunction=n.isReversedDepthBuffer()?Pt:Rt,s=Uo):s=Io,n.setTexture2D(t||s,r)}function cl(e,t,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),n.setTexture3D(t||Oo,r)}function hl(e,t,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),n.setTextureCube(t||Bo,r)}function dl(e,t,n){const i=this.cache,r=n.allocateTextureUnit();i[0]!==r&&(e.uniform1i(this.addr,r),i[0]=r),n.setTexture2DArray(t||Fo,r)}function pl(e,t){e.uniform1fv(this.addr,t)}function fl(e,t){const n=jo(t,this.size,2);e.uniform2fv(this.addr,n)}function ml(e,t){const n=jo(t,this.size,3);e.uniform3fv(this.addr,n)}function gl(e,t){const n=jo(t,this.size,4);e.uniform4fv(this.addr,n)}function _l(e,t){const n=jo(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function vl(e,t){const n=jo(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function yl(e,t){const n=jo(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function bl(e,t){e.uniform1iv(this.addr,t)}function xl(e,t){e.uniform2iv(this.addr,t)}function Tl(e,t){e.uniform3iv(this.addr,t)}function Sl(e,t){e.uniform4iv(this.addr,t)}function Ml(e,t){e.uniform1uiv(this.addr,t)}function El(e,t){e.uniform2uiv(this.addr,t)}function wl(e,t){e.uniform3uiv(this.addr,t)}function Al(e,t){e.uniform4uiv(this.addr,t)}function Rl(e,t,n){const i=this.cache,r=t.length,s=Xo(n,r);let a;Wo(i,s)||(e.uniform1iv(this.addr,s),$o(i,s)),a=this.type===e.SAMPLER_2D_SHADOW?Uo:Io;for(let e=0;e!==r;++e)n.setTexture2D(t[e]||a,s[e])}function Cl(e,t,n){const i=this.cache,r=t.length,s=Xo(n,r);Wo(i,s)||(e.uniform1iv(this.addr,s),$o(i,s));for(let e=0;e!==r;++e)n.setTexture3D(t[e]||Oo,s[e])}function Nl(e,t,n){const i=this.cache,r=t.length,s=Xo(n,r);Wo(i,s)||(e.uniform1iv(this.addr,s),$o(i,s));for(let e=0;e!==r;++e)n.setTextureCube(t[e]||Bo,s[e])}function Pl(e,t,n){const i=this.cache,r=t.length,s=Xo(n,r);Wo(i,s)||(e.uniform1iv(this.addr,s),$o(i,s));for(let e=0;e!==r;++e)n.setTexture2DArray(t[e]||Fo,s[e])}class Ll{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=function(e){switch(e){case 5126:return qo;case 35664:return Yo;case 35665:return Ko;case 35666:return Zo;case 35674:return Qo;case 35675:return Jo;case 35676:return el;case 5124:case 35670:return tl;case 35667:case 35671:return nl;case 35668:case 35672:return il;case 35669:case 35673:return rl;case 5125:return sl;case 36294:return al;case 36295:return ol;case 36296:return ll;case 35678:case 36198:case 36298:case 36306:case 35682:return ul;case 35679:case 36299:case 36307:return cl;case 35680:case 36300:case 36308:case 36293:return hl;case 36289:case 36303:case 36311:case 36292:return dl}}(t.type)}}class Dl{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=function(e){switch(e){case 5126:return pl;case 35664:return fl;case 35665:return ml;case 35666:return gl;case 35674:return _l;case 35675:return vl;case 35676:return yl;case 5124:case 35670:return bl;case 35667:case 35671:return xl;case 35668:case 35672:return Tl;case 35669:case 35673:return Sl;case 5125:return Ml;case 36294:return El;case 36295:return wl;case 36296:return Al;case 35678:case 36198:case 36298:case 36306:case 35682:return Rl;case 35679:case 36299:case 36307:return Cl;case 35680:case 36300:case 36308:case 36293:return Nl;case 36289:case 36303:case 36311:case 36292:return Pl}}(t.type)}}class Il{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const i=this.seq;for(let r=0,s=i.length;r!==s;++r){const s=i[r];s.setValue(e,t[s.id],n)}}}const Ul=/(\w+)(\])?(\[|\.)?/g;function Fl(e,t){e.seq.push(t),e.map[t.id]=t}function Ol(e,t,n){const i=e.name,r=i.length;for(Ul.lastIndex=0;;){const s=Ul.exec(i),a=Ul.lastIndex;let o=s[1];const l="]"===s[2],u=s[3];if(l&&(o|=0),void 0===u||"["===u&&a+2===r){Fl(n,void 0===u?new Ll(o,e,t):new Dl(o,e,t));break}{let e=n.map[o];void 0===e&&(e=new Il(o),Fl(n,e)),n=e}}}class Bl{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let i=0;i<n;++i){const n=e.getActiveUniform(t,i);Ol(n,e.getUniformLocation(t,n.name),this)}const i=[],r=[];for(const t of this.seq)t.type===e.SAMPLER_2D_SHADOW||t.type===e.SAMPLER_CUBE_SHADOW||t.type===e.SAMPLER_2D_ARRAY_SHADOW?i.push(t):r.push(t);i.length>0&&(this.seq=i.concat(r))}setValue(e,t,n,i){const r=this.map[t];void 0!==r&&r.setValue(e,n,i)}setOptional(e,t,n){const i=t[n];void 0!==i&&this.setValue(e,n,i)}static upload(e,t,n,i){for(let r=0,s=t.length;r!==s;++r){const s=t[r],a=n[s.id];!1!==a.needsUpdate&&s.setValue(e,a.value,i)}}static seqWithValue(e,t){const n=[];for(let i=0,r=e.length;i!==r;++i){const r=e[i];r.id in t&&n.push(r)}return n}}function kl(e,t,n){const i=e.createShader(t);return e.shaderSource(i,n),e.compileShader(i),i}let zl=0;const Vl=new mn;function Gl(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(i&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const i=parseInt(s[1]);return n.toUpperCase()+"\n\n"+r+"\n\n"+function(e,t){const n=e.split("\n"),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let e=r;e<s;e++){const r=e+1;i.push(`${r===t?">":" "} ${r}: ${n[e]}`)}return i.join("\n")}(e.getShaderSource(t),i)}return r}function Hl(e,t){const n=function(e){bn._getMatrix(Vl,bn.workingColorSpace,e);const t=`mat3( ${Vl.elements.map(e=>e.toFixed(4))} )`;switch(bn.getTransfer(e)){case Tt:return[t,"LinearTransferOETF"];case St:return[t,"sRGBTransferOETF"];default:return Xt("WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}(t);return[`vec4 ${e}( vec4 value ) {`,`\treturn ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join("\n")}const jl={[X]:"Linear",[q]:"Reinhard",[Y]:"Cineon",[K]:"ACESFilmic",[Q]:"AgX",[J]:"Neutral",[Z]:"Custom"};function Wl(e,t){const n=jl[t];return void 0===n?(Xt("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+e+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const $l=new dn;function Xl(){bn.getLuminanceCoefficients($l);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${$l.x.toFixed(4)}, ${$l.y.toFixed(4)}, ${$l.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function ql(e){return""!==e}function Yl(e,t){const n=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,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_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 Kl(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const Zl=/^[ \t]*#include +<([\w\d./]+)>/gm;function Ql(e){return e.replace(Zl,eu)}const Jl=new Map;function eu(e,t){let n=Za[t];if(void 0===n){const e=Jl.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=Za[e],Xt('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return Ql(n)}const tu=/#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 nu(e){return e.replace(tu,iu)}function iu(e,t,n,i){let r="";for(let e=parseInt(t);e<parseInt(n);e++)r+=i.replace(/\[\s*i\s*\]/g,"[ "+e+" ]").replace(/UNROLLED_LOOP_INDEX/g,e);return r}function ru(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}const su={[p]:"SHADOWMAP_TYPE_PCF",[f]:"SHADOWMAP_TYPE_VSM"};const au={[ee]:"ENVMAP_TYPE_CUBE",[te]:"ENVMAP_TYPE_CUBE",[re]:"ENVMAP_TYPE_CUBE_UV"};const ou={[te]:"ENVMAP_MODE_REFRACTION"};const lu={[j]:"ENVMAP_BLENDING_MULTIPLY",[W]:"ENVMAP_BLENDING_MIX",[$]:"ENVMAP_BLENDING_ADD"};function uu(e,t,n,i){const r=e.getContext(),s=n.defines;let a=n.vertexShader,o=n.fragmentShader;const l=function(e){return su[e.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}(n),u=function(e){return!1===e.envMap?"ENVMAP_TYPE_CUBE":au[e.envMapMode]||"ENVMAP_TYPE_CUBE"}(n),c=function(e){return!1===e.envMap?"ENVMAP_MODE_REFLECTION":ou[e.envMapMode]||"ENVMAP_MODE_REFLECTION"}(n),h=function(e){return!1===e.envMap?"ENVMAP_BLENDING_NONE":lu[e.combine]||"ENVMAP_BLENDING_NONE"}(n),d=function(e){const t=e.envMapCubeUVHeight;if(null===t)return null;const n=Math.log2(t)-2,i=1/t;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:i,maxMip:n}}(n),p=function(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(ql).join("\n")}(n),f=function(e){const t=[];for(const n in e){const i=e[n];!1!==i&&t.push("#define "+n+" "+i)}return t.join("\n")}(s),m=r.createProgram();let g,_,v=n.glslVersion?"#version "+n.glslVersion+"\n":"";n.isRawShaderMaterial?(g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(ql).join("\n"),g.length>0&&(g+="\n"),_=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(ql).join("\n"),_.length>0&&(_+="\n")):(g=[ru(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+c:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(ql).join("\n"),_=[ru(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.envMap?"#define "+c:"",n.envMap?"#define "+h:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor?"#define USE_COLOR":"",n.vertexAlphas||n.batchingColor?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?Za.tonemapping_pars_fragment:"",0!==n.toneMapping?Wl("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Za.colorspace_pars_fragment,Hl("linearToOutputTexel",n.outputColorSpace),Xl(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(ql).join("\n")),a=Ql(a),a=Yl(a,n),a=Kl(a,n),o=Ql(o),o=Yl(o,n),o=Kl(o,n),a=nu(a),o=nu(o),!0!==n.isRawShaderMaterial&&(v="#version 300 es\n",g=[p,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,_=["#define varying in",n.glslVersion===Ut?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===Ut?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+_);const y=v+g+a,b=v+_+o,x=kl(r,r.VERTEX_SHADER,y),T=kl(r,r.FRAGMENT_SHADER,b);function S(t){if(e.debug.checkShaderErrors){const n=r.getProgramInfoLog(m)||"",i=r.getShaderInfoLog(x)||"",s=r.getShaderInfoLog(T)||"",a=n.trim(),o=i.trim(),l=s.trim();let u=!0,c=!0;if(!1===r.getProgramParameter(m,r.LINK_STATUS))if(u=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(r,m,x,T);else{const e=Gl(r,x,"vertex"),n=Gl(r,T,"fragment");qt("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(m,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+a+"\n"+e+"\n"+n)}else""!==a?Xt("WebGLProgram: Program Info Log:",a):""!==o&&""!==l||(c=!1);c&&(t.diagnostics={runnable:u,programLog:a,vertexShader:{log:o,prefix:g},fragmentShader:{log:l,prefix:_}})}r.deleteShader(x),r.deleteShader(T),M=new Bl(r,m),E=function(e,t){const n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<i;r++){const i=e.getActiveAttrib(t,r),s=i.name;let a=1;i.type===e.FLOAT_MAT2&&(a=2),i.type===e.FLOAT_MAT3&&(a=3),i.type===e.FLOAT_MAT4&&(a=4),n[s]={type:i.type,location:e.getAttribLocation(t,s),locationSize:a}}return n}(r,m)}let M,E;r.attachShader(m,x),r.attachShader(m,T),void 0!==n.index0AttributeName?r.bindAttribLocation(m,0,n.index0AttributeName):!0===n.morphTargets&&r.bindAttribLocation(m,0,"position"),r.linkProgram(m),this.getUniforms=function(){return void 0===M&&S(this),M},this.getAttributes=function(){return void 0===E&&S(this),E};let w=!1===n.rendererExtensionParallelShaderCompile;return this.isReady=function(){return!1===w&&(w=r.getProgramParameter(m,37297)),w},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(m),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=zl++,this.cacheKey=t,this.usedTimes=1,this.program=m,this.vertexShader=x,this.fragmentShader=T,this}let cu=0;class hu{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,i=this._getShaderStage(t),r=this._getShaderStage(n),s=this._getShaderCacheForMaterial(e);return!1===s.has(i)&&(s.add(i),i.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 n=t.get(e);return void 0===n&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return void 0===n&&(n=new du(e),t.set(e,n)),n}}class du{constructor(e){this.id=cu++,this.code=e,this.usedTimes=0}}function pu(e,t,n,i,r,s){const a=new Xn,o=new hu,l=new Set,u=[],c=new Map,h=i.logarithmicDepthBuffer;let d=i.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function f(e){return l.add(e),0===e?"uv":`uv${e}`}return{getParameters:function(r,a,u,c,m){const g=c.fog,_=m.geometry,v=r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial?c.environment:null,y=r.isMeshStandardMaterial||r.isMeshLambertMaterial&&!r.envMap||r.isMeshPhongMaterial&&!r.envMap,b=t.get(r.envMap||v,y),x=b&&b.mapping===re?b.image.height:null,T=p[r.type];null!==r.precision&&(d=i.getMaxPrecision(r.precision),d!==r.precision&&Xt("WebGLProgram.getParameters:",r.precision,"not supported, using",d,"instead."));const S=_.morphAttributes.position||_.morphAttributes.normal||_.morphAttributes.color,M=void 0!==S?S.length:0;let E,w,A,R,C=0;if(void 0!==_.morphAttributes.position&&(C=1),void 0!==_.morphAttributes.normal&&(C=2),void 0!==_.morphAttributes.color&&(C=3),T){const e=Ja[T];E=e.vertexShader,w=e.fragmentShader}else E=r.vertexShader,w=r.fragmentShader,o.update(r),A=o.getVertexShaderID(r),R=o.getFragmentShaderID(r);const N=e.getRenderTarget(),P=e.state.buffers.depth.getReversed(),L=!0===m.isInstancedMesh,D=!0===m.isBatchedMesh,I=!!r.map,U=!!r.matcap,F=!!b,O=!!r.aoMap,B=!!r.lightMap,k=!!r.bumpMap,z=!!r.normalMap,V=!!r.displacementMap,G=!!r.emissiveMap,H=!!r.metalnessMap,j=!!r.roughnessMap,W=r.anisotropy>0,$=r.clearcoat>0,X=r.dispersion>0,q=r.iridescence>0,Y=r.sheen>0,K=r.transmission>0,Z=W&&!!r.anisotropyMap,Q=$&&!!r.clearcoatMap,J=$&&!!r.clearcoatNormalMap,ee=$&&!!r.clearcoatRoughnessMap,te=q&&!!r.iridescenceMap,ne=q&&!!r.iridescenceThicknessMap,ie=Y&&!!r.sheenColorMap,se=Y&&!!r.sheenRoughnessMap,ae=!!r.specularMap,oe=!!r.specularColorMap,le=!!r.specularIntensityMap,ue=K&&!!r.transmissionMap,ce=K&&!!r.thicknessMap,he=!!r.gradientMap,de=!!r.alphaMap,pe=r.alphaTest>0,fe=!!r.alphaHash,me=!!r.extensions;let ge=0;r.toneMapped&&(null!==N&&!0!==N.isXRRenderTarget||(ge=e.toneMapping));const _e={shaderID:T,shaderType:r.type,shaderName:r.name,vertexShader:E,fragmentShader:w,defines:r.defines,customVertexShaderID:A,customFragmentShaderID:R,isRawShaderMaterial:!0===r.isRawShaderMaterial,glslVersion:r.glslVersion,precision:d,batching:D,batchingColor:D&&null!==m._colorsTexture,instancing:L,instancingColor:L&&null!==m.instanceColor,instancingMorph:L&&null!==m.morphTexture,outputColorSpace:null===N?e.outputColorSpace:!0===N.isXRRenderTarget?N.texture.colorSpace:xt,alphaToCoverage:!!r.alphaToCoverage,map:I,matcap:U,envMap:F,envMapMode:F&&b.mapping,envMapCubeUVHeight:x,aoMap:O,lightMap:B,bumpMap:k,normalMap:z,displacementMap:V,emissiveMap:G,normalMapObjectSpace:z&&1===r.normalMapType,normalMapTangentSpace:z&&0===r.normalMapType,metalnessMap:H,roughnessMap:j,anisotropy:W,anisotropyMap:Z,clearcoat:$,clearcoatMap:Q,clearcoatNormalMap:J,clearcoatRoughnessMap:ee,dispersion:X,iridescence:q,iridescenceMap:te,iridescenceThicknessMap:ne,sheen:Y,sheenColorMap:ie,sheenRoughnessMap:se,specularMap:ae,specularColorMap:oe,specularIntensityMap:le,transmission:K,transmissionMap:ue,thicknessMap:ce,gradientMap:he,opaque:!1===r.transparent&&1===r.blending&&!1===r.alphaToCoverage,alphaMap:de,alphaTest:pe,alphaHash:fe,combine:r.combine,mapUv:I&&f(r.map.channel),aoMapUv:O&&f(r.aoMap.channel),lightMapUv:B&&f(r.lightMap.channel),bumpMapUv:k&&f(r.bumpMap.channel),normalMapUv:z&&f(r.normalMap.channel),displacementMapUv:V&&f(r.displacementMap.channel),emissiveMapUv:G&&f(r.emissiveMap.channel),metalnessMapUv:H&&f(r.metalnessMap.channel),roughnessMapUv:j&&f(r.roughnessMap.channel),anisotropyMapUv:Z&&f(r.anisotropyMap.channel),clearcoatMapUv:Q&&f(r.clearcoatMap.channel),clearcoatNormalMapUv:J&&f(r.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ee&&f(r.clearcoatRoughnessMap.channel),iridescenceMapUv:te&&f(r.iridescenceMap.channel),iridescenceThicknessMapUv:ne&&f(r.iridescenceThicknessMap.channel),sheenColorMapUv:ie&&f(r.sheenColorMap.channel),sheenRoughnessMapUv:se&&f(r.sheenRoughnessMap.channel),specularMapUv:ae&&f(r.specularMap.channel),specularColorMapUv:oe&&f(r.specularColorMap.channel),specularIntensityMapUv:le&&f(r.specularIntensityMap.channel),transmissionMapUv:ue&&f(r.transmissionMap.channel),thicknessMapUv:ce&&f(r.thicknessMap.channel),alphaMapUv:de&&f(r.alphaMap.channel),vertexTangents:!!_.attributes.tangent&&(z||W),vertexColors:r.vertexColors,vertexAlphas:!0===r.vertexColors&&!!_.attributes.color&&4===_.attributes.color.itemSize,pointsUvs:!0===m.isPoints&&!!_.attributes.uv&&(I||de),fog:!!g,useFog:!0===r.fog,fogExp2:!!g&&g.isFogExp2,flatShading:!1===r.wireframe&&(!0===r.flatShading||void 0===_.attributes.normal&&!1===z&&(r.isMeshLambertMaterial||r.isMeshPhongMaterial||r.isMeshStandardMaterial||r.isMeshPhysicalMaterial)),sizeAttenuation:!0===r.sizeAttenuation,logarithmicDepthBuffer:h,reversedDepthBuffer:P,skinning:!0===m.isSkinnedMesh,morphTargets:void 0!==_.morphAttributes.position,morphNormals:void 0!==_.morphAttributes.normal,morphColors:void 0!==_.morphAttributes.color,morphTargetsCount:M,morphTextureStride:C,numDirLights:a.directional.length,numPointLights:a.point.length,numSpotLights:a.spot.length,numSpotLightMaps:a.spotLightMap.length,numRectAreaLights:a.rectArea.length,numHemiLights:a.hemi.length,numDirLightShadows:a.directionalShadowMap.length,numPointLightShadows:a.pointShadowMap.length,numSpotLightShadows:a.spotShadowMap.length,numSpotLightShadowsWithMaps:a.numSpotLightShadowsWithMaps,numLightProbes:a.numLightProbes,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:r.dithering,shadowMapEnabled:e.shadowMap.enabled&&u.length>0,shadowMapType:e.shadowMap.type,toneMapping:ge,decodeVideoTexture:I&&!0===r.map.isVideoTexture&&bn.getTransfer(r.map.colorSpace)===St,decodeVideoTextureEmissive:G&&!0===r.emissiveMap.isVideoTexture&&bn.getTransfer(r.emissiveMap.colorSpace)===St,premultipliedAlpha:r.premultipliedAlpha,doubleSided:2===r.side,flipSided:1===r.side,useDepthPacking:r.depthPacking>=0,depthPacking:r.depthPacking||0,index0AttributeName:r.index0AttributeName,extensionClipCullDistance:me&&!0===r.extensions.clipCullDistance&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(me&&!0===r.extensions.multiDraw||D)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:r.customProgramCacheKey()};return _e.vertexUv1s=l.has(1),_e.vertexUv2s=l.has(2),_e.vertexUv3s=l.has(3),l.clear(),_e},getProgramCacheKey:function(t){const n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)n.push(e),n.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)}(n,t),function(e,t){a.disableAll(),t.instancing&&a.enable(0);t.instancingColor&&a.enable(1);t.instancingMorph&&a.enable(2);t.matcap&&a.enable(3);t.envMap&&a.enable(4);t.normalMapObjectSpace&&a.enable(5);t.normalMapTangentSpace&&a.enable(6);t.clearcoat&&a.enable(7);t.iridescence&&a.enable(8);t.alphaTest&&a.enable(9);t.vertexColors&&a.enable(10);t.vertexAlphas&&a.enable(11);t.vertexUv1s&&a.enable(12);t.vertexUv2s&&a.enable(13);t.vertexUv3s&&a.enable(14);t.vertexTangents&&a.enable(15);t.anisotropy&&a.enable(16);t.alphaHash&&a.enable(17);t.batching&&a.enable(18);t.dispersion&&a.enable(19);t.batchingColor&&a.enable(20);t.gradientMap&&a.enable(21);e.push(a.mask),a.disableAll(),t.fog&&a.enable(0);t.useFog&&a.enable(1);t.flatShading&&a.enable(2);t.logarithmicDepthBuffer&&a.enable(3);t.reversedDepthBuffer&&a.enable(4);t.skinning&&a.enable(5);t.morphTargets&&a.enable(6);t.morphNormals&&a.enable(7);t.morphColors&&a.enable(8);t.premultipliedAlpha&&a.enable(9);t.shadowMapEnabled&&a.enable(10);t.doubleSided&&a.enable(11);t.flipSided&&a.enable(12);t.useDepthPacking&&a.enable(13);t.dithering&&a.enable(14);t.transmission&&a.enable(15);t.sheen&&a.enable(16);t.opaque&&a.enable(17);t.pointsUvs&&a.enable(18);t.decodeVideoTexture&&a.enable(19);t.decodeVideoTextureEmissive&&a.enable(20);t.alphaToCoverage&&a.enable(21);e.push(a.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){const t=p[e.type];let n;if(t){const e=Ja[t];n=js.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let i=c.get(n);return void 0!==i?++i.usedTimes:(i=new uu(e,n,t,r),u.push(i),c.set(n,i)),i},releaseProgram:function(e){if(0===--e.usedTimes){const t=u.indexOf(e);u[t]=u[u.length-1],u.pop(),c.delete(e.cacheKey),e.destroy()}},releaseShaderCache:function(e){o.remove(e)},programs:u,dispose:function(){o.dispose()}}}function fu(){let e=new WeakMap;return{has:function(t){return e.has(t)},get:function(t){let n=e.get(t);return void 0===n&&(n={},e.set(t,n)),n},remove:function(t){e.delete(t)},update:function(t,n,i){e.get(t)[n]=i},dispose:function(){e=new WeakMap}}}function mu(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.materialVariant!==t.materialVariant?e.materialVariant-t.materialVariant:e.z!==t.z?e.z-t.z:e.id-t.id}function gu(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 _u(){const e=[];let t=0;const n=[],i=[],r=[];function s(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function a(n,i,r,a,o,l){let u=e[t];return void 0===u?(u={id:n.id,object:n,geometry:i,material:r,materialVariant:s(n),groupOrder:a,renderOrder:n.renderOrder,z:o,group:l},e[t]=u):(u.id=n.id,u.object=n,u.geometry=i,u.material=r,u.materialVariant=s(n),u.groupOrder=a,u.renderOrder=n.renderOrder,u.z=o,u.group=l),t++,u}return{opaque:n,transmissive:i,transparent:r,init:function(){t=0,n.length=0,i.length=0,r.length=0},push:function(e,t,s,o,l,u){const c=a(e,t,s,o,l,u);s.transmission>0?i.push(c):!0===s.transparent?r.push(c):n.push(c)},unshift:function(e,t,s,o,l,u){const c=a(e,t,s,o,l,u);s.transmission>0?i.unshift(c):!0===s.transparent?r.unshift(c):n.unshift(c)},finish:function(){for(let n=t,i=e.length;n<i;n++){const t=e[n];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}},sort:function(e,t){n.length>1&&n.sort(e||mu),i.length>1&&i.sort(t||gu),r.length>1&&r.sort(t||gu)}}}function vu(){let e=new WeakMap;return{get:function(t,n){const i=e.get(t);let r;return void 0===i?(r=new _u,e.set(t,[r])):n>=i.length?(r=new _u,i.push(r)):r=i[n],r},dispose:function(){e=new WeakMap}}}function yu(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":n={direction:new dn,color:new _i};break;case"SpotLight":n={position:new dn,direction:new dn,color:new _i,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new dn,color:new _i,distance:0,decay:0};break;case"HemisphereLight":n={direction:new dn,skyColor:new _i,groundColor:new _i};break;case"RectAreaLight":n={color:new _i,position:new dn,halfWidth:new dn,halfHeight:new dn}}return e[t.id]=n,n}}}let bu=0;function xu(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Tu(e){const t=new yu,n=function(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new cn};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new cn,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)i.probe.push(new dn);const r=new dn,s=new Fn,a=new Fn;return{setup:function(r){let s=0,a=0,o=0;for(let e=0;e<9;e++)i.probe[e].set(0,0,0);let l=0,u=0,c=0,h=0,d=0,p=0,f=0,m=0,g=0,_=0,v=0;r.sort(xu);for(let e=0,y=r.length;e<y;e++){const y=r[e],b=y.color,x=y.intensity,T=y.distance;let S=null;if(y.shadow&&y.shadow.map&&(S=y.shadow.map.texture.format===Ie?y.shadow.map.texture:y.shadow.map.depthTexture||y.shadow.map.texture),y.isAmbientLight)s+=b.r*x,a+=b.g*x,o+=b.b*x;else if(y.isLightProbe){for(let e=0;e<9;e++)i.probe[e].addScaledVector(y.sh.coefficients[e],x);v++}else if(y.isDirectionalLight){const e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),y.castShadow){const e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,i.directionalShadow[l]=t,i.directionalShadowMap[l]=S,i.directionalShadowMatrix[l]=y.shadow.matrix,p++}i.directional[l]=e,l++}else if(y.isSpotLight){const e=t.get(y);e.position.setFromMatrixPosition(y.matrixWorld),e.color.copy(b).multiplyScalar(x),e.distance=T,e.coneCos=Math.cos(y.angle),e.penumbraCos=Math.cos(y.angle*(1-y.penumbra)),e.decay=y.decay,i.spot[c]=e;const r=y.shadow;if(y.map&&(i.spotLightMap[g]=y.map,g++,r.updateMatrices(y),y.castShadow&&_++),i.spotLightMatrix[c]=r.matrix,y.castShadow){const e=n.get(y);e.shadowIntensity=r.intensity,e.shadowBias=r.bias,e.shadowNormalBias=r.normalBias,e.shadowRadius=r.radius,e.shadowMapSize=r.mapSize,i.spotShadow[c]=e,i.spotShadowMap[c]=S,m++}c++}else if(y.isRectAreaLight){const e=t.get(y);e.color.copy(b).multiplyScalar(x),e.halfWidth.set(.5*y.width,0,0),e.halfHeight.set(0,.5*y.height,0),i.rectArea[h]=e,h++}else if(y.isPointLight){const e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),e.distance=y.distance,e.decay=y.decay,y.castShadow){const e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,i.pointShadow[u]=t,i.pointShadowMap[u]=S,i.pointShadowMatrix[u]=y.shadow.matrix,f++}i.point[u]=e,u++}else if(y.isHemisphereLight){const e=t.get(y);e.skyColor.copy(y.color).multiplyScalar(x),e.groundColor.copy(y.groundColor).multiplyScalar(x),i.hemi[d]=e,d++}}h>0&&(!0===e.has("OES_texture_float_linear")?(i.rectAreaLTC1=Qa.LTC_FLOAT_1,i.rectAreaLTC2=Qa.LTC_FLOAT_2):(i.rectAreaLTC1=Qa.LTC_HALF_1,i.rectAreaLTC2=Qa.LTC_HALF_2)),i.ambient[0]=s,i.ambient[1]=a,i.ambient[2]=o;const y=i.hash;y.directionalLength===l&&y.pointLength===u&&y.spotLength===c&&y.rectAreaLength===h&&y.hemiLength===d&&y.numDirectionalShadows===p&&y.numPointShadows===f&&y.numSpotShadows===m&&y.numSpotMaps===g&&y.numLightProbes===v||(i.directional.length=l,i.spot.length=c,i.rectArea.length=h,i.point.length=u,i.hemi.length=d,i.directionalShadow.length=p,i.directionalShadowMap.length=p,i.pointShadow.length=f,i.pointShadowMap.length=f,i.spotShadow.length=m,i.spotShadowMap.length=m,i.directionalShadowMatrix.length=p,i.pointShadowMatrix.length=f,i.spotLightMatrix.length=m+g-_,i.spotLightMap.length=g,i.numSpotLightShadowsWithMaps=_,i.numLightProbes=v,y.directionalLength=l,y.pointLength=u,y.spotLength=c,y.rectAreaLength=h,y.hemiLength=d,y.numDirectionalShadows=p,y.numPointShadows=f,y.numSpotShadows=m,y.numSpotMaps=g,y.numLightProbes=v,i.version=bu++)},setupView:function(e,t){let n=0,o=0,l=0,u=0,c=0;const h=t.matrixWorldInverse;for(let t=0,d=e.length;t<d;t++){const d=e[t];if(d.isDirectionalLight){const e=i.directional[n];e.direction.setFromMatrixPosition(d.matrixWorld),r.setFromMatrixPosition(d.target.matrixWorld),e.direction.sub(r),e.direction.transformDirection(h),n++}else if(d.isSpotLight){const e=i.spot[l];e.position.setFromMatrixPosition(d.matrixWorld),e.position.applyMatrix4(h),e.direction.setFromMatrixPosition(d.matrixWorld),r.setFromMatrixPosition(d.target.matrixWorld),e.direction.sub(r),e.direction.transformDirection(h),l++}else if(d.isRectAreaLight){const e=i.rectArea[u];e.position.setFromMatrixPosition(d.matrixWorld),e.position.applyMatrix4(h),a.identity(),s.copy(d.matrixWorld),s.premultiply(h),a.extractRotation(s),e.halfWidth.set(.5*d.width,0,0),e.halfHeight.set(0,.5*d.height,0),e.halfWidth.applyMatrix4(a),e.halfHeight.applyMatrix4(a),u++}else if(d.isPointLight){const e=i.point[o];e.position.setFromMatrixPosition(d.matrixWorld),e.position.applyMatrix4(h),o++}else if(d.isHemisphereLight){const e=i.hemi[c];e.direction.setFromMatrixPosition(d.matrixWorld),e.direction.transformDirection(h),c++}}},state:i}}function Su(e){const t=new Tu(e),n=[],i=[];const r={lightsArray:n,shadowsArray:i,camera:null,lights:t,transmissionRenderTarget:{}};return{init:function(e){r.camera=e,n.length=0,i.length=0},state:r,setupLights:function(){t.setup(n)},setupLightsView:function(e){t.setupView(n,e)},pushLight:function(e){n.push(e)},pushShadow:function(e){i.push(e)}}}function Mu(e){let t=new WeakMap;return{get:function(n,i=0){const r=t.get(n);let s;return void 0===r?(s=new Su(e),t.set(n,[s])):i>=r.length?(s=new Su(e),r.push(s)):s=r[i],s},dispose:function(){t=new WeakMap}}}const Eu=[new dn(1,0,0),new dn(-1,0,0),new dn(0,1,0),new dn(0,-1,0),new dn(0,0,1),new dn(0,0,-1)],wu=[new dn(0,-1,0),new dn(0,-1,0),new dn(0,0,1),new dn(0,0,-1),new dn(0,-1,0),new dn(0,-1,0)],Au=new Fn,Ru=new dn,Cu=new dn;function Nu(e,t,n){let i=new ns;const r=new cn,s=new cn,a=new Pn,o=new Js,l=new ea,u={},c=n.maxTextureSize,h={[m]:1,[g]:0,[_]:2},d=new Ws({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new cn},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;\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 = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;\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 = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;\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( max( 0.0, squared_mean - mean * mean ) );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}"}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const f=new vr;f.setAttribute("position",new nr(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Wr(f,d),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let b=this.type;function x(n,i){const s=t.update(v);d.defines.VSM_SAMPLES!==n.blurSamples&&(d.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new Dn(r.x,r.y,{format:Ie,type:xe})),d.uniforms.shadow_pass.value=n.map.depthTexture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(i,null,s,d,v,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(i,null,s,p,v,null)}function T(t,n,i,r){let s=null;const a=!0===i.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?l:o,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||!0===n.alphaToCoverage){const e=s.uuid,t=n.uuid;let i=u[e];void 0===i&&(i={},u[e]=i);let r=i[t];void 0===r&&(r=s.clone(),i[t]=r,n.addEventListener("dispose",M)),s=r}if(s.visible=n.visible,s.wireframe=n.wireframe,s.side=3===r?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:h[n.side],s.alphaMap=n.alphaMap,s.alphaTest=!0===n.alphaToCoverage?.5:n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===i.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=i}return s}function S(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=t.update(n),l=n.material;if(Array.isArray(l)){const t=i.groups;for(let u=0,c=t.length;u<c;u++){const c=t[u],h=l[c.materialIndex];if(h&&h.visible){const t=T(n,h,a,o);n.onBeforeShadow(e,n,r,s,i,t,c),e.renderBufferDirect(s,null,i,t,n,c),n.onAfterShadow(e,n,r,s,i,t,c)}}}else if(l.visible){const t=T(n,l,a,o);n.onBeforeShadow(e,n,r,s,i,t,null),e.renderBufferDirect(s,null,i,t,n,null),n.onAfterShadow(e,n,r,s,i,t,null)}}const l=n.children;for(let e=0,t=l.length;e<t;e++)S(l[e],r,s,a,o)}function M(e){e.target.removeEventListener("dispose",M);for(const t in u){const n=u[t],i=e.target.uuid;if(i in n){n[i].dispose(),delete n[i]}}}this.render=function(t,n,o){if(!1===y.enabled)return;if(!1===y.autoUpdate&&!1===y.needsUpdate)return;if(0===t.length)return;2===this.type&&(Xt("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=1);const l=e.getRenderTarget(),u=e.getActiveCubeFace(),h=e.getActiveMipmapLevel(),d=e.state;d.setBlending(0),!0===d.buffers.depth.getReversed()?d.buffers.color.setClear(0,0,0,0):d.buffers.color.setClear(1,1,1,1),d.buffers.depth.setTest(!0),d.setScissorTest(!1);const p=b!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let l=0,u=t.length;l<u;l++){const u=t[l],h=u.shadow;if(void 0===h){Xt("WebGLShadowMap:",u,"has no shadow.");continue}if(!1===h.autoUpdate&&!1===h.needsUpdate)continue;r.copy(h.mapSize);const f=h.getFrameExtents();r.multiply(f),s.copy(h.mapSize),(r.x>c||r.y>c)&&(r.x>c&&(s.x=Math.floor(c/f.x),r.x=s.x*f.x,h.mapSize.x=s.x),r.y>c&&(s.y=Math.floor(c/f.y),r.y=s.y*f.y,h.mapSize.y=s.y));const m=e.state.buffers.depth.getReversed();if(h.camera._reversedDepth=m,null===h.map||!0===p){if(null!==h.map&&(null!==h.map.depthTexture&&(h.map.depthTexture.dispose(),h.map.depthTexture=null),h.map.dispose()),3===this.type){if(u.isPointLight){Xt("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}h.map=new Dn(r.x,r.y,{format:Ie,type:xe,minFilter:he,magFilter:he,generateMipmaps:!1}),h.map.texture.name=u.name+".shadowMap",h.map.depthTexture=new vs(r.x,r.y,be),h.map.depthTexture.name=u.name+".shadowMapDepth",h.map.depthTexture.format=Ne,h.map.depthTexture.compareFunction=null,h.map.depthTexture.minFilter=le,h.map.depthTexture.magFilter=le}else u.isPointLight?(h.map=new Mo(r.x),h.map.depthTexture=new ys(r.x,ye)):(h.map=new Dn(r.x,r.y),h.map.depthTexture=new vs(r.x,r.y,ye)),h.map.depthTexture.name=u.name+".shadowMap",h.map.depthTexture.format=Ne,1===this.type?(h.map.depthTexture.compareFunction=m?Pt:Rt,h.map.depthTexture.minFilter=he,h.map.depthTexture.magFilter=he):(h.map.depthTexture.compareFunction=null,h.map.depthTexture.minFilter=le,h.map.depthTexture.magFilter=le);h.camera.updateProjectionMatrix()}const g=h.map.isWebGLCubeRenderTarget?6:1;for(let t=0;t<g;t++){if(h.map.isWebGLCubeRenderTarget)e.setRenderTarget(h.map,t),e.clear();else{0===t&&(e.setRenderTarget(h.map),e.clear());const n=h.getViewport(t);a.set(s.x*n.x,s.y*n.y,s.x*n.z,s.y*n.w),d.viewport(a)}if(u.isPointLight){const e=h.camera,n=h.matrix,i=u.distance||e.far;i!==e.far&&(e.far=i,e.updateProjectionMatrix()),Ru.setFromMatrixPosition(u.matrixWorld),e.position.copy(Ru),Cu.copy(e.position),Cu.add(Eu[t]),e.up.copy(wu[t]),e.lookAt(Cu),e.updateMatrixWorld(),n.makeTranslation(-Ru.x,-Ru.y,-Ru.z),Au.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),h._frustum.setFromProjectionMatrix(Au,e.coordinateSystem,e.reversedDepth)}else h.updateMatrices(u);i=h.getFrustum(),S(n,o,h.camera,u,this.type)}!0!==h.isPointLightShadow&&3===this.type&&x(h,o),h.needsUpdate=!1}b=this.type,y.needsUpdate=!1,e.setRenderTarget(l,u,h)}}function Pu(e,t){const n=new function(){let t=!1;const n=new Pn;let i=null;const r=new Pn(0,0,0,0);return{setMask:function(n){i===n||t||(e.colorMask(n,n,n,n),i=n)},setLocked:function(e){t=e},setClear:function(t,i,s,a,o){!0===o&&(t*=a,i*=a,s*=a),n.set(t,i,s,a),!1===r.equals(n)&&(e.clearColor(t,i,s,a),r.copy(n))},reset:function(){t=!1,i=null,r.set(-1,0,0,0)}}},i=new function(){let n=!1,i=!1,r=null,s=null,a=null;return{setReversed:function(e){if(i!==e){const n=t.get("EXT_clip_control");e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),i=e;const r=a;a=null,this.setClear(r)}},getReversed:function(){return i},setTest:function(t){t?re(e.DEPTH_TEST):se(e.DEPTH_TEST)},setMask:function(t){r===t||n||(e.depthMask(t),r=t)},setFunc:function(t){if(i&&(t=Kt[t]),s!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:default:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL)}s=t}},setLocked:function(e){n=e},setClear:function(t){a!==t&&(a=t,i&&(t=1-t),e.clearDepth(t))},reset:function(){n=!1,r=null,s=null,a=null,i=!1}}},r=new function(){let t=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,u=null;return{setTest:function(n){t||(n?re(e.STENCIL_TEST):se(e.STENCIL_TEST))},setMask:function(i){n===i||t||(e.stencilMask(i),n=i)},setFunc:function(t,n,a){i===t&&r===n&&s===a||(e.stencilFunc(t,n,a),i=t,r=n,s=a)},setOp:function(t,n,i){a===t&&o===n&&l===i||(e.stencilOp(t,n,i),a=t,o=n,l=i)},setLocked:function(e){t=e},setClear:function(t){u!==t&&(e.clearStencil(t),u=t)},reset:function(){t=!1,n=null,i=null,r=null,s=null,a=null,o=null,l=null,u=null}}},s=new WeakMap,a=new WeakMap;let o={},l={},u=new WeakMap,c=[],h=null,d=!1,p=null,f=null,m=null,g=null,_=null,F=null,O=null,B=new _i(0,0,0),k=0,z=!1,V=null,G=null,H=null,j=null,W=null;const $=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let X=!1,q=0;const Y=e.getParameter(e.VERSION);-1!==Y.indexOf("WebGL")?(q=parseFloat(/^WebGL (\d)/.exec(Y)[1]),X=q>=1):-1!==Y.indexOf("OpenGL ES")&&(q=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),X=q>=2);let K=null,Z={};const Q=e.getParameter(e.SCISSOR_BOX),J=e.getParameter(e.VIEWPORT),ee=(new Pn).fromArray(Q),te=(new Pn).fromArray(J);function ne(t,n,i,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<i;a++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,r,0,e.RGBA,e.UNSIGNED_BYTE,s):e.texImage2D(n+a,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,s);return a}const ie={};function re(t){!0!==o[t]&&(e.enable(t),o[t]=!0)}function se(t){!1!==o[t]&&(e.disable(t),o[t]=!1)}ie[e.TEXTURE_2D]=ne(e.TEXTURE_2D,e.TEXTURE_2D,1),ie[e.TEXTURE_CUBE_MAP]=ne(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),ie[e.TEXTURE_2D_ARRAY]=ne(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),ie[e.TEXTURE_3D]=ne(e.TEXTURE_3D,e.TEXTURE_3D,1,1),n.setClear(0,0,0,1),i.setClear(1),r.setClear(0),re(e.DEPTH_TEST),i.setFunc(3),ue(!1),ce(1),re(e.CULL_FACE),le(0);const ae={[v]:e.FUNC_ADD,[y]:e.FUNC_SUBTRACT,[b]:e.FUNC_REVERSE_SUBTRACT};ae[103]=e.MIN,ae[104]=e.MAX;const oe={[x]:e.ZERO,[T]:e.ONE,[S]:e.SRC_COLOR,[E]:e.SRC_ALPHA,[P]:e.SRC_ALPHA_SATURATE,[C]:e.DST_COLOR,[A]:e.DST_ALPHA,[M]:e.ONE_MINUS_SRC_COLOR,[w]:e.ONE_MINUS_SRC_ALPHA,[N]:e.ONE_MINUS_DST_COLOR,[R]:e.ONE_MINUS_DST_ALPHA,[L]:e.CONSTANT_COLOR,[D]:e.ONE_MINUS_CONSTANT_COLOR,[I]:e.CONSTANT_ALPHA,[U]:e.ONE_MINUS_CONSTANT_ALPHA};function le(t,n,i,r,s,a,o,l,u,c){if(0!==t){if(!1===d&&(re(e.BLEND),d=!0),5===t)s=s||n,a=a||i,o=o||r,n===f&&s===_||(e.blendEquationSeparate(ae[n],ae[s]),f=n,_=s),i===m&&r===g&&a===F&&o===O||(e.blendFuncSeparate(oe[i],oe[r],oe[a],oe[o]),m=i,g=r,F=a,O=o),!1!==l.equals(B)&&u===k||(e.blendColor(l.r,l.g,l.b,u),B.copy(l),k=u),p=t,z=!1;else if(t!==p||c!==z){if(f===v&&_===v||(e.blendEquation(e.FUNC_ADD),f=v,_=v),c)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:qt("WebGLState: Invalid blending: ",t)}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:qt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:qt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:qt("WebGLState: Invalid blending: ",t)}m=null,g=null,F=null,O=null,B.set(0,0,0),k=0,p=t,z=c}}else!0===d&&(se(e.BLEND),d=!1)}function ue(t){V!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),V=t)}function ce(t){0!==t?(re(e.CULL_FACE),t!==G&&(1===t?e.cullFace(e.BACK):2===t?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))):se(e.CULL_FACE),G=t}function he(t,n,r){t?(re(e.POLYGON_OFFSET_FILL),j===n&&W===r||(j=n,W=r,i.getReversed()&&(n=-n),e.polygonOffset(n,r))):se(e.POLYGON_OFFSET_FILL)}return{buffers:{color:n,depth:i,stencil:r},enable:re,disable:se,bindFramebuffer:function(t,n){return l[t]!==n&&(e.bindFramebuffer(t,n),l[t]=n,t===e.DRAW_FRAMEBUFFER&&(l[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(l[e.DRAW_FRAMEBUFFER]=n),!0)},drawBuffers:function(t,n){let i=c,r=!1;if(t){i=u.get(n),void 0===i&&(i=[],u.set(n,i));const s=t.textures;if(i.length!==s.length||i[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=s.length;t<n;t++)i[t]=e.COLOR_ATTACHMENT0+t;i.length=s.length,r=!0}}else i[0]!==e.BACK&&(i[0]=e.BACK,r=!0);r&&e.drawBuffers(i)},useProgram:function(t){return h!==t&&(e.useProgram(t),h=t,!0)},setBlending:le,setMaterial:function(t,s){2===t.side?se(e.CULL_FACE):re(e.CULL_FACE);let a=1===t.side;s&&(a=!a),ue(a),1===t.blending&&!1===t.transparent?le(0):le(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),i.setFunc(t.depthFunc),i.setTest(t.depthTest),i.setMask(t.depthWrite),n.setMask(t.colorWrite);const o=t.stencilWrite;r.setTest(o),o&&(r.setMask(t.stencilWriteMask),r.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),r.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),he(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),!0===t.alphaToCoverage?re(e.SAMPLE_ALPHA_TO_COVERAGE):se(e.SAMPLE_ALPHA_TO_COVERAGE)},setFlipSided:ue,setCullFace:ce,setLineWidth:function(t){t!==H&&(X&&e.lineWidth(t),H=t)},setPolygonOffset:he,setScissorTest:function(t){t?re(e.SCISSOR_TEST):se(e.SCISSOR_TEST)},activeTexture:function(t){void 0===t&&(t=e.TEXTURE0+$-1),K!==t&&(e.activeTexture(t),K=t)},bindTexture:function(t,n,i){void 0===i&&(i=null===K?e.TEXTURE0+$-1:K);let r=Z[i];void 0===r&&(r={type:void 0,texture:void 0},Z[i]=r),r.type===t&&r.texture===n||(K!==i&&(e.activeTexture(i),K=i),e.bindTexture(t,n||ie[t]),r.type=t,r.texture=n)},unbindTexture:function(){const t=Z[K];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(...arguments)}catch(e){qt("WebGLState:",e)}},compressedTexImage3D:function(){try{e.compressedTexImage3D(...arguments)}catch(e){qt("WebGLState:",e)}},texImage2D:function(){try{e.texImage2D(...arguments)}catch(e){qt("WebGLState:",e)}},texImage3D:function(){try{e.texImage3D(...arguments)}catch(e){qt("WebGLState:",e)}},updateUBOMapping:function(t,n){let i=a.get(n);void 0===i&&(i=new WeakMap,a.set(n,i));let r=i.get(t);void 0===r&&(r=e.getUniformBlockIndex(n,t.name),i.set(t,r))},uniformBlockBinding:function(t,n){const i=a.get(n).get(t);s.get(n)!==i&&(e.uniformBlockBinding(n,i,t.__bindingPointIndex),s.set(n,i))},texStorage2D:function(){try{e.texStorage2D(...arguments)}catch(e){qt("WebGLState:",e)}},texStorage3D:function(){try{e.texStorage3D(...arguments)}catch(e){qt("WebGLState:",e)}},texSubImage2D:function(){try{e.texSubImage2D(...arguments)}catch(e){qt("WebGLState:",e)}},texSubImage3D:function(){try{e.texSubImage3D(...arguments)}catch(e){qt("WebGLState:",e)}},compressedTexSubImage2D:function(){try{e.compressedTexSubImage2D(...arguments)}catch(e){qt("WebGLState:",e)}},compressedTexSubImage3D:function(){try{e.compressedTexSubImage3D(...arguments)}catch(e){qt("WebGLState:",e)}},scissor:function(t){!1===ee.equals(t)&&(e.scissor(t.x,t.y,t.z,t.w),ee.copy(t))},viewport:function(t){!1===te.equals(t)&&(e.viewport(t.x,t.y,t.z,t.w),te.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),i.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),o={},K=null,Z={},l={},u=new WeakMap,c=[],h=null,d=!1,p=null,f=null,m=null,g=null,_=null,F=null,O=null,B=new _i(0,0,0),k=0,z=!1,V=null,G=null,H=null,j=null,W=null,ee.set(0,0,e.canvas.width,e.canvas.height),te.set(0,0,e.canvas.width,e.canvas.height),n.reset(),i.reset(),r.reset()}}}function Lu(e,t,n,i,r,s,a){const o=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,l="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),u=new cn,c=new WeakMap;let h;const d=new WeakMap;let p=!1;try{p="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(e){}function f(e,t){return p?new OffscreenCanvas(e,t):Gt("canvas")}function m(e,t,n){let i=1;const r=H(e);if((r.width>n||r.height>n)&&(i=n/Math.max(r.width,r.height)),i<1){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&e instanceof VideoFrame){const n=Math.floor(i*r.width),s=Math.floor(i*r.height);void 0===h&&(h=f(n,s));const a=t?f(n,s):h;a.width=n,a.height=s;return a.getContext("2d").drawImage(e,0,0,n,s),Xt("WebGLRenderer: Texture has been resized from ("+r.width+"x"+r.height+") to ("+n+"x"+s+")."),a}return"data"in e&&Xt("WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.height+")."),e}return e}function g(e){return e.generateMipmaps}function _(t){e.generateMipmap(t)}function v(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function y(n,i,r,s,a=!1){if(null!==n){if(void 0!==e[n])return e[n];Xt("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let o=i;if(i===e.RED&&(r===e.FLOAT&&(o=e.R32F),r===e.HALF_FLOAT&&(o=e.R16F),r===e.UNSIGNED_BYTE&&(o=e.R8)),i===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)),i===e.RG&&(r===e.FLOAT&&(o=e.RG32F),r===e.HALF_FLOAT&&(o=e.RG16F),r===e.UNSIGNED_BYTE&&(o=e.RG8)),i===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)),i===e.RGB_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGB8UI),r===e.UNSIGNED_SHORT&&(o=e.RGB16UI),r===e.UNSIGNED_INT&&(o=e.RGB32UI),r===e.BYTE&&(o=e.RGB8I),r===e.SHORT&&(o=e.RGB16I),r===e.INT&&(o=e.RGB32I)),i===e.RGBA_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGBA8UI),r===e.UNSIGNED_SHORT&&(o=e.RGBA16UI),r===e.UNSIGNED_INT&&(o=e.RGBA32UI),r===e.BYTE&&(o=e.RGBA8I),r===e.SHORT&&(o=e.RGBA16I),r===e.INT&&(o=e.RGBA32I)),i===e.RGB&&(r===e.UNSIGNED_INT_5_9_9_9_REV&&(o=e.RGB9_E5),r===e.UNSIGNED_INT_10F_11F_11F_REV&&(o=e.R11F_G11F_B10F)),i===e.RGBA){const t=a?Tt:bn.getTransfer(s);r===e.FLOAT&&(o=e.RGBA32F),r===e.HALF_FLOAT&&(o=e.RGBA16F),r===e.UNSIGNED_BYTE&&(o=t===St?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 b(t,n){let i;return t?null===n||n===ye||n===Me?i=e.DEPTH24_STENCIL8:n===be?i=e.DEPTH32F_STENCIL8:n===_e&&(i=e.DEPTH24_STENCIL8,Xt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===ye||n===Me?i=e.DEPTH_COMPONENT24:n===be?i=e.DEPTH_COMPONENT32F:n===_e&&(i=e.DEPTH_COMPONENT16),i}function x(e,t){return!0===g(e)||e.isFramebufferTexture&&e.minFilter!==le&&e.minFilter!==he?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 T(e){const t=e.target;t.removeEventListener("dispose",T),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const n=e.source,r=d.get(n);if(r){const i=r[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&M(e),0===Object.keys(r).length&&d.delete(n)}i.remove(e)}(t),t.isVideoTexture&&c.delete(t)}function S(t){const n=t.target;n.removeEventListener("dispose",S),function(t){const n=i.get(t);t.depthTexture&&(t.depthTexture.dispose(),i.remove(t.depthTexture));if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let i=0;i<n.__webglFramebuffer[t].length;i++)e.deleteFramebuffer(n.__webglFramebuffer[t][i]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}const r=t.textures;for(let t=0,n=r.length;t<n;t++){const n=i.get(r[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),a.memory.textures--),i.remove(r[t])}i.remove(t)}(n)}function M(t){const n=i.get(t);e.deleteTexture(n.__webglTexture);const r=t.source;delete d.get(r)[n.__cacheKey],a.memory.textures--}let E=0;function w(t,r){const s=i.get(t);if(t.isVideoTexture&&function(e){const t=a.render.frame;c.get(e)!==t&&(c.set(e,t),e.update())}(t),!1===t.isRenderTargetTexture&&!0!==t.isExternalTexture&&t.version>0&&s.__version!==t.version){const e=t.image;if(null===e)Xt("WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void D(s,t,r);Xt("WebGLRenderer: Texture marked for update but image is incomplete")}}else t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+r)}const A={[se]:e.REPEAT,[ae]:e.CLAMP_TO_EDGE,[oe]:e.MIRRORED_REPEAT},R={[le]:e.NEAREST,[ue]:e.NEAREST_MIPMAP_NEAREST,[ce]:e.NEAREST_MIPMAP_LINEAR,[he]:e.LINEAR,[de]:e.LINEAR_MIPMAP_NEAREST,[pe]:e.LINEAR_MIPMAP_LINEAR},C={[Et]:e.NEVER,[Lt]:e.ALWAYS,[wt]:e.LESS,[Rt]:e.LEQUAL,[At]:e.EQUAL,[Pt]:e.GEQUAL,[Ct]:e.GREATER,[Nt]:e.NOTEQUAL};function N(n,s){if(s.type!==be||!1!==t.has("OES_texture_float_linear")||s.magFilter!==he&&s.magFilter!==de&&s.magFilter!==ce&&s.magFilter!==pe&&s.minFilter!==he&&s.minFilter!==de&&s.minFilter!==ce&&s.minFilter!==pe||Xt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(n,e.TEXTURE_WRAP_S,A[s.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,A[s.wrapT]),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,A[s.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,R[s.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,R[s.minFilter]),s.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,C[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(s.magFilter===le)return;if(s.minFilter!==ce&&s.minFilter!==pe)return;if(s.type===be&&!1===t.has("OES_texture_float_linear"))return;if(s.anisotropy>1||i.get(s).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy}}}function P(t,n){let i=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",T));const r=n.source;let s=d.get(r);void 0===s&&(s={},d.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()}(n);if(o!==t.__cacheKey){void 0===s[o]&&(s[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[t.__cacheKey];void 0!==r&&(s[t.__cacheKey].usedTimes--,0===r.usedTimes&&M(n)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return i}function L(e,t,n){return Math.floor(Math.floor(e/n)/t)}function D(t,a,o){let l=e.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=e.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=e.TEXTURE_3D);const u=P(t,a),c=a.source;n.bindTexture(l,t.__webglTexture,e.TEXTURE0+o);const h=i.get(c);if(c.version!==h.__version||!0===u){n.activeTexture(e.TEXTURE0+o);const t=bn.getPrimaries(bn.workingColorSpace),i=a.colorSpace===yt?null:bn.getPrimaries(a.colorSpace),d=a.colorSpace===yt||t===i?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);let p=m(a.image,!1,r.maxTextureSize);p=G(a,p);const f=s.convert(a.format,a.colorSpace),v=s.convert(a.type);let T,S=y(a.internalFormat,f,v,a.colorSpace,a.isVideoTexture);N(l,a);const M=a.mipmaps,E=!0!==a.isVideoTexture,w=void 0===h.__version||!0===u,A=c.dataReady,R=x(a,p);if(a.isDepthTexture)S=b(a.format===Pe,a.type),w&&(E?n.texStorage2D(e.TEXTURE_2D,1,S,p.width,p.height):n.texImage2D(e.TEXTURE_2D,0,S,p.width,p.height,0,f,v,null));else if(a.isDataTexture)if(M.length>0){E&&w&&n.texStorage2D(e.TEXTURE_2D,R,S,M[0].width,M[0].height);for(let t=0,i=M.length;t<i;t++)T=M[t],E?A&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,T.width,T.height,f,v,T.data):n.texImage2D(e.TEXTURE_2D,t,S,T.width,T.height,0,f,v,T.data);a.generateMipmaps=!1}else E?(w&&n.texStorage2D(e.TEXTURE_2D,R,S,p.width,p.height),A&&function(t,i,r,s){const a=t.updateRanges;if(0===a.length)n.texSubImage2D(e.TEXTURE_2D,0,0,0,i.width,i.height,r,s,i.data);else{a.sort((e,t)=>e.start-t.start);let o=0;for(let e=1;e<a.length;e++){const t=a[o],n=a[e],r=t.start+t.count,s=L(n.start,i.width,4),l=L(t.start,i.width,4);n.start<=r+1&&s===l&&L(n.start+n.count-1,i.width,4)===s?t.count=Math.max(t.count,n.start+n.count-t.start):(++o,a[o]=n)}a.length=o+1;const l=e.getParameter(e.UNPACK_ROW_LENGTH),u=e.getParameter(e.UNPACK_SKIP_PIXELS),c=e.getParameter(e.UNPACK_SKIP_ROWS);e.pixelStorei(e.UNPACK_ROW_LENGTH,i.width);for(let t=0,o=a.length;t<o;t++){const o=a[t],l=Math.floor(o.start/4),u=Math.ceil(o.count/4),c=l%i.width,h=Math.floor(l/i.width),d=u,p=1;e.pixelStorei(e.UNPACK_SKIP_PIXELS,c),e.pixelStorei(e.UNPACK_SKIP_ROWS,h),n.texSubImage2D(e.TEXTURE_2D,0,c,h,d,p,r,s,i.data)}t.clearUpdateRanges(),e.pixelStorei(e.UNPACK_ROW_LENGTH,l),e.pixelStorei(e.UNPACK_SKIP_PIXELS,u),e.pixelStorei(e.UNPACK_SKIP_ROWS,c)}}(a,p,f,v)):n.texImage2D(e.TEXTURE_2D,0,S,p.width,p.height,0,f,v,p.data);else if(a.isCompressedTexture)if(a.isCompressedArrayTexture){E&&w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,R,S,M[0].width,M[0].height,p.depth);for(let t=0,i=M.length;t<i;t++)if(T=M[t],a.format!==Ce)if(null!==f)if(E){if(A)if(a.layerUpdates.size>0){const i=qa(T.width,T.height,a.format,a.type);for(const r of a.layerUpdates){const s=T.data.subarray(r*i/T.data.BYTES_PER_ELEMENT,(r+1)*i/T.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,r,T.width,T.height,1,f,s)}a.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,T.width,T.height,p.depth,f,T.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,S,T.width,T.height,p.depth,0,T.data,0,0);else Xt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else E?A&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,T.width,T.height,p.depth,f,v,T.data):n.texImage3D(e.TEXTURE_2D_ARRAY,t,S,T.width,T.height,p.depth,0,f,v,T.data)}else{E&&w&&n.texStorage2D(e.TEXTURE_2D,R,S,M[0].width,M[0].height);for(let t=0,i=M.length;t<i;t++)T=M[t],a.format!==Ce?null!==f?E?A&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,T.width,T.height,f,T.data):n.compressedTexImage2D(e.TEXTURE_2D,t,S,T.width,T.height,0,T.data):Xt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):E?A&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,T.width,T.height,f,v,T.data):n.texImage2D(e.TEXTURE_2D,t,S,T.width,T.height,0,f,v,T.data)}else if(a.isDataArrayTexture)if(E){if(w&&n.texStorage3D(e.TEXTURE_2D_ARRAY,R,S,p.width,p.height,p.depth),A)if(a.layerUpdates.size>0){const t=qa(p.width,p.height,a.format,a.type);for(const i of a.layerUpdates){const r=p.data.subarray(i*t/p.data.BYTES_PER_ELEMENT,(i+1)*t/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,i,p.width,p.height,1,f,v,r)}a.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,S,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isData3DTexture)E?(w&&n.texStorage3D(e.TEXTURE_3D,R,S,p.width,p.height,p.depth),A&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)):n.texImage3D(e.TEXTURE_3D,0,S,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isFramebufferTexture){if(w)if(E)n.texStorage2D(e.TEXTURE_2D,R,S,p.width,p.height);else{let t=p.width,i=p.height;for(let r=0;r<R;r++)n.texImage2D(e.TEXTURE_2D,r,S,t,i,0,f,v,null),t>>=1,i>>=1}}else if(M.length>0){if(E&&w){const t=H(M[0]);n.texStorage2D(e.TEXTURE_2D,R,S,t.width,t.height)}for(let t=0,i=M.length;t<i;t++)T=M[t],E?A&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,f,v,T):n.texImage2D(e.TEXTURE_2D,t,S,f,v,T);a.generateMipmaps=!1}else if(E){if(w){const t=H(p);n.texStorage2D(e.TEXTURE_2D,R,S,t.width,t.height)}A&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,f,v,p)}else n.texImage2D(e.TEXTURE_2D,0,S,f,v,p);g(a)&&_(l),h.__version=c.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}function I(t,r,a,l,u,c){const h=s.convert(a.format,a.colorSpace),d=s.convert(a.type),p=y(a.internalFormat,h,d,a.colorSpace),f=i.get(r),m=i.get(a);if(m.__renderTarget=r,!f.__hasExternalTextures){const t=Math.max(1,r.width>>c),i=Math.max(1,r.height>>c);u===e.TEXTURE_3D||u===e.TEXTURE_2D_ARRAY?n.texImage3D(u,c,p,t,i,r.depth,0,h,d,null):n.texImage2D(u,c,p,t,i,0,h,d,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),V(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,u,m.__webglTexture,0,z(r)):(u===e.TEXTURE_2D||u>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&u<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,l,u,m.__webglTexture,c),n.bindFramebuffer(e.FRAMEBUFFER,null)}function U(t,n,i){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){const r=n.depthTexture,s=r&&r.isDepthTexture?r.type:null,a=b(n.stencilBuffer,s),l=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;V(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,z(n),a,n.width,n.height):i?e.renderbufferStorageMultisample(e.RENDERBUFFER,z(n),a,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,a,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,l,e.RENDERBUFFER,t)}else{const t=n.textures;for(let r=0;r<t.length;r++){const a=t[r],l=s.convert(a.format,a.colorSpace),u=s.convert(a.type),c=y(a.internalFormat,l,u,a.colorSpace);V(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,z(n),c,n.width,n.height):i?e.renderbufferStorageMultisample(e.RENDERBUFFER,z(n),c,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,c,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function F(t,r,a){const l=!0===r.isWebGLCubeRenderTarget;if(n.bindFramebuffer(e.FRAMEBUFFER,t),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const u=i.get(r.depthTexture);if(u.__renderTarget=r,u.__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),l){if(void 0===u.__webglInit&&(u.__webglInit=!0,r.depthTexture.addEventListener("dispose",T)),void 0===u.__webglTexture){u.__webglTexture=e.createTexture(),n.bindTexture(e.TEXTURE_CUBE_MAP,u.__webglTexture),N(e.TEXTURE_CUBE_MAP,r.depthTexture);const t=s.convert(r.depthTexture.format),i=s.convert(r.depthTexture.type);let a;r.depthTexture.format===Ne?a=e.DEPTH_COMPONENT24:r.depthTexture.format===Pe&&(a=e.DEPTH24_STENCIL8);for(let n=0;n<6;n++)e.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0,a,r.width,r.height,0,t,i,null)}}else w(r.depthTexture,0);const c=u.__webglTexture,h=z(r),d=l?e.TEXTURE_CUBE_MAP_POSITIVE_X+a:e.TEXTURE_2D,p=r.depthTexture.format===Pe?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;if(r.depthTexture.format===Ne)V(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,d,c,0,h):e.framebufferTexture2D(e.FRAMEBUFFER,p,d,c,0);else{if(r.depthTexture.format!==Pe)throw new Error("Unknown depthTexture format");V(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,p,d,c,0,h):e.framebufferTexture2D(e.FRAMEBUFFER,p,d,c,0)}}function O(t){const r=i.get(t),s=!0===t.isWebGLCubeRenderTarget;if(r.__boundDepthTexture!==t.depthTexture){const e=t.depthTexture;if(r.__depthDisposeCallback&&r.__depthDisposeCallback(),e){const t=()=>{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),r.__depthDisposeCallback=t}r.__boundDepthTexture=e}if(t.depthTexture&&!r.__autoAllocateDepthBuffer)if(s)for(let e=0;e<6;e++)F(r.__webglFramebuffer[e],t,e);else{const e=t.texture.mipmaps;e&&e.length>0?F(r.__webglFramebuffer[0],t,0):F(r.__webglFramebuffer,t,0)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[i]),void 0===r.__webglDepthbuffer[i])r.__webglDepthbuffer[i]=e.createRenderbuffer(),U(r.__webglDepthbuffer[i],t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[i];e.bindRenderbuffer(e.RENDERBUFFER,s),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,s)}}else{const i=t.texture.mipmaps;if(i&&i.length>0?n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=e.createRenderbuffer(),U(r.__webglDepthbuffer,t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,i=r.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,i)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}const B=[],k=[];function z(e){return Math.min(r.maxSamples,e.samples)}function V(e){const n=i.get(e);return e.samples>0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function G(e,t){const n=e.colorSpace,i=e.format,r=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||n!==xt&&n!==yt&&(bn.getTransfer(n)===St?i===Ce&&r===fe||Xt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):qt("WebGLTextures: Unsupported texture color space:",n)),t}function H(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement?(u.width=e.naturalWidth||e.width,u.height=e.naturalHeight||e.height):"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?(u.width=e.displayWidth,u.height=e.displayHeight):(u.width=e.width,u.height=e.height),u}this.allocateTextureUnit=function(){const e=E;return e>=r.maxTextures&&Xt("WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+r.maxTextures),E+=1,e},this.resetTextureUnits=function(){E=0},this.setTexture2D=w,this.setTexture2DArray=function(t,r){const s=i.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?D(s,t,r):(t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null),n.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+r))},this.setTexture3D=function(t,r){const s=i.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?D(s,t,r):n.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+r)},this.setTextureCube=function(t,a){const o=i.get(t);!0!==t.isCubeDepthTexture&&t.version>0&&o.__version!==t.version?function(t,a,o){if(6!==a.image.length)return;const l=P(t,a),u=a.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+o);const c=i.get(u);if(u.version!==c.__version||!0===l){n.activeTexture(e.TEXTURE0+o);const t=bn.getPrimaries(bn.workingColorSpace),i=a.colorSpace===yt?null:bn.getPrimaries(a.colorSpace),h=a.colorSpace===yt||t===i?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,h);const d=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,f=[];for(let e=0;e<6;e++)f[e]=d||p?p?a.image[e].image:a.image[e]:m(a.image[e],!0,r.maxCubemapSize),f[e]=G(a,f[e]);const v=f[0],b=s.convert(a.format,a.colorSpace),T=s.convert(a.type),S=y(a.internalFormat,b,T,a.colorSpace),M=!0!==a.isVideoTexture,E=void 0===c.__version||!0===l,w=u.dataReady;let A,R=x(a,v);if(N(e.TEXTURE_CUBE_MAP,a),d){M&&E&&n.texStorage2D(e.TEXTURE_CUBE_MAP,R,S,v.width,v.height);for(let t=0;t<6;t++){A=f[t].mipmaps;for(let i=0;i<A.length;i++){const r=A[i];a.format!==Ce?null!==b?M?w&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,0,0,r.width,r.height,b,r.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,S,r.width,r.height,0,r.data):Xt("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):M?w&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,0,0,r.width,r.height,b,T,r.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i,S,r.width,r.height,0,b,T,r.data)}}}else{if(A=a.mipmaps,M&&E){A.length>0&&R++;const t=H(f[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,R,S,t.width,t.height)}for(let t=0;t<6;t++)if(p){M?w&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,f[t].width,f[t].height,b,T,f[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,S,f[t].width,f[t].height,0,b,T,f[t].data);for(let i=0;i<A.length;i++){const r=A[i].image[t].image;M?w&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,0,0,r.width,r.height,b,T,r.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,S,r.width,r.height,0,b,T,r.data)}}else{M?w&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,b,T,f[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,S,b,T,f[t]);for(let i=0;i<A.length;i++){const r=A[i];M?w&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,0,0,b,T,r.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,i+1,S,b,T,r.image[t])}}}g(a)&&_(e.TEXTURE_CUBE_MAP),c.__version=u.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}(o,t,a):n.bindTexture(e.TEXTURE_CUBE_MAP,o.__webglTexture,e.TEXTURE0+a)},this.rebindTextures=function(t,n,r){const s=i.get(t);void 0!==n&&I(s.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),void 0!==r&&O(t)},this.setupRenderTarget=function(t){const r=t.texture,o=i.get(t),l=i.get(r);t.addEventListener("dispose",S);const u=t.textures,c=!0===t.isWebGLCubeRenderTarget,h=u.length>1;if(h||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=r.version,a.memory.textures++),c){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let n=0;n<r.mipmaps.length;n++)o.__webglFramebuffer[t][n]=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(h)for(let t=0,n=u.length;t<n;t++){const n=i.get(u[t]);void 0===n.__webglTexture&&(n.__webglTexture=e.createTexture(),a.memory.textures++)}if(t.samples>0&&!1===V(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n<u.length;n++){const i=u[n];o.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,o.__webglColorRenderbuffer[n]);const r=s.convert(i.format,i.colorSpace),a=s.convert(i.type),l=y(i.internalFormat,r,a,i.colorSpace,!0===t.isXRRenderTarget),c=z(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,c,l,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,o.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(o.__webglDepthRenderbuffer=e.createRenderbuffer(),U(o.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(c){n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),N(e.TEXTURE_CUBE_MAP,r);for(let n=0;n<6;n++)if(r.mipmaps&&r.mipmaps.length>0)for(let i=0;i<r.mipmaps.length;i++)I(o.__webglFramebuffer[n][i],t,r,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,i);else I(o.__webglFramebuffer[n],t,r,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);g(r)&&_(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(h){for(let r=0,s=u.length;r<s;r++){const s=u[r],a=i.get(s);let l=e.TEXTURE_2D;(t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(l=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(l,a.__webglTexture),N(l,s),I(o.__webglFramebuffer,t,s,e.COLOR_ATTACHMENT0+r,l,0),g(s)&&_(l)}n.unbindTexture()}else{let i=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(i=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(i,l.__webglTexture),N(i,r),r.mipmaps&&r.mipmaps.length>0)for(let n=0;n<r.mipmaps.length;n++)I(o.__webglFramebuffer[n],t,r,e.COLOR_ATTACHMENT0,i,n);else I(o.__webglFramebuffer,t,r,e.COLOR_ATTACHMENT0,i,0);g(r)&&_(i),n.unbindTexture()}t.depthBuffer&&O(t)},this.updateRenderTargetMipmap=function(e){const t=e.textures;for(let r=0,s=t.length;r<s;r++){const s=t[r];if(g(s)){const t=v(e),r=i.get(s).__webglTexture;n.bindTexture(t,r),_(t),n.unbindTexture()}}},this.updateMultisampleRenderTarget=function(t){if(t.samples>0)if(!1===V(t)){const r=t.textures,s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const u=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,c=i.get(t),h=r.length>1;if(h)for(let t=0;t<r.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,c.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,c.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,c.__webglMultisampledFramebuffer);const d=t.texture.mipmaps;d&&d.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer);for(let n=0;n<r.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(o|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(o|=e.STENCIL_BUFFER_BIT)),h){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,c.__webglColorRenderbuffer[n]);const t=i.get(r[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,s,a,0,0,s,a,o,e.NEAREST),!0===l&&(B.length=0,k.length=0,B.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&!1===t.resolveDepthBuffer&&(B.push(u),k.push(u),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,k)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,B))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),h)for(let t=0;t<r.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,c.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,c.__webglColorRenderbuffer[t]);const s=i.get(r[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,c.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,s,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&!1===t.resolveDepthBuffer&&l){const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}},this.setupDepthRenderbuffer=O,this.setupFrameBufferTexture=I,this.useMultisampledRTT=V,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function Du(e,t){return{convert:function(n,i=""){let r;const s=bn.getTransfer(i);if(n===fe)return e.UNSIGNED_BYTE;if(n===Te)return e.UNSIGNED_SHORT_4_4_4_4;if(n===Se)return e.UNSIGNED_SHORT_5_5_5_1;if(n===Ee)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===we)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===me)return e.BYTE;if(n===ge)return e.SHORT;if(n===_e)return e.UNSIGNED_SHORT;if(n===ve)return e.INT;if(n===ye)return e.UNSIGNED_INT;if(n===be)return e.FLOAT;if(n===xe)return e.HALF_FLOAT;if(n===Ae)return e.ALPHA;if(n===Re)return e.RGB;if(n===Ce)return e.RGBA;if(n===Ne)return e.DEPTH_COMPONENT;if(n===Pe)return e.DEPTH_STENCIL;if(n===Le)return e.RED;if(n===De)return e.RED_INTEGER;if(n===Ie)return e.RG;if(n===Ue)return e.RG_INTEGER;if(n===Fe)return e.RGBA_INTEGER;if(n===Oe||n===Be||n===ke||n===ze)if(s===St){if(r=t.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(n===Oe)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Be)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===ke)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===ze)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=t.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(n===Oe)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Be)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===ke)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===ze)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(n===Ve||n===Ge||n===He||n===je){if(r=t.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(n===Ve)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===Ge)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===He)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===je)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(n===We||n===$e||n===Xe||n===qe||n===Ye||n===Ke||n===Ze){if(r=t.get("WEBGL_compressed_texture_etc"),null===r)return null;if(n===We||n===$e)return s===St?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===Xe)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===qe)return r.COMPRESSED_R11_EAC;if(n===Ye)return r.COMPRESSED_SIGNED_R11_EAC;if(n===Ke)return r.COMPRESSED_RG11_EAC;if(n===Ze)return r.COMPRESSED_SIGNED_RG11_EAC}if(n===Qe||n===Je||n===et||n===tt||n===nt||n===it||n===rt||n===st||n===at||n===ot||n===lt||n===ut||n===ct||n===ht){if(r=t.get("WEBGL_compressed_texture_astc"),null===r)return null;if(n===Qe)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Je)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===et)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===tt)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===nt)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===it)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===rt)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===st)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===at)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===ot)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===lt)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===ut)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===ct)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===ht)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(n===dt||n===pt||n===ft){if(r=t.get("EXT_texture_compression_bptc"),null===r)return null;if(n===dt)return s===St?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===pt)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===ft)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(n===mt||n===gt||n===_t||n===vt){if(r=t.get("EXT_texture_compression_rgtc"),null===r)return null;if(n===mt)return r.COMPRESSED_RED_RGTC1_EXT;if(n===gt)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===_t)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===vt)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return n===Me?e.UNSIGNED_INT_24_8:void 0!==e[n]?e[n]:null}}}class Iu{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(null===this.texture){const n=new bs(e.texture);e.depthNear===t.depthNear&&e.depthFar===t.depthFar||(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(null!==this.texture&&null===this.mesh){const t=e.cameras[0].viewport,n=new Ws({vertexShader:"\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}",fragmentShader:"\nuniform sampler2DArray depthColor;\nuniform float depthWidth;\nuniform float depthHeight;\n\nvoid main() {\n\n\tvec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );\n\n\tif ( coord.x >= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Wr(new Os(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Uu extends Zt{constructor(e,t){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,u=null,c=null,h=null,d=null,p=null;const f="undefined"!=typeof XRWebGLBinding,m=new Iu,g={},_=t.getContextAttributes();let v=null,y=null;const b=[],x=[],T=new cn;let S=null;const M=new Sa;M.viewport=new Pn;const E=new Sa;E.viewport=new Pn;const w=[M,E],A=new Oa;let R=null,C=null;function N(e){const t=x.indexOf(e.inputSource);if(-1===t)return;const n=b[t];void 0!==n&&(n.update(e.inputSource,e.frame,l||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function P(){i.removeEventListener("select",N),i.removeEventListener("selectstart",N),i.removeEventListener("selectend",N),i.removeEventListener("squeeze",N),i.removeEventListener("squeezestart",N),i.removeEventListener("squeezeend",N),i.removeEventListener("end",P),i.removeEventListener("inputsourceschange",L);for(let e=0;e<b.length;e++){const t=x[e];null!==t&&(x[e]=null,b[e].disconnect(t))}R=null,C=null,m.reset();for(const e in g)delete g[e];e.setRenderTarget(v),d=null,h=null,c=null,i=null,y=null,O.stop(),n.isPresenting=!1,e.setPixelRatio(S),e.setSize(T.width,T.height,!1),n.dispatchEvent({type:"sessionend"})}function L(e){for(let t=0;t<e.removed.length;t++){const n=e.removed[t],i=x.indexOf(n);i>=0&&(x[i]=null,b[i].disconnect(n))}for(let t=0;t<e.added.length;t++){const n=e.added[t];let i=x.indexOf(n);if(-1===i){for(let e=0;e<b.length;e++){if(e>=x.length){x.push(n),i=e;break}if(null===x[e]){x[e]=n,i=e;break}}if(-1===i)break}const r=b[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return void 0===t&&(t=new di,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return void 0===t&&(t=new di,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return void 0===t&&(t=new di,b[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){r=e,!0===n.isPresenting&&Xt("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===n.isPresenting&&Xt("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!==h?h:d},this.getBinding=function(){return null===c&&f&&(c=new XRWebGLBinding(i,t)),c},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(u){if(i=u,null!==i){v=e.getRenderTarget(),i.addEventListener("select",N),i.addEventListener("selectstart",N),i.addEventListener("selectend",N),i.addEventListener("squeeze",N),i.addEventListener("squeezestart",N),i.addEventListener("squeezeend",N),i.addEventListener("end",P),i.addEventListener("inputsourceschange",L),!0!==_.xrCompatible&&await t.makeXRCompatible(),S=e.getPixelRatio(),e.getSize(T);if(f&&"createProjectionLayer"in XRWebGLBinding.prototype){let n=null,s=null,a=null;_.depth&&(a=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?Pe:Ne,s=_.stencil?Me:ye);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:r};c=this.getBinding(),h=c.createProjectionLayer(o),i.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),y=new Dn(h.textureWidth,h.textureHeight,{format:Ce,type:fe,depthTexture:new vs(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.ignoreDepthValues})}else{const n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,t,n),i.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),y=new Dn(d.framebufferWidth,d.framebufferHeight,{format:Ce,type:fe,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:!1===d.ignoreDepthValues,resolveStencilBuffer:!1===d.ignoreDepthValues})}y.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),O.setContext(i),O.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};const D=new dn,I=new dn;function U(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===i)return;let t=e.near,n=e.far;null!==m.texture&&(m.depthNear>0&&(t=m.depthNear),m.depthFar>0&&(n=m.depthFar)),A.near=E.near=M.near=t,A.far=E.far=M.far=n,R===A.near&&C===A.far||(i.updateRenderState({depthNear:A.near,depthFar:A.far}),R=A.near,C=A.far),A.layers.mask=6|e.layers.mask,M.layers.mask=-5&A.layers.mask,E.layers.mask=-3&A.layers.mask;const r=e.parent,s=A.cameras;U(A,r);for(let e=0;e<s.length;e++)U(s[e],r);2===s.length?function(e,t,n){D.setFromMatrixPosition(t.matrixWorld),I.setFromMatrixPosition(n.matrixWorld);const i=D.distanceTo(I),r=t.projectionMatrix.elements,s=n.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),l=(r[9]+1)/r[5],u=(r[9]-1)/r[5],c=(r[8]-1)/r[0],h=(s[8]+1)/s[0],d=a*c,p=a*h,f=i/(-c+h),m=f*-c;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(m),e.translateZ(f),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===r[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+f,n=o+f,r=d-m,s=p+(i-m),c=l*o/n*t,h=u*o/n*t;e.projectionMatrix.makePerspective(r,s,c,h,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(A,M,E):A.projectionMatrix.copy(M.projectionMatrix),function(e,t,n){null===n?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*tn*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,A,r)},this.getCamera=function(){return A},this.getFoveation=function(){if(null!==h||null!==d)return o},this.setFoveation=function(e){o=e,null!==h&&(h.fixedFoveation=e),null!==d&&void 0!==d.fixedFoveation&&(d.fixedFoveation=e)},this.hasDepthSensing=function(){return null!==m.texture},this.getDepthSensingMesh=function(){return m.getMesh(A)},this.getCameraTexture=function(e){return g[e]};let F=null;const O=new Ya;O.setAnimationLoop(function(t,r){if(u=r.getViewerPose(l||s),p=r,null!==u){const t=u.views;null!==d&&(e.setRenderTargetFramebuffer(y,d.framebuffer),e.setRenderTarget(y));let r=!1;t.length!==A.cameras.length&&(A.cameras.length=0,r=!0);for(let n=0;n<t.length;n++){const i=t[n];let s=null;if(null!==d)s=d.getViewport(i);else{const t=c.getViewSubImage(h,i);s=t.viewport,0===n&&(e.setRenderTargetTextures(y,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(y))}let a=w[n];void 0===a&&(a=new Sa,a.layers.enable(n),a.viewport=new Pn,w[n]=a),a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.projectionMatrix.fromArray(i.projectionMatrix),a.projectionMatrixInverse.copy(a.projectionMatrix).invert(),a.viewport.set(s.x,s.y,s.width,s.height),0===n&&(A.matrix.copy(a.matrix),A.matrix.decompose(A.position,A.quaternion,A.scale)),!0===r&&A.cameras.push(a)}const s=i.enabledFeatures;if(s&&s.includes("depth-sensing")&&"gpu-optimized"==i.depthUsage&&f){c=n.getBinding();const e=c.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&m.init(e,i.renderState)}if(s&&s.includes("camera-access")&&f){e.state.unbindTexture(),c=n.getBinding();for(let e=0;e<t.length;e++){const n=t[e].camera;if(n){let e=g[n];e||(e=new bs,g[n]=e);const t=c.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<b.length;e++){const t=x[e],n=b[e];null!==t&&void 0!==n&&n.update(t,r,l||s)}F&&F(t,r),r.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:r}),p=null}),this.setAnimationLoop=function(e){F=e},this.dispose=function(){}}}const Fu=new $n,Ou=new Fn;function Bu(e,t){function n(e,t){!0===e.matrixAutoUpdate&&e.updateMatrix(),t.value.copy(e.matrix)}function i(e,i){e.opacity.value=i.opacity,i.color&&e.diffuse.value.copy(i.color),i.emissive&&e.emissive.value.copy(i.emissive).multiplyScalar(i.emissiveIntensity),i.map&&(e.map.value=i.map,n(i.map,e.mapTransform)),i.alphaMap&&(e.alphaMap.value=i.alphaMap,n(i.alphaMap,e.alphaMapTransform)),i.bumpMap&&(e.bumpMap.value=i.bumpMap,n(i.bumpMap,e.bumpMapTransform),e.bumpScale.value=i.bumpScale,1===i.side&&(e.bumpScale.value*=-1)),i.normalMap&&(e.normalMap.value=i.normalMap,n(i.normalMap,e.normalMapTransform),e.normalScale.value.copy(i.normalScale),1===i.side&&e.normalScale.value.negate()),i.displacementMap&&(e.displacementMap.value=i.displacementMap,n(i.displacementMap,e.displacementMapTransform),e.displacementScale.value=i.displacementScale,e.displacementBias.value=i.displacementBias),i.emissiveMap&&(e.emissiveMap.value=i.emissiveMap,n(i.emissiveMap,e.emissiveMapTransform)),i.specularMap&&(e.specularMap.value=i.specularMap,n(i.specularMap,e.specularMapTransform)),i.alphaTest>0&&(e.alphaTest.value=i.alphaTest);const r=t.get(i),s=r.envMap,a=r.envMapRotation;s&&(e.envMap.value=s,Fu.copy(a),Fu.x*=-1,Fu.y*=-1,Fu.z*=-1,s.isCubeTexture&&!1===s.isRenderTargetTexture&&(Fu.y*=-1,Fu.z*=-1),e.envMapRotation.value.setFromMatrix4(Ou.makeRotationFromEuler(Fu)),e.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,e.reflectivity.value=i.reflectivity,e.ior.value=i.ior,e.refractionRatio.value=i.refractionRatio),i.lightMap&&(e.lightMap.value=i.lightMap,e.lightMapIntensity.value=i.lightMapIntensity,n(i.lightMap,e.lightMapTransform)),i.aoMap&&(e.aoMap.value=i.aoMap,e.aoMapIntensity.value=i.aoMapIntensity,n(i.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,Hs(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,r,s,a,o){r.isMeshBasicMaterial?i(e,r):r.isMeshLambertMaterial?(i(e,r),r.envMap&&(e.envMapIntensity.value=r.envMapIntensity)):r.isMeshToonMaterial?(i(e,r),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,r)):r.isMeshPhongMaterial?(i(e,r),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,r),r.envMap&&(e.envMapIntensity.value=r.envMapIntensity)):r.isMeshStandardMaterial?(i(e,r),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform));e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform));t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,r),r.isMeshPhysicalMaterial&&function(e,t,i){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform)));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),1===t.side&&e.clearcoatNormalScale.value.negate()));t.dispersion>0&&(e.dispersion.value=t.dispersion);t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform)));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=i.texture,e.transmissionSamplerSize.value.set(i.width,i.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,r,o)):r.isMeshMatcapMaterial?(i(e,r),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,r)):r.isMeshDepthMaterial?i(e,r):r.isMeshDistanceMaterial?(i(e,r),function(e,n){const i=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(i.matrixWorld),e.nearDistance.value=i.shadow.camera.near,e.farDistance.value=i.shadow.camera.far}(e,r)):r.isMeshNormalMaterial?i(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,n(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,i,r){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*i,e.scale.value=.5*r,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(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,n(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r):r.isShadowMaterial?(e.color.value.copy(r.color),e.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function ku(e,t,n,i){let r={},s={},a=[];const o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(e,t,n,i){const r=e.value,s=t+"_"+n;if(void 0===i[s])return i[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const e=i[s];if("number"==typeof r||"boolean"==typeof r){if(e!==r)return i[s]=r,!0}else if(!1===e.equals(r))return e.copy(r),!0}return!1}function u(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?Xt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Xt("WebGLRenderer: Unsupported uniform value type.",e),t}function c(t){const n=t.target;n.removeEventListener("dispose",c);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),e.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(e,t){const n=t.program;i.uniformBlockBinding(e,n)},update:function(n,h){let d=r[n.id];void 0===d&&(!function(e){const t=e.uniforms;let n=0;const i=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=u(s[e]),a=n%i,o=a%r.boundary,l=a+o;n+=o,0!==l&&i-l<r.storage&&(n+=i-l),t.__data=new Float32Array(r.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=r.storage}}}const r=n%i;r>0&&(n+=i-r);e.__size=n,e.__cache={}}(n),d=function(t){const n=function(){for(let e=0;e<o;e++)if(-1===a.indexOf(e))return a.push(e),e;return qt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}();t.__bindingPointIndex=n;const i=e.createBuffer(),r=t.__size,s=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,i),e.bufferData(e.UNIFORM_BUFFER,r,s),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,i),i}(n),r[n.id]=d,n.addEventListener("dispose",c));const p=h.program;i.updateUBOMapping(n,p);const f=t.render.frame;s[n.id]!==f&&(!function(t){const n=r[t.id],i=t.uniforms,s=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let t=0,n=i.length;t<n;t++){const n=Array.isArray(i[t])?i[t]:[i[t]];for(let i=0,r=n.length;i<r;i++){const r=n[i];if(!0===l(r,t,i,s)){const t=r.__offset,n=Array.isArray(r.value)?r.value:[r.value];let i=0;for(let s=0;s<n.length;s++){const a=n[s],o=u(a);"number"==typeof a||"boolean"==typeof a?(r.__data[0]=a,e.bufferSubData(e.UNIFORM_BUFFER,t+i,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,i),i+=o.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,r.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}(n),s[n.id]=f)},dispose:function(){for(const t in r)e.deleteBuffer(r[t]);a=[],r={},s={}}}}const zu=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let Vu=null;const Gu=new Qr,Hu=new cn,ju=new dn,Wu=new cn,$u=new cn,Xu=new dn,qu=new dn,Yu=new Fn,Ku=new dn,Zu=new dn;let Qu=null,Ju=null;const ec=[],tc=-1,nc=0,ic=1;class rc extends Xa{constructor(e,t,n=null){super(t,n),this.objects=e,this.recursive=!0,this.transformGroup=!1,this.rotateSpeed=1,this.raycaster=new Ga,this.mouseButtons={LEFT:l,MIDDLE:l,RIGHT:a},this.touches={ONE:c},this._onPointerMove=sc.bind(this),this._onPointerDown=ac.bind(this),this._onPointerCancel=oc.bind(this),this._onContextMenu=lc.bind(this),null!==n&&this.connect(n)}connect(e){super.connect(e),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerCancel),this.domElement.addEventListener("pointerleave",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerCancel),this.domElement.removeEventListener("pointerleave",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="auto",this.domElement.style.cursor=""}dispose(){this.disconnect()}_updatePointer(e){const t=this.domElement.getBoundingClientRect();Hu.x=(e.clientX-t.left)/t.width*2-1,Hu.y=-(e.clientY-t.top)/t.height*2+1}_updateState(e){let t;if("touch"===e.pointerType)t=this.touches.ONE;else switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=null}switch(t){case l:case c:this.state=nc;break;case a:case u:this.state=ic;break;default:this.state=tc}}}function sc(e){const t=this.object,n=this.domElement,i=this.raycaster;if(!1!==this.enabled){if(this._updatePointer(e),i.setFromCamera(Hu,t),Qu)this.state===nc?i.ray.intersectPlane(Gu,Xu)&&(Qu.position.copy(Xu.sub(ju).applyMatrix4(Yu)),this.dispatchEvent({type:"drag",object:Qu})):this.state===ic&&(Wu.subVectors(Hu,$u).multiplyScalar(this.rotateSpeed),Qu.rotateOnWorldAxis(Ku,Wu.x),Qu.rotateOnWorldAxis(Zu.normalize(),-Wu.y),this.dispatchEvent({type:"drag",object:Qu})),$u.copy(Hu);else if("mouse"===e.pointerType||"pen"===e.pointerType)if(ec.length=0,i.setFromCamera(Hu,t),i.intersectObjects(this.objects,this.recursive,ec),ec.length>0){const e=ec[0].object;Gu.setFromNormalAndCoplanarPoint(t.getWorldDirection(Gu.normal),qu.setFromMatrixPosition(e.matrixWorld)),Ju!==e&&null!==Ju&&(this.dispatchEvent({type:"hoveroff",object:Ju}),n.style.cursor="auto",Ju=null),Ju!==e&&(this.dispatchEvent({type:"hoveron",object:e}),n.style.cursor="pointer",Ju=e)}else null!==Ju&&(this.dispatchEvent({type:"hoveroff",object:Ju}),n.style.cursor="auto",Ju=null);$u.copy(Hu)}}function ac(e){const t=this.object,n=this.domElement,i=this.raycaster;!1!==this.enabled&&(this._updatePointer(e),this._updateState(e),ec.length=0,i.setFromCamera(Hu,t),i.intersectObjects(this.objects,this.recursive,ec),ec.length>0&&(Qu=!0===this.transformGroup?uc(ec[0].object):ec[0].object,Gu.setFromNormalAndCoplanarPoint(t.getWorldDirection(Gu.normal),qu.setFromMatrixPosition(Qu.matrixWorld)),i.ray.intersectPlane(Gu,Xu)&&(this.state===nc?(Yu.copy(Qu.parent.matrixWorld).invert(),ju.copy(Xu).sub(qu.setFromMatrixPosition(Qu.matrixWorld)),n.style.cursor="move",this.dispatchEvent({type:"dragstart",object:Qu})):this.state===ic&&(Ku.set(0,1,0).applyQuaternion(t.quaternion).normalize(),Zu.set(1,0,0).applyQuaternion(t.quaternion).normalize(),n.style.cursor="move",this.dispatchEvent({type:"dragstart",object:Qu})))),$u.copy(Hu))}function oc(){!1!==this.enabled&&(Qu&&(this.dispatchEvent({type:"dragend",object:Qu}),Qu=null),this.domElement.style.cursor=Ju?"pointer":"auto",this.state=tc)}function lc(e){!1!==this.enabled&&e.preventDefault()}function uc(e,t=null){return e.isGroup&&(t=e),null===e.parent?t:uc(e.parent,t)}function cc(e,t,n){var i,r=1;function s(){var s,a,o=i.length,l=0,u=0,c=0;for(s=0;s<o;++s)l+=(a=i[s]).x||0,u+=a.y||0,c+=a.z||0;for(l=(l/o-e)*r,u=(u/o-t)*r,c=(c/o-n)*r,s=0;s<o;++s)a=i[s],l&&(a.x-=l),u&&(a.y-=u),c&&(a.z-=c)}return null==e&&(e=0),null==t&&(t=0),null==n&&(n=0),s.initialize=function(e){i=e},s.x=function(t){return arguments.length?(e=+t,s):e},s.y=function(e){return arguments.length?(t=+e,s):t},s.z=function(e){return arguments.length?(n=+e,s):n},s.strength=function(e){return arguments.length?(r=+e,s):r},s}function hc(e,t,n){if(isNaN(t))return e;var i,r,s,a,o,l,u=e._root,c={data:n},h=e._x0,d=e._x1;if(!u)return e._root=c,e;for(;u.length;)if((a=t>=(r=(h+d)/2))?h=r:d=r,i=u,!(u=u[o=+a]))return i[o]=c,e;if(t===(s=+e._x.call(null,u.data)))return c.next=u,i?i[o]=c:e._root=c,e;do{i=i?i[o]=new Array(2):e._root=new Array(2),(a=t>=(r=(h+d)/2))?h=r:d=r}while((o=+a)===(l=+(s>=r)));return i[l]=u,i[o]=c,e}function dc(e,t,n){this.node=e,this.x0=t,this.x1=n}function pc(e){return e[0]}function fc(e,t){var n=new mc(null==t?pc:t,NaN,NaN);return null==e?n:n.addAll(e)}function mc(e,t,n){this._x=e,this._x0=t,this._x1=n,this._root=void 0}function gc(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var _c=fc.prototype=mc.prototype;function vc(e,t,n,i){if(isNaN(t)||isNaN(n))return e;var r,s,a,o,l,u,c,h,d,p=e._root,f={data:i},m=e._x0,g=e._y0,_=e._x1,v=e._y1;if(!p)return e._root=f,e;for(;p.length;)if((u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a,r=p,!(p=p[h=c<<1|u]))return r[h]=f,e;if(o=+e._x.call(null,p.data),l=+e._y.call(null,p.data),t===o&&n===l)return f.next=p,r?r[h]=f:e._root=f,e;do{r=r?r[h]=new Array(4):e._root=new Array(4),(u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a}while((h=c<<1|u)==(d=(l>=a)<<1|o>=s));return r[d]=p,r[h]=f,e}function yc(e,t,n,i,r){this.node=e,this.x0=t,this.y0=n,this.x1=i,this.y1=r}function bc(e){return e[0]}function xc(e){return e[1]}function Tc(e,t,n){var i=new Sc(null==t?bc:t,null==n?xc:n,NaN,NaN,NaN,NaN);return null==e?i:i.addAll(e)}function Sc(e,t,n,i,r,s){this._x=e,this._y=t,this._x0=n,this._y0=i,this._x1=r,this._y1=s,this._root=void 0}function Mc(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}_c.copy=function(){var e,t,n=new mc(this._x,this._x0,this._x1),i=this._root;if(!i)return n;if(!i.length)return n._root=gc(i),n;for(e=[{source:i,target:n._root=new Array(2)}];i=e.pop();)for(var r=0;r<2;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(2)}):i.target[r]=gc(t));return n},_c.add=function(e){const t=+this._x.call(null,e);return hc(this.cover(t),t,e)},_c.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t);let i=1/0,r=-1/0;for(let s,a=0;a<t;++a)isNaN(s=+this._x.call(null,e[a]))||(n[a]=s,s<i&&(i=s),s>r&&(r=s));if(i>r)return this;this.cover(i).cover(r);for(let i=0;i<t;++i)hc(this,n[i],e[i]);return this},_c.cover=function(e){if(isNaN(e=+e))return this;var t=this._x0,n=this._x1;if(isNaN(t))n=(t=Math.floor(e))+1;else{for(var i,r,s=n-t||1,a=this._root;t>e||e>=n;)switch(r=+(e<t),(i=new Array(2))[r]=a,a=i,s*=2,r){case 0:n=t+s;break;case 1:t=n-s}this._root&&this._root.length&&(this._root=a)}return this._x0=t,this._x1=n,this},_c.data=function(){var e=[];return this.visit(function(t){if(!t.length)do{e.push(t.data)}while(t=t.next)}),e},_c.extent=function(e){return arguments.length?this.cover(+e[0][0]).cover(+e[1][0]):isNaN(this._x0)?void 0:[[this._x0],[this._x1]]},_c.find=function(e,t){var n,i,r,s,a,o=this._x0,l=this._x1,u=[],c=this._root;for(c&&u.push(new dc(c,o,l)),null==t?t=1/0:(o=e-t,l=e+t);s=u.pop();)if(!(!(c=s.node)||(i=s.x0)>l||(r=s.x1)<o))if(c.length){var h=(i+r)/2;u.push(new dc(c[1],h,r),new dc(c[0],i,h)),(a=+(e>=h))&&(s=u[u.length-1],u[u.length-1]=u[u.length-1-a],u[u.length-1-a]=s)}else{var d=Math.abs(e-+this._x.call(null,c.data));d<t&&(t=d,o=e-d,l=e+d,n=c.data)}return n},_c.remove=function(e){if(isNaN(s=+this._x.call(null,e)))return this;var t,n,i,r,s,a,o,l,u,c=this._root,h=this._x0,d=this._x1;if(!c)return this;if(c.length)for(;;){if((o=s>=(a=(h+d)/2))?h=a:d=a,t=c,!(c=c[l=+o]))return this;if(!c.length)break;t[l+1&1]&&(n=t,u=l)}for(;c.data!==e;)if(i=c,!(c=c.next))return this;return(r=c.next)&&delete c.next,i?(r?i.next=r:delete i.next,this):t?(r?t[l]=r:delete t[l],(c=t[0]||t[1])&&c===(t[1]||t[0])&&!c.length&&(n?n[u]=c:this._root=c),this):(this._root=r,this)},_c.removeAll=function(e){for(var t=0,n=e.length;t<n;++t)this.remove(e[t]);return this},_c.root=function(){return this._root},_c.size=function(){var e=0;return this.visit(function(t){if(!t.length)do{++e}while(t=t.next)}),e},_c.visit=function(e){var t,n,i,r,s=[],a=this._root;for(a&&s.push(new dc(a,this._x0,this._x1));t=s.pop();)if(!e(a=t.node,i=t.x0,r=t.x1)&&a.length){var o=(i+r)/2;(n=a[1])&&s.push(new dc(n,o,r)),(n=a[0])&&s.push(new dc(n,i,o))}return this},_c.visitAfter=function(e){var t,n=[],i=[];for(this._root&&n.push(new dc(this._root,this._x0,this._x1));t=n.pop();){var r=t.node;if(r.length){var s,a=t.x0,o=t.x1,l=(a+o)/2;(s=r[0])&&n.push(new dc(s,a,l)),(s=r[1])&&n.push(new dc(s,l,o))}i.push(t)}for(;t=i.pop();)e(t.node,t.x0,t.x1);return this},_c.x=function(e){return arguments.length?(this._x=e,this):this._x};var Ec=Tc.prototype=Sc.prototype;function wc(e,t,n,i,r){if(isNaN(t)||isNaN(n)||isNaN(i))return e;var s,a,o,l,u,c,h,d,p,f,m,g,_=e._root,v={data:r},y=e._x0,b=e._y0,x=e._z0,T=e._x1,S=e._y1,M=e._z1;if(!_)return e._root=v,e;for(;_.length;)if((d=t>=(a=(y+T)/2))?y=a:T=a,(p=n>=(o=(b+S)/2))?b=o:S=o,(f=i>=(l=(x+M)/2))?x=l:M=l,s=_,!(_=_[m=f<<2|p<<1|d]))return s[m]=v,e;if(u=+e._x.call(null,_.data),c=+e._y.call(null,_.data),h=+e._z.call(null,_.data),t===u&&n===c&&i===h)return v.next=_,s?s[m]=v:e._root=v,e;do{s=s?s[m]=new Array(8):e._root=new Array(8),(d=t>=(a=(y+T)/2))?y=a:T=a,(p=n>=(o=(b+S)/2))?b=o:S=o,(f=i>=(l=(x+M)/2))?x=l:M=l}while((m=f<<2|p<<1|d)==(g=(h>=l)<<2|(c>=o)<<1|u>=a));return s[g]=_,s[m]=v,e}function Ac(e,t,n,i,r,s,a){this.node=e,this.x0=t,this.y0=n,this.z0=i,this.x1=r,this.y1=s,this.z1=a}Ec.copy=function(){var e,t,n=new Sc(this._x,this._y,this._x0,this._y0,this._x1,this._y1),i=this._root;if(!i)return n;if(!i.length)return n._root=Mc(i),n;for(e=[{source:i,target:n._root=new Array(4)}];i=e.pop();)for(var r=0;r<4;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(4)}):i.target[r]=Mc(t));return n},Ec.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e);return vc(this.cover(t,n),t,n,e)},Ec.addAll=function(e){var t,n,i,r,s=e.length,a=new Array(s),o=new Array(s),l=1/0,u=1/0,c=-1/0,h=-1/0;for(n=0;n<s;++n)isNaN(i=+this._x.call(null,t=e[n]))||isNaN(r=+this._y.call(null,t))||(a[n]=i,o[n]=r,i<l&&(l=i),i>c&&(c=i),r<u&&(u=r),r>h&&(h=r));if(l>c||u>h)return this;for(this.cover(l,u).cover(c,h),n=0;n<s;++n)vc(this,a[n],o[n],e[n]);return this},Ec.cover=function(e,t){if(isNaN(e=+e)||isNaN(t=+t))return this;var n=this._x0,i=this._y0,r=this._x1,s=this._y1;if(isNaN(n))r=(n=Math.floor(e))+1,s=(i=Math.floor(t))+1;else{for(var a,o,l=r-n||1,u=this._root;n>e||e>=r||i>t||t>=s;)switch(o=(t<i)<<1|e<n,(a=new Array(4))[o]=u,u=a,l*=2,o){case 0:r=n+l,s=i+l;break;case 1:n=r-l,s=i+l;break;case 2:r=n+l,i=s-l;break;case 3:n=r-l,i=s-l}this._root&&this._root.length&&(this._root=u)}return this._x0=n,this._y0=i,this._x1=r,this._y1=s,this},Ec.data=function(){var e=[];return this.visit(function(t){if(!t.length)do{e.push(t.data)}while(t=t.next)}),e},Ec.extent=function(e){return arguments.length?this.cover(+e[0][0],+e[0][1]).cover(+e[1][0],+e[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},Ec.find=function(e,t,n){var i,r,s,a,o,l,u,c=this._x0,h=this._y0,d=this._x1,p=this._y1,f=[],m=this._root;for(m&&f.push(new yc(m,c,h,d,p)),null==n?n=1/0:(c=e-n,h=t-n,d=e+n,p=t+n,n*=n);l=f.pop();)if(!(!(m=l.node)||(r=l.x0)>d||(s=l.y0)>p||(a=l.x1)<c||(o=l.y1)<h))if(m.length){var g=(r+a)/2,_=(s+o)/2;f.push(new yc(m[3],g,_,a,o),new yc(m[2],r,_,g,o),new yc(m[1],g,s,a,_),new yc(m[0],r,s,g,_)),(u=(t>=_)<<1|e>=g)&&(l=f[f.length-1],f[f.length-1]=f[f.length-1-u],f[f.length-1-u]=l)}else{var v=e-+this._x.call(null,m.data),y=t-+this._y.call(null,m.data),b=v*v+y*y;if(b<n){var x=Math.sqrt(n=b);c=e-x,h=t-x,d=e+x,p=t+x,i=m.data}}return i},Ec.remove=function(e){if(isNaN(s=+this._x.call(null,e))||isNaN(a=+this._y.call(null,e)))return this;var t,n,i,r,s,a,o,l,u,c,h,d,p=this._root,f=this._x0,m=this._y0,g=this._x1,_=this._y1;if(!p)return this;if(p.length)for(;;){if((u=s>=(o=(f+g)/2))?f=o:g=o,(c=a>=(l=(m+_)/2))?m=l:_=l,t=p,!(p=p[h=c<<1|u]))return this;if(!p.length)break;(t[h+1&3]||t[h+2&3]||t[h+3&3])&&(n=t,d=h)}for(;p.data!==e;)if(i=p,!(p=p.next))return this;return(r=p.next)&&delete p.next,i?(r?i.next=r:delete i.next,this):t?(r?t[h]=r:delete t[h],(p=t[0]||t[1]||t[2]||t[3])&&p===(t[3]||t[2]||t[1]||t[0])&&!p.length&&(n?n[d]=p:this._root=p),this):(this._root=r,this)},Ec.removeAll=function(e){for(var t=0,n=e.length;t<n;++t)this.remove(e[t]);return this},Ec.root=function(){return this._root},Ec.size=function(){var e=0;return this.visit(function(t){if(!t.length)do{++e}while(t=t.next)}),e},Ec.visit=function(e){var t,n,i,r,s,a,o=[],l=this._root;for(l&&o.push(new yc(l,this._x0,this._y0,this._x1,this._y1));t=o.pop();)if(!e(l=t.node,i=t.x0,r=t.y0,s=t.x1,a=t.y1)&&l.length){var u=(i+s)/2,c=(r+a)/2;(n=l[3])&&o.push(new yc(n,u,c,s,a)),(n=l[2])&&o.push(new yc(n,i,c,u,a)),(n=l[1])&&o.push(new yc(n,u,r,s,c)),(n=l[0])&&o.push(new yc(n,i,r,u,c))}return this},Ec.visitAfter=function(e){var t,n=[],i=[];for(this._root&&n.push(new yc(this._root,this._x0,this._y0,this._x1,this._y1));t=n.pop();){var r=t.node;if(r.length){var s,a=t.x0,o=t.y0,l=t.x1,u=t.y1,c=(a+l)/2,h=(o+u)/2;(s=r[0])&&n.push(new yc(s,a,o,c,h)),(s=r[1])&&n.push(new yc(s,c,o,l,h)),(s=r[2])&&n.push(new yc(s,a,h,c,u)),(s=r[3])&&n.push(new yc(s,c,h,l,u))}i.push(t)}for(;t=i.pop();)e(t.node,t.x0,t.y0,t.x1,t.y1);return this},Ec.x=function(e){return arguments.length?(this._x=e,this):this._x},Ec.y=function(e){return arguments.length?(this._y=e,this):this._y};const Rc=(e,t,n,i,r,s)=>Math.sqrt((e-i)**2+(t-r)**2+(n-s)**2);function Cc(e){return e[0]}function Nc(e){return e[1]}function Pc(e){return e[2]}function Lc(e,t,n,i){var r=new Dc(null==t?Cc:t,null==n?Nc:n,null==i?Pc:i,NaN,NaN,NaN,NaN,NaN,NaN);return null==e?r:r.addAll(e)}function Dc(e,t,n,i,r,s,a,o,l){this._x=e,this._y=t,this._z=n,this._x0=i,this._y0=r,this._z0=s,this._x1=a,this._y1=o,this._z1=l,this._root=void 0}function Ic(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var Uc=Lc.prototype=Dc.prototype;function Fc(e){return function(){return e}}function Oc(e){return 1e-6*(e()-.5)}function Bc(e){return e.index}function kc(e,t){var n=e.get(t);if(!n)throw new Error("node not found: "+t);return n}function zc(e){var t,n,i,r,s,a,o,l=Bc,u=function(e){return 1/Math.min(s[e.source.index],s[e.target.index])},c=Fc(30),h=1;function d(i){for(var s=0,l=e.length;s<h;++s)for(var u,c,d,p,f,m=0,g=0,_=0,v=0;m<l;++m)c=(u=e[m]).source,g=(d=u.target).x+d.vx-c.x-c.vx||Oc(o),r>1&&(_=d.y+d.vy-c.y-c.vy||Oc(o)),r>2&&(v=d.z+d.vz-c.z-c.vz||Oc(o)),g*=p=((p=Math.sqrt(g*g+_*_+v*v))-n[m])/p*i*t[m],_*=p,v*=p,d.vx-=g*(f=a[m]),r>1&&(d.vy-=_*f),r>2&&(d.vz-=v*f),c.vx+=g*(f=1-f),r>1&&(c.vy+=_*f),r>2&&(c.vz+=v*f)}function p(){if(i){var r,o,u=i.length,c=e.length,h=new Map(i.map((e,t)=>[l(e,t,i),e]));for(r=0,s=new Array(u);r<c;++r)(o=e[r]).index=r,"object"!=typeof o.source&&(o.source=kc(h,o.source)),"object"!=typeof o.target&&(o.target=kc(h,o.target)),s[o.source.index]=(s[o.source.index]||0)+1,s[o.target.index]=(s[o.target.index]||0)+1;for(r=0,a=new Array(c);r<c;++r)o=e[r],a[r]=s[o.source.index]/(s[o.source.index]+s[o.target.index]);t=new Array(c),f(),n=new Array(c),m()}}function f(){if(i)for(var n=0,r=e.length;n<r;++n)t[n]=+u(e[n],n,e)}function m(){if(i)for(var t=0,r=e.length;t<r;++t)n[t]=+c(e[t],t,e)}return null==e&&(e=[]),d.initialize=function(e,...t){i=e,o=t.find(e=>"function"==typeof e)||Math.random,r=t.find(e=>[1,2,3].includes(e))||2,p()},d.links=function(t){return arguments.length?(e=t,p(),d):e},d.id=function(e){return arguments.length?(l=e,d):l},d.iterations=function(e){return arguments.length?(h=+e,d):h},d.strength=function(e){return arguments.length?(u="function"==typeof e?e:Fc(+e),f(),d):u},d.distance=function(e){return arguments.length?(c="function"==typeof e?e:Fc(+e),m(),d):c},d}Uc.copy=function(){var e,t,n=new Dc(this._x,this._y,this._z,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1),i=this._root;if(!i)return n;if(!i.length)return n._root=Ic(i),n;for(e=[{source:i,target:n._root=new Array(8)}];i=e.pop();)for(var r=0;r<8;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(8)}):i.target[r]=Ic(t));return n},Uc.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e),i=+this._z.call(null,e);return wc(this.cover(t,n,i),t,n,i,e)},Uc.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t),i=new Float64Array(t),r=new Float64Array(t);let s=1/0,a=1/0,o=1/0,l=-1/0,u=-1/0,c=-1/0;for(let h,d,p,f,m=0;m<t;++m)isNaN(d=+this._x.call(null,h=e[m]))||isNaN(p=+this._y.call(null,h))||isNaN(f=+this._z.call(null,h))||(n[m]=d,i[m]=p,r[m]=f,d<s&&(s=d),d>l&&(l=d),p<a&&(a=p),p>u&&(u=p),f<o&&(o=f),f>c&&(c=f));if(s>l||a>u||o>c)return this;this.cover(s,a,o).cover(l,u,c);for(let s=0;s<t;++s)wc(this,n[s],i[s],r[s],e[s]);return this},Uc.cover=function(e,t,n){if(isNaN(e=+e)||isNaN(t=+t)||isNaN(n=+n))return this;var i=this._x0,r=this._y0,s=this._z0,a=this._x1,o=this._y1,l=this._z1;if(isNaN(i))a=(i=Math.floor(e))+1,o=(r=Math.floor(t))+1,l=(s=Math.floor(n))+1;else{for(var u,c,h=a-i||1,d=this._root;i>e||e>=a||r>t||t>=o||s>n||n>=l;)switch(c=(n<s)<<2|(t<r)<<1|e<i,(u=new Array(8))[c]=d,d=u,h*=2,c){case 0:a=i+h,o=r+h,l=s+h;break;case 1:i=a-h,o=r+h,l=s+h;break;case 2:a=i+h,r=o-h,l=s+h;break;case 3:i=a-h,r=o-h,l=s+h;break;case 4:a=i+h,o=r+h,s=l-h;break;case 5:i=a-h,o=r+h,s=l-h;break;case 6:a=i+h,r=o-h,s=l-h;break;case 7:i=a-h,r=o-h,s=l-h}this._root&&this._root.length&&(this._root=d)}return this._x0=i,this._y0=r,this._z0=s,this._x1=a,this._y1=o,this._z1=l,this},Uc.data=function(){var e=[];return this.visit(function(t){if(!t.length)do{e.push(t.data)}while(t=t.next)}),e},Uc.extent=function(e){return arguments.length?this.cover(+e[0][0],+e[0][1],+e[0][2]).cover(+e[1][0],+e[1][1],+e[1][2]):isNaN(this._x0)?void 0:[[this._x0,this._y0,this._z0],[this._x1,this._y1,this._z1]]},Uc.find=function(e,t,n,i){var r,s,a,o,l,u,c,h,d,p=this._x0,f=this._y0,m=this._z0,g=this._x1,_=this._y1,v=this._z1,y=[],b=this._root;for(b&&y.push(new Ac(b,p,f,m,g,_,v)),null==i?i=1/0:(p=e-i,f=t-i,m=n-i,g=e+i,_=t+i,v=n+i,i*=i);h=y.pop();)if(!(!(b=h.node)||(s=h.x0)>g||(a=h.y0)>_||(o=h.z0)>v||(l=h.x1)<p||(u=h.y1)<f||(c=h.z1)<m))if(b.length){var x=(s+l)/2,T=(a+u)/2,S=(o+c)/2;y.push(new Ac(b[7],x,T,S,l,u,c),new Ac(b[6],s,T,S,x,u,c),new Ac(b[5],x,a,S,l,T,c),new Ac(b[4],s,a,S,x,T,c),new Ac(b[3],x,T,o,l,u,S),new Ac(b[2],s,T,o,x,u,S),new Ac(b[1],x,a,o,l,T,S),new Ac(b[0],s,a,o,x,T,S)),(d=(n>=S)<<2|(t>=T)<<1|e>=x)&&(h=y[y.length-1],y[y.length-1]=y[y.length-1-d],y[y.length-1-d]=h)}else{var M=e-+this._x.call(null,b.data),E=t-+this._y.call(null,b.data),w=n-+this._z.call(null,b.data),A=M*M+E*E+w*w;if(A<i){var R=Math.sqrt(i=A);p=e-R,f=t-R,m=n-R,g=e+R,_=t+R,v=n+R,r=b.data}}return r},Uc.findAllWithinRadius=function(e,t,n,i){const r=[],s=e-i,a=t-i,o=n-i,l=e+i,u=t+i,c=n+i;return this.visit((h,d,p,f,m,g,_)=>{if(!h.length)do{const s=h.data;Rc(e,t,n,this._x(s),this._y(s),this._z(s))<=i&&r.push(s)}while(h=h.next);return d>l||p>u||f>c||m<s||g<a||_<o}),r},Uc.remove=function(e){if(isNaN(s=+this._x.call(null,e))||isNaN(a=+this._y.call(null,e))||isNaN(o=+this._z.call(null,e)))return this;var t,n,i,r,s,a,o,l,u,c,h,d,p,f,m,g=this._root,_=this._x0,v=this._y0,y=this._z0,b=this._x1,x=this._y1,T=this._z1;if(!g)return this;if(g.length)for(;;){if((h=s>=(l=(_+b)/2))?_=l:b=l,(d=a>=(u=(v+x)/2))?v=u:x=u,(p=o>=(c=(y+T)/2))?y=c:T=c,t=g,!(g=g[f=p<<2|d<<1|h]))return this;if(!g.length)break;(t[f+1&7]||t[f+2&7]||t[f+3&7]||t[f+4&7]||t[f+5&7]||t[f+6&7]||t[f+7&7])&&(n=t,m=f)}for(;g.data!==e;)if(i=g,!(g=g.next))return this;return(r=g.next)&&delete g.next,i?(r?i.next=r:delete i.next,this):t?(r?t[f]=r:delete t[f],(g=t[0]||t[1]||t[2]||t[3]||t[4]||t[5]||t[6]||t[7])&&g===(t[7]||t[6]||t[5]||t[4]||t[3]||t[2]||t[1]||t[0])&&!g.length&&(n?n[m]=g:this._root=g),this):(this._root=r,this)},Uc.removeAll=function(e){for(var t=0,n=e.length;t<n;++t)this.remove(e[t]);return this},Uc.root=function(){return this._root},Uc.size=function(){var e=0;return this.visit(function(t){if(!t.length)do{++e}while(t=t.next)}),e},Uc.visit=function(e){var t,n,i,r,s,a,o,l,u=[],c=this._root;for(c&&u.push(new Ac(c,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));t=u.pop();)if(!e(c=t.node,i=t.x0,r=t.y0,s=t.z0,a=t.x1,o=t.y1,l=t.z1)&&c.length){var h=(i+a)/2,d=(r+o)/2,p=(s+l)/2;(n=c[7])&&u.push(new Ac(n,h,d,p,a,o,l)),(n=c[6])&&u.push(new Ac(n,i,d,p,h,o,l)),(n=c[5])&&u.push(new Ac(n,h,r,p,a,d,l)),(n=c[4])&&u.push(new Ac(n,i,r,p,h,d,l)),(n=c[3])&&u.push(new Ac(n,h,d,s,a,o,p)),(n=c[2])&&u.push(new Ac(n,i,d,s,h,o,p)),(n=c[1])&&u.push(new Ac(n,h,r,s,a,d,p)),(n=c[0])&&u.push(new Ac(n,i,r,s,h,d,p))}return this},Uc.visitAfter=function(e){var t,n=[],i=[];for(this._root&&n.push(new Ac(this._root,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));t=n.pop();){var r=t.node;if(r.length){var s,a=t.x0,o=t.y0,l=t.z0,u=t.x1,c=t.y1,h=t.z1,d=(a+u)/2,p=(o+c)/2,f=(l+h)/2;(s=r[0])&&n.push(new Ac(s,a,o,l,d,p,f)),(s=r[1])&&n.push(new Ac(s,d,o,l,u,p,f)),(s=r[2])&&n.push(new Ac(s,a,p,l,d,c,f)),(s=r[3])&&n.push(new Ac(s,d,p,l,u,c,f)),(s=r[4])&&n.push(new Ac(s,a,o,f,d,p,h)),(s=r[5])&&n.push(new Ac(s,d,o,f,u,p,h)),(s=r[6])&&n.push(new Ac(s,a,p,f,d,c,h)),(s=r[7])&&n.push(new Ac(s,d,p,f,u,c,h))}i.push(t)}for(;t=i.pop();)e(t.node,t.x0,t.y0,t.z0,t.x1,t.y1,t.z1);return this},Uc.x=function(e){return arguments.length?(this._x=e,this):this._x},Uc.y=function(e){return arguments.length?(this._y=e,this):this._y},Uc.z=function(e){return arguments.length?(this._z=e,this):this._z};var Vc={value:()=>{}};function Gc(){for(var e,t=0,n=arguments.length,i={};t<n;++t){if(!(e=arguments[t]+"")||e in i||/[\s.]/.test(e))throw new Error("illegal type: "+e);i[e]=[]}return new Hc(i)}function Hc(e){this._=e}function jc(e,t){for(var n,i=0,r=e.length;i<r;++i)if((n=e[i]).name===t)return n.value}function Wc(e,t,n){for(var i=0,r=e.length;i<r;++i)if(e[i].name===t){e[i]=Vc,e=e.slice(0,i).concat(e.slice(i+1));break}return null!=n&&e.push({name:t,value:n}),e}Hc.prototype=Gc.prototype={constructor:Hc,on:function(e,t){var n,i,r=this._,s=(i=r,(e+"").trim().split(/^|\s+/).map(function(e){var t="",n=e.indexOf(".");if(n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),e&&!i.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:t}})),a=-1,o=s.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++a<o;)if(n=(e=s[a]).type)r[n]=Wc(r[n],e.name,t);else if(null==t)for(n in r)r[n]=Wc(r[n],e.name,null);return this}for(;++a<o;)if((n=(e=s[a]).type)&&(n=jc(r[n],e.name)))return n},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new Hc(e)},call:function(e,t){if((n=arguments.length-2)>0)for(var n,i,r=new Array(n),s=0;s<n;++s)r[s]=arguments[s+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(s=0,n=(i=this._[e]).length;s<n;++s)i[s].value.apply(t,r)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var i=this._[e],r=0,s=i.length;r<s;++r)i[r].value.apply(t,n)}};var $c,Xc,qc=0,Yc=0,Kc=0,Zc=0,Qc=0,Jc=0,eh="object"==typeof performance&&performance.now?performance:Date,th="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function nh(){return Qc||(th(ih),Qc=eh.now()+Jc)}function ih(){Qc=0}function rh(){this._call=this._time=this._next=null}function sh(e,t,n){var i=new rh;return i.restart(e,t,n),i}function ah(){Qc=(Zc=eh.now())+Jc,qc=Yc=0;try{!function(){nh(),++qc;for(var e,t=$c;t;)(e=Qc-t._time)>=0&&t._call.call(void 0,e),t=t._next;--qc}()}finally{qc=0,function(){var e,t,n=$c,i=1/0;for(;n;)n._call?(i>n._time&&(i=n._time),e=n,n=n._next):(t=n._next,n._next=null,n=e?e._next=t:$c=t);Xc=e,lh(i)}(),Qc=0}}function oh(){var e=eh.now(),t=e-Zc;t>1e3&&(Jc-=t,Zc=e)}function lh(e){qc||(Yc&&(Yc=clearTimeout(Yc)),e-Qc>24?(e<1/0&&(Yc=setTimeout(ah,e-eh.now()-Jc)),Kc&&(Kc=clearInterval(Kc))):(Kc||(Zc=eh.now(),Kc=setInterval(oh,1e3)),qc=1,th(ah)))}rh.prototype=sh.prototype={constructor:rh,restart:function(e,t,n){if("function"!=typeof e)throw new TypeError("callback is not a function");n=(null==n?nh():+n)+(null==t?0:+t),this._next||Xc===this||(Xc?Xc._next=this:$c=this,Xc=this),this._call=e,this._time=n,lh()},stop:function(){this._call&&(this._call=null,this._time=1/0,lh())}};const uh=4294967296;function ch(e){return e.x}function hh(e){return e.y}function dh(e){return e.z}var ph=Math.PI*(3-Math.sqrt(5)),fh=20*Math.PI/(9+Math.sqrt(221));function mh(e,t){t=t||2;var n,i=Math.min(3,Math.max(1,Math.round(t))),r=1,s=.001,a=1-Math.pow(s,1/300),o=0,l=.6,u=new Map,c=sh(p),h=Gc("tick","end"),d=function(){let e=1;return()=>(e=(1664525*e+1013904223)%uh)/uh}();function p(){f(),h.call("tick",n),r<s&&(c.stop(),h.call("end",n))}function f(t){var s,c,h=e.length;void 0===t&&(t=1);for(var d=0;d<t;++d)for(r+=(o-r)*a,u.forEach(function(e){e(r)}),s=0;s<h;++s)null==(c=e[s]).fx?c.x+=c.vx*=l:(c.x=c.fx,c.vx=0),i>1&&(null==c.fy?c.y+=c.vy*=l:(c.y=c.fy,c.vy=0)),i>2&&(null==c.fz?c.z+=c.vz*=l:(c.z=c.fz,c.vz=0));return n}function m(){for(var t,n=0,r=e.length;n<r;++n){if((t=e[n]).index=n,null!=t.fx&&(t.x=t.fx),null!=t.fy&&(t.y=t.fy),null!=t.fz&&(t.z=t.fz),isNaN(t.x)||i>1&&isNaN(t.y)||i>2&&isNaN(t.z)){var s=10*(i>2?Math.cbrt(.5+n):i>1?Math.sqrt(.5+n):n),a=n*ph,o=n*fh;1===i?t.x=s:2===i?(t.x=s*Math.cos(a),t.y=s*Math.sin(a)):(t.x=s*Math.sin(a)*Math.cos(o),t.y=s*Math.cos(a),t.z=s*Math.sin(a)*Math.sin(o))}(isNaN(t.vx)||i>1&&isNaN(t.vy)||i>2&&isNaN(t.vz))&&(t.vx=0,i>1&&(t.vy=0),i>2&&(t.vz=0))}}function g(t){return t.initialize&&t.initialize(e,d,i),t}return null==e&&(e=[]),m(),n={tick:f,restart:function(){return c.restart(p),n},stop:function(){return c.stop(),n},numDimensions:function(e){return arguments.length?(i=Math.min(3,Math.max(1,Math.round(e))),u.forEach(g),n):i},nodes:function(t){return arguments.length?(e=t,m(),u.forEach(g),n):e},alpha:function(e){return arguments.length?(r=+e,n):r},alphaMin:function(e){return arguments.length?(s=+e,n):s},alphaDecay:function(e){return arguments.length?(a=+e,n):+a},alphaTarget:function(e){return arguments.length?(o=+e,n):o},velocityDecay:function(e){return arguments.length?(l=1-e,n):1-l},randomSource:function(e){return arguments.length?(d=e,u.forEach(g),n):d},force:function(e,t){return arguments.length>1?(null==t?u.delete(e):u.set(e,g(t)),n):u.get(e)},find:function(){var t,n,r,s,a,o,l=Array.prototype.slice.call(arguments),u=l.shift()||0,c=(i>1?l.shift():null)||0,h=(i>2?l.shift():null)||0,d=l.shift()||1/0,p=0,f=e.length;for(d*=d,p=0;p<f;++p)(s=(t=u-(a=e[p]).x)*t+(n=c-(a.y||0))*n+(r=h-(a.z||0))*r)<d&&(o=a,d=s);return o},on:function(e,t){return arguments.length>1?(h.on(e,t),n):h.on(e)}}}function gh(){var e,t,n,i,r,s,a=Fc(-30),o=1,l=1/0,u=.81;function c(i){var s,a=e.length,o=(1===t?fc(e,ch):2===t?Tc(e,ch,hh):3===t?Lc(e,ch,hh,dh):null).visitAfter(d);for(r=i,s=0;s<a;++s)n=e[s],o.visit(p)}function h(){if(e){var t,n,i=e.length;for(s=new Array(i),t=0;t<i;++t)n=e[t],s[n.index]=+a(n,t,e)}}function d(e){var n,i,r,a,o,l,u=0,c=0,h=e.length;if(h){for(r=a=o=l=0;l<h;++l)(n=e[l])&&(i=Math.abs(n.value))&&(u+=n.value,c+=i,r+=i*(n.x||0),a+=i*(n.y||0),o+=i*(n.z||0));u*=Math.sqrt(4/h),e.x=r/c,t>1&&(e.y=a/c),t>2&&(e.z=o/c)}else{(n=e).x=n.data.x,t>1&&(n.y=n.data.y),t>2&&(n.z=n.data.z);do{u+=s[n.data.index]}while(n=n.next)}e.value=u}function p(e,a,c,h,d){if(!e.value)return!0;var p=[c,h,d][t-1],f=e.x-n.x,m=t>1?e.y-n.y:0,g=t>2?e.z-n.z:0,_=p-a,v=f*f+m*m+g*g;if(_*_/u<v)return v<l&&(0===f&&(v+=(f=Oc(i))*f),t>1&&0===m&&(v+=(m=Oc(i))*m),t>2&&0===g&&(v+=(g=Oc(i))*g),v<o&&(v=Math.sqrt(o*v)),n.vx+=f*e.value*r/v,t>1&&(n.vy+=m*e.value*r/v),t>2&&(n.vz+=g*e.value*r/v)),!0;if(!(e.length||v>=l)){(e.data!==n||e.next)&&(0===f&&(v+=(f=Oc(i))*f),t>1&&0===m&&(v+=(m=Oc(i))*m),t>2&&0===g&&(v+=(g=Oc(i))*g),v<o&&(v=Math.sqrt(o*v)));do{e.data!==n&&(_=s[e.data.index]*r/v,n.vx+=f*_,t>1&&(n.vy+=m*_),t>2&&(n.vz+=g*_))}while(e=e.next)}}return c.initialize=function(n,...r){e=n,i=r.find(e=>"function"==typeof e)||Math.random,t=r.find(e=>[1,2,3].includes(e))||2,h()},c.strength=function(e){return arguments.length?(a="function"==typeof e?e:Fc(+e),h(),c):a},c.distanceMin=function(e){return arguments.length?(o=e*e,c):Math.sqrt(o)},c.distanceMax=function(e){return arguments.length?(l=e*e,c):Math.sqrt(l)},c.theta=function(e){return arguments.length?(u=e*e,c):Math.sqrt(u)},c}function _h(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");const t=["on","fire","off"];for(let n=0;n<t.length;++n)if(e.hasOwnProperty(t[n]))throw new Error("Subject cannot be eventified, since it already has property '"+t[n]+"'")}(e);const t=function(e){let t=Object.create(null);return{on:function(n,i,r){if("function"!=typeof i)throw new Error("callback is expected to be a function");let s=t[n];return s||(s=t[n]=[]),s.push({callback:i,ctx:r}),e},off:function(n,i){if(void 0===n)return t=Object.create(null),e;if(t[n]){if("function"!=typeof i)delete t[n];else{const e=t[n];for(let t=0;t<e.length;++t)e[t].callback===i&&e.splice(t,1)}}return e},fire:function(n){const i=t[n];if(!i)return e;let r;arguments.length>1&&(r=Array.prototype.slice.call(arguments,1));for(let e=0;e<i.length;++e){const t=i[e];t.callback.apply(t.ctx,r)}return e}}}(e);return e.on=t.on,e.off=t.off,e.fire=t.fire,e}function vh(e,t){this.id=e,this.links=null,this.data=t}function yh(e,t){e.links?e.links.add(t):e.links=new Set([t])}function bh(e,t,n,i){this.fromId=e,this.toId=t,this.data=n,this.id=i}function xh(e,t){return e.toString()+"👉 "+t.toString()}function Th(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Sh,Mh,Eh,wh,Ah,Rh={exports:{}},Ch={exports:{}};function Nh(){return Mh||(Mh=1,Sh=function(e){return 0===e?"x":1===e?"y":2===e?"z":"c"+(e+1)}),Sh}function Ph(){if(wh)return Eh;wh=1;const e=Nh();return Eh=function(t){return function(n,i){let r=i&&i.indent||0,s=i&&void 0!==i.join?i.join:"\n",a=Array(r+1).join(" "),o=[];for(let i=0;i<t;++i){let t=e(i),r=0===i?"":a;o.push(r+n.replace(/{var}/g,t))}return o.join(s)}},Eh}var Lh,Dh={exports:{}};var Ih,Uh={exports:{}};var Fh,Oh={exports:{}};var Bh,kh={exports:{}};var zh,Vh,Gh,Hh,jh,Wh,$h,Xh={exports:{}};function qh(){if($h)return Wh;return $h=1,Wh=function(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");const t=["on","fire","off"];for(let n=0;n<t.length;++n)if(e.hasOwnProperty(t[n]))throw new Error("Subject cannot be eventified, since it already has property '"+t[n]+"'")}(e);const t=function(e){let t=Object.create(null);return{on:function(n,i,r){if("function"!=typeof i)throw new Error("callback is expected to be a function");let s=t[n];return s||(s=t[n]=[]),s.push({callback:i,ctx:r}),e},off:function(n,i){if(typeof n>"u")return t=Object.create(null),e;if(t[n])if("function"!=typeof i)delete t[n];else{const e=t[n];for(let t=0;t<e.length;++t)e[t].callback===i&&e.splice(t,1)}return e},fire:function(n){const i=t[n];if(!i)return e;let r;arguments.length>1&&(r=Array.prototype.slice.call(arguments,1));for(let e=0;e<i.length;++e){const t=i[e];t.callback.apply(t.ctx,r)}return e}}}(e);return e.on=t.on,e.off=t.off,e.fire=t.fire,e},Wh}var Yh,Kh,Zh,Qh,Jh={exports:{}};function ed(){if(Zh)return Kh;Zh=1,Kh=function(l){var u=(Gh||(Gh=1,Vh=function(e,t,n,i){this.from=e,this.to=t,this.length=n,this.coefficient=i}),Vh),c=(jh||(jh=1,Hh=function e(t,n){var i;if(t||(t={}),n)for(i in n)if(n.hasOwnProperty(i)){var r=t.hasOwnProperty(i),s=typeof n[i];r&&typeof t[i]===s?"object"===s&&(t[i]=e(t[i],n[i])):t[i]=n[i]}return t}),Hh),h=qh();if(l){if(void 0!==l.springCoeff)throw new Error("springCoeff was renamed to springCoefficient");if(void 0!==l.dragCoeff)throw new Error("dragCoeff was renamed to dragCoefficient")}l=c(l,{springLength:10,springCoefficient:.8,gravity:-12,theta:.8,dragCoefficient:.9,timeStep:.5,adaptiveTimeStepWeight:0,dimensions:2,debug:!1});var d=a[l.dimensions];if(!d){var p=l.dimensions;d={Body:e(p,l.debug),createQuadTree:t(p),createBounds:n(p),createDragForce:i(p),createSpringForce:r(p),integrate:s(p)},a[p]=d}var f=d.Body,m=d.createQuadTree,g=d.createBounds,_=d.createDragForce,v=d.createSpringForce,y=d.integrate,b=function(){if(Yh)return Jh.exports;function e(e){return new t("number"==typeof e?e:+new Date)}function t(e){this.seed=e}function n(e){return Math.sqrt(2*Math.PI/e)*Math.pow(1/Math.E*(e+1/(12*e-1/(10*e))),e)}function i(){var e=this.seed;return e=4294967295&(3042594569^(e=4251993797+(e=4294967295&(3550635116+(e=374761393+(e=4294967295&(3345072700^(e=e+2127912214+(e<<12)&4294967295)^e>>>19))+(e<<5)&4294967295)^e<<9))+(e<<3)&4294967295)^e>>>16),this.seed=e,(268435455&e)/268435456}return Yh=1,Jh.exports=e,Jh.exports.random=e,Jh.exports.randomIterator=function(t,n){var i=n||e();if("function"!=typeof i.next)throw new Error("customRandom does not match expected API: next() function is missing");return{forEach:function(e){var n,r,s;for(n=t.length-1;n>0;--n)r=i.next(n+1),s=t[r],t[r]=t[n],t[n]=s,e(s);t.length&&e(t[0])},shuffle:function(){var e,n,r;for(e=t.length-1;e>0;--e)n=i.next(e+1),r=t[n],t[n]=t[e],t[e]=r;return t}}},t.prototype.next=function(e){return Math.floor(this.nextDouble()*e)},t.prototype.nextDouble=i,t.prototype.uniform=i,t.prototype.gaussian=function(){var e,t,n;do{e=(t=2*this.nextDouble()-1)*t+(n=2*this.nextDouble()-1)*n}while(e>=1||0===e);return t*Math.sqrt(-2*Math.log(e)/e)},t.prototype.random=i,t.prototype.levy=function(){var e=1.5,t=Math.pow(n(2.5)*Math.sin(Math.PI*e/2)/(n(1.25)*e*Math.pow(2,.25)),1/e);return this.gaussian()*t/Math.pow(Math.abs(this.gaussian()),1/e)},Jh.exports}().random(42),x=[],T=[],S=m(l,b),M=g(x,l,b),E=v(l,b),w=_(l),A=[],R=new Map,C=0;L("nbody",function(){if(0===x.length)return;S.insertBodies(x);var e=x.length;for(;e--;){var t=x[e];t.isPinned||(t.reset(),S.updateBodyForce(t),w.update(t))}}),L("spring",function(){var e=T.length;for(;e--;)E.update(T[e])});var N={bodies:x,quadTree:S,springs:T,settings:l,addForce:L,removeForce:function(e){var t=A.indexOf(R.get(e));if(t<0)return;A.splice(t,1),R.delete(e)},getForces:function(){return R},step:function(){for(var e=0;e<A.length;++e)A[e](C);var t=y(x,l.timeStep,l.adaptiveTimeStepWeight);return C+=1,t},addBody:function(e){if(!e)throw new Error("Body is required");return x.push(e),e},addBodyAt:function(e){if(!e)throw new Error("Body position is required");var t=(e=>new f(e))(e);return x.push(t),t},removeBody:function(e){if(e){var t=x.indexOf(e);if(!(t<0))return x.splice(t,1),0===x.length&&M.reset(),!0}},addSpring:function(e,t,n,i){if(!e||!t)throw new Error("Cannot add null spring to force simulator");"number"!=typeof n&&(n=-1);var r=new u(e,t,n,i>=0?i:-1);return T.push(r),r},getTotalMovement:function(){return 0},removeSpring:function(e){if(e){var t=T.indexOf(e);return t>-1?(T.splice(t,1),!0):void 0}},getBestNewBodyPosition:function(e){return M.getBestNewPosition(e)},getBBox:P,getBoundingBox:P,invalidateBBox:function(){console.warn("invalidateBBox() is deprecated, bounds always recomputed on `getBBox()` call")},gravity:function(e){return void 0!==e?(l.gravity=e,S.options({gravity:e}),this):l.gravity},theta:function(e){return void 0!==e?(l.theta=e,S.options({theta:e}),this):l.theta},random:b};return function(e,t){for(var n in e)o(e,t,n)}(l,N),h(N),N;function P(){return M.update(),M.box}function L(e,t){if(R.has(e))throw new Error("Force "+e+" is already added");R.set(e,t),A.push(t)}};var e=function(){if(Ah)return Ch.exports;Ah=1;const e=Ph();function t(e,t){return`\n${i(e,t)}\n${n(e)}\nreturn {Body: Body, Vector: Vector};\n`}function n(t){let n=e(t),i=n("{var}",{join:", "});return`\nfunction Body(${i}) {\n this.isPinned = false;\n this.pos = new Vector(${i});\n this.force = new Vector();\n this.velocity = new Vector();\n this.mass = 1;\n\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.reset = function() {\n this.force.reset();\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.setPosition = function (${i}) {\n ${n("this.pos.{var} = {var} || 0;",{indent:2})}\n};`}function i(t,n){let i=e(t),r="";return n&&(r=`${i("\n\t var v{var};\n\tObject.defineProperty(this, '{var}', {\n\t set: function(v) { \n\t if (!Number.isFinite(v)) throw new Error('Cannot set non-numbers to {var}');\n\t v{var} = v; \n\t },\n\t get: function() { return v{var}; }\n\t});")}`),`function Vector(${i("{var}",{join:", "})}) {\n ${r}\n if (typeof arguments[0] === 'object') {\n // could be another vector\n let v = arguments[0];\n ${i('if (!Number.isFinite(v.{var})) throw new Error("Expected value is not a finite number at Vector constructor ({var})");',{indent:4})}\n ${i("this.{var} = v.{var};",{indent:4})}\n } else {\n ${i('this.{var} = typeof {var} === "number" ? {var} : 0;',{indent:4})}\n }\n }\n \n Vector.prototype.reset = function () {\n ${i("this.{var} = ",{join:""})}0;\n };`}return Ch.exports=function(e,n){let i=t(e,n),{Body:r}=new Function(i)();return r},Ch.exports.generateCreateBodyFunctionBody=t,Ch.exports.getVectorCode=i,Ch.exports.getBodyCode=n,Ch.exports}(),t=function(){if(Lh)return Dh.exports;Lh=1;const e=Ph(),t=Nh();function n(n){let l=e(n),u=Math.pow(2,n),c=`\n${o()}\n${a(n)}\n${i(n)}\n${s(n)}\n${r(n)}\n\nfunction createQuadTree(options, random) {\n options = options || {};\n options.gravity = typeof options.gravity === 'number' ? options.gravity : -1;\n options.theta = typeof options.theta === 'number' ? options.theta : 0.8;\n\n var gravity = options.gravity;\n var updateQueue = [];\n var insertStack = new InsertStack();\n var theta = options.theta;\n\n var nodesCache = [];\n var currentInCache = 0;\n var root = newNode();\n\n return {\n insertBodies: insertBodies,\n\n /**\n * Gets root node if it is present\n */\n getRoot: function() {\n return root;\n },\n\n updateBodyForce: update,\n\n options: function(newOptions) {\n if (newOptions) {\n if (typeof newOptions.gravity === 'number') {\n gravity = newOptions.gravity;\n }\n if (typeof newOptions.theta === 'number') {\n theta = newOptions.theta;\n }\n\n return this;\n }\n\n return {\n gravity: gravity,\n theta: theta\n };\n }\n };\n\n function newNode() {\n // To avoid pressure on GC we reuse nodes.\n var node = nodesCache[currentInCache];\n if (node) {\n${function(e){let t=[];for(let n=0;n<u;++n)t.push(`${e}quad${n} = null;`);return t.join("\n")}(" node.")}\n node.body = null;\n node.mass = ${l("node.mass_{var} = ",{join:""})}0;\n ${l("node.min_{var} = node.max_{var} = ",{join:""})}0;\n } else {\n node = new QuadNode();\n nodesCache[currentInCache] = node;\n }\n\n ++currentInCache;\n return node;\n }\n\n function update(sourceBody) {\n var queue = updateQueue;\n var v;\n ${l("var d{var};",{indent:4})}\n var r; \n ${l("var f{var} = 0;",{indent:4})}\n var queueLength = 1;\n var shiftIdx = 0;\n var pushIdx = 1;\n\n queue[0] = root;\n\n while (queueLength) {\n var node = queue[shiftIdx];\n var body = node.body;\n\n queueLength -= 1;\n shiftIdx += 1;\n var differentBody = (body !== sourceBody);\n if (body && differentBody) {\n // If the current node is a leaf node (and it is not source body),\n // calculate the force exerted by the current node on body, and add this\n // amount to body's net force.\n ${l("d{var} = body.pos.{var} - sourceBody.pos.{var};",{indent:8})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n // Poor man's protection against zero distance.\n ${l("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:10})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n }\n\n // This is standard gravitation force calculation but we divide\n // by r^3 to save two operations when normalizing force vector.\n v = gravity * body.mass * sourceBody.mass / (r * r * r);\n ${l("f{var} += v * d{var};",{indent:8})}\n } else if (differentBody) {\n // Otherwise, calculate the ratio s / r, where s is the width of the region\n // represented by the internal node, and r is the distance between the body\n // and the node's center-of-mass\n ${l("d{var} = node.mass_{var} / node.mass - sourceBody.pos.{var};",{indent:8})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n // Sorry about code duplication. I don't want to create many functions\n // right away. Just want to see performance first.\n ${l("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:10})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n }\n // If s / r < θ, treat this internal node as a single body, and calculate the\n // force it exerts on sourceBody, and add this amount to sourceBody's net force.\n if ((node.max_${t(0)} - node.min_${t(0)}) / r < theta) {\n // in the if statement above we consider node's width only\n // because the region was made into square during tree creation.\n // Thus there is no difference between using width or height.\n v = gravity * node.mass * sourceBody.mass / (r * r * r);\n ${l("f{var} += v * d{var};",{indent:10})}\n } else {\n // Otherwise, run the procedure recursively on each of the current node's children.\n\n // I intentionally unfolded this loop, to save several CPU cycles.\n${function(){let e=Array(11).join(" "),t=[];for(let n=0;n<u;++n)t.push(e+`if (node.quad${n}) {`),t.push(e+` queue[pushIdx] = node.quad${n};`),t.push(e+" queueLength += 1;"),t.push(e+" pushIdx += 1;"),t.push(e+"}");return t.join("\n")}()}\n }\n }\n }\n\n ${l("sourceBody.force.{var} += f{var};",{indent:4})}\n }\n\n function insertBodies(bodies) {\n ${l("var {var}min = Number.MAX_VALUE;",{indent:4})}\n ${l("var {var}max = Number.MIN_VALUE;",{indent:4})}\n var i = bodies.length;\n\n // To reduce quad tree depth we are looking for exact bounding box of all particles.\n while (i--) {\n var pos = bodies[i].pos;\n ${l("if (pos.{var} < {var}min) {var}min = pos.{var};",{indent:6})}\n ${l("if (pos.{var} > {var}max) {var}max = pos.{var};",{indent:6})}\n }\n\n // Makes the bounds square.\n var maxSideLength = -Infinity;\n ${l("if ({var}max - {var}min > maxSideLength) maxSideLength = {var}max - {var}min ;",{indent:4})}\n\n currentInCache = 0;\n root = newNode();\n ${l("root.min_{var} = {var}min;",{indent:4})}\n ${l("root.max_{var} = {var}min + maxSideLength;",{indent:4})}\n\n i = bodies.length - 1;\n if (i >= 0) {\n root.body = bodies[i];\n }\n while (i--) {\n insert(bodies[i], root);\n }\n }\n\n function insert(newBody) {\n insertStack.reset();\n insertStack.push(root, newBody);\n\n while (!insertStack.isEmpty()) {\n var stackItem = insertStack.pop();\n var node = stackItem.node;\n var body = stackItem.body;\n\n if (!node.body) {\n // This is internal node. Update the total mass of the node and center-of-mass.\n ${l("var {var} = body.pos.{var};",{indent:8})}\n node.mass += body.mass;\n ${l("node.mass_{var} += body.mass * {var};",{indent:8})}\n\n // Recursively insert the body in the appropriate quadrant.\n // But first find the appropriate quadrant.\n var quadIdx = 0; // Assume we are in the 0's quad.\n ${l("var min_{var} = node.min_{var};",{indent:8})}\n ${l("var max_{var} = (min_{var} + node.max_{var}) / 2;",{indent:8})}\n\n${function(){let e=[],i=Array(8+1).join(" ");for(let r=0;r<n;++r)e.push(i+`if (${t(r)} > max_${t(r)}) {`),e.push(i+` quadIdx = quadIdx + ${Math.pow(2,r)};`),e.push(i+` min_${t(r)} = max_${t(r)};`),e.push(i+` max_${t(r)} = node.max_${t(r)};`),e.push(i+"}");return e.join("\n")}()}\n\n var child = getChild(node, quadIdx);\n\n if (!child) {\n // The node is internal but this quadrant is not taken. Add\n // subnode to it.\n child = newNode();\n ${l("child.min_{var} = min_{var};",{indent:10})}\n ${l("child.max_{var} = max_{var};",{indent:10})}\n child.body = body;\n\n setChild(node, quadIdx, child);\n } else {\n // continue searching in this quadrant.\n insertStack.push(child, body);\n }\n } else {\n // We are trying to add to the leaf node.\n // We have to convert current leaf into internal node\n // and continue adding two nodes.\n var oldBody = node.body;\n node.body = null; // internal nodes do not cary bodies\n\n if (isSamePosition(oldBody.pos, body.pos)) {\n // Prevent infinite subdivision by bumping one node\n // anywhere in this quadrant\n var retriesCount = 3;\n do {\n var offset = random.nextDouble();\n ${l("var d{var} = (node.max_{var} - node.min_{var}) * offset;",{indent:12})}\n\n ${l("oldBody.pos.{var} = node.min_{var} + d{var};",{indent:12})}\n retriesCount -= 1;\n // Make sure we don't bump it out of the box. If we do, next iteration should fix it\n } while (retriesCount > 0 && isSamePosition(oldBody.pos, body.pos));\n\n if (retriesCount === 0 && isSamePosition(oldBody.pos, body.pos)) {\n // This is very bad, we ran out of precision.\n // if we do not return from the method we'll get into\n // infinite loop here. So we sacrifice correctness of layout, and keep the app running\n // Next layout iteration should get larger bounding box in the first step and fix this\n return;\n }\n }\n // Next iteration should subdivide node further.\n insertStack.push(node, oldBody);\n insertStack.push(node, body);\n }\n }\n }\n}\nreturn createQuadTree;\n\n`;return c}function i(t){let n=e(t);return`\n function isSamePosition(point1, point2) {\n ${n("var d{var} = Math.abs(point1.{var} - point2.{var});",{indent:2})}\n \n return ${n("d{var} < 1e-8",{join:" && "})};\n } \n`}function r(e){var t=Math.pow(2,e);return`\nfunction setChild(node, idx, child) {\n ${function(){let e=[];for(let n=0;n<t;++n){let t=0===n?" ":" else ";e.push(`${t}if (idx === ${n}) node.quad${n} = child;`)}return e.join("\n")}()}\n}`}function s(e){return`function getChild(node, idx) {\n${function(){let t=[],n=Math.pow(2,e);for(let e=0;e<n;++e)t.push(` if (idx === ${e}) return node.quad${e};`);return t.join("\n")}()}\n return null;\n}`}function a(t){let n=e(t),i=Math.pow(2,t);var r=`\nfunction QuadNode() {\n // body stored inside this node. In quad tree only leaf nodes (by construction)\n // contain bodies:\n this.body = null;\n\n // Child nodes are stored in quads. Each quad is presented by number:\n // 0 | 1\n // -----\n // 2 | 3\n${function(e){let t=[];for(let n=0;n<i;++n)t.push(`${e}quad${n} = null;`);return t.join("\n")}(" this.")}\n\n // Total mass of current node\n this.mass = 0;\n\n // Center of mass coordinates\n ${n("this.mass_{var} = 0;",{indent:2})}\n\n // bounding box coordinates\n ${n("this.min_{var} = 0;",{indent:2})}\n ${n("this.max_{var} = 0;",{indent:2})}\n}\n`;return r}function o(){return"\n/**\n * Our implementation of QuadTree is non-recursive to avoid GC hit\n * This data structure represent stack of elements\n * which we are trying to insert into quad tree.\n */\nfunction InsertStack () {\n this.stack = [];\n this.popIdx = 0;\n}\n\nInsertStack.prototype = {\n isEmpty: function() {\n return this.popIdx === 0;\n },\n push: function (node, body) {\n var item = this.stack[this.popIdx];\n if (!item) {\n // we are trying to avoid memory pressure: create new element\n // only when absolutely necessary\n this.stack[this.popIdx] = new InsertStackElement(node, body);\n } else {\n item.node = node;\n item.body = body;\n }\n ++this.popIdx;\n },\n pop: function () {\n if (this.popIdx > 0) {\n return this.stack[--this.popIdx];\n }\n },\n reset: function () {\n this.popIdx = 0;\n }\n};\n\nfunction InsertStackElement(node, body) {\n this.node = node; // QuadTree node\n this.body = body; // physical body which needs to be inserted to node\n}\n"}return Dh.exports=function(e){let t=n(e);return new Function(t)()},Dh.exports.generateQuadTreeFunctionBody=n,Dh.exports.getInsertStackCode=o,Dh.exports.getQuadNodeCode=a,Dh.exports.isSamePosition=i,Dh.exports.getChildBodyCode=s,Dh.exports.setChildBodyCode=r,Dh.exports}(),n=function(){if(Ih)return Uh.exports;Ih=1,Uh.exports=function(e){let n=t(e);return new Function("bodies","settings","random",n)},Uh.exports.generateFunctionBody=t;const e=Ph();function t(t){let n=e(t);return`\n var boundingBox = {\n ${n("min_{var}: 0, max_{var}: 0,",{indent:4})}\n };\n\n return {\n box: boundingBox,\n\n update: updateBoundingBox,\n\n reset: resetBoundingBox,\n\n getBestNewPosition: function (neighbors) {\n var ${n("base_{var} = 0",{join:", "})};\n\n if (neighbors.length) {\n for (var i = 0; i < neighbors.length; ++i) {\n let neighborPos = neighbors[i].pos;\n ${n("base_{var} += neighborPos.{var};",{indent:10})}\n }\n\n ${n("base_{var} /= neighbors.length;",{indent:8})}\n } else {\n ${n("base_{var} = (boundingBox.min_{var} + boundingBox.max_{var}) / 2;",{indent:8})}\n }\n\n var springLength = settings.springLength;\n return {\n ${n("{var}: base_{var} + (random.nextDouble() - 0.5) * springLength,",{indent:8})}\n };\n }\n };\n\n function updateBoundingBox() {\n var i = bodies.length;\n if (i === 0) return; // No bodies - no borders.\n\n ${n("var max_{var} = -Infinity;",{indent:4})}\n ${n("var min_{var} = Infinity;",{indent:4})}\n\n while(i--) {\n // this is O(n), it could be done faster with quadtree, if we check the root node bounds\n var bodyPos = bodies[i].pos;\n ${n("if (bodyPos.{var} < min_{var}) min_{var} = bodyPos.{var};",{indent:6})}\n ${n("if (bodyPos.{var} > max_{var}) max_{var} = bodyPos.{var};",{indent:6})}\n }\n\n ${n("boundingBox.min_{var} = min_{var};",{indent:4})}\n ${n("boundingBox.max_{var} = max_{var};",{indent:4})}\n }\n\n function resetBoundingBox() {\n ${n("boundingBox.min_{var} = boundingBox.max_{var} = 0;",{indent:4})}\n }\n`}return Uh.exports}(),i=function(){if(Fh)return Oh.exports;Fh=1;const e=Ph();function t(t){return`\n if (!Number.isFinite(options.dragCoefficient)) throw new Error('dragCoefficient is not a finite number');\n\n return {\n update: function(body) {\n ${e(t)("body.force.{var} -= options.dragCoefficient * body.velocity.{var};",{indent:6})}\n }\n };\n`}return Oh.exports=function(e){let n=t(e);return new Function("options",n)},Oh.exports.generateCreateDragForceFunctionBody=t,Oh.exports}(),r=function(){if(Bh)return kh.exports;Bh=1;const e=Ph();function t(t){let n=e(t);return`\n if (!Number.isFinite(options.springCoefficient)) throw new Error('Spring coefficient is not a number');\n if (!Number.isFinite(options.springLength)) throw new Error('Spring length is not a number');\n\n return {\n /**\n * Updates forces acting on a spring\n */\n update: function (spring) {\n var body1 = spring.from;\n var body2 = spring.to;\n var length = spring.length < 0 ? options.springLength : spring.length;\n ${n("var d{var} = body2.pos.{var} - body1.pos.{var};",{indent:6})}\n var r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n ${n("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:8})}\n r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n }\n\n var d = r - length;\n var coefficient = ((spring.coefficient > 0) ? spring.coefficient : options.springCoefficient) * d / r;\n\n ${n("body1.force.{var} += coefficient * d{var}",{indent:6})};\n body1.springCount += 1;\n body1.springLength += r;\n\n ${n("body2.force.{var} -= coefficient * d{var}",{indent:6})};\n body2.springCount += 1;\n body2.springLength += r;\n }\n };\n`}return kh.exports=function(e){let n=t(e);return new Function("options","random",n)},kh.exports.generateCreateSpringForceFunctionBody=t,kh.exports}(),s=function(){if(zh)return Xh.exports;zh=1;const e=Ph();function t(t){let n=e(t);return`\n var length = bodies.length;\n if (length === 0) return 0;\n\n ${n("var d{var} = 0, t{var} = 0;",{indent:2})}\n\n for (var i = 0; i < length; ++i) {\n var body = bodies[i];\n if (body.isPinned) continue;\n\n if (adaptiveTimeStepWeight && body.springCount) {\n timeStep = (adaptiveTimeStepWeight * body.springLength/body.springCount);\n }\n\n var coeff = timeStep / body.mass;\n\n ${n("body.velocity.{var} += coeff * body.force.{var};",{indent:4})}\n ${n("var v{var} = body.velocity.{var};",{indent:4})}\n var v = Math.sqrt(${n("v{var} * v{var}",{join:" + "})});\n\n if (v > 1) {\n // We normalize it so that we move within timeStep range. \n // for the case when v <= 1 - we let velocity to fade out.\n ${n("body.velocity.{var} = v{var} / v;",{indent:6})}\n }\n\n ${n("d{var} = timeStep * body.velocity.{var};",{indent:4})}\n\n ${n("body.pos.{var} += d{var};",{indent:4})}\n\n ${n("t{var} += Math.abs(d{var});",{indent:4})}\n }\n\n return (${n("t{var} * t{var}",{join:" + "})})/length;\n`}return Xh.exports=function(e){let n=t(e);return new Function("bodies","timeStep","adaptiveTimeStepWeight",n)},Xh.exports.generateIntegratorFunctionBody=t,Xh.exports}(),a={};function o(e,t,n){if(e.hasOwnProperty(n)&&"function"!=typeof t[n]){var i=Number.isFinite(e[n]);t[n]=i?function(i){if(void 0!==i){if(!Number.isFinite(i))throw new Error("Value of "+n+" should be a valid number.");return e[n]=i,t}return e[n]}:function(i){return void 0!==i?(e[n]=i,t):e[n]}}}return Kh}var td=function(){if(Qh)return Rh.exports;Qh=1,Rh.exports=function(n,i){if(!n)throw new Error("Graph structure cannot be undefined");var r=(i&&i.createSimulator||ed())(i);if(Array.isArray(i))throw new Error("Physics settings is expected to be an object");var s=n.version>19?function(e){var t=n.getLinks(e);return t?1+t.size/3:1}:function(e){var t=n.getLinks(e);return t?1+t.length/3:1};i&&"function"==typeof i.nodeMass&&(s=i.nodeMass);var a=new Map,o={},l=0,u=r.settings.springTransform||t;l=0,n.forEachNode(function(e){m(e.id),l+=1}),n.forEachLink(_),n.on("changed",f);var c=!1,h={step:function(){if(0===l)return d(!0),!0;var e=r.step();h.lastMove=e,h.fire("step");var t=e/l<=.01;return d(t),t},getNodePosition:function(e){return b(e).pos},setNodePosition:function(e){var t=b(e);t.setPosition.apply(t,Array.prototype.slice.call(arguments,1))},getLinkPosition:function(e){var t=o[e];if(t)return{from:t.from.pos,to:t.to.pos}},getGraphRect:function(){return r.getBBox()},forEachBody:p,pinNode:function(e,t){b(e.id).isPinned=!!t},isNodePinned:function(e){return b(e.id).isPinned},dispose:function(){n.off("changed",f),h.fire("disposed")},getBody:function(e){return a.get(e)},getSpring:function(e,t){var i;if(void 0===t)i="object"!=typeof e?e:e.id;else{var r=n.hasLink(e,t);if(!r)return;i=r.id}return o[i]},getForceVectorLength:function(){var e=0,t=0;return p(function(n){e+=Math.abs(n.force.x),t+=Math.abs(n.force.y)}),Math.sqrt(e*e+t*t)},simulator:r,graph:n,lastMove:0};return e(h),h;function d(e){var t;c!==e&&(c=e,t=e,h.fire("stable",t))}function p(e){a.forEach(e)}function f(e){for(var t=0;t<e.length;++t){var i=e[t];"add"===i.changeType?(i.node&&m(i.node.id),i.link&&_(i.link)):"remove"===i.changeType&&(i.node&&g(i.node),i.link&&v(i.link))}l=n.getNodesCount()}function m(e){var t=a.get(e);if(!t){var i=n.getNode(e);if(!i)throw new Error("initBody() was called with unknown node id");var s=i.position;if(!s){var o=function(e){var t=[];if(!e.links)return t;for(var n=Math.min(e.links.length,2),i=0;i<n;++i){var r=e.links[i],s=r.fromId!==e.id?a.get(r.fromId):a.get(r.toId);s&&s.pos&&t.push(s)}return t}(i);s=r.getBestNewBodyPosition(o)}(t=r.addBodyAt(s)).id=e,a.set(e,t),y(e),function(e){return e&&(e.isPinned||e.data&&e.data.isPinned)}(i)&&(t.isPinned=!0)}}function g(e){var t=e.id,n=a.get(t);n&&(a.delete(t),r.removeBody(n))}function _(e){y(e.fromId),y(e.toId);var t=a.get(e.fromId),n=a.get(e.toId),i=r.addSpring(t,n,e.length);u(e,i),o[e.id]=i}function v(e){var t=o[e.id];if(t){var i=n.getNode(e.fromId),s=n.getNode(e.toId);i&&y(i.id),s&&y(s.id),delete o[e.id],r.removeSpring(t)}}function y(e){var t=a.get(e);if(t.mass=s(e),Number.isNaN(t.mass))throw new Error("Node mass should be a number")}function b(e){var t=a.get(e);return t||(m(e),t=a.get(e)),t}},Rh.exports.simulator=ed();var e=qh();function t(){}return Rh.exports}(),nd=Th(td);function id(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var rd="object"==typeof global&&global&&global.Object===Object&&global,sd="object"==typeof self&&self&&self.Object===Object&&self,ad=rd||sd||Function("return this")(),od=function(){return ad.Date.now()},ld=/\s/;var ud=/^\s+/;function cd(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&ld.test(e.charAt(t)););return t}(e)+1).replace(ud,""):e}var hd=ad.Symbol,dd=Object.prototype,pd=dd.hasOwnProperty,fd=dd.toString,md=hd?hd.toStringTag:void 0;var gd=Object.prototype.toString;var _d=hd?hd.toStringTag:void 0;function vd(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":_d&&_d in Object(e)?function(e){var t=pd.call(e,md),n=e[md];try{e[md]=void 0;var i=!0}catch(e){}var r=fd.call(e);return i&&(t?e[md]=n:delete e[md]),r}(e):function(e){return gd.call(e)}(e)}var yd=/^[-+]0x[0-9a-f]+$/i,bd=/^0b[01]+$/i,xd=/^0o[0-7]+$/i,Td=parseInt;function Sd(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return null!=e&&"object"==typeof e}(e)&&"[object Symbol]"==vd(e)}(e))return NaN;if(id(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=id(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=cd(e);var n=bd.test(e);return n||xd.test(e)?Td(e.slice(2),n?2:8):yd.test(e)?NaN:+e}var Md=Math.max,Ed=Math.min;function wd(e,t,n){var i,r,s,a,o,l,u=0,c=!1,h=!1,d=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function p(t){var n=i,s=r;return i=r=void 0,u=t,a=e.apply(s,n)}function f(e){var n=e-l;return void 0===l||n>=t||n<0||h&&e-u>=s}function m(){var e=od();if(f(e))return g(e);o=setTimeout(m,function(e){var n=t-(e-l);return h?Ed(n,s-(e-u)):n}(e))}function g(e){return o=void 0,d&&i?p(e):(i=r=void 0,a)}function _(){var e=od(),n=f(e);if(i=arguments,r=this,l=e,n){if(void 0===o)return function(e){return u=e,o=setTimeout(m,t),c?p(e):a}(l);if(h)return clearTimeout(o),o=setTimeout(m,t),p(l)}return void 0===o&&(o=setTimeout(m,t)),a}return t=Sd(t)||0,id(n)&&(c=!!n.leading,s=(h="maxWait"in n)?Md(Sd(n.maxWait)||0,t):s,d="trailing"in n?!!n.trailing:d),_.cancel=function(){void 0!==o&&clearTimeout(o),u=0,i=l=r=o=void 0},_.flush=function(){return void 0===o?a:g(od())},_}function Ad(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function Rd(e,t,n){return Object.defineProperty(e,"prototype",{writable:!1}),e}function Cd(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(i=s.call(n)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,r=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ad(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ad(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var Nd=Rd(function e(t,n){var i=n.default,r=void 0===i?null:i,s=n.triggerUpdate,a=void 0===s||s,o=n.onChange,l=void 0===o?function(e,t){}:o;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name=t,this.defaultVal=r,this.triggerUpdate=a,this.onChange=l});function Pd(e){var t=e.stateInit,n=void 0===t?function(){return{}}:t,i=e.props,r=void 0===i?{}:i,s=e.methods,a=void 0===s?{}:s,o=e.aliases,l=void 0===o?{}:o,u=e.init,c=void 0===u?function(){}:u,h=e.update,d=void 0===h?function(){}:h,p=Object.keys(r).map(function(e){return new Nd(e,r[e])});return function e(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];var s=!!(this instanceof e?this.constructor:void 0),o=s?i.shift():void 0,u=i[0],h=void 0===u?{}:u,f=Object.assign({},n instanceof Function?n(h):n,{initialised:!1}),m={};function g(e){return _(e,h),v(),g}var _=function(e,t){c.call(g,e,f,t),f.initialised=!0},v=wd(function(){f.initialised&&(d.call(g,f,m),m={})},1);return p.forEach(function(e){g[e.name]=function(e){var t=e.name,n=e.triggerUpdate,i=void 0!==n&&n,r=e.onChange,s=void 0===r?function(e,t){}:r,a=e.defaultVal,o=void 0===a?null:a;return function(e){var n=f[t];if(!arguments.length)return n;var r=void 0===e?o:e;return f[t]=r,s.call(g,r,f,n),!m.hasOwnProperty(t)&&(m[t]=n),i&&v(),g}}(e)}),Object.keys(a).forEach(function(e){g[e]=function(){for(var t,n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];return(t=a[e]).call.apply(t,[g,f].concat(i))}}),Object.entries(l).forEach(function(e){var t=Cd(e,2),n=t[0],i=t[1];return g[n]=g[i]}),g.resetProps=function(){return p.forEach(function(e){g[e.name](e.defaultVal)}),g},g.resetProps(),f._rerender=v,s&&o&&g(o),g}}var Ld=function(e){return"function"==typeof e?e:"string"==typeof e?function(t){return t[e]}:function(t){return e}};class Dd extends Map{constructor(e,t=Ud){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:t}}),null!=e)for(const[t,n]of e)this.set(t,n)}get(e){return super.get(Id(this,e))}has(e){return super.has(Id(this,e))}set(e,t){return super.set(function({_intern:e,_key:t},n){const i=t(n);return e.has(i)?e.get(i):(e.set(i,n),n)}(this,e),t)}delete(e){return super.delete(function({_intern:e,_key:t},n){const i=t(n);e.has(i)&&(n=e.get(i),e.delete(i));return n}(this,e))}}function Id({_intern:e,_key:t},n){const i=t(n);return e.has(i)?e.get(i):n}function Ud(e){return null!==e&&"object"==typeof e?e.valueOf():e}function Fd(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n<t||void 0===n&&t>=t)&&(n=t);else{let i=-1;for(let r of e)null!=(r=t(r,++i,e))&&(n<r||void 0===n&&r>=r)&&(n=r)}return n}function Od(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n>t||void 0===n&&t>=t)&&(n=t);else{let i=-1;for(let r of e)null!=(r=t(r,++i,e))&&(n>r||void 0===n&&r>=r)&&(n=r)}return n}function Bd(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function kd(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}function zd(e,t){return e.get(kd(e,t))}function Vd(e,t,n){(function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")})(e,t),t.set(e,n)}function Gd(e,t,n){return e.set(kd(e,t),n),n}function Hd(e,t,n){return t&&function(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,$d(i.key),i)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function jd(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(i=s.call(n)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,r=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return o}}(e,t)||Xd(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Wd(e){return function(e){if(Array.isArray(e))return Bd(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||Xd(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function $d(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function Xd(e,t){if(e){if("string"==typeof e)return Bd(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Bd(e,t):void 0}}var qd=new WeakMap,Yd=new WeakMap,Kd=new WeakMap,Zd=new WeakMap,Qd=new WeakMap,Jd=new WeakMap,ep=function(){return Hd(function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Vd(this,qd,new Map),Vd(this,Yd,new Map),Vd(this,Kd,function(e){return e}),Vd(this,Zd,function(){return{}}),Vd(this,Qd,function(){}),Vd(this,Jd,function(){})},[{key:"getObj",value:function(e){return zd(qd,this).get(zd(Kd,this).call(this,e))}},{key:"getData",value:function(e){return zd(Yd,this).get(e)}},{key:"entries",value:function(){return Wd(zd(Yd,this).entries()).map(function(e){var t=jd(e,2),n=t[0];return[t[1],n]})}},{key:"id",value:function(e){return Gd(Kd,this,Ld(e)),this}},{key:"onCreateObj",value:function(e){return Gd(Zd,this,e),this}},{key:"onUpdateObj",value:function(e){return Gd(Qd,this,e),this}},{key:"onRemoveObj",value:function(e){return Gd(Jd,this,e),this}},{key:"digest",value:function(e){var t=this;e.filter(function(e){return!zd(qd,t).has(zd(Kd,t).call(t,e))}).forEach(function(e){var n=zd(Zd,t).call(t,e);zd(qd,t).set(zd(Kd,t).call(t,e),n),zd(Yd,t).set(n,e)});var n=new Map(e.map(function(e){return[zd(Kd,t).call(t,e),e]}));return zd(qd,this).forEach(function(e,i){n.has(i)?zd(Qd,t).call(t,e,n.get(i)):(zd(Jd,t).call(t,e,i),zd(qd,t).delete(i),zd(Yd,t).delete(e))}),this}},{key:"clear",value:function(){return this.digest([]),this}}])}();function tp(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e)}return this}const np=Symbol("implicit");var ip=function(e){for(var t=e.length/6|0,n=new Array(t),i=0;i<t;)n[i]="#"+e.slice(6*i,6*++i);return n}("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");function rp(e){return rp="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},rp(e)}var sp=/^\s+/,ap=/\s+$/;function op(e,t){if(t=t||{},(e=e||"")instanceof op)return e;if(!(this instanceof op))return new op(e,t);var n=function(e){var t={r:0,g:0,b:0},n=1,i=null,r=null,s=null,a=!1,o=!1;"string"==typeof e&&(e=function(e){e=e.replace(sp,"").replace(ap,"").toLowerCase();var t,n=!1;if(Mp[e])e=Mp[e],n=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(t=Op.rgb.exec(e))return{r:t[1],g:t[2],b:t[3]};if(t=Op.rgba.exec(e))return{r:t[1],g:t[2],b:t[3],a:t[4]};if(t=Op.hsl.exec(e))return{h:t[1],s:t[2],l:t[3]};if(t=Op.hsla.exec(e))return{h:t[1],s:t[2],l:t[3],a:t[4]};if(t=Op.hsv.exec(e))return{h:t[1],s:t[2],v:t[3]};if(t=Op.hsva.exec(e))return{h:t[1],s:t[2],v:t[3],a:t[4]};if(t=Op.hex8.exec(e))return{r:Cp(t[1]),g:Cp(t[2]),b:Cp(t[3]),a:Dp(t[4]),format:n?"name":"hex8"};if(t=Op.hex6.exec(e))return{r:Cp(t[1]),g:Cp(t[2]),b:Cp(t[3]),format:n?"name":"hex"};if(t=Op.hex4.exec(e))return{r:Cp(t[1]+""+t[1]),g:Cp(t[2]+""+t[2]),b:Cp(t[3]+""+t[3]),a:Dp(t[4]+""+t[4]),format:n?"name":"hex8"};if(t=Op.hex3.exec(e))return{r:Cp(t[1]+""+t[1]),g:Cp(t[2]+""+t[2]),b:Cp(t[3]+""+t[3]),format:n?"name":"hex"};return!1}(e));"object"==rp(e)&&(Bp(e.r)&&Bp(e.g)&&Bp(e.b)?(t=function(e,t,n){return{r:255*Ap(e,255),g:255*Ap(t,255),b:255*Ap(n,255)}}(e.r,e.g,e.b),a=!0,o="%"===String(e.r).substr(-1)?"prgb":"rgb"):Bp(e.h)&&Bp(e.s)&&Bp(e.v)?(i=Pp(e.s),r=Pp(e.v),t=function(e,t,n){e=6*Ap(e,360),t=Ap(t,100),n=Ap(n,100);var i=Math.floor(e),r=e-i,s=n*(1-t),a=n*(1-r*t),o=n*(1-(1-r)*t),l=i%6,u=[n,a,s,s,o,n][l],c=[o,n,n,a,s,s][l],h=[s,s,o,n,n,a][l];return{r:255*u,g:255*c,b:255*h}}(e.h,i,r),a=!0,o="hsv"):Bp(e.h)&&Bp(e.s)&&Bp(e.l)&&(i=Pp(e.s),s=Pp(e.l),t=function(e,t,n){var i,r,s;function a(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=Ap(e,360),t=Ap(t,100),n=Ap(n,100),0===t)i=r=s=n;else{var o=n<.5?n*(1+t):n+t-n*t,l=2*n-o;i=a(l,o,e+1/3),r=a(l,o,e),s=a(l,o,e-1/3)}return{r:255*i,g:255*r,b:255*s}}(e.h,i,s),a=!0,o="hsl"),e.hasOwnProperty("a")&&(n=e.a));return n=wp(n),{ok:a,format:e.format||o,r:Math.min(255,Math.max(t.r,0)),g:Math.min(255,Math.max(t.g,0)),b:Math.min(255,Math.max(t.b,0)),a:n}}(e);this._originalInput=e,this._r=n.r,this._g=n.g,this._b=n.b,this._a=n.a,this._roundA=Math.round(100*this._a)/100,this._format=t.format||n.format,this._gradientType=t.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=n.ok}function lp(e,t,n){e=Ap(e,255),t=Ap(t,255),n=Ap(n,255);var i,r,s=Math.max(e,t,n),a=Math.min(e,t,n),o=(s+a)/2;if(s==a)i=r=0;else{var l=s-a;switch(r=o>.5?l/(2-s-a):l/(s+a),s){case e:i=(t-n)/l+(t<n?6:0);break;case t:i=(n-e)/l+2;break;case n:i=(e-t)/l+4}i/=6}return{h:i,s:r,l:o}}function up(e,t,n){e=Ap(e,255),t=Ap(t,255),n=Ap(n,255);var i,r,s=Math.max(e,t,n),a=Math.min(e,t,n),o=s,l=s-a;if(r=0===s?0:l/s,s==a)i=0;else{switch(s){case e:i=(t-n)/l+(t<n?6:0);break;case t:i=(n-e)/l+2;break;case n:i=(e-t)/l+4}i/=6}return{h:i,s:r,v:o}}function cp(e,t,n,i){var r=[Np(Math.round(e).toString(16)),Np(Math.round(t).toString(16)),Np(Math.round(n).toString(16))];return i&&r[0].charAt(0)==r[0].charAt(1)&&r[1].charAt(0)==r[1].charAt(1)&&r[2].charAt(0)==r[2].charAt(1)?r[0].charAt(0)+r[1].charAt(0)+r[2].charAt(0):r.join("")}function hp(e,t,n,i){return[Np(Lp(i)),Np(Math.round(e).toString(16)),Np(Math.round(t).toString(16)),Np(Math.round(n).toString(16))].join("")}function dp(e,t){t=0===t?0:t||10;var n=op(e).toHsl();return n.s-=t/100,n.s=Rp(n.s),op(n)}function pp(e,t){t=0===t?0:t||10;var n=op(e).toHsl();return n.s+=t/100,n.s=Rp(n.s),op(n)}function fp(e){return op(e).desaturate(100)}function mp(e,t){t=0===t?0:t||10;var n=op(e).toHsl();return n.l+=t/100,n.l=Rp(n.l),op(n)}function gp(e,t){t=0===t?0:t||10;var n=op(e).toRgb();return n.r=Math.max(0,Math.min(255,n.r-Math.round(-t/100*255))),n.g=Math.max(0,Math.min(255,n.g-Math.round(-t/100*255))),n.b=Math.max(0,Math.min(255,n.b-Math.round(-t/100*255))),op(n)}function _p(e,t){t=0===t?0:t||10;var n=op(e).toHsl();return n.l-=t/100,n.l=Rp(n.l),op(n)}function vp(e,t){var n=op(e).toHsl(),i=(n.h+t)%360;return n.h=i<0?360+i:i,op(n)}function yp(e){var t=op(e).toHsl();return t.h=(t.h+180)%360,op(t)}function bp(e,t){if(isNaN(t)||t<=0)throw new Error("Argument to polyad must be a positive number");for(var n=op(e).toHsl(),i=[op(e)],r=360/t,s=1;s<t;s++)i.push(op({h:(n.h+s*r)%360,s:n.s,l:n.l}));return i}function xp(e){var t=op(e).toHsl(),n=t.h;return[op(e),op({h:(n+72)%360,s:t.s,l:t.l}),op({h:(n+216)%360,s:t.s,l:t.l})]}function Tp(e,t,n){t=t||6,n=n||30;var i=op(e).toHsl(),r=360/n,s=[op(e)];for(i.h=(i.h-(r*t>>1)+720)%360;--t;)i.h=(i.h+r)%360,s.push(op(i));return s}function Sp(e,t){t=t||6;for(var n=op(e).toHsv(),i=n.h,r=n.s,s=n.v,a=[],o=1/t;t--;)a.push(op({h:i,s:r,v:s})),s=(s+o)%1;return a}op.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var e,t,n,i=this.toRgb();return e=i.r/255,t=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))+.7152*(t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))},setAlpha:function(e){return this._a=wp(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=up(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=up(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),i=Math.round(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+i+"%)":"hsva("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHsl:function(){var e=lp(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=lp(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),i=Math.round(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+i+"%)":"hsla("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHex:function(e){return cp(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,i,r){var s=[Np(Math.round(e).toString(16)),Np(Math.round(t).toString(16)),Np(Math.round(n).toString(16)),Np(Lp(i))];if(r&&s[0].charAt(0)==s[0].charAt(1)&&s[1].charAt(0)==s[1].charAt(1)&&s[2].charAt(0)==s[2].charAt(1)&&s[3].charAt(0)==s[3].charAt(1))return s[0].charAt(0)+s[1].charAt(0)+s[2].charAt(0)+s[3].charAt(0);return s.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(100*Ap(this._r,255))+"%",g:Math.round(100*Ap(this._g,255))+"%",b:Math.round(100*Ap(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*Ap(this._r,255))+"%, "+Math.round(100*Ap(this._g,255))+"%, "+Math.round(100*Ap(this._b,255))+"%)":"rgba("+Math.round(100*Ap(this._r,255))+"%, "+Math.round(100*Ap(this._g,255))+"%, "+Math.round(100*Ap(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(Ep[cp(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+hp(this._r,this._g,this._b,this._a),n=t,i=this._gradientType?"GradientType = 1, ":"";if(e){var r=op(e);n="#"+hp(r._r,r._g,r._b,r._a)}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,i=this._a<1&&this._a>=0;return t||!i||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return op(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(mp,arguments)},brighten:function(){return this._applyModification(gp,arguments)},darken:function(){return this._applyModification(_p,arguments)},desaturate:function(){return this._applyModification(dp,arguments)},saturate:function(){return this._applyModification(pp,arguments)},greyscale:function(){return this._applyModification(fp,arguments)},spin:function(){return this._applyModification(vp,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(Tp,arguments)},complement:function(){return this._applyCombination(yp,arguments)},monochromatic:function(){return this._applyCombination(Sp,arguments)},splitcomplement:function(){return this._applyCombination(xp,arguments)},triad:function(){return this._applyCombination(bp,[3])},tetrad:function(){return this._applyCombination(bp,[4])}},op.fromRatio=function(e,t){if("object"==rp(e)){var n={};for(var i in e)e.hasOwnProperty(i)&&(n[i]="a"===i?e[i]:Pp(e[i]));e=n}return op(e,t)},op.equals=function(e,t){return!(!e||!t)&&op(e).toRgbString()==op(t).toRgbString()},op.random=function(){return op.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},op.mix=function(e,t,n){n=0===n?0:n||50;var i=op(e).toRgb(),r=op(t).toRgb(),s=n/100;return op({r:(r.r-i.r)*s+i.r,g:(r.g-i.g)*s+i.g,b:(r.b-i.b)*s+i.b,a:(r.a-i.a)*s+i.a})},
|
|
3
|
+
// <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)
|
|
4
|
+
// Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
|
|
5
|
+
op.readability=function(e,t){var n=op(e),i=op(t);return(Math.max(n.getLuminance(),i.getLuminance())+.05)/(Math.min(n.getLuminance(),i.getLuminance())+.05)},op.isReadable=function(e,t,n){var i,r,s=op.readability(e,t);switch(r=!1,(i=function(e){var t,n;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),n=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==n&&"large"!==n&&(n="small");return{level:t,size:n}}(n)).level+i.size){case"AAsmall":case"AAAlarge":r=s>=4.5;break;case"AAlarge":r=s>=3;break;case"AAAsmall":r=s>=7}return r},op.mostReadable=function(e,t,n){var i,r,s,a,o=null,l=0;r=(n=n||{}).includeFallbackColors,s=n.level,a=n.size;for(var u=0;u<t.length;u++)(i=op.readability(e,t[u]))>l&&(l=i,o=op(t[u]));return op.isReadable(e,o,{level:s,size:a})||!r?o:(n.includeFallbackColors=!1,op.mostReadable(e,["#fff","#000"],n))};var Mp=op.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Ep=op.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(Mp);function wp(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function Ap(e,t){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(e)&&(e="100%");var n=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(e);return e=Math.min(t,Math.max(0,parseFloat(e))),n&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function Rp(e){return Math.min(1,Math.max(0,e))}function Cp(e){return parseInt(e,16)}function Np(e){return 1==e.length?"0"+e:""+e}function Pp(e){return e<=1&&(e=100*e+"%"),e}function Lp(e){return Math.round(255*parseFloat(e)).toString(16)}function Dp(e){return Cp(e)/255}var Ip,Up,Fp,Op=(Up="[\\s|\\(]+("+(Ip="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+Ip+")[,|\\s]+("+Ip+")\\s*\\)?",Fp="[\\s|\\(]+("+Ip+")[,|\\s]+("+Ip+")[,|\\s]+("+Ip+")[,|\\s]+("+Ip+")\\s*\\)?",{CSS_UNIT:new RegExp(Ip),rgb:new RegExp("rgb"+Up),rgba:new RegExp("rgba"+Fp),hsl:new RegExp("hsl"+Up),hsla:new RegExp("hsla"+Fp),hsv:new RegExp("hsv"+Up),hsva:new RegExp("hsva"+Fp),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function Bp(e){return!!Op.CSS_UNIT.exec(e)}function kp(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function zp(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}function Vp(e,t,n){return t=Kp(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Qp()?Reflect.construct(t,n||[],Kp(e).constructor):t.apply(e,n))}function Gp(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Hp(e,t){return e.get(zp(e,t))}function jp(e,t,n){(function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")})(e,t),t.set(e,n)}function Wp(e,t,n){return e.set(zp(e,t),n),n}function $p(e,t,n){if(Qp())return Reflect.construct.apply(null,arguments);var i=[null];return i.push.apply(i,t),new(e.bind.apply(e,i))}function Xp(e,t,n){return t&&function(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,sf(i.key),i)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function qp(e,t,n){return(t=sf(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yp(){return Yp="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,n){var i=function(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=Kp(e)););return e}(e,t);if(i){var r=Object.getOwnPropertyDescriptor(i,t);return r.get?r.get.call(arguments.length<3?e:n):r.value}},Yp.apply(null,arguments)}function Kp(e){return Kp=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Kp(e)}function Zp(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ef(e,t)}function Qp(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Qp=function(){return!!e})()}function Jp(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,i)}return n}function ef(e,t){return ef=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},ef(e,t)}function tf(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(i=s.call(n)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,r=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return o}}(e,t)||of(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function nf(e,t,n,i){var r=Yp(Kp(e.prototype),t,n);return"function"==typeof r?function(e){return r.apply(n,e)}:r}function rf(e){return function(e){if(Array.isArray(e))return kp(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||of(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function sf(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function af(e){return af="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},af(e)}function of(e,t){if(e){if("string"==typeof e)return kp(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?kp(e,t):void 0}}var lf=function(e){e instanceof Array?e.forEach(lf):(e.map&&e.map.dispose(),e.dispose())},uf=function(e){e.geometry&&e.geometry.dispose(),e.material&&lf(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(uf)},cf=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),uf(t)}},hf=new WeakMap,df=new WeakMap,pf=function(e){function t(e){var n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=i.dataBindAttr,s=void 0===r?"__data":r,a=i.objBindAttr,o=void 0===a?"__threeObj":a;return Gp(this,t),qp(n=Vp(this,t),"scene",void 0),jp(n,hf,void 0),jp(n,df,void 0),n.scene=e,Wp(hf,n,s),Wp(df,n,o),n.onRemoveObj(function(){}),n}return Zp(t,e),Xp(t,[{key:"onCreateObj",value:function(e){var n=this;return nf(t,"onCreateObj",this)([function(t){var i=e(t);return t[Hp(df,n)]=i,i[Hp(hf,n)]=t,n.scene.add(i),i}]),this}},{key:"onRemoveObj",value:function(e){var n=this;return nf(t,"onRemoveObj",this)([function(i,r){var s=nf(t,"getData",n)([i]);e(i,r),n.scene.remove(i),uf(i),delete s[Hp(df,n)]}]),this}}])}(ep),ff=function(e){return isNaN(e)?parseInt(op(e).toHex(),16):e},mf=function(e){return isNaN(e)?op(e).getAlpha():1},gf=function e(){var t=new Dd,n=[],i=[],r=np;function s(e){let s=t.get(e);if(void 0===s){if(r!==np)return r;t.set(e,s=n.push(e)-1)}return i[s%i.length]}return s.domain=function(e){if(!arguments.length)return n.slice();n=[],t=new Dd;for(const i of e)t.has(i)||t.set(i,n.push(i)-1);return s},s.range=function(e){return arguments.length?(i=Array.from(e),s):i.slice()},s.unknown=function(e){return arguments.length?(r=e,s):r},s.copy=function(){return e(n,i).unknown(r)},tp.apply(s,arguments),s}(ip);function _f(e,t,n){t&&"string"==typeof n&&e.filter(function(e){return!e[n]}).forEach(function(e){e[n]=gf(t(e))})}var vf=window.THREE?window.THREE:{Group:ci,Mesh:Wr,MeshLambertMaterial:Qs,Color:_i,BufferGeometry:vr,BufferAttribute:nr,Matrix4:Fn,Vector3:dn,SphereGeometry:Bs,CylinderGeometry:Ts,TubeGeometry:ks,ConeGeometry:Ss,Line:class extends ui{constructor(e=new vr,t=new as){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,n=[0];for(let e=1,i=t.count;e<i;e++)os.fromBufferAttribute(t,e-1),ls.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=os.distanceTo(ls);e.setAttribute("lineDistance",new ar(n,1))}else Xt("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const n=this.geometry,i=this.matrixWorld,r=e.params.Line.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),hs.copy(n.boundingSphere),hs.applyMatrix4(i),hs.radius+=r,!1===e.ray.intersectsSphere(hs))return;us.copy(i).invert(),cs.copy(e.ray).applyMatrix4(us);const a=r/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=this.isLineSegments?2:1,u=n.index,c=n.attributes.position;if(null!==u){const n=Math.max(0,s.start),i=Math.min(u.count,s.start+s.count);for(let r=n,s=i-1;r<s;r+=l){const n=u.getX(r),i=u.getX(r+1),s=fs(this,e,cs,o,n,i,r);s&&t.push(s)}if(this.isLineLoop){const r=u.getX(i-1),s=u.getX(n),a=fs(this,e,cs,o,r,s,i-1);a&&t.push(a)}}else{const n=Math.max(0,s.start),i=Math.min(c.count,s.start+s.count);for(let r=n,s=i-1;r<s;r+=l){const n=fs(this,e,cs,o,r,r+1,r);n&&t.push(n)}if(this.isLineLoop){const r=fs(this,e,cs,o,i-1,n,i-1);r&&t.push(r)}}}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){const t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}},LineBasicMaterial:as,QuadraticBezierCurve3:Us,CubicBezierCurve3:Is,Box3:Ii},yf={graph:function(e){if("uniqueLinkId"in(e=e||{})&&(console.warn("ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\nUse `multigraph` option instead\n","\n","Note: there is also change in default behavior: From now on each graph\nis considered to be not a multigraph by default (each edge is unique)."),e.multigraph=e.uniqueLinkId),void 0===e.multigraph&&(e.multigraph=!1),"function"!=typeof Map)throw new Error("ngraph.graph requires `Map` to be defined. Please polyfill it before using ngraph");var t,n=new Map,i=new Map,r={},s=0,a=e.multigraph?function(e,t,n){var i=xh(e,t),s=r.hasOwnProperty(i);if(s||x(e,t)){s||(r[i]=0);var a="@"+ ++r[i];i=xh(e+a,t+a)}return new bh(e,t,n,i)}:function(e,t,n){var r=xh(e,t),s=i.get(r);if(s)return s.data=n,s;return new bh(e,t,n,r)},o=[],l=T,u=T,c=T,h=T,d={version:20,addNode:m,addLink:function(e,t,n){c();var r=g(e)||m(e),s=g(t)||m(t),o=a(e,t,n),u=i.has(o.id);i.set(o.id,o),yh(r,o),e!==t&&yh(s,o);return l(o,u?"update":"add"),h(),o},removeLink:function(e,t){void 0!==t&&(e=x(e,t));return b(e)},removeNode:_,getNode:g,getNodeCount:v,getLinkCount:y,getEdgeCount:y,getLinksCount:y,getNodesCount:v,getLinks:function(e){var t=g(e);return t?t.links:null},forEachNode:E,forEachLinkedNode:function(e,t,i){var r=g(e);if(r&&r.links&&"function"==typeof t)return i?function(e,t,i){var r=e.values(),s=r.next();for(;!s.done;){var a=s.value;if(a.fromId===t&&i(n.get(a.toId),a))return!0;s=r.next()}}(r.links,e,t):function(e,t,i){var r=e.values(),s=r.next();for(;!s.done;){var a=s.value,o=a.fromId===t?a.toId:a.fromId;if(i(n.get(o),a))return!0;s=r.next()}}(r.links,e,t)},forEachLink:function(e){if("function"==typeof e)for(var t=i.values(),n=t.next();!n.done;){if(e(n.value))return!0;n=t.next()}},beginUpdate:c,endUpdate:h,clear:function(){c(),E(function(e){_(e.id)}),h()},hasLink:x,hasNode:g,getLink:x,getLinkById:function(e){return void 0===e?void 0:i.get(e)}};return _h(d),t=d.on,d.on=function(){return d.beginUpdate=c=S,d.endUpdate=h=M,l=p,u=f,d.on=t,t.apply(d,arguments)},d;function p(e,t){o.push({link:e,changeType:t})}function f(e,t){o.push({node:e,changeType:t})}function m(e,t){if(void 0===e)throw new Error("Invalid node identifier");c();var i=g(e);return i?(i.data=t,u(i,"update")):(i=new vh(e,t),u(i,"add")),n.set(e,i),h(),i}function g(e){return n.get(e)}function _(e){var t=g(e);if(!t)return!1;c();var i=t.links;return i&&(i.forEach(b),t.links=null),n.delete(e),u(t,"remove"),h(),!0}function v(){return n.size}function y(){return i.size}function b(e){if(!e)return!1;if(!i.get(e.id))return!1;c(),i.delete(e.id);var t=g(e.fromId),n=g(e.toId);return t&&t.links.delete(e),n&&n.links.delete(e),l(e,"remove"),h(),!0}function x(e,t){if(void 0!==e&&void 0!==t)return i.get(xh(e,t))}function T(){}function S(){s+=1}function M(){0===(s-=1)&&o.length>0&&(d.fire("changed",o),o.length=0)}function E(e){if("function"!=typeof e)throw new Error("Function is expected to iterate over graph nodes. You passed "+e);for(var t=n.values(),i=t.next();!i.done;){if(e(i.value))return!0;i=t.next()}}},forcelayout:nd},bf=(new vf.BufferGeometry).setAttribute?"setAttribute":"addAttribute",xf=(new vf.BufferGeometry).applyMatrix4?"applyMatrix4":"applyMatrix",Tf=Pd({props:{jsonUrl:{onChange:function(e,t){var n=this;e&&!t.fetchingJson&&(t.fetchingJson=!0,t.onLoading(),fetch(e).then(function(e){return e.json()}).then(function(e){t.fetchingJson=!1,t.onFinishLoading(e),n.graphData(e)}))},triggerUpdate:!1},graphData:{default:{nodes:[],links:[]},onChange:function(e,t){t.engineRunning=!1}},numDimensions:{default:3,onChange:function(e,t){var n=t.d3ForceLayout.force("charge");function i(e,t){e.forEach(function(e){delete e[t],delete e["v".concat(t)]})}n&&n.strength(e>2?-60:-30),e<3&&i(t.graphData.nodes,"z"),e<2&&i(t.graphData.nodes,"y")}},dagMode:{onChange:function(e,t){!e&&"d3"===t.forceEngine&&(t.graphData.nodes||[]).forEach(function(e){return e.fx=e.fy=e.fz=void 0})}},dagLevelDistance:{},dagNodeFilter:{default:function(e){return!0}},onDagError:{triggerUpdate:!1},nodeRelSize:{default:4},nodeId:{default:"id"},nodeVal:{default:"val"},nodeResolution:{default:8},nodeColor:{default:"color"},nodeAutoColorBy:{},nodeOpacity:{default:.75},nodeVisibility:{default:!0},nodeThreeObject:{},nodeThreeObjectExtend:{default:!1},nodePositionUpdate:{triggerUpdate:!1},linkSource:{default:"source"},linkTarget:{default:"target"},linkVisibility:{default:!0},linkColor:{default:"color"},linkAutoColorBy:{},linkOpacity:{default:.2},linkWidth:{},linkResolution:{default:6},linkCurvature:{default:0,triggerUpdate:!1},linkCurveRotation:{default:0,triggerUpdate:!1},linkMaterial:{},linkThreeObject:{},linkThreeObjectExtend:{default:!1},linkPositionUpdate:{triggerUpdate:!1},linkDirectionalArrowLength:{default:0},linkDirectionalArrowColor:{},linkDirectionalArrowRelPos:{default:.5,triggerUpdate:!1},linkDirectionalArrowResolution:{default:8},linkDirectionalParticles:{default:0},linkDirectionalParticleSpeed:{default:.01,triggerUpdate:!1},linkDirectionalParticleOffset:{default:0,triggerUpdate:!1},linkDirectionalParticleWidth:{default:.5},linkDirectionalParticleColor:{},linkDirectionalParticleResolution:{default:4},linkDirectionalParticleThreeObject:{},forceEngine:{default:"d3"},d3AlphaMin:{default:0},d3AlphaDecay:{default:.0228,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaDecay(e)}},d3AlphaTarget:{default:0,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaTarget(e)}},d3VelocityDecay:{default:.4,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.velocityDecay(e)}},ngraphPhysics:{default:{timeStep:20,gravity:-1.2,theta:.8,springLength:30,springCoefficient:8e-4,dragCoefficient:.02}},warmupTicks:{default:0,triggerUpdate:!1},cooldownTicks:{default:1/0,triggerUpdate:!1},cooldownTime:{default:15e3,triggerUpdate:!1},onLoading:{default:function(){},triggerUpdate:!1},onFinishLoading:{default:function(){},triggerUpdate:!1},onUpdate:{default:function(){},triggerUpdate:!1},onFinishUpdate:{default:function(){},triggerUpdate:!1},onEngineTick:{default:function(){},triggerUpdate:!1},onEngineStop:{default:function(){},triggerUpdate:!1}},methods:{refresh:function(e){return e._flushObjects=!0,e._rerender(),this},d3Force:function(e,t,n){return void 0===n?e.d3ForceLayout.force(t):(e.d3ForceLayout.force(t,n),this)},d3ReheatSimulation:function(e){return e.d3ForceLayout.alpha(1),this.resetCountdown(),this},resetCountdown:function(e){return e.cntTicks=0,e.startTickTime=new Date,e.engineRunning=!0,this},tickFrame:function(e){var t,n,i,r,s,a="ngraph"!==e.forceEngine;return e.engineRunning&&function(){++e.cntTicks>e.cooldownTicks||new Date-e.startTickTime>e.cooldownTime||a&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin?(e.engineRunning=!1,e.onEngineStop()):(e.layout[a?"tick":"step"](),e.onEngineTick());var t=Ld(e.nodeThreeObjectExtend);e.nodeDataMapper.entries().forEach(function(n){var i=tf(n,2),r=i[0],s=i[1];if(s){var o=a?r:e.layout.getNodePosition(r[e.nodeId]),l=t(r);e.nodePositionUpdate&&e.nodePositionUpdate(l?s.children[0]:s,{x:o.x,y:o.y,z:o.z},r)&&!l||(s.position.x=o.x,s.position.y=o.y||0,s.position.z=o.z||0)}});var n=Ld(e.linkWidth),i=Ld(e.linkCurvature),r=Ld(e.linkCurveRotation),s=Ld(e.linkThreeObjectExtend);function o(t){var n=a?t:e.layout.getLinkPosition(e.layout.graph.getLink(t.source,t.target).id),s=n[a?"source":"from"],o=n[a?"target":"to"];if(s&&o&&s.hasOwnProperty("x")&&o.hasOwnProperty("x")){var l=i(t);if(l){var u,c=new vf.Vector3(s.x,s.y||0,s.z||0),h=new vf.Vector3(o.x,o.y||0,o.z||0),d=c.distanceTo(h),p=r(t);if(d>0){var f=o.x-s.x,m=o.y-s.y||0,g=(new vf.Vector3).subVectors(h,c),_=g.clone().multiplyScalar(l).cross(0!==f||0!==m?new vf.Vector3(0,0,1):new vf.Vector3(0,1,0)).applyAxisAngle(g.normalize(),p).add((new vf.Vector3).addVectors(c,h).divideScalar(2));u=new vf.QuadraticBezierCurve3(c,_,h)}else{var v=70*l,y=-p,b=y+Math.PI/2;u=new vf.CubicBezierCurve3(c,new vf.Vector3(v*Math.cos(b),v*Math.sin(b),0).add(c),new vf.Vector3(v*Math.cos(y),v*Math.sin(y),0).add(c),h)}t.__curve=u}else t.__curve=null}}e.linkDataMapper.entries().forEach(function(t){var i=tf(t,2),r=i[0],l=i[1];if(l){var u=a?r:e.layout.getLinkPosition(e.layout.graph.getLink(r.source,r.target).id),c=u[a?"source":"from"],h=u[a?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){o(r);var d=s(r);if(!e.linkPositionUpdate||!e.linkPositionUpdate(d?l.children[1]:l,{start:{x:c.x,y:c.y,z:c.z},end:{x:h.x,y:h.y,z:h.z}},r)||d){var p=30,f=r.__curve,m=l.children.length?l.children[0]:l;if("Line"===m.type){if(f){var g=f.getPoints(p);m.geometry.getAttribute("position").array.length!==3*g.length&&m.geometry[bf]("position",new vf.BufferAttribute(new Float32Array(3*g.length),3)),m.geometry.setFromPoints(g)}else{var _=m.geometry.getAttribute("position");_&&_.array&&6===_.array.length||m.geometry[bf]("position",_=new vf.BufferAttribute(new Float32Array(6),3)),_.array[0]=c.x,_.array[1]=c.y||0,_.array[2]=c.z||0,_.array[3]=h.x,_.array[4]=h.y||0,_.array[5]=h.z||0,_.needsUpdate=!0}m.geometry.computeBoundingSphere()}else if("Mesh"===m.type)if(f){m.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(m.position.set(0,0,0),m.rotation.set(0,0,0),m.scale.set(1,1,1));var v=Math.ceil(10*n(r))/10/2,y=new vf.TubeGeometry(f,p,v,e.linkResolution,!1);m.geometry.dispose(),m.geometry=y}else{if(!m.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var b=Math.ceil(10*n(r))/10/2,x=new vf.CylinderGeometry(b,b,1,e.linkResolution,1,!1);x[xf]((new vf.Matrix4).makeTranslation(0,.5,0)),x[xf]((new vf.Matrix4).makeRotationX(Math.PI/2)),m.geometry.dispose(),m.geometry=x}var T=new vf.Vector3(c.x,c.y||0,c.z||0),S=new vf.Vector3(h.x,h.y||0,h.z||0),M=T.distanceTo(S);m.position.x=T.x,m.position.y=T.y,m.position.z=T.z,m.scale.z=M,m.parent.localToWorld(S),m.lookAt(S)}}}}})}(),t=Ld(e.linkDirectionalArrowRelPos),n=Ld(e.linkDirectionalArrowLength),i=Ld(e.nodeVal),e.arrowDataMapper.entries().forEach(function(r){var s=tf(r,2),o=s[0],l=s[1];if(l){var u=a?o:e.layout.getLinkPosition(e.layout.graph.getLink(o.source,o.target).id),c=u[a?"source":"from"],h=u[a?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){var d=Math.cbrt(Math.max(0,i(c)||1))*e.nodeRelSize,p=Math.cbrt(Math.max(0,i(h)||1))*e.nodeRelSize,f=n(o),m=t(o),g=o.__curve?function(e){return o.__curve.getPoint(e)}:function(e){var t=function(e,t,n,i){return t[e]+(n[e]-t[e])*i||0};return{x:t("x",c,h,e),y:t("y",c,h,e),z:t("z",c,h,e)}},_=o.__curve?o.__curve.getLength():Math.sqrt(["x","y","z"].map(function(e){return Math.pow((h[e]||0)-(c[e]||0),2)}).reduce(function(e,t){return e+t},0)),v=d+f+(_-d-p-f)*m,y=g(v/_),b=g((v-f)/_);["x","y","z"].forEach(function(e){return l.position[e]=b[e]});var x=$p(vf.Vector3,rf(["x","y","z"].map(function(e){return y[e]})));l.parent.localToWorld(x),l.lookAt(x)}}}),r=Ld(e.linkDirectionalParticleSpeed),s=Ld(e.linkDirectionalParticleOffset),e.graphData.links.forEach(function(t){var n=e.particlesDataMapper.getObj(t),i=n&&n.children,o=t.__singleHopPhotonsObj&&t.__singleHopPhotonsObj.children;if(o&&o.length||i&&i.length){var l=a?t:e.layout.getLinkPosition(e.layout.graph.getLink(t.source,t.target).id),u=l[a?"source":"from"],c=l[a?"target":"to"];if(u&&c&&u.hasOwnProperty("x")&&c.hasOwnProperty("x")){var h=r(t),d=Math.abs(s(t)),p=t.__curve?function(e){return t.__curve.getPoint(e)}:function(e){var t=function(e,t,n,i){return t[e]+(n[e]-t[e])*i||0};return{x:t("x",u,c,e),y:t("y",u,c,e),z:t("z",u,c,e)}};[].concat(rf(i||[]),rf(o||[])).forEach(function(e,t){var n="singleHopPhotons"===e.parent.__linkThreeObjType;if(e.hasOwnProperty("__progressRatio")||(e.__progressRatio=n?0:(t+d)/i.length),e.__progressRatio+=h,e.__progressRatio>=1){if(n)return e.parent.remove(e),void cf(e);e.__progressRatio=e.__progressRatio%1}var r=e.__progressRatio,s=p(r);"SphereGeometry"!==e.geometry.type&&e.lookAt(s.x,s.y,s.z),["x","y","z"].forEach(function(t){return e.position[t]=s[t]})})}}}),this},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){var n=new vf.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var i=Ld(e.linkDirectionalParticleThreeObject)(t);if(i&&e.linkDirectionalParticleThreeObject===i&&(i=i.clone()),!i){var r=Ld(e.linkDirectionalParticleWidth),s=Math.ceil(10*r(t))/10/2,a=e.linkDirectionalParticleResolution,o=new vf.SphereGeometry(s,a,a),l=Ld(e.linkColor),u=Ld(e.linkDirectionalParticleColor)(t)||l(t)||"#f0f0f0",c=new vf.Color(ff(u)),h=3*e.linkOpacity,d=new vf.MeshLambertMaterial({color:c,transparent:!0,opacity:h});i=new vf.Mesh(o,d)}t.__singleHopPhotonsObj.add(i)}return this},getGraphBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0};if(!e.initialised)return null;var n=function e(n){var i=[];if(n.geometry){n.geometry.computeBoundingBox();var r=new vf.Box3;r.copy(n.geometry.boundingBox).applyMatrix4(n.matrixWorld),i.push(r)}return i.concat.apply(i,rf((n.children||[]).filter(function(e){return!e.hasOwnProperty("__graphObjType")||"node"===e.__graphObjType&&t(e.__data)}).map(e)))}(e.graphScene);return n.length?Object.assign.apply(Object,rf(["x","y","z"].map(function(e){return qp({},e,[Od(n,function(t){return t.min[e]}),Fd(n,function(t){return t.max[e]})])}))):null}},stateInit:function(){return{d3ForceLayout:mh().force("link",zc()).force("charge",gh()).force("center",cc()).force("dagRadial",null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new pf(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new pf(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new pf(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new pf(e,{objBindAttr:"__photonsObj"})},update:function(e,t){var n=function(e){return e.some(function(e){return t.hasOwnProperty(e)})};if(e.engineRunning=!1,"function"==typeof e.onUpdate&&e.onUpdate(),null!==e.nodeAutoColorBy&&n(["nodeAutoColorBy","graphData","nodeColor"])&&_f(e.graphData.nodes,Ld(e.nodeAutoColorBy),e.nodeColor),null!==e.linkAutoColorBy&&n(["linkAutoColorBy","graphData","linkColor"])&&_f(e.graphData.links,Ld(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){var i=Ld(e.nodeThreeObject),r=Ld(e.nodeThreeObjectExtend),s=Ld(e.nodeVal),a=Ld(e.nodeColor),o=Ld(e.nodeVisibility),l={},u={};(e._flushObjects||n(["nodeThreeObject","nodeThreeObjectExtend"]))&&e.nodeDataMapper.clear(),e.nodeDataMapper.onCreateObj(function(t){var n,s=i(t),a=r(t);return s&&e.nodeThreeObject===s&&(s=s.clone()),s&&!a?n=s:((n=new vf.Mesh).__graphDefaultObj=!0,s&&a&&n.add(s)),n.__graphObjType="node",n}).onUpdateObj(function(t,n){if(t.__graphDefaultObj){var i=s(n)||1,r=Math.cbrt(i)*e.nodeRelSize,o=e.nodeResolution;t.geometry.type.match(/^Sphere(Buffer)?Geometry$/)&&t.geometry.parameters.radius===r&&t.geometry.parameters.widthSegments===o||(l.hasOwnProperty(i)||(l[i]=new vf.SphereGeometry(r,o,o)),t.geometry.dispose(),t.geometry=l[i]);var c=a(n),h=new vf.Color(ff(c||"#ffffaa")),d=e.nodeOpacity*mf(c);"MeshLambertMaterial"===t.material.type&&t.material.color.equals(h)&&t.material.opacity===d||(u.hasOwnProperty(c)||(u[c]=new vf.MeshLambertMaterial({color:h,transparent:!0,opacity:d})),t.material.dispose(),t.material=u[c])}}).digest(e.graphData.nodes.filter(o))}if(e._flushObjects||n(["graphData","linkThreeObject","linkThreeObjectExtend","linkMaterial","linkColor","linkWidth","linkVisibility","linkResolution","linkOpacity","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject"])){var c=Ld(e.linkThreeObject),h=Ld(e.linkThreeObjectExtend),d=Ld(e.linkMaterial),p=Ld(e.linkVisibility),f=Ld(e.linkColor),m=Ld(e.linkWidth),g={},_={},v={},y=e.graphData.links.filter(p);if((e._flushObjects||n(["linkThreeObject","linkThreeObjectExtend","linkWidth"]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj(function(e){var t=e.__data&&e.__data.__singleHopPhotonsObj;t&&(t.parent.remove(t),cf(t),delete e.__data.__singleHopPhotonsObj)}).onCreateObj(function(t){var n,i,r=c(t),s=h(t);if(r&&e.linkThreeObject===r&&(r=r.clone()),!r||s)if(!!m(t))n=new vf.Mesh;else{var a=new vf.BufferGeometry;a[bf]("position",new vf.BufferAttribute(new Float32Array(6),3)),n=new vf.Line(a)}return r?s?((i=new vf.Group).__graphDefaultObj=!0,i.add(n),i.add(r)):i=r:(i=n).__graphDefaultObj=!0,i.renderOrder=10,i.__graphObjType="link",i}).onUpdateObj(function(t,n){if(t.__graphDefaultObj){var i=t.children.length?t.children[0]:t,r=Math.ceil(10*m(n))/10,s=!!r;if(s){var a=r/2,o=e.linkResolution;if(!i.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||i.geometry.parameters.radiusTop!==a||i.geometry.parameters.radialSegments!==o){if(!g.hasOwnProperty(r)){var l=new vf.CylinderGeometry(a,a,1,o,1,!1);l[xf]((new vf.Matrix4).makeTranslation(0,.5,0)),l[xf]((new vf.Matrix4).makeRotationX(Math.PI/2)),g[r]=l}i.geometry.dispose(),i.geometry=g[r]}}var u=d(n);if(u)i.material=u;else{var c=f(n),h=new vf.Color(ff(c||"#f0f0f0")),p=e.linkOpacity*mf(c),y=s?"MeshLambertMaterial":"LineBasicMaterial";if(i.material.type!==y||!i.material.color.equals(h)||i.material.opacity!==p){var b=s?_:v;b.hasOwnProperty(c)||(b[c]=new vf[y]({color:h,transparent:p<1,opacity:p,depthWrite:p>=1})),i.material.dispose(),i.material=b[c]}}}}).digest(y),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){var b=Ld(e.linkDirectionalArrowLength),x=Ld(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj(function(){var e=new vf.Mesh(void 0,new vf.MeshLambertMaterial({transparent:!0}));return e.__linkThreeObjType="arrow",e}).onUpdateObj(function(t,n){var i=b(n),r=e.linkDirectionalArrowResolution;if(!t.geometry.type.match(/^Cone(Buffer)?Geometry$/)||t.geometry.parameters.height!==i||t.geometry.parameters.radialSegments!==r){var s=new vf.ConeGeometry(.25*i,i,r);s.translate(0,i/2,0),s.rotateX(Math.PI/2),t.geometry.dispose(),t.geometry=s}var a=x(n)||f(n)||"#f0f0f0";t.material.color=new vf.Color(ff(a)),t.material.opacity=3*e.linkOpacity*mf(a)}).digest(y.filter(b))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){var T=Ld(e.linkDirectionalParticles),S=Ld(e.linkDirectionalParticleWidth),M=Ld(e.linkDirectionalParticleColor),E=Ld(e.linkDirectionalParticleThreeObject),w={},A={};e.particlesDataMapper.onCreateObj(function(){var e=new vf.Group;return e.__linkThreeObjType="photons",e.__photonDataMapper=new pf(e),e}).onUpdateObj(function(t,n){var i,r,s=!!t.children.length&&t.children[0],a=E(n);if(a)i=a.geometry,r=a.material;else{var o=Math.ceil(10*S(n))/10/2,l=e.linkDirectionalParticleResolution;s&&s.geometry.parameters.radius===o&&s.geometry.parameters.widthSegments===l?i=s.geometry:(A.hasOwnProperty(o)||(A[o]=new vf.SphereGeometry(o,l,l)),i=A[o]);var u=M(n)||f(n)||"#f0f0f0",c=new vf.Color(ff(u)),h=3*e.linkOpacity;s&&s.material.color.equals(c)&&s.material.opacity===h?r=s.material:(w.hasOwnProperty(u)||(w[u]=new vf.MeshLambertMaterial({color:c,transparent:!0,opacity:h})),r=w[u])}s&&(s.geometry!==i&&s.geometry.dispose(),s.material!==r&&s.material.dispose());var d=Math.round(Math.abs(T(n)));t.__photonDataMapper.id(function(e){return e.idx}).onCreateObj(function(){return new vf.Mesh(i,r)}).onUpdateObj(function(e){e.geometry=i,e.material=r}).digest(rf(new Array(d)).map(function(e,t){return{idx:t}}))}).digest(y.filter(T))}}if(e._flushObjects=!1,n(["graphData","nodeId","linkSource","linkTarget","numDimensions","forceEngine","dagMode","dagNodeFilter","dagLevelDistance"])){e.engineRunning=!1,e.graphData.links.forEach(function(t){t.source=t[e.linkSource],t.target=t[e.linkTarget]});var R,C="ngraph"!==e.forceEngine;if(C){(R=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);var N=e.d3ForceLayout.force("link");N&&N.id(function(t){return t[e.nodeId]}).links(e.graphData.links);var P=e.dagMode&&function(e,t){var n=e.nodes,i=e.links,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=r.nodeFilter,a=void 0===s?function(){return!0}:s,o=r.onLoopError,l=void 0===o?function(e){throw"Invalid DAG structure! Found cycle in node path: ".concat(e.join(" -> "),".")}:o,u={};n.forEach(function(e){return u[t(e)]={data:e,out:[],depth:-1,skip:!a(e)}}),i.forEach(function(e){var n=e.source,i=e.target,r=l(n),s=l(i);if(!u.hasOwnProperty(r))throw"Missing source node with id: ".concat(r);if(!u.hasOwnProperty(s))throw"Missing target node with id: ".concat(s);var a=u[r],o=u[s];function l(e){return"object"===af(e)?t(e):e}a.out.push(o)});var c=[];return function e(n){for(var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=function(){var s=n[a];if(-1!==i.indexOf(s)){var o=[].concat(rf(i.slice(i.indexOf(s))),[s]).map(function(e){return t(e.data)});return c.some(function(e){return e.length===o.length&&e.every(function(e,t){return e===o[t]})})||(c.push(o),l(o)),1}r>s.depth&&(s.depth=r,e(s.out,[].concat(rf(i),[s]),r+(s.skip?0:1)))},a=0,o=n.length;a<o;a++)s()}(Object.values(u)),Object.assign.apply(Object,[{}].concat(rf(Object.entries(u).filter(function(e){return!tf(e,2)[1].skip}).map(function(e){var t=tf(e,2);return qp({},t[0],t[1].depth)}))))}(e.graphData,function(t){return t[e.nodeId]},{nodeFilter:e.dagNodeFilter,onLoopError:e.onDagError||void 0}),L=Math.max.apply(Math,rf(Object.values(P||[]))),D=e.dagLevelDistance||e.graphData.nodes.length/(L||1)*2*(-1!==["radialin","radialout"].indexOf(e.dagMode)?.7:1);if(["lr","rl","td","bu","zin","zout"].includes(t.dagMode)){var I=["lr","rl"].includes(t.dagMode)?"fx":["td","bu"].includes(t.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(e){return delete e[I]})}if(["lr","rl","td","bu","zin","zout"].includes(e.dagMode)){var U=["rl","td","zout"].includes(e.dagMode),F=["lr","rl"].includes(e.dagMode)?"fx":["td","bu"].includes(e.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(t){return t[F]=function(t){return(P[t[e.nodeId]]-L/2)*D*(U?-1:1)}(t)})}e.d3ForceLayout.force("dagRadial",-1!==["radialin","radialout"].indexOf(e.dagMode)?function(e,t,n,i){var r,s,a,o,l=Fc(.1);function u(e){for(var l=0,u=r.length;l<u;++l){var c=r[l],h=c.x-t||1e-6,d=(c.y||0)-n||1e-6,p=(c.z||0)-i||1e-6,f=Math.sqrt(h*h+d*d+p*p),m=(o[l]-f)*a[l]*e/f;c.vx+=h*m,s>1&&(c.vy+=d*m),s>2&&(c.vz+=p*m)}}function c(){if(r){var t,n=r.length;for(a=new Array(n),o=new Array(n),t=0;t<n;++t)o[t]=+e(r[t],t,r),a[t]=isNaN(o[t])?0:+l(r[t],t,r)}}return"function"!=typeof e&&(e=Fc(+e)),null==t&&(t=0),null==n&&(n=0),null==i&&(i=0),u.initialize=function(e,...t){r=e,s=t.find(e=>[1,2,3].includes(e))||2,c()},u.strength=function(e){return arguments.length?(l="function"==typeof e?e:Fc(+e),c(),u):l},u.radius=function(t){return arguments.length?(e="function"==typeof t?t:Fc(+t),c(),u):e},u.x=function(e){return arguments.length?(t=+e,u):t},u.y=function(e){return arguments.length?(n=+e,u):n},u.z=function(e){return arguments.length?(i=+e,u):i},u}(function(t){var n=P[t[e.nodeId]]||-1;return("radialin"===e.dagMode?L-n:n)*D}).strength(function(t){return e.dagNodeFilter(t)?1:0}):null)}else{var O=yf.graph();e.graphData.nodes.forEach(function(t){O.addNode(t[e.nodeId])}),e.graphData.links.forEach(function(e){O.addLink(e.source,e.target)}),R=yf.forcelayout(O,function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Jp(Object(n),!0).forEach(function(t){qp(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Jp(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({dimensions:e.numDimensions},e.ngraphPhysics)),R.graph=O}for(var B=0;B<e.warmupTicks&&!(C&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin);B++)R[C?"tick":"step"]();e.layout=R,this.resetCountdown()}e.engineRunning=!0,e.onFinishUpdate()}});var Sf=function(e){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=function(n){function i(){var n;Gp(this,i);for(var r=arguments.length,s=new Array(r),a=0;a<r;a++)s[a]=arguments[a];return(n=Vp(this,i,[].concat(s))).__kapsuleInstance=$p(e,[].concat(rf(t?[n]:[]),s)),n}return Zp(i,n),Xp(i)}(arguments.length>1&&void 0!==arguments[1]?arguments[1]:Object);return Object.keys(e()).forEach(function(e){return n.prototype[e]=function(){var t,n=(t=this.__kapsuleInstance)[e].apply(t,arguments);return n===this.__kapsuleInstance?this:n}}),n}(Tf,(window.THREE?window.THREE:{Group:ci}).Group,!0);const Mf=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],Ef=new WeakMap;class wf{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Mf,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:n,material:i,object:r}=e;if(t={material:this.getMaterialData(i),geometry:{id:n.id,attributes:this.getAttributesData(n.attributes),indexId:n.index?n.index.id:null,indexVersion:n.index?n.index.version:null,drawRange:{start:n.drawRange.start,count:n.drawRange.count}},worldMatrix:r.matrixWorld.clone()},r.center&&(t.center=r.center.clone()),r.morphTargetInfluences&&(t.morphTargetInfluences=r.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),t.material.transmission>0){const{width:n,height:i}=e.context;t.bufferWidth=n,t.bufferHeight=i}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const n in e){const i=e[n];t[n]={id:i.id,version:i.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getMaterialData(e){const t={};for(const n of this.refreshUniforms){const i=e[n];null!=i&&("object"==typeof i&&void 0!==i.clone?!0===i.isTexture?t[n]={id:i.id,version:i.version}:t[n]=i.clone():t[n]=i)}return t}equals(e,t){const{object:n,material:i,geometry:r}=e,s=this.getRenderObjectData(e);if(!0!==s.worldMatrix.equals(n.matrixWorld))return s.worldMatrix.copy(n.matrixWorld),!1;const a=s.material;for(const e in a){const t=a[e],n=i[e];if(void 0!==t.equals){if(!1===t.equals(n))return t.copy(n),!1}else if(!0===n.isTexture){if(t.id!==n.id||t.version!==n.version)return t.id=n.id,t.version=n.version,!1}else if(t!==n)return a[e]=n,!1}if(a.transmission>0){const{width:t,height:n}=e.context;if(s.bufferWidth!==t||s.bufferHeight!==n)return s.bufferWidth=t,s.bufferHeight=n,!1}const o=s.geometry,l=r.attributes,u=o.attributes,c=Object.keys(u),h=Object.keys(l);if(o.id!==r.id)return o.id=r.id,!1;if(c.length!==h.length)return s.geometry.attributes=this.getAttributesData(l),!1;for(const e of c){const t=u[e],n=l[e];if(void 0===n)return delete u[e],!1;if(t.id!==n.id||t.version!==n.version)return t.id=n.id,t.version=n.version,!1}const d=r.index,p=o.indexId,f=o.indexVersion,m=d?d.id:null,g=d?d.version:null;if(p!==m||f!==g)return o.indexId=m,o.indexVersion=g,!1;if(o.drawRange.start!==r.drawRange.start||o.drawRange.count!==r.drawRange.count)return o.drawRange.start=r.drawRange.start,o.drawRange.count=r.drawRange.count,!1;if(s.morphTargetInfluences){let e=!1;for(let t=0;t<s.morphTargetInfluences.length;t++)s.morphTargetInfluences[t]!==n.morphTargetInfluences[t]&&(s.morphTargetInfluences[t]=n.morphTargetInfluences[t],e=!0);if(e)return!1}if(s.lights)for(let e=0;e<t.length;e++)if(s.lights[e].map!==t[e].map)return!1;return s.center&&!1===s.center.equals(n.center)?(s.center.copy(n.center),!0):(null!==e.bundle&&(s.version=e.bundle.version),!0)}getLightsData(e){const t=[];for(const n of e)!0===n.isSpotLight&&null!==n.map&&t.push({map:n.map.version});return t}getLights(e,t){if(Ef.has(e)){const n=Ef.get(e);if(n.renderId===t)return n.lightsData}const n=this.getLightsData(e.getLights());return Ef.set(e,{renderId:t,lightsData:n}),n}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:n}=t;if(this.renderId!==n)return this.renderId=n,!0;const i=!0===e.object.static,r=null!==e.bundle&&!0===e.bundle.static&&this.getRenderObjectData(e).version===e.bundle.version;if(i||r)return!1;const s=this.getLights(e.lightsNode,n);return!0!==this.equals(e,s)}}const Af=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];class Rf{constructor(e=null){this.isStackTrace=!0,this.stack=function(e){const t=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return e.split("\n").map(e=>{const n=e.match(t);if(!n)return null;const i=n[1]||n[2]||"",r=n[3].split("?")[0],s=parseInt(n[4],10),a=parseInt(n[5],10);return{fn:i,file:r.split("/").pop(),line:s,column:a}}).filter(e=>e&&!Af.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;const t=this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n");return`${e}\n${t}`}}function Cf(e,t=0){let n=3735928559^t,i=1103547991^t;if(e instanceof Array)for(let t,r=0;r<e.length;r++)t=e[r],n=Math.imul(n^t,2654435761),i=Math.imul(i^t,1597334677);else for(let t,r=0;r<e.length;r++)t=e.charCodeAt(r),n=Math.imul(n^t,2654435761),i=Math.imul(i^t,1597334677);return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&i)+(n>>>0)}const Nf=e=>Cf(e),Pf=e=>Cf(e),Lf=(...e)=>Cf(e),Df=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),If=new WeakMap;function Uf(e){return Df.get(e)}function Ff(e){if(null==e)return null;const t=typeof e;return!0===e.isNode?"node":"number"===t?"float":"boolean"===t?"bool":"string"===t?"string":"function"===t?"shader":!0===e.isVector2?"vec2":!0===e.isVector3?"vec3":!0===e.isVector4?"vec4":!0===e.isMatrix2?"mat2":!0===e.isMatrix3?"mat3":!0===e.isMatrix4?"mat4":!0===e.isColor?"color":e instanceof ArrayBuffer?"ArrayBuffer":null}function Of(e,...t){const n=e?e.slice(-4):void 0;return 1===t.length&&("vec2"===n?t=[t[0],t[0]]:"vec3"===n?t=[t[0],t[0],t[0]]:"vec4"===n&&(t=[t[0],t[0],t[0],t[0]])),"color"===e?new _i(...t):"vec2"===n?new cn(...t):"vec3"===n?new dn(...t):"vec4"===n?new Pn(...t):"mat2"===n?new $a(...t):"mat3"===n?new mn(...t):"mat4"===n?new Fn(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?(i=t[0],Uint8Array.from(atob(i),e=>e.charCodeAt(0)).buffer):null;var i}function Bf(e){let t=If.get(e);return void 0===t&&(t={},If.set(e,t)),t}const kf="vertex",zf="none",Vf="frame",Gf="render",Hf="object",jf="readOnly",Wf="writeOnly",$f="readWrite",Xf=["setup","analyze","generate"],qf=["fragment","vertex","compute"],Yf=["x","y","z","w"],Kf={analyze:"setup",generate:"analyze"};let Zf=0;class Qf extends Zt{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=zf,this.updateBeforeType=zf,this.updateAfterType=zf,this.uuid=un.generateUUID(),this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Zf++}),this.stackTrace=null,!0===Qf.captureStackTrace&&(this.stackTrace=new Rf)}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,Vf)}onRenderUpdate(e){return this.onUpdate(e,Gf)}onObjectUpdate(e){return this.onUpdate(e,Hf)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const n of Object.getOwnPropertyNames(this)){const i=this[n];if(!0!==n.startsWith("_")&&!e.has(i))if(!0===Array.isArray(i))for(let e=0;e<i.length;e++){const r=i[e];r&&!0===r.isNode&&t.push({property:n,index:e,childNode:r})}else if(i&&!0===i.isNode)t.push({property:n,childNode:i});else if(i&&Object.getPrototypeOf(i)===Object.prototype)for(const e in i){if(!0===e.startsWith("_"))continue;const r=i[e];r&&!0===r.isNode&&t.push({property:n,index:e,childNode:r})}}return t}getCacheKey(e=!1,t=null){if(!0===(e=e||this.version!==this._cacheKeyVersion)||null===this._cacheKey){null===t&&(t=new Set);const n=[];for(const{property:i,childNode:r}of this._getChildren(t))n.push(Nf(i.slice(0,-4)),r.getCacheKey(e,t));this._cacheKey=Lf(Pf(n),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let n=0;for(const e of this.getChildren())t["node"+n++]=e;return t.outputNode||null}analyze(e,t=null){const n=e.increaseUsage(this);if(!0===this.parents){const n=e.getDataFromNode(this,"any");n.stages=n.stages||{},n.stages[e.shaderStage]=n.stages[e.shaderStage]||[],n.stages[e.shaderStage].push(t)}if(1===n){const t=e.getNodeProperties(this);for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e,this)}}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);if(n&&!0===n.isNode)return n.build(e,t)}updateBefore(){Xt("Abstract function.")}updateAfter(){Xt("Abstract function.")}update(){Xt("Abstract function.")}before(e){return null===this._beforeNodes&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){const n=this.getShared(e);if(this!==n)return n.build(e,t);if(null!==this._beforeNodes){const n=this._beforeNodes;this._beforeNodes=null;for(const i of n)i.build(e,t);this._beforeNodes=n}const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const r=Kf[e.buildStage];if(r&&!0!==i.buildStages[r]){const t=e.getBuildStage();e.setBuildStage(r),this.build(e),e.setBuildStage(t)}e.addChain(this);let s=null;const a=e.getBuildStage();if("setup"===a){e.addNode(this),this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const n of Object.values(t))if(n&&!0===n.isNode){if(!0===n.parents){const t=e.getNodeProperties(n);t.parents=t.parents||[],t.parents.push(this)}n.build(e)}e.addSequentialNode(this)}s=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(this.generate.length<2){const n=this.getNodeType(e),i=e.getDataFromNode(this);s=i.snippet,void 0===s?void 0===i.generated?(i.generated=!0,s=this.generate(e)||"",i.snippet=s):(Xt("Node: Recursion detected.",this),s="/* Recursion detected. */"):void 0!==i.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),s=e.format(s,n,t)}else s=this.generate(e,t)||"";""===s&&null!==t&&"void"!==t&&"OutputType"!==t&&(qt(`TSL: Invalid generated code, expected a "${t}".`),s=e.generateConst(t))}return e.removeChain(this),s}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:i,index:r,childNode:s}of t)void 0!==r?(void 0===n[i]&&(n[i]=Number.isInteger(r)?[]:{}),n[i][r]=s.toJSON(e.meta).uuid):n[i]=s.toJSON(e.meta).uuid;Object.keys(n).length>0&&(e.inputNodes=n)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const i=[];for(const r of e.inputNodes[n])i.push(t[r]);this[n]=i}else if("object"==typeof e.inputNodes[n]){const i={};for(const r in e.inputNodes[n]){const s=e.inputNodes[n][r];i[r]=t[s]}this[n]=i}else{const i=e.inputNodes[n];this[n]=t[i]}}}toJSON(e){const{uuid:t,type:n}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:n,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=s(e.textures),n=s(e.images),i=s(e.nodes);t.length>0&&(r.textures=t),n.length>0&&(r.images=n),i.length>0&&(r.nodes=i)}return r}}Qf.captureStackTrace=!1;class Jf extends Qf{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class em extends Qf{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const i of this.convertTo.split("|"))null!==n&&e.getTypeLength(t)!==e.getTypeLength(i)||(n=i);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const n=this.node,i=this.getNodeType(e),r=n.build(e,i);return e.format(r,i,t)}}class tm extends Qf{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const n=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,n,t);if("void"!==n&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,n),s=e.getVarFromNode(this,null,n),a=e.getPropertyName(s);return e.addLineFlowCode(`${a} = ${r}`,this),i.snippet=r,i.propertyName=a,e.format(i.propertyName,n,t)}}return super.build(e,t)}}class nm extends tm{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,n)=>t+e.getTypeLength(n.getNodeType(e)),0))}generate(e,t){const n=this.getNodeType(e),i=e.getTypeLength(n),r=this.nodes,s=e.getComponentType(n),a=[];let o=0;for(const t of r){if(o>=i){qt(`TSL: Length of parameters exceeds maximum length of function '${n}()' type.`,this.stackTrace);break}let r,l=t.getNodeType(e),u=e.getTypeLength(l);o+u>i&&(qt(`TSL: Length of '${n}()' data exceeds maximum length of output type.`,this.stackTrace),u=i-o,l=e.getTypeFromLength(u)),o+=u,r=t.build(e,l);if(e.getComponentType(l)!==s){const t=e.getTypeFromLength(u,s);r=e.format(r,l,t)}a.push(r)}const l=`${e.getType(n)}( ${a.join(", ")} )`;return e.format(l,n,t)}}const im=Yf.join("");class rm extends Qf{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(Yf.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const n=this.node,i=e.getTypeLength(n.getNodeType(e));let r=null;if(i>1){let s=null;this.getVectorLength()>=i&&(s=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=n.build(e,s);r=this.components.length===i&&this.components===im.slice(0,this.components.length)?e.format(a,s,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else r=n.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class sm extends tm{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:i}=this,r=this.getNodeType(e),s=e.getComponentType(i.getNodeType(e)),a=e.getTypeFromLength(n.length,s),o=i.build(e,a),l=t.build(e,r),u=e.getTypeLength(r),c=[];for(let e=0;e<u;e++){const t=Yf[e];t===n[0]?(c.push(o),e+=n.length-1):c.push(l+"."+t)}return`${e.getType(r)}( ${c.join(", ")} )`}}class am extends tm{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:n}=this,i=this.getNodeType(e),r=n.build(e),s=e.getVarFromNode(this),a=e.getPropertyName(s);e.addLineFlowCode(a+" = "+r,this);const o=e.getTypeLength(i),l=[];let u=0;for(let e=0;e<o;e++){const n=Yf[e];n===t[u]?(l.push("1.0 - "+a+"."+n),u++):l.push(a+"."+n)}return`${e.getType(i)}( ${l.join(", ")} )`}}class om extends Qf{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return null===this.nodeType?Ff(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=Ff(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=function(e){let t="";const n=new Uint8Array(e);for(let e=0;e<n.length;e++)t+=String.fromCharCode(n[e]);return btoa(t)}(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?Of(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){Xt("Abstract function.")}}const lm=/float|u?int/;class um extends om{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const n=this.getNodeType(e);return lm.test(n)&&lm.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),n,t)}}class cm extends Qf{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return(!this.structNode.isMemberNode||!1!==this.structNode.hasMember(e))&&"void"!==this.structNode.getMemberType(e,this.property)}getNodeType(e){return!1===this.hasMember(e)?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(!1===this.hasMember(e))return"float";const n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}generate(e){if(!1===this.hasMember(e)){Xt(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);const t=this.getNodeType(e);return e.generateConst(t)}return this.structNode.build(e)+"."+this.property}}let hm=null;const dm=new Map;function pm(e,t){if(dm.has(e))Xt(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);dm.set(e,t),"assign"!==e&&(Qf.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},Qf.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const fm=e=>(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");Qf.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==hm?hm.assign(this,...e):qt("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Rf),this;{const t=dm.get("assign");return this.addToStack(t(...e))}},Qf.prototype.toVarIntent=function(){return this},Qf.prototype.get=function(e){return new cm(this,e)};const mm={};function gm(e,t,n){mm[e]=mm[t]=mm[n]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new rm(this,e),this._cache[e]=t),t},set(t){this[e].assign(Vm(t))}};const i=e.toUpperCase(),r=t.toUpperCase(),s=n.toUpperCase();Qf.prototype["set"+i]=Qf.prototype["set"+r]=Qf.prototype["set"+s]=function(t){const n=fm(e);return new sm(this,n,Vm(t))},Qf.prototype["flip"+i]=Qf.prototype["flip"+r]=Qf.prototype["flip"+s]=function(){const t=fm(e);return new am(this,t)}}const _m=["x","y","z","w"],vm=["r","g","b","a"],ym=["s","t","p","q"];for(let e=0;e<4;e++){let t=_m[e],n=vm[e],i=ym[e];gm(t,n,i);for(let r=0;r<4;r++){t=_m[e]+_m[r],n=vm[e]+vm[r],i=ym[e]+ym[r],gm(t,n,i);for(let s=0;s<4;s++){t=_m[e]+_m[r]+_m[s],n=vm[e]+vm[r]+vm[s],i=ym[e]+ym[r]+ym[s],gm(t,n,i);for(let a=0;a<4;a++)t=_m[e]+_m[r]+_m[s]+_m[a],n=vm[e]+vm[r]+vm[s]+vm[a],i=ym[e]+ym[r]+ym[s]+ym[a],gm(t,n,i)}}}for(let e=0;e<32;e++)mm[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new Jf(this,new um(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(Vm(t))}};Object.defineProperties(Qf.prototype,mm);const bm=new WeakMap,xm=function(e,t=null){for(const n in e)e[n]=Vm(e[n],t);return e},Tm=function(e,t=null){const n=e.length;for(let i=0;i<n;i++)e[i]=Vm(e[i],t);return e},Sm=function(e,t=null,n=null,i=null){function r(e){return null!==i?(e=Vm(Object.assign(e,i)),!0===i.intent&&(e=e.toVarIntent())):e=Vm(e),e}let s,a,o,l=t;function u(t){let n;return n=l?/[a-z]/i.test(l)?l+"()":l:e.type,void 0!==a&&t.length<a?(qt(`TSL: "${n}" parameter length is less than minimum required.`,new Rf),t.concat(new Array(a-t.length).fill(0))):void 0!==o&&t.length>o?(qt(`TSL: "${n}" parameter length exceeds limit.`,new Rf),t.slice(0,o)):t}return null===t?s=(...t)=>r(new e(...jm(u(t)))):null!==n?(n=Vm(n),s=(...i)=>r(new e(t,...jm(u(i)),n))):s=(...n)=>r(new e(t,...jm(u(n)))),s.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),s),s.setName=e=>(l=e,s),s},Mm=function(e,...t){return new e(...jm(t))};class Em extends Qf{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:n}=this,i=e.getNodeProperties(t),r=e.getClosestSubBuild(t.subBuilds)||"",s=r||"default";if(i[s])return i[s];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=r,e.fnCall=this;let l=null;if(t.layout){let i=bm.get(e.constructor);void 0===i&&(i=new WeakMap,bm.set(e.constructor,i));let r=i.get(t);void 0===r&&(r=Vm(e.buildFunctionNode(t)),i.set(t,r)),e.addInclude(r);const s=n?function(e){let t;Hm(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(n):null;l=Vm(r.call(s))}else{const i=new Proxy(e,{get:(e,t,n)=>{let i;return i=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,n),i}}),r=n?function(e){let t=0;return Hm(e),new Proxy(e,{get:(n,i,r)=>{let s;if("length"===i)return s=e.length,s;if(Symbol.iterator===i)s=function*(){for(const t of e)yield Vm(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const n=e[0];s=void 0===n[i]?n[t++]:Reflect.get(n,i,r)}else e[0]instanceof Qf&&(s=void 0===e[i]?e[t++]:Reflect.get(e,i,r));else s=Reflect.get(n,i,r);s=Vm(s)}return s}})}(n):null,s=Array.isArray(n)?n.length>0:null!==n,a=t.jsFunc,o=s||a.length>1?a(r,i):a(i);l=Vm(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(i[s]=l),l}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),n=e.getSubBuildOutput(this);return t[n]=t[n]||this.setupOutput(e),t[n].subBuild=e.getClosestSubBuild(this),t[n]}build(e,t=null){let n=null;const i=e.getBuildStage(),r=e.getNodeProperties(this),s=e.getSubBuildOutput(this),a=this.getOutputNode(e),o=e.fnCall;if(e.fnCall=this,"setup"===i){const t=e.getSubBuildProperty("initialized",this);if(!0!==r[t]&&(r[t]=!0,r[s]=this.getOutputNode(e),r[s].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const n=e.getDataFromNode(t,"any");n.subBuilds=n.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)n.subBuilds.add(e)}n=r[s]}else"analyze"===i?a.build(e,t):"generate"===i&&(n=a.build(e,t)||"");return e.fnCall=o,n}}class wm extends Qf{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new Em(this,e)}setup(){return this.call()}}const Am=[!1,!0],Rm=[0,1,2,3],Cm=[-1,-2],Nm=[.5,1.5,1/3,1e-6,1e6,Math.PI,2*Math.PI,1/Math.PI,2/Math.PI,1/(2*Math.PI),Math.PI/2],Pm=new Map;for(const e of Am)Pm.set(e,new um(e));const Lm=new Map;for(const e of Rm)Lm.set(e,new um(e,"uint"));const Dm=new Map([...Lm].map(e=>new um(e.value,"int")));for(const e of Cm)Dm.set(e,new um(e,"int"));const Im=new Map([...Dm].map(e=>new um(e.value)));for(const e of Nm)Im.set(e,new um(e));for(const e of Nm)Im.set(-e,new um(-e));const Um={bool:Pm,uint:Lm,ints:Dm,float:Im},Fm=new Map([...Pm,...Im]),Om=(e,t)=>Fm.has(e)?Fm.get(e):!0===e.isNode?e:new um(e,t),Bm=function(e,t=null){return(...n)=>{for(const t of n)if(void 0===t)return qt(`TSL: Invalid parameter for the type "${e}".`,new Rf),new um(0,e);if((0===n.length||!["bool","float","int","uint"].includes(e)&&n.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(n=[Of(e,...n)]),1===n.length&&null!==t&&t.has(n[0]))return Gm(t.get(n[0]));if(1===n.length){const t=Om(n[0],e);return t.nodeType===e?Gm(t):Gm(new em(t,e))}const i=n.map(e=>Om(e));return Gm(new nm(i,e))}},km=e=>"object"==typeof e&&null!==e?e.value:e;function zm(e,t){return new wm(e,t)}const Vm=(e,t=null)=>function(e,t=null){const n=Ff(e);return"node"===n?e:null===t&&("float"===n||"boolean"===n)||n&&"shader"!==n&&"string"!==n?Vm(Om(e,t)):"shader"===n?e.isFn?e:Km(e):e}(e,t),Gm=(e,t=null)=>Vm(e,t).toVarIntent(),Hm=(e,t=null)=>new xm(e,t),jm=(e,t=null)=>new Tm(e,t),Wm=(e,t=null,n=null,i=null)=>new Sm(e,t,n,i),$m=(e,...t)=>new Mm(e,...t),Xm=(e,t=null,n=null,i={})=>new Sm(e,t,n,{...i,intent:!0});let qm=0;class Ym extends Qf{constructor(e,t=null){super();let n=null;null!==t&&("object"==typeof t?n=t.return:("string"==typeof t?n=t:qt("TSL: Invalid layout type.",new Rf),t=null)),this.shaderNode=new zm(e,n),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const n={name:"fn"+qm++,type:t,inputs:[]};for(const t in e)"return"!==t&&n.inputs.push({name:t,type:e[t]});e=n}return this.shaderNode.setLayout(e),this}getNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return qt('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function Km(e,t=null){const n=new Ym(e,t);return new Proxy(()=>{},{apply:(e,t,i)=>n.call(...i),get:(e,t,i)=>Reflect.get(n,t,i),set:(e,t,i,r)=>Reflect.set(n,t,i,r)})}const Zm=e=>{hm=e},Qm=()=>hm,Jm=(...e)=>hm.If(...e);function eg(e){return hm&&hm.addToStack(e),e}pm("toStack",eg);const tg=new Bm("color"),ng=new Bm("float",Um.float),ig=new Bm("int",Um.ints),rg=new Bm("uint",Um.uint),sg=new Bm("bool",Um.bool),ag=new Bm("vec2"),og=new Bm("ivec2"),lg=new Bm("uvec2"),ug=new Bm("bvec2"),cg=new Bm("vec3"),hg=new Bm("ivec3"),dg=new Bm("uvec3"),pg=new Bm("bvec3"),fg=new Bm("vec4"),mg=new Bm("ivec4"),gg=new Bm("uvec4"),_g=new Bm("bvec4"),vg=new Bm("mat2"),yg=new Bm("mat3"),bg=new Bm("mat4");pm("toColor",tg),pm("toFloat",ng),pm("toInt",ig),pm("toUint",rg),pm("toBool",sg),pm("toVec2",ag),pm("toIVec2",og),pm("toUVec2",lg),pm("toBVec2",ug),pm("toVec3",cg),pm("toIVec3",hg),pm("toUVec3",dg),pm("toBVec3",pg),pm("toVec4",fg),pm("toIVec4",mg),pm("toUVec4",gg),pm("toBVec4",_g),pm("toMat2",vg),pm("toMat3",yg),pm("toMat4",bg);pm("element",Wm(Jf).setParameterLength(2)),pm("convert",(e,t)=>new em(Vm(e),t)),pm("append",e=>(Xt("TSL: .append() has been renamed to .toStack().",new Rf),eg(e)));class xg extends Qf{static get type(){return"PropertyNode"}constructor(e,t=null,n=!1){super(e),this.name=t,this.varying=n,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return Nf(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Tg=(e,t)=>new xg(e,t),Sg=(e,t)=>new xg(e,t,!0),Mg=$m(xg,"vec4","DiffuseColor"),Eg=$m(xg,"vec3","DiffuseContribution"),wg=$m(xg,"vec3","EmissiveColor"),Ag=$m(xg,"float","Roughness"),Rg=$m(xg,"float","Metalness"),Cg=$m(xg,"float","Clearcoat"),Ng=$m(xg,"float","ClearcoatRoughness"),Pg=$m(xg,"vec3","Sheen"),Lg=$m(xg,"float","SheenRoughness"),Dg=$m(xg,"float","Iridescence"),Ig=$m(xg,"float","IridescenceIOR"),Ug=$m(xg,"float","IridescenceThickness"),Fg=$m(xg,"float","AlphaT"),Og=$m(xg,"float","Anisotropy"),Bg=$m(xg,"vec3","AnisotropyT"),kg=$m(xg,"vec3","AnisotropyB"),zg=$m(xg,"color","SpecularColor"),Vg=$m(xg,"color","SpecularColorBlended"),Gg=$m(xg,"float","SpecularF90"),Hg=$m(xg,"float","Shininess"),jg=$m(xg,"vec4","Output"),Wg=$m(xg,"float","dashSize"),$g=$m(xg,"float","gapSize"),Xg=$m(xg,"float","IOR"),qg=$m(xg,"float","Transmission"),Yg=$m(xg,"float","Thickness"),Kg=$m(xg,"float","AttenuationDistance"),Zg=$m(xg,"color","AttenuationColor"),Qg=$m(xg,"float","Dispersion");class Jg extends Qf{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1){super("string"),this.name=e,this.shared=t,this.order=n,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const e_=e=>new Jg(e),t_=(e,t=0)=>new Jg(e,!0,t),n_=t_("frame"),i_=t_("render"),r_=e_("object");class s_ extends om{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=r_}setName(e){return this.name=e,this}label(e){return Xt('TSL: "label()" has been deprecated. Use "setName()" instead.',new Rf),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const n=e(t,this);void 0!==n&&(this.value=n)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const n=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const s=r.getInputType(e),a=e.getUniformFromNode(r,s,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let l=o;if("bool"===n){const t=e.getDataFromNode(this);let i=t.propertyName;if(void 0===i){const r=e.getVarFromNode(this,null,"bool");i=e.getPropertyName(r),t.propertyName=i,l=e.format(o,s,n),e.addLineFlowCode(`${i} = ${l}`,this)}l=i}return e.format(l,n,t)}}const a_=(e,t)=>{const n=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e);if(n===e&&(e=Of(n)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new s_(e,n)};class o_ extends tm{static get type(){return"ArrayNode"}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getArrayCount(){return this.count}getNodeType(e){return null===this.nodeType?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return null===this.nodeType?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}pm("toArray",(e,t)=>((...e)=>{let t;if(1===e.length){const n=e[0];t=new o_(null,n.length,n)}else{const n=e[0],i=e[1];t=new o_(n,i)}return Vm(t)})(Array(t).fill(e)));class l_ extends tm{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const n=e.getTypeLength(t.node.getNodeType(e));return Yf.join("").slice(0,n)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:n}=this,i=t.getScope();e.getDataFromNode(i).assign=!0;const r=e.getNodeProperties(this);r.sourceNode=n,r.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:n,sourceNode:i}=e.getNodeProperties(this),r=this.needsSplitAssign(e),s=n.build(e),a=n.getNodeType(e),o=i.build(e,a),l=i.getNodeType(e),u=e.getDataFromNode(this);let c;if(!0===u.initialized)"void"!==t&&(c=s);else if(r){const i=e.getVarFromNode(this,null,a),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${o}`,this);const l=n.node,u=l.node.context({assign:!0}).build(e);for(let t=0;t<l.components.length;t++){const n=l.components[t];e.addLineFlowCode(`${u}.${n} = ${r}[ ${t} ]`,this)}"void"!==t&&(c=s)}else c=`${s} = ${o}`,"void"!==t&&"void"!==l||(e.addLineFlowCode(c,this),"void"!==t&&(c=s));return u.initialized=!0,e.format(c,a,t)}}pm("assign",Wm(l_).setParameterLength(2));class u_ extends tm{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],n=this.functionNode,i=n.getInputs(e),r=this.parameters,s=(t,n)=>{const i=n.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r)){if(r.length>i.length)qt("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),r.length=i.length;else if(r.length<i.length)for(qt("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<i.length;)r.push(ng(0));for(let e=0;e<r.length;e++)t.push(s(r[e],i[e]))}else for(const e of i){const n=r[e.name];void 0!==n?t.push(s(n,e)):(qt(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(s(ng(0),e)))}return`${n.build(e,"property")}( ${t.join(", ")} )`}}pm("call",(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?jm(t):Hm(t[0]),new u_(Vm(e),t)));const c_={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class h_ extends tm{static get type(){return"OperatorNode"}constructor(e,t,n,...i){if(super(),i.length>0){let r=new h_(e,t,n);for(let t=0;t<i.length-1;t++)r=new h_(e,r,i[t]);t=r,n=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=n,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(c_[this.op],t)}getNodeType(e,t=null){const n=this.op,i=this.aNode,r=this.bNode,s=i.getNodeType(e),a=r?r.getNodeType(e):null;if("void"===s||"void"===a)return t||"void";if("%"===n)return s;if("~"===n||"&"===n||"|"===n||"^"===n||">>"===n||"<<"===n)return e.getIntegerType(s);if("!"===n||"&&"===n||"||"===n||"^^"===n)return"bool";if("=="===n||"!="===n||"<"===n||">"===n||"<="===n||">="===n){const t=Math.max(e.getTypeLength(s),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(s)){if("float"===a)return s;if(e.isVector(a))return e.getVectorFromMatrix(s);if(e.isMatrix(a))return s}else if(e.isMatrix(a)){if("float"===s)return a;if(e.isVector(s))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(s)?a:s}generate(e,t){const n=this.op,{aNode:i,bNode:r}=this,s=this.getNodeType(e,t);let a=null,o=null;"void"!==s?(a=i.getNodeType(e),o=r?r.getNodeType(e):null,"<"===n||">"===n||"<="===n||">="===n||"=="===n||"!="===n?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===n||"<<"===n?(a=s,o=e.changeComponentType(o,"uint")):"%"===n?(a=s,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=s):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=s:o=s):a=o=s;const l=i.build(e,a),u=r?r.build(e,o):null,c=e.getFunctionOperator(n);if("void"!==t){const i=e.renderer.coordinateSystem===Ft;if("=="===n||"!="===n||"<"===n||">"===n||"<="===n||">="===n)return i&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} ${n} ${u} )`,s,t);if("%"===n)return e.isInteger(o)?e.format(`( ${l} % ${u} )`,s,t):e.format(`${this.getOperatorMethod(e,s)}( ${l}, ${u} )`,s,t);if("!"===n||"~"===n)return e.format(`(${n}${l})`,a,t);if(c)return e.format(`${c}( ${l}, ${u} )`,s,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${u} ${n} ${l} )`,s,t);if("float"===a&&e.isMatrix(o))return e.format(`${l} ${n} ${u}`,s,t);{let r=`( ${l} ${n} ${u} )`;return!i&&"bool"===s&&e.isVector(a)&&e.isVector(o)&&(r=`all${r}`),e.format(r,s,t)}}if("void"!==a)return c?e.format(`${c}( ${l}, ${u} )`,s,t):e.isMatrix(a)&&"float"===o?e.format(`${u} ${n} ${l}`,s,t):e.format(`${l} ${n} ${u}`,s,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const d_=Xm(h_,"+").setParameterLength(2,1/0).setName("add"),p_=Xm(h_,"-").setParameterLength(2,1/0).setName("sub"),f_=Xm(h_,"*").setParameterLength(2,1/0).setName("mul"),m_=Xm(h_,"/").setParameterLength(2,1/0).setName("div"),g_=Xm(h_,"%").setParameterLength(2).setName("mod"),__=Xm(h_,"==").setParameterLength(2).setName("equal"),v_=Xm(h_,"!=").setParameterLength(2).setName("notEqual"),y_=Xm(h_,"<").setParameterLength(2).setName("lessThan"),b_=Xm(h_,">").setParameterLength(2).setName("greaterThan"),x_=Xm(h_,"<=").setParameterLength(2).setName("lessThanEqual"),T_=Xm(h_,">=").setParameterLength(2).setName("greaterThanEqual"),S_=Xm(h_,"&&").setParameterLength(2,1/0).setName("and"),M_=Xm(h_,"||").setParameterLength(2,1/0).setName("or"),E_=Xm(h_,"!").setParameterLength(1).setName("not"),w_=Xm(h_,"^^").setParameterLength(2).setName("xor"),A_=Xm(h_,"&").setParameterLength(2).setName("bitAnd"),R_=Xm(h_,"~").setParameterLength(1).setName("bitNot"),C_=Xm(h_,"|").setParameterLength(2).setName("bitOr"),N_=Xm(h_,"^").setParameterLength(2).setName("bitXor"),P_=Xm(h_,"<<").setParameterLength(2).setName("shiftLeft"),L_=Xm(h_,">>").setParameterLength(2).setName("shiftRight"),D_=Km(([e])=>(e.addAssign(1),e)),I_=Km(([e])=>(e.subAssign(1),e)),U_=Km(([e])=>{const t=ig(e).toConst();return e.addAssign(1),t}),F_=Km(([e])=>{const t=ig(e).toConst();return e.subAssign(1),t});pm("add",d_),pm("sub",p_),pm("mul",f_),pm("div",m_),pm("mod",g_),pm("equal",__),pm("notEqual",v_),pm("lessThan",y_),pm("greaterThan",b_),pm("lessThanEqual",x_),pm("greaterThanEqual",T_),pm("and",S_),pm("or",M_),pm("not",E_),pm("xor",w_),pm("bitAnd",A_),pm("bitNot",R_),pm("bitOr",C_),pm("bitXor",N_),pm("shiftLeft",P_),pm("shiftRight",L_),pm("incrementBefore",D_),pm("decrementBefore",I_),pm("increment",U_),pm("decrement",F_);pm("modInt",(e,t)=>(Xt('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new Rf),g_(ig(e),ig(t))));class O_ extends tm{static get type(){return"MathNode"}constructor(e,t,n=null,i=null){if(super(),(e===O_.MAX||e===O_.MIN)&&arguments.length>3){let r=new O_(e,t,n);for(let t=2;t<arguments.length-1;t++)r=new O_(e,r,arguments[t]);t=r,n=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=n,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(i)?0:e.getTypeLength(i);return r>s&&r>a?t:s>a?n:a>r?i:t}getNodeType(e){const t=this.method;return t===O_.LENGTH||t===O_.DISTANCE||t===O_.DOT?"float":t===O_.CROSS?"vec3":t===O_.ALL||t===O_.ANY?"bool":t===O_.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:n,method:i}=this;let r=null;if(i===O_.ONE_MINUS)r=p_(1,t);else if(i===O_.RECIPROCAL)r=m_(1,t);else if(i===O_.DIFFERENCE)r=av(p_(t,n));else if(i===O_.TRANSFORM_DIRECTION){let i=t,s=n;e.isMatrix(i.getNodeType(e))?s=fg(cg(s),0):i=fg(cg(i),0);const a=f_(i,s).xyz;r=Q_(a)}return null!==r?r:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let n=this.method;const i=this.getNodeType(e),r=this.getInputType(e),s=this.aNode,a=this.bNode,o=this.cNode,l=e.renderer.coordinateSystem;if(n===O_.NEGATE)return e.format("( - "+s.build(e,r)+" )",i,t);{const u=[];return n===O_.CROSS?u.push(s.build(e,i),a.build(e,i)):l===Ft&&n===O_.STEP?u.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":r),a.build(e,r)):l!==Ft||n!==O_.MIN&&n!==O_.MAX?n===O_.REFRACT?u.push(s.build(e,r),a.build(e,r),o.build(e,"float")):n===O_.MIX?u.push(s.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(l===Ot&&n===O_.ATAN&&null!==a&&(n="atan2"),"fragment"===e.shaderStage||n!==O_.DFDX&&n!==O_.DFDY||(Xt(`TSL: '${n}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),n="/*"+n+"*/"),u.push(s.build(e,r)),null!==a&&u.push(a.build(e,r)),null!==o&&u.push(o.build(e,r))):u.push(s.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)),e.format(`${e.getMethod(n,i)}( ${u.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}O_.ALL="all",O_.ANY="any",O_.RADIANS="radians",O_.DEGREES="degrees",O_.EXP="exp",O_.EXP2="exp2",O_.LOG="log",O_.LOG2="log2",O_.SQRT="sqrt",O_.INVERSE_SQRT="inversesqrt",O_.FLOOR="floor",O_.CEIL="ceil",O_.NORMALIZE="normalize",O_.FRACT="fract",O_.SIN="sin",O_.COS="cos",O_.TAN="tan",O_.ASIN="asin",O_.ACOS="acos",O_.ATAN="atan",O_.ABS="abs",O_.SIGN="sign",O_.LENGTH="length",O_.NEGATE="negate",O_.ONE_MINUS="oneMinus",O_.DFDX="dFdx",O_.DFDY="dFdy",O_.ROUND="round",O_.RECIPROCAL="reciprocal",O_.TRUNC="trunc",O_.FWIDTH="fwidth",O_.TRANSPOSE="transpose",O_.DETERMINANT="determinant",O_.INVERSE="inverse",O_.EQUALS="equals",O_.MIN="min",O_.MAX="max",O_.STEP="step",O_.REFLECT="reflect",O_.DISTANCE="distance",O_.DIFFERENCE="difference",O_.DOT="dot",O_.CROSS="cross",O_.POW="pow",O_.TRANSFORM_DIRECTION="transformDirection",O_.MIX="mix",O_.CLAMP="clamp",O_.REFRACT="refract",O_.SMOOTHSTEP="smoothstep",O_.FACEFORWARD="faceforward";const B_=ng(1e-6),k_=ng(Math.PI),z_=Xm(O_,O_.ALL).setParameterLength(1),V_=Xm(O_,O_.ANY).setParameterLength(1),G_=Xm(O_,O_.RADIANS).setParameterLength(1),H_=Xm(O_,O_.DEGREES).setParameterLength(1),j_=Xm(O_,O_.EXP).setParameterLength(1),W_=Xm(O_,O_.EXP2).setParameterLength(1),$_=Xm(O_,O_.LOG).setParameterLength(1),X_=Xm(O_,O_.LOG2).setParameterLength(1),q_=Xm(O_,O_.SQRT).setParameterLength(1),Y_=Xm(O_,O_.INVERSE_SQRT).setParameterLength(1),K_=Xm(O_,O_.FLOOR).setParameterLength(1),Z_=Xm(O_,O_.CEIL).setParameterLength(1),Q_=Xm(O_,O_.NORMALIZE).setParameterLength(1),J_=Xm(O_,O_.FRACT).setParameterLength(1),ev=Xm(O_,O_.SIN).setParameterLength(1),tv=Xm(O_,O_.COS).setParameterLength(1),nv=Xm(O_,O_.TAN).setParameterLength(1),iv=Xm(O_,O_.ASIN).setParameterLength(1),rv=Xm(O_,O_.ACOS).setParameterLength(1),sv=Xm(O_,O_.ATAN).setParameterLength(1,2),av=Xm(O_,O_.ABS).setParameterLength(1),ov=Xm(O_,O_.SIGN).setParameterLength(1),lv=Xm(O_,O_.LENGTH).setParameterLength(1),uv=Xm(O_,O_.NEGATE).setParameterLength(1),cv=Xm(O_,O_.ONE_MINUS).setParameterLength(1),hv=Xm(O_,O_.DFDX).setParameterLength(1),dv=Xm(O_,O_.DFDY).setParameterLength(1),pv=Xm(O_,O_.ROUND).setParameterLength(1),fv=Xm(O_,O_.RECIPROCAL).setParameterLength(1),mv=Xm(O_,O_.TRUNC).setParameterLength(1),gv=Xm(O_,O_.FWIDTH).setParameterLength(1),_v=Xm(O_,O_.TRANSPOSE).setParameterLength(1),vv=Xm(O_,O_.DETERMINANT).setParameterLength(1),yv=Xm(O_,O_.INVERSE).setParameterLength(1),bv=Xm(O_,O_.MIN).setParameterLength(2,1/0),xv=Xm(O_,O_.MAX).setParameterLength(2,1/0),Tv=Xm(O_,O_.STEP).setParameterLength(2),Sv=Xm(O_,O_.REFLECT).setParameterLength(2),Mv=Xm(O_,O_.DISTANCE).setParameterLength(2),Ev=Xm(O_,O_.DIFFERENCE).setParameterLength(2),wv=Xm(O_,O_.DOT).setParameterLength(2),Av=Xm(O_,O_.CROSS).setParameterLength(2),Rv=Xm(O_,O_.POW).setParameterLength(2),Cv=e=>f_(e,e),Nv=e=>f_(e,e,e,e),Pv=Xm(O_,O_.TRANSFORM_DIRECTION).setParameterLength(2),Lv=e=>wv(e,e),Dv=Xm(O_,O_.MIX).setParameterLength(3),Iv=(e,t=0,n=1)=>new O_(O_.CLAMP,Vm(e),Vm(t),Vm(n)),Uv=e=>Iv(e),Fv=Xm(O_,O_.REFRACT).setParameterLength(3),Ov=Xm(O_,O_.SMOOTHSTEP).setParameterLength(3),Bv=Xm(O_,O_.FACEFORWARD).setParameterLength(3),kv=Km(([e])=>{const t=wv(e.xy,ag(12.9898,78.233)),n=g_(t,k_);return J_(ev(n).mul(43758.5453))});pm("all",z_),pm("any",V_),pm("radians",G_),pm("degrees",H_),pm("exp",j_),pm("exp2",W_),pm("log",$_),pm("log2",X_),pm("sqrt",q_),pm("inverseSqrt",Y_),pm("floor",K_),pm("ceil",Z_),pm("normalize",Q_),pm("fract",J_),pm("sin",ev),pm("cos",tv),pm("tan",nv),pm("asin",iv),pm("acos",rv),pm("atan",sv),pm("abs",av),pm("sign",ov),pm("length",lv),pm("lengthSq",Lv),pm("negate",uv),pm("oneMinus",cv),pm("dFdx",hv),pm("dFdy",dv),pm("round",pv),pm("reciprocal",fv),pm("trunc",mv),pm("fwidth",gv),pm("min",bv),pm("max",xv),pm("step",(e,t)=>Tv(t,e)),pm("reflect",Sv),pm("distance",Mv),pm("dot",wv),pm("cross",Av),pm("pow",Rv),pm("pow2",Cv),pm("pow3",e=>f_(e,e,e)),pm("pow4",Nv),pm("transformDirection",Pv),pm("mix",(e,t,n)=>Dv(t,n,e)),pm("clamp",Iv),pm("refract",Fv),pm("smoothstep",(e,t,n)=>Ov(t,n,e)),pm("faceForward",Bv),pm("difference",Ev),pm("saturate",Uv),pm("cbrt",e=>f_(ov(e),Rv(av(e),1/3))),pm("transpose",_v),pm("determinant",vv),pm("inverse",yv),pm("rand",kv);class zv extends Qf{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}getNodeType(e){const{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const i=t.getNodeType(e);if(null!==n){const t=n.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(i))return t}return i}setup(e){const t=this.condNode,n=this.ifNode.isolate(),i=this.elseNode?this.elseNode.isolate():null,r=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const s=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=s?n:n.context({nodeBlock:n}),a.elseNode=i?s?i:i.context({nodeBlock:i}):null}generate(e,t){const n=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:s,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,l="void"!==t,u=l?Tg(n).build(e):"";i.nodeProperty=u;const c=r.build(e,"bool");if(e.context.uniformFlow&&null!==a){const i=s.build(e,n),r=a.build(e,n),o=e.getTernary(c,i,r);return e.format(o,n,t)}e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let h=s.build(e,n);if(h&&(l?h=u+" = "+h+";":(h="return "+h+";",null===o&&(Xt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),h="// "+h))),e.removeFlowTab().addFlowCode(e.tab+"\t"+h+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,n);t&&(l?t=u+" = "+t+";":(t="return "+t+";",null===o&&(Xt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(u,n,t)}}const Vv=Wm(zv).setParameterLength(2,3);pm("select",Vv);class Gv extends Qf{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const n=e.addContext(this.value),i=this.node.build(e,t);return e.setContext(n),i}}const Hv=(e=null,t={})=>{let n=e;return null!==n&&!0===n.isNode||(t=n||t,n=null),new Gv(n,t)},jv=(e,t)=>Hv(e,{nodeName:t});pm("context",Hv),pm("label",function(e,t){return Xt('TSL: "label()" has been deprecated. Use "setName()" instead.'),jv(e,t)}),pm("uniformFlow",e=>Hv(e,{uniformFlow:!0})),pm("setName",jv),pm("builtinShadowContext",(e,t,n)=>function(e,t,n=null){return Hv(n,{getShadow:({light:n,shadowColorNode:i})=>t===n?i.mul(e):i})}(t,n,e)),pm("builtinAOContext",(e,t)=>function(e,t=null){return Hv(t,{getAO:(t,{material:n})=>!0===n.transparent?t:null!==t?t.mul(e):e})}(t,e));class Wv extends Qf{static get type(){return"VarNode"}constructor(e,t=null,n=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=n,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const n=t.getBaseStack();e?n.addToStackBefore(this):n.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:n,readOnly:i}=this,{renderer:r}=e,s=!0===r.backend.isWebGPUBackend;let a=!1,o=!1;i&&(a=e.isDeterministic(t),o=s?i:a);const l=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&qt('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const u=e.getVectorType(l),c=t.build(e,u),h=e.getVarFromNode(this,n,u,void 0,o),d=e.getPropertyName(h);let p=d;if(o)if(s)p=a?`const ${d}`:`let ${d}`;else{const n=t.getArrayCount(e);p=`const ${e.getVar(h.type,d,n)}`}return e.addLineFlowCode(`${p} = ${c}`,this),d}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const $v=Wm(Wv);pm("toVar",(e,t=null)=>$v(e,t).toStack()),pm("toConst",(e,t=null)=>$v(e,t,!0).toStack()),pm("toVarIntent",e=>$v(e).setIntent(!0).toStack());class Xv extends Qf{static get type(){return"SubBuild"}constructor(e,t,n=null){super(n),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const n=this.node.build(e,...t);return e.removeSubBuild(),n}}const qv=(e,t,n=null)=>new Xv(Vm(e),t,n);class Yv extends Qf{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=qv(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let n=t.varying;if(void 0===n){const i=this.name,r=this.getNodeType(e),s=this.interpolationType,a=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,i,r,s,a),t.node=qv(this.node,"VERTEX")}return n.needsInterpolation||(n.needsInterpolation="fragment"===e.shaderStage),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(kf,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(kf,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),n=e.getNodeProperties(this),i=this.setupVarying(e);if(void 0===n[t]){const r=this.getNodeType(e),s=e.getPropertyName(i,kf);e.flowNodeFromShaderStage(kf,n.node,r,s),n[t]=s}return e.getPropertyName(i)}}const Kv=Wm(Yv).setParameterLength(1,2);pm("toVarying",Kv),pm("toVertexStage",e=>Kv(e));const Zv=Km(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),n=e.mul(.0773993808),i=e.lessThanEqual(.04045);return Dv(t,n,i)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Qv=Km(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),n=e.mul(12.92),i=e.lessThanEqual(.0031308);return Dv(t,n,i)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Jv="WorkingColorSpace";class ey extends tm{static get type(){return"ColorSpaceNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.source=t,this.target=n}resolveColorSpace(e,t){return t===Jv?bn.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let r=t;return!1!==bn.enabled&&n!==i&&n&&i?(bn.getTransfer(n)===St&&(r=fg(Zv(r.rgb),r.a)),bn.getPrimaries(n)!==bn.getPrimaries(i)&&(r=fg(yg(bn._getMatrix(new mn,n,i)).mul(r.rgb),r.a)),bn.getTransfer(i)===St&&(r=fg(Qv(r.rgb),r.a)),r):r}}const ty=(e,t)=>new ey(Vm(e),t,Jv);pm("workingToColorSpace",(e,t)=>new ey(Vm(e),Jv,t)),pm("colorSpaceToWorking",ty);let ny=class extends Jf{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,n,i)}};class iy extends Qf{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=Hf}setGroup(e){return this.group=e,this}element(e){return new ny(this,Vm(e))}setNodeType(e){const t=a_(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;e<t.length;e++)n=n[t[e]];return n}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}class ry extends iy{static get type(){return"RendererReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.renderer=n,this.setGroup(i_)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const sy=(e,t,n=null)=>new ry(e,t,n);class ay extends tm{static get type(){return"ToneMappingNode"}constructor(e,t=oy,n=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return Lf(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,n=this._toneMapping;if(0===n)return t;let i=null;const r=e.renderer.library.getToneMappingFunction(n);return null!==r?i=fg(r(t.rgb,this.exposureNode),t.a):(qt("ToneMappingNode: Unsupported Tone Mapping configuration.",n),i=t),i}}const oy=sy("toneMappingExposure","float");pm("toneMapping",(e,t,n)=>((e,t,n)=>new ay(e,Vm(t),Vm(n)))(t,n,e));const ly=new WeakMap;function uy(e,t){let n=ly.get(e);return void 0===n&&(n=new yr(e,t),ly.set(e,n)),n}class cy extends om{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=i,this.usage=Dt,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),n=e.getTypeLength(t),i=this.value,r=this.bufferStride||n,s=this.bufferOffset;let a;a=!0===i.isInterleavedBuffer?i:!0===i.isBufferAttribute?uy(i.array,r):uy(i,r);const o=new xr(a,n,s);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(n);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=Kv(this).build(e,t)}return r}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function hy(e,t=null,n=0,i=0,r=35044,s=!1){return"mat3"===t||null===t&&9===e.itemSize?yg(new cy(e,"vec3",9,0).setUsage(r).setInstanced(s),new cy(e,"vec3",9,3).setUsage(r).setInstanced(s),new cy(e,"vec3",9,6).setUsage(r).setInstanced(s)):"mat4"===t||null===t&&16===e.itemSize?bg(new cy(e,"vec4",16,0).setUsage(r).setInstanced(s),new cy(e,"vec4",16,4).setUsage(r).setInstanced(s),new cy(e,"vec4",16,8).setUsage(r).setInstanced(s),new cy(e,"vec4",16,12).setUsage(r).setInstanced(s)):new cy(e,t,n,i).setUsage(r)}const dy=(e,t=null,n=0,i=0)=>hy(e,t,n,i),py=(e,t=null,n=0,i=0)=>hy(e,t,n,i,Dt,!0),fy=(e,t=null,n=0,i=0)=>hy(e,t,n,i,It,!0);pm("toAttribute",e=>dy(e.value));class my extends Qf{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.version=1,this.name="",this.updateBeforeType=Hf,this.onInitFunction=null}setCount(e){return this.count=e,this}getCount(){return this.count}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return Xt('TSL: "label()" has been deprecated. Use "setName()" instead.',new Rf),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:n}=e;if("compute"===n){const t=this.computeNode.build(e,"void");""!==t&&e.addLineFlowCode(t,this)}else{const n=e.getNodeProperties(this).outputComputeNode;if(n)return n.build(e,t)}}}const gy=(e,t=[64])=>{(0===t.length||t.length>3)&&qt("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Rf);for(let e=0;e<t.length;e++){const n=t[e];("number"!=typeof n||n<=0||!Number.isInteger(n))&&qt(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`,new Rf)}for(;t.length<3;)t.push(1);return new my(Vm(e),t)};pm("compute",(e,t,n)=>gy(e,n).setCount(t)),pm("computeKernel",gy);class _y extends Qf{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}getNodeType(e){const t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const n=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(n),r}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const vy=e=>new _y(Vm(e));pm("cache",function(e,t=!0){return Xt('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),vy(e).setParent(t)}),pm("isolate",vy);class yy extends Qf{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}pm("bypass",Wm(yy).setParameterLength(2));class by extends Qf{static get type(){return"RemapNode"}constructor(e,t,n,i=ng(0),r=ng(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=n,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:n,outLowNode:i,outHighNode:r,doClamp:s}=this;let a=e.sub(t).div(n.sub(t));return!0===s&&(a=a.clamp()),a.mul(r.sub(i)).add(i)}}const xy=Wm(by,null,null,{doClamp:!1}).setParameterLength(3,5),Ty=Wm(by).setParameterLength(3,5);pm("remap",xy),pm("remapClamp",Ty);class Sy extends Qf{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),i=this.snippet;if("void"!==n)return e.format(i,n,t);e.addLineFlowCode(i,this)}}const My=Wm(Sy).setParameterLength(1,2);pm("discard",e=>(e?Vv(e,My("discard")):My("discard")).toStack());class Ey extends tm{static get type(){return"RenderOutputNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const n=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||yt;return 0!==n&&(t=t.toneMapping(n)),i!==yt&&i!==bn.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}pm("renderOutput",(e,t=null,n=null)=>new Ey(Vm(e),t,n));class wy extends tm{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,n=this.node.build(e);if(null!==t)t(e,n);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(t.length);let r="";r+="// #"+t+"#\n",r+=e.flow.code.replace(/^\t/gm,"")+"\n",r+="/* ... */ "+n+" /* ... */\n",r+="// #"+i+"#\n",Wt(r)}return n}}pm("debug",(e,t=null)=>new wy(Vm(e),t).toStack());class Ay{constructor(){this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class Ry extends Qf{static get type(){return"InspectorNode"}constructor(e,t="",n=null){super(),this.node=e,this.name=t,this.callback=n,this.updateType=Vf,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}getNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return!0===e.context.inspector&&null!==this.callback&&(t=this.callback(t)),!0!==e.renderer.backend.isWebGPUBackend&&e.renderer.inspector.constructor!==Ay&&Yt('TSL: ".toInspector()" is only available with WebGPU.'),t}}pm("toInspector",function(e,t="",n=null){return(e=Vm(e)).before(new Ry(e,t,n))});class Cy extends Qf{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const i=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),n=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),s=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(s.name,r,n);return Kv(this).build(e,n)}return Xt(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(n)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const Ny=(e,t=null)=>new Cy(e,t),Py=(e=0)=>Ny("uv"+(e>0?e:""),"vec2");class Ly extends Qf{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const n=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${i} )`,this.getNodeType(e),t)}}const Dy=Wm(Ly).setParameterLength(1,2);class Iy extends s_{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Vf}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&void 0!==n.width){const{width:e,height:t}=n;this.value=Math.log2(Math.max(e,t))}}}const Uy=Wm(Iy).setParameterLength(1);class Fy extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const Oy=new Nn;class By extends s_{static get type(){return"TextureNode"}constructor(e=Oy,t=null,n=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=zf,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===ye?"uvec4":this.value.type===ve?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Py(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=a_(this.value.matrix)),this._matrixUniform.mul(cg(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=a_(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(ig(Dy(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const n=this.value;if(!n||!0!==n.isTexture)throw new Fy("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const i=Km(()=>{let t=this.uvNode;return null!==t&&!0!==e.context.forceUVContext||!e.context.getUV||(t=e.context.getUV(this,e)),t||(t=this.getDefaultUV()),!0===this.updateMatrix&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=null!==this._matrixUniform||null!==this._flipYUniform?Hf:zf,t})();let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this));let s=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(zt))s=this.compareNode;else{const e=n.compareFunction;null===e||e===wt||e===Rt||e===Ct||e===Pt?a=this.compareNode:(s=this.compareNode,Yt('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=s,t.compareStepNode=a,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,n,i,r,s,a,o,l){const u=this.value;let c;return c=r?e.generateTextureBias(u,t,n,r,s,l):o?e.generateTextureGrad(u,t,n,o,s,l):a?e.generateTextureCompare(u,t,n,a,s,l):!1===this.sampler?e.generateTextureLoad(u,t,n,i,s,l):i?e.generateTextureLevel(u,t,n,i,s,l):e.generateTexture(u,t,n,s,l),c}generate(e,t){const n=this.value,i=e.getNodeProperties(this),r=super.generate(e,"property");if(/^sampler/.test(t))return r+"_sampler";if(e.isReference(t))return r;{const s=e.getDataFromNode(this),a=this.getNodeType(e);let o=s.propertyName;if(void 0===o){const{uvNode:t,levelNode:l,biasNode:u,compareNode:c,compareStepNode:h,depthNode:d,gradNode:p,offsetNode:f}=i,m=this.generateUV(e,t),g=l?l.build(e,"float"):null,_=u?u.build(e,"float"):null,v=d?d.build(e,"int"):null,y=c?c.build(e,"float"):null,b=h?h.build(e,"float"):null,x=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,T=f?this.generateOffset(e,f):null,S=e.getVarFromNode(this);o=e.getPropertyName(S);let M=this.generateSnippet(e,r,m,g,_,v,y,x,T);if(null!==b){const t=n.compareFunction;M=t===Ct||t===Pt?Tv(My(M,a),My(b,"float")).build(e,a):Tv(My(b,"float"),My(M,a)).build(e,a)}e.addLineFlowCode(`${o} = ${M}`,this),s.snippet=M,s.propertyName=o}let l=o;return e.needsToWorkingColorSpace(n)&&(l=ty(My(l,a),n.colorSpace).setup(e).build(e,a)),e.format(l,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=Vm(e).mul(Uy(t)),t.referenceNode=this.getBase();const n=t.value;return!1===t.generateMipmaps&&(n&&!1===n.generateMipmaps||n.minFilter===le||n.magFilter===le)&&(Xt("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Vm(t)}level(e){const t=this.clone();return t.levelNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}size(e){return Dy(this,e)}bias(e){const t=this.clone();return t.biasNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}grad(e,t){const n=this.clone();return n.gradNode=[Vm(e),Vm(t)],n.referenceNode=this.getBase(),Vm(n)}depth(e){const t=this.clone();return t.depthNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}offset(e){const t=this.clone();return t.offsetNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix();const n=this._flipYUniform;null!==n&&(n.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const ky=Wm(By).setParameterLength(1,4).setName("texture"),zy=(e=Oy,t=null,n=null,i=null)=>{let r;return e&&!0===e.isTextureNode?(r=Vm(e.clone()),r.referenceNode=e.getBase(),null!==t&&(r.uvNode=Vm(t)),null!==n&&(r.levelNode=Vm(n)),null!==i&&(r.biasNode=Vm(i))):r=ky(e,t,n,i),r},Vy=(...e)=>zy(...e).setSampler(!1);class Gy extends s_{static get type(){return"BufferNode"}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Hy=(e,t,n)=>new Gy(e,t,n);class jy extends Jf{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),n=this.getNodeType(),i=this.node.getPaddedType();return e.format(t,i,n)}}class Wy extends Gy{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ff(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Gf,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,n=this.elementType;if("float"===n||"int"===n||"uint"===n)for(let n=0;n<e.length;n++){t[4*n]=e[n]}else if("color"===n)for(let n=0;n<e.length;n++){const i=4*n,r=e[n];t[i]=r.r,t[i+1]=r.g,t[i+2]=r.b||0}else if("mat2"===n)for(let n=0;n<e.length;n++){const i=4*n,r=e[n];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+3]=r.elements[3]}else if("mat3"===n)for(let n=0;n<e.length;n++){const i=16*n,r=e[n];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+4]=r.elements[3],t[i+5]=r.elements[4],t[i+6]=r.elements[5],t[i+8]=r.elements[6],t[i+9]=r.elements[7],t[i+10]=r.elements[8],t[i+15]=1}else if("mat4"===n)for(let n=0;n<e.length;n++){const i=16*n,r=e[n];for(let e=0;e<r.elements.length;e++)t[i+e]=r.elements[e]}else for(let n=0;n<e.length;n++){const i=4*n,r=e[n];t[i]=r.x,t[i+1]=r.y,t[i+2]=r.z||0,t[i+3]=r.w||0}}setup(e){const t=this.array.length,n=this.elementType;let i=Float32Array;const r=this.paddedType,s=e.getTypeLength(r);return"i"===n.charAt(0)&&(i=Int32Array),"u"===n.charAt(0)&&(i=Uint32Array),this.value=new i(t*s),this.bufferCount=t,this.bufferType=r,this.update(),super.setup(e)}element(e){return new jy(this,Vm(e))}}const $y=(e,t)=>new Wy(e,t);const Xy=Wm(class extends Qf{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);let qy,Yy;class Ky extends Qf{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}getNodeType(){return this.scope===Ky.DPR?"float":this.scope===Ky.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=zf;return this.scope!==Ky.SIZE&&this.scope!==Ky.VIEWPORT&&this.scope!==Ky.DPR||(e=Gf),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Ky.VIEWPORT?null!==t?Yy.copy(t.viewport):(e.getViewport(Yy),Yy.multiplyScalar(e.getPixelRatio())):this.scope===Ky.DPR?this._output.value=e.getPixelRatio():null!==t?(qy.width=t.width,qy.height=t.height):e.getDrawingBufferSize(qy)}setup(){const e=this.scope;let t=null;return t=e===Ky.SIZE?a_(qy||(qy=new cn)):e===Ky.VIEWPORT?a_(Yy||(Yy=new Pn)):e===Ky.DPR?a_(1):ag(eb.div(Jy)),this._output=t,t}generate(e){if(this.scope===Ky.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(Jy).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}Ky.COORDINATE="coordinate",Ky.VIEWPORT="viewport",Ky.SIZE="size",Ky.UV="uv",Ky.DPR="dpr";const Zy=$m(Ky,Ky.DPR),Qy=$m(Ky,Ky.UV),Jy=$m(Ky,Ky.SIZE),eb=$m(Ky,Ky.COORDINATE),tb=$m(Ky,Ky.VIEWPORT),nb=tb.zw;tb.xy;let ib=null,rb=null,sb=null,ab=null,ob=null,lb=null,ub=null,cb=null;const hb=a_(0,"uint").setName("u_cameraIndex").setGroup(t_("cameraIndex")).toVarying("v_cameraIndex"),db=a_("float").setName("cameraNear").setGroup(i_).onRenderUpdate(({camera:e})=>e.near),pb=a_("float").setName("cameraFar").setGroup(i_).onRenderUpdate(({camera:e})=>e.far),fb=Km(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.projectionMatrix);null===rb?rb=$y(n).setGroup(i_).setName("cameraProjectionMatrices"):rb.array=n,t=rb.element(e.isMultiViewCamera?Xy("gl_ViewID_OVR"):hb).toConst("cameraProjectionMatrix")}else null===ib&&(ib=a_(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(i_).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=ib;return t}).once()(),mb=Km(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.projectionMatrixInverse);null===ab?ab=$y(n).setGroup(i_).setName("cameraProjectionMatricesInverse"):ab.array=n,t=ab.element(e.isMultiViewCamera?Xy("gl_ViewID_OVR"):hb).toConst("cameraProjectionMatrixInverse")}else null===sb&&(sb=a_(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(i_).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=sb;return t}).once()(),gb=Km(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.matrixWorldInverse);null===lb?lb=$y(n).setGroup(i_).setName("cameraViewMatrices"):lb.array=n,t=lb.element(e.isMultiViewCamera?Xy("gl_ViewID_OVR"):hb).toConst("cameraViewMatrix")}else null===ob&&(ob=a_(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(i_).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=ob;return t}).once()(),_b=Km(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(let t=0,i=e.cameras.length;t<i;t++)n.push(new dn);null===cb?cb=$y(n).setGroup(i_).setName("cameraPositions").onRenderUpdate(({camera:e},t)=>{const n=e.cameras,i=t.array;for(let e=0,t=n.length;e<t;e++)i[e].setFromMatrixPosition(n[e].matrixWorld)}):cb.array=n,t=cb.element(e.isMultiViewCamera?Xy("gl_ViewID_OVR"):hb).toConst("cameraPosition")}else null===ub&&(ub=a_(new dn).setName("cameraPosition").setGroup(i_).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),t=ub;return t}).once()(),vb=new cr;class yb extends Qf{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Hf,this.uniformNode=new s_(null)}getNodeType(){const e=this.scope;return e===yb.WORLD_MATRIX?"mat4":e===yb.POSITION||e===yb.VIEW_POSITION||e===yb.DIRECTION||e===yb.SCALE?"vec3":e===yb.RADIUS?"float":void 0}update(e){const t=this.object3d,n=this.uniformNode,i=this.scope;if(i===yb.WORLD_MATRIX)n.value=t.matrixWorld;else if(i===yb.POSITION)n.value=n.value||new dn,n.value.setFromMatrixPosition(t.matrixWorld);else if(i===yb.SCALE)n.value=n.value||new dn,n.value.setFromMatrixScale(t.matrixWorld);else if(i===yb.DIRECTION)n.value=n.value||new dn,t.getWorldDirection(n.value);else if(i===yb.VIEW_POSITION){const i=e.camera;n.value=n.value||new dn,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(i.matrixWorldInverse)}else if(i===yb.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),vb.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),n.value=vb.radius}}generate(e){const t=this.scope;return t===yb.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===yb.POSITION||t===yb.VIEW_POSITION||t===yb.DIRECTION||t===yb.SCALE?this.uniformNode.nodeType="vec3":t===yb.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}yb.WORLD_MATRIX="worldMatrix",yb.POSITION="position",yb.SCALE="scale",yb.VIEW_POSITION="viewPosition",yb.DIRECTION="direction",yb.RADIUS="radius";class bb extends yb{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const xb=$m(bb,bb.WORLD_MATRIX),Tb=a_(new mn).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),Sb=Km(e=>e.context.modelViewMatrix||Mb).once()().toVar("modelViewMatrix"),Mb=gb.mul(xb),Eb=Km(e=>(e.context.isHighPrecisionModelViewMatrix=!0,a_("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),wb=Km(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return a_("mat3").onObjectUpdate(({object:e,camera:n})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),Ab=Km(e=>"fragment"!==e.shaderStage?(Yt("TSL: `clipSpace` is only available in fragment stage."),fg()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),Rb=Ny("position","vec3"),Cb=Rb.toVarying("positionLocal"),Nb=Rb.toVarying("positionPrevious"),Pb=Km(e=>xb.mul(Cb).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),Lb=Km(()=>Cb.transformDirection(xb).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Db=Km(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=mb.mul(Ab);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),Ib=Km(e=>{let t;return t=e.camera.isOrthographicCamera?cg(0,0,1):Db.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class Ub extends Qf{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return 1===t.side?"false":e.getFrontFacing()}}const Fb=ng($m(Ub)).mul(2).sub(1),Ob=Km(([e],{material:t})=>{const n=t.side;return 1===n?e=e.mul(-1):2===n&&(e=e.mul(Fb)),e}),Bb=Ny("normal","vec3"),kb=Km(e=>!1===e.geometry.hasAttribute("normal")?(Xt('TSL: Vertex attribute "normal" not found on geometry.'),cg(0,1,0)):Bb,"vec3").once()().toVar("normalLocal"),zb=Db.dFdx().cross(Db.dFdy()).normalize().toVar("normalFlat"),Vb=Km(e=>{let t;return t=e.isFlatShading()?zb:Xb(kb).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),Gb=Km(e=>{let t=Vb.transformDirection(gb);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Hb=Km(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=Vb,!0!==e.isFlatShading()&&(t=Ob(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),jb=Hb.transformDirection(gb).toVar("normalWorld"),Wb=Km(({subBuildFn:e,context:t})=>{let n;return n="NORMAL"===e||"VERTEX"===e?Hb:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),n},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),$b=Km(([e,t=xb])=>{const n=yg(t),i=e.div(cg(n[0].dot(n[0]),n[1].dot(n[1]),n[2].dot(n[2])));return n.mul(i).xyz}),Xb=Km(([e],t)=>{const n=t.context.modelNormalViewMatrix;if(n)return n.transformDirection(e);const i=Tb.mul(e);return gb.transformDirection(i)});Km(()=>(Xt('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Hb)).once(["NORMAL","VERTEX"])(),Km(()=>(Xt('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),jb)).once(["NORMAL","VERTEX"])(),Km(()=>(Xt('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Wb)).once(["NORMAL","VERTEX"])();const qb=new $n,Yb=new Fn,Kb=a_(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Zb=a_(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Qb=a_(new Fn).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const n=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return n?(qb.copy(n),Yb.makeRotationFromEuler(qb)):Yb.identity(),Yb}),Jb=Ib.negate().reflect(Hb),ex=Ib.negate().refract(Hb,Kb),tx=Jb.transformDirection(gb).toVar("reflectVector"),nx=ex.transformDirection(gb).toVar("reflectVector"),ix=new _s;class rx extends By{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,i=null){super(e,t,n,i),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===ee?tx:e.mapping===te?nx:(qt('CubeTextureNode: Mapping "%s" not supported.',e.mapping),cg(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return!0===n.isDepthTexture?e.renderer.coordinateSystem===Ot?cg(t.x,t.y.negate(),t.z):t:(e.renderer.coordinateSystem!==Ot&&n.isRenderTargetTexture||(t=cg(t.x.negate(),t.yz)),Qb.mul(t))}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const sx=Wm(rx).setParameterLength(1,4).setName("cubeTexture"),ax=(e=ix,t=null,n=null,i=null)=>{let r;return e&&!0===e.isCubeTextureNode?(r=Vm(e.clone()),r.referenceNode=e,null!==t&&(r.uvNode=Vm(t)),null!==n&&(r.levelNode=Vm(n)),null!==i&&(r.biasNode=Vm(i))):r=sx(e,t,n,i),r};class ox extends Jf{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,n,i)}}class lx extends Qf{static get type(){return"ReferenceNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=Hf}element(e){return new ox(this,Vm(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return Xt('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?Hy(null,e,this.count):Array.isArray(this.getValueFromReference())?$y(null,e):"texture"===e?zy(null):"cubeTexture"===e?ax(null):a_(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;e<t.length;e++)n=n[t[e]];return n}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const ux=(e,t,n)=>new lx(e,t,n),cx=(e,t,n,i)=>new lx(e,t,i,n);class hx extends lx{static get type(){return"MaterialReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.material=n,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const dx=(e,t,n=null)=>new hx(e,t,n),px=Py(),fx=Db.dFdx(),mx=Db.dFdy(),gx=px.dFdx(),_x=px.dFdy(),vx=Hb,yx=mx.cross(vx),bx=vx.cross(fx),xx=yx.mul(gx.x).add(bx.mul(_x.x)),Tx=yx.mul(gx.y).add(bx.mul(_x.y)),Sx=xx.dot(xx).max(Tx.dot(Tx)),Mx=Sx.equal(0).select(0,Sx.inverseSqrt()),Ex=xx.mul(Mx).toVar("tangentViewFrame"),wx=Tx.mul(Mx).toVar("bitangentViewFrame"),Ax=Ny("tangent","vec4"),Rx=Ax.xyz.toVar("tangentLocal"),Cx=Km(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Sb.mul(fg(Rx,0)).xyz.toVarying("v_tangentView").normalize():Ex,!0!==e.isFlatShading()&&(t=Ob(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),Nx=Km(([e,t],n)=>{let i=e.mul(Ax.w).xyz;return"NORMAL"===n.subBuildFn&&!0!==n.isFlatShading()&&(i=i.toVarying(t)),i}).once(["NORMAL"]),Px=yg(Cx,Km(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Nx(Hb.cross(Cx),"v_bitangentView").normalize():wx,!0!==e.isFlatShading()&&(t=Ob(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),Hb).toVar("TBNViewMatrix"),Lx=Km(()=>{let e=kg.cross(Ib);return e=e.cross(kg).normalize(),e=Dv(e,Hb,Og.mul(Ag.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),Dx=e=>cg(e,q_(Uv(ng(1).sub(wv(e,e)))));class Ix extends tm{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=""}setup(e){const{normalMapType:t,scaleNode:n,unpackNormalMode:i}=this;let r=this.node.mul(2).sub(1);if(0===t?"rg"===i?r=Dx(r.xy):"ga"===i?r=Dx(r.yw):""!==i&&console.error(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):""!==i&&console.error(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),null!==n){let t=n;!0===e.isFlatShading()&&(t=Ob(t)),r=cg(r.xy.mul(t),r.z)}let s=null;return 1===t?s=Xb(r):0===t?s=Px.mul(r).normalize():(qt(`NodeMaterial: Unsupported normal map type: ${t}`),s=Hb),s}}const Ux=Wm(Ix).setParameterLength(1,2),Fx=Km(({textureNode:e,bumpScale:t})=>{const n=t=>e.isolate().context({getUV:e=>t(e.uvNode||Py()),forceUVContext:!0}),i=ng(n(e=>e));return ag(ng(n(e=>e.add(e.dFdx()))).sub(i),ng(n(e=>e.add(e.dFdy()))).sub(i)).mul(t)}),Ox=Km(e=>{const{surf_pos:t,surf_norm:n,dHdxy:i}=e,r=t.dFdx().normalize(),s=n,a=t.dFdy().normalize().cross(s),o=s.cross(r),l=r.dot(a).mul(Fb),u=l.sign().mul(i.x.mul(a).add(i.y.mul(o)));return l.abs().mul(n).sub(u).normalize()});class Bx extends tm{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Fx({textureNode:this.textureNode,bumpScale:e});return Ox({surf_pos:Db,surf_norm:Hb,dHdxy:t})}}const kx=Wm(Bx).setParameterLength(1,2),zx=new Map;class Vx extends Qf{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=zx.get(e);return void 0===n&&(n=dx(e,t),zx.set(e,n)),n}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,n=this.scope;let i=null;if(n===Vx.COLOR){const e=void 0!==t.color?this.getColor(n):cg();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(n===Vx.OPACITY){const e=this.getFloat(n);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(n===Vx.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:ng(1);else if(n===Vx.SPECULAR_INTENSITY){const e=this.getFloat(n);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(n).a):e}else if(n===Vx.SPECULAR_COLOR){const e=this.getColor(n);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(n).rgb):e}else if(n===Vx.ROUGHNESS){const e=this.getFloat(n);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(n).g):e}else if(n===Vx.METALNESS){const e=this.getFloat(n);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(n).b):e}else if(n===Vx.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(n).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(n)):r}else if(n===Vx.NORMAL)t.normalMap?(i=Ux(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,t.normalMap.format!=Ie&&t.normalMap.format!=_t&&t.normalMap.format!=Ke||(i.unpackNormalMode="rg")):i=t.bumpMap?kx(this.getTexture("bump").r,this.getFloat("bumpScale")):Hb;else if(n===Vx.CLEARCOAT){const e=this.getFloat(n);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===Vx.CLEARCOAT_ROUGHNESS){const e=this.getFloat(n);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===Vx.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?Ux(this.getTexture(n),this.getCache(n+"Scale","vec2")):Hb;else if(n===Vx.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(n===Vx.SHEEN_ROUGHNESS){const e=this.getFloat(n);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(n).a):e,i=i.clamp(1e-4,1)}else if(n===Vx.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(n);i=vg(MT.x,MT.y,MT.y.negate(),MT.x).mul(e.rg.mul(2).sub(ag(1)).normalize().mul(e.b))}else i=MT;else if(n===Vx.IRIDESCENCE_THICKNESS){const e=ux("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=ux("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(n).g).add(r)}else i=e}else if(n===Vx.TRANSMISSION){const e=this.getFloat(n);i=t.transmissionMap?e.mul(this.getTexture(n).r):e}else if(n===Vx.THICKNESS){const e=this.getFloat(n);i=t.thicknessMap?e.mul(this.getTexture(n).g):e}else if(n===Vx.IOR)i=this.getFloat(n);else if(n===Vx.LIGHT_MAP)i=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity"));else if(n===Vx.AO)i=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(n===Vx.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(n):ng(0);else{const t=this.getNodeType(e);i=this.getCache(n,t)}return i}}Vx.ALPHA_TEST="alphaTest",Vx.COLOR="color",Vx.OPACITY="opacity",Vx.SHININESS="shininess",Vx.SPECULAR="specular",Vx.SPECULAR_STRENGTH="specularStrength",Vx.SPECULAR_INTENSITY="specularIntensity",Vx.SPECULAR_COLOR="specularColor",Vx.REFLECTIVITY="reflectivity",Vx.ROUGHNESS="roughness",Vx.METALNESS="metalness",Vx.NORMAL="normal",Vx.CLEARCOAT="clearcoat",Vx.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Vx.CLEARCOAT_NORMAL="clearcoatNormal",Vx.EMISSIVE="emissive",Vx.ROTATION="rotation",Vx.SHEEN="sheen",Vx.SHEEN_ROUGHNESS="sheenRoughness",Vx.ANISOTROPY="anisotropy",Vx.IRIDESCENCE="iridescence",Vx.IRIDESCENCE_IOR="iridescenceIOR",Vx.IRIDESCENCE_THICKNESS="iridescenceThickness",Vx.IOR="ior",Vx.TRANSMISSION="transmission",Vx.THICKNESS="thickness",Vx.ATTENUATION_DISTANCE="attenuationDistance",Vx.ATTENUATION_COLOR="attenuationColor",Vx.LINE_SCALE="scale",Vx.LINE_DASH_SIZE="dashSize",Vx.LINE_GAP_SIZE="gapSize",Vx.LINE_WIDTH="linewidth",Vx.LINE_DASH_OFFSET="dashOffset",Vx.POINT_SIZE="size",Vx.DISPERSION="dispersion",Vx.LIGHT_MAP="light",Vx.AO="ao";const Gx=$m(Vx,Vx.ALPHA_TEST),Hx=$m(Vx,Vx.COLOR),jx=$m(Vx,Vx.SHININESS),Wx=$m(Vx,Vx.EMISSIVE),$x=$m(Vx,Vx.OPACITY),Xx=$m(Vx,Vx.SPECULAR),qx=$m(Vx,Vx.SPECULAR_INTENSITY),Yx=$m(Vx,Vx.SPECULAR_COLOR),Kx=$m(Vx,Vx.SPECULAR_STRENGTH),Zx=$m(Vx,Vx.REFLECTIVITY),Qx=$m(Vx,Vx.ROUGHNESS),Jx=$m(Vx,Vx.METALNESS),eT=$m(Vx,Vx.NORMAL),tT=$m(Vx,Vx.CLEARCOAT),nT=$m(Vx,Vx.CLEARCOAT_ROUGHNESS),iT=$m(Vx,Vx.CLEARCOAT_NORMAL),rT=$m(Vx,Vx.ROTATION),sT=$m(Vx,Vx.SHEEN),aT=$m(Vx,Vx.SHEEN_ROUGHNESS),oT=$m(Vx,Vx.ANISOTROPY),lT=$m(Vx,Vx.IRIDESCENCE),uT=$m(Vx,Vx.IRIDESCENCE_IOR),cT=$m(Vx,Vx.IRIDESCENCE_THICKNESS),hT=$m(Vx,Vx.TRANSMISSION),dT=$m(Vx,Vx.THICKNESS),pT=$m(Vx,Vx.IOR),fT=$m(Vx,Vx.ATTENUATION_DISTANCE),mT=$m(Vx,Vx.ATTENUATION_COLOR),gT=$m(Vx,Vx.LINE_SCALE),_T=$m(Vx,Vx.LINE_DASH_SIZE),vT=$m(Vx,Vx.LINE_GAP_SIZE);Vx.LINE_WIDTH;const yT=$m(Vx,Vx.LINE_DASH_OFFSET),bT=$m(Vx,Vx.POINT_SIZE),xT=$m(Vx,Vx.DISPERSION),TT=$m(Vx,Vx.LIGHT_MAP),ST=$m(Vx,Vx.AO),MT=a_(new cn).onReference(function(e){return e.material}).onRenderUpdate(function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))}),ET=Km(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class wT extends Jf{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const n=this.storageBufferNode.structTypeNode;return n?n.getMemberType(e,t):"void"}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.isPBO&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let n;const i=e.context.assign;if(n=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===i||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==i){const i=this.getNodeType(e);n=e.format(n,i,t)}return n}}const AT=Wm(wT).setParameterLength(2);class RT extends Gy{static get type(){return"StorageBufferNode"}constructor(e,t=null,n=0){let i,r=null;t&&t.isStruct?(i="struct",r=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(n=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=Uf(e.itemSize),n=e.count):i=t,super(e,i,n),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=$f,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,!0!==e.isStorageBufferAttribute&&!0!==e.isStorageInstancedBufferAttribute&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return AT(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(jf)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=dy(this.value),this._varying=Kv(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return null!==this.structTypeNode?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(null!==this.structTypeNode&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:n}=this.getAttributeData(),i=n.build(e);return e.registerTransform(i,t),i}}const CT=(e,t=null,n=0)=>new RT(e,t,n);class NT extends Qf{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),n=this.scope;let i,r;if(n===NT.VERTEX)i=e.getVertexIndex();else if(n===NT.INSTANCE)i=e.getInstanceIndex();else if(n===NT.DRAW)i=e.getDrawIndex();else if(n===NT.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(n===NT.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(n!==NT.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+n);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=Kv(this).build(e,t)}return r}}NT.VERTEX="vertex",NT.INSTANCE="instance",NT.SUBGROUP="subgroup",NT.INVOCATION_LOCAL="invocationLocal",NT.INVOCATION_SUBGROUP="invocationSubgroup",NT.DRAW="draw";const PT=$m(NT,NT.VERTEX),LT=$m(NT,NT.INSTANCE);NT.SUBGROUP,NT.INVOCATION_SUBGROUP,NT.INVOCATION_LOCAL;const DT=$m(NT,NT.DRAW);class IT extends Qf{static get type(){return"InstanceNode"}constructor(e,t,n=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=n,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=Vf,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}get isStorageColor(){const{instanceColor:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}setup(e){let{instanceMatrixNode:t,instanceColorNode:n}=this;null===t&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:i,isStorageColor:r}=this;if(i&&null===n){if(r)n=CT(i,"vec3",Math.max(i.count,1)).element(LT);else{const e=new qr(i.array,3),t=i.usage===It?fy:py;this.bufferColor=e,n=cg(t(e,"vec3",3,0))}this.instanceColorNode=n}const s=t.mul(Cb).xyz;if(Cb.assign(s),e.needsPreviousData()&&Nb.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const e=$b(kb,t);kb.assign(e)}null!==this.instanceColorNode&&Sg("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&!0!==this.isStorageColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),null!==this.previousInstanceMatrixNode&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return null===this.previousInstanceMatrixNode&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(Nb).xyz}_createInstanceMatrixNode(e,t){let n;const{instanceMatrix:i}=this,{count:r}=i;if(this.isStorageMatrix)n=CT(i,"mat4",Math.max(r,1)).element(LT);else{if(16*r*4<=t.getUniformBufferLimit())n=Hy(i.array,"mat4",Math.max(r,1)).element(LT);else{const t=new za(i.array,16,1);!0===e&&(this.buffer=t);const r=i.usage===It?fy:py,s=[r(t,"vec4",16,0),r(t,"vec4",16,4),r(t,"vec4",16,8),r(t,"vec4",16,12)];n=bg(...s)}}return n}}class UT extends IT{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:n,instanceColor:i}=e;super(t,n,i),this.instancedMesh=e}}const FT=Wm(UT).setParameterLength(1);class OT extends Qf{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=LT:this.batchingIdNode=DT);const t=Km(([e])=>{const t=ig(Dy(Vy(this.batchMesh._indirectTexture),0).x).toConst(),n=ig(e).mod(t).toConst(),i=ig(e).div(t).toConst();return Vy(this.batchMesh._indirectTexture,og(n,i)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),n=t(ig(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=ig(Dy(Vy(i),0).x).toConst(),s=ng(n).mul(4).toInt().toConst(),a=s.mod(r).toConst(),o=s.div(r).toConst(),l=bg(Vy(i,og(a,o)),Vy(i,og(a.add(1),o)),Vy(i,og(a.add(2),o)),Vy(i,og(a.add(3),o))),u=this.batchMesh._colorsTexture;if(null!==u){const e=Km(([e])=>{const t=ig(Dy(Vy(u),0).x).toConst(),n=e,i=n.mod(t).toConst(),r=n.div(t).toConst();return Vy(u,og(i,r)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(n);Sg("vec3","vBatchColor").assign(t)}const c=yg(l);Cb.assign(l.mul(Cb));const h=kb.div(cg(c[0].dot(c[0]),c[1].dot(c[1]),c[2].dot(c[2]))),d=c.mul(h).xyz;kb.assign(d),e.hasGeometryAttribute("tangent")&&Rx.mulAssign(c)}}const BT=Wm(OT).setParameterLength(1),kT=new WeakMap;class zT extends Qf{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=Hf,this.skinIndexNode=Ny("skinIndex","uvec4"),this.skinWeightNode=Ny("skinWeight","vec4"),this.bindMatrixNode=ux("bindMatrix","mat4"),this.bindMatrixInverseNode=ux("bindMatrixInverse","mat4"),this.boneMatricesNode=cx("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Cb,this.toPositionNode=Cb,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:n,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:s}=this,a=e.element(n.x),o=e.element(n.y),l=e.element(n.z),u=e.element(n.w),c=r.mul(t),h=d_(a.mul(i.x).mul(c),o.mul(i.y).mul(c),l.mul(i.z).mul(c),u.mul(i.w).mul(c));return s.mul(h).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=kb,n=Rx){const{skinIndexNode:i,skinWeightNode:r,bindMatrixNode:s,bindMatrixInverseNode:a}=this,o=e.element(i.x),l=e.element(i.y),u=e.element(i.z),c=e.element(i.w);let h=d_(r.x.mul(o),r.y.mul(l),r.z.mul(u),r.w.mul(c));h=a.mul(h).mul(s);return{skinNormal:h.transformDirection(t).xyz,skinTangent:h.transformDirection(n).xyz}}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=cx("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Nb)}setup(e){e.needsPreviousData()&&Nb.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:t,skinTangent:n}=this.getSkinnedNormalAndTangent();kb.assign(t),e.hasGeometryAttribute("tangent")&&Rx.assign(n)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;kT.get(t)!==e.frameId&&(kT.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}class VT extends Qf{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const n={};for(let e=0,t=this.params.length-1;e<t;e++){const t=this.params[e],i=!0!==t.isNode&&t.name||this.getVarName(e),r=!0!==t.isNode&&t.type||"int";n[i]=My(i,r)}const i=e.addStack(),r=this.params[this.params.length-1](n);t.returnsNode=r.context({nodeLoop:r}),t.stackNode=i;const s=this.params[0];if(!0!==s.isNode&&"function"==typeof s.update){const e=Km(this.params[0].update)(n);t.updateNode=e.context({nodeLoop:e})}return e.removeStack(),t}setup(e){if(this.getProperties(e),e.fnCall){e.getDataFromNode(e.fnCall.shaderNode).hasLoop=!0}}generate(e){const t=this.getProperties(e),n=this.params,i=t.stackNode;for(let i=0,r=n.length-1;i<r;i++){const r=n[i];let s,a=!1,o=null,l=null,u=null,c=null,h=null,d=null;if(r.isNode?"bool"===r.getNodeType(e)?(a=!0,c="bool",l=r.build(e,c)):(c="int",u=this.getVarName(i),o="0",l=r.build(e,c),h="<"):(c=r.type||"int",u=r.name||this.getVarName(i),o=r.start,l=r.end,h=r.condition,d=r.update,"number"==typeof o?o=e.generateConst(c,o):o&&o.isNode&&(o=o.build(e,c)),"number"==typeof l?l=e.generateConst(c,l):l&&l.isNode&&(l=l.build(e,c)),void 0!==o&&void 0===l?(o+=" - 1",l="0",h=">="):void 0!==l&&void 0===o&&(o="0",h="<"),void 0===h&&(h=Number(o)>Number(l)?">=":"<")),a)s=`while ( ${l} )`;else{const n={start:o,end:l},i=n.start,r=n.end;let a;const p=()=>h.includes("<")?"+=":"-=";if(null!=d)switch(typeof d){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=u+" "+p()+" "+e.generateConst(c,d);break;case"string":a=u+" "+d;break;default:d.isNode?a=u+" "+p()+" "+d.build(e):(qt("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else d="int"===c||"uint"===c?h.includes("<")?"++":"--":p()+" 1.",a=u+" "+d;s=`for ( ${e.getVar(c,u)+" = "+i}; ${u+" "+h+" "+r}; ${a} )`}e.addFlowCode((0===i?"\n":"")+e.tab+s+" {\n\n").addFlowTab()}const r=i.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,n=this.params.length-1;t<n;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();e.addFlowTab()}}const GT=(...e)=>new VT(jm(e,"int")).toStack(),HT=new WeakMap,jT=new Pn,WT=Km(({bufferMap:e,influence:t,stride:n,width:i,depth:r,offset:s})=>{const a=ig(PT).mul(n).add(s),o=a.div(i),l=a.sub(o.mul(i));return Vy(e,og(l,o)).depth(r).xyz.mul(t)});class $T extends Qf{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=a_(1),this.updateType=Hf}setup(e){const{geometry:t}=e,n=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,s=void 0!==r?r.length:0,{texture:a,stride:o,size:l}=function(e){const t=void 0!==e.morphAttributes.position,n=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=void 0!==r?r.length:0;let a=HT.get(e);if(void 0===a||a.count!==s){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let c=0;!0===t&&(c=1),!0===n&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,d=1;const p=4096;h>p&&(d=Math.ceil(h/p),h=p);const f=new Float32Array(h*d*4*s),m=new In(f,h,d,s);m.type=be,m.needsUpdate=!0;const g=4*c;for(let v=0;v<s;v++){const y=o[v],b=l[v],x=u[v],T=h*d*4*v;for(let S=0;S<y.count;S++){const M=S*g;!0===t&&(jT.fromBufferAttribute(y,S),f[T+M+0]=jT.x,f[T+M+1]=jT.y,f[T+M+2]=jT.z,f[T+M+3]=0),!0===n&&(jT.fromBufferAttribute(b,S),f[T+M+4]=jT.x,f[T+M+5]=jT.y,f[T+M+6]=jT.z,f[T+M+7]=0),!0===i&&(jT.fromBufferAttribute(x,S),f[T+M+8]=jT.x,f[T+M+9]=jT.y,f[T+M+10]=jT.z,f[T+M+11]=4===x.itemSize?jT.w:1)}}function _(){m.dispose(),HT.delete(e),e.removeEventListener("dispose",_)}a={count:s,texture:m,stride:c,size:new cn(h,d)},HT.set(e,a),e.addEventListener("dispose",_)}return a}(t);!0===n&&Cb.mulAssign(this.morphBaseInfluence),!0===i&&kb.mulAssign(this.morphBaseInfluence);const u=ig(l.width);GT(s,({i:e})=>{const t=ng(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Vy(this.mesh.morphTexture,og(ig(e).add(1),ig(LT))).r):t.assign(ux("morphTargetInfluences","float").element(e).toVar()),Jm(t.notEqual(0),()=>{!0===n&&Cb.addAssign(WT({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:ig(0)})),!0===i&&kb.addAssign(WT({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:ig(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((e,t)=>e+t,0)}}const XT=Wm($T).setParameterLength(1);class qT extends Qf{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class YT extends qT{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class KT extends Gv{static get type(){return"LightingContextNode"}constructor(e,t=null,n=null,i=null){super(e),this.lightingModel=t,this.backdropNode=n,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,n={directDiffuse:cg().toVar("directDiffuse"),directSpecular:cg().toVar("directSpecular"),indirectDiffuse:cg().toVar("indirectDiffuse"),indirectSpecular:cg().toVar("indirectSpecular")};return{radiance:cg().toVar("radiance"),irradiance:cg().toVar("irradiance"),iblIrradiance:cg().toVar("iblIrradiance"),ambientOcclusion:ng(1).toVar("ambientOcclusion"),reflectedLight:n,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const ZT=Wm(KT);class QT extends qT{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const JT=new cn;class eS extends By{static get type(){return"ViewportTextureNode"}constructor(e=Qy,t=null,n=null){let i=null;null===n?(i=new gs,i.minFilter=pe,n=i):i=n,super(n,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=Gf,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,n;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,n=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,n=this._cacheTextures),null===e)return t;if(!1===n.has(e)){const i=t.clone();n.set(e,i)}return n.get(e)}updateReference(e){const t=e.renderer.getRenderTarget();return this.value=this.getTextureForReference(t),this.value}updateBefore(e){const t=e.renderer,n=t.getRenderTarget();null===n?t.getDrawingBufferSize(JT):JT.set(n.width,n.height);const i=this.getTextureForReference(n);i.image.width===JT.width&&i.image.height===JT.height||(i.image.width=JT.width,i.image.height=JT.height,i.needsUpdate=!0);const r=i.generateMipmaps;i.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(i),i.generateMipmaps=r}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const tS=Wm(eS,null,null,{generateMipmaps:!0}).setParameterLength(0,3),nS=tS(),iS=(e=Qy,t=null)=>nS.sample(e,t);let rS=null;class sS extends eS{static get type(){return"ViewportDepthTextureNode"}constructor(e=Qy,t=null){null===rS&&(rS=new vs),super(e,t,rS)}getTextureForReference(){return rS}}const aS=Wm(sS).setParameterLength(0,2);class oS extends Qf{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===oS.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let i=null;if(t===oS.DEPTH_BASE)null!==n&&(i=dS().assign(n));else if(t===oS.DEPTH)i=e.isPerspectiveCamera?uS(Db.z,db,pb):lS(Db.z,db,pb);else if(t===oS.LINEAR_DEPTH)if(null!==n)if(e.isPerspectiveCamera){const e=cS(n,db,pb);i=lS(e,db,pb)}else i=n;else i=lS(Db.z,db,pb);return i}}oS.DEPTH_BASE="depthBase",oS.DEPTH="depth",oS.LINEAR_DEPTH="linearDepth";const lS=(e,t,n)=>e.add(t).div(t.sub(n)),uS=(e,t,n)=>t.add(e).mul(n).div(n.sub(t).mul(e)),cS=Km(([e,t,n],i)=>!0===i.renderer.reversedDepthBuffer?t.mul(n).div(t.sub(n).mul(e).sub(t)):t.mul(n).div(n.sub(t).mul(e).sub(n))),hS=(e,t,n)=>{t=t.max(1e-6).toVar();const i=X_(e.negate().div(t)),r=X_(n.div(t));return i.div(r)},dS=Wm(oS,oS.DEPTH_BASE),pS=$m(oS,oS.DEPTH);aS(),pS.assign=e=>dS(e);class fS extends Qf{static get type(){return"ClippingNode"}constructor(e=fS.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:n,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===fS.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,i):this.scope===fS.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(n,i)}setupAlphaToCoverage(e,t){return Km(()=>{const n=ng().toVar("distanceToPlane"),i=ng().toVar("distanceToGradient"),r=ng(1).toVar("clipOpacity"),s=t.length;if(!1===this.hardwareClipping&&s>0){const e=$y(t).setGroup(i_);GT(s,({i:t})=>{const s=e.element(t);n.assign(Db.dot(s.xyz).negate().add(s.w)),i.assign(n.fwidth().div(2)),r.mulAssign(Ov(i.negate(),i,n))})}const a=e.length;if(a>0){const t=$y(e).setGroup(i_),s=ng(1).toVar("intersectionClipOpacity");GT(a,({i:e})=>{const r=t.element(e);n.assign(Db.dot(r.xyz).negate().add(r.w)),i.assign(n.fwidth().div(2)),s.mulAssign(Ov(i.negate(),i,n).oneMinus())}),r.mulAssign(s.oneMinus())}Mg.a.mulAssign(r),Mg.a.equal(0).discard()})()}setupDefault(e,t){return Km(()=>{const n=t.length;if(!1===this.hardwareClipping&&n>0){const e=$y(t).setGroup(i_);GT(n,({i:t})=>{const n=e.element(t);Db.dot(n.xyz).greaterThan(n.w).discard()})}const i=e.length;if(i>0){const t=$y(e).setGroup(i_),n=sg(!0).toVar("clipped");GT(i,({i:e})=>{const i=t.element(e);n.assign(Db.dot(i.xyz).greaterThan(i.w).and(n))}),n.discard()}})()}setupHardwareClipping(e,t){const n=e.length;return t.enableHardwareClipping(n),Km(()=>{const i=$y(e).setGroup(i_),r=Xy(t.getClipDistance());GT(n,({i:e})=>{const t=i.element(e),n=Db.dot(t.xyz).sub(t.w).negate();r.element(e).assign(n)})})()}}fS.ALPHA_TO_COVERAGE="alphaToCoverage",fS.DEFAULT="default",fS.HARDWARE="hardware";const mS=Km(([e])=>J_(f_(1e4,ev(f_(17,e.x).add(f_(.1,e.y)))).mul(d_(.1,av(ev(f_(13,e.y).add(e.x))))))),gS=Km(([e])=>mS(ag(mS(e.xy),e.z))),_S=Km(([e])=>{const t=xv(lv(hv(e.xyz)),lv(dv(e.xyz))),n=ng(1).div(ng(.05).mul(t)).toVar("pixScale"),i=ag(W_(K_(X_(n))),W_(Z_(X_(n)))),r=ag(gS(K_(i.x.mul(e.xyz))),gS(K_(i.y.mul(e.xyz)))),s=J_(X_(n)),a=d_(f_(s.oneMinus(),r.x),f_(s,r.y)),o=bv(s,s.oneMinus()),l=cg(a.mul(a).div(f_(2,o).mul(p_(1,o))),a.sub(f_(.5,o)).div(p_(1,o)),p_(1,p_(1,a).mul(p_(1,a)).div(f_(2,o).mul(p_(1,o))))),u=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return Iv(u,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class vS extends Cy{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let n;return n=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new Pn(1,1,1,1)),n}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const yS=Km(([e])=>fg(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"});class bS extends Sr{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const n=this[t];n&&!0===n.isNode&&e.push({property:t,childNode:n})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:n}of this._getNodeChildren())e.push(Nf(t.slice(0,-4)),n.getCacheKey());return this.type+Pf(e)}build(e){this.setup(e)}setupObserver(e){return new wf(e)}setup(e){e.context.setupNormal=()=>qv(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();!0===t.contextNode.isContextNode?e.context={...e.context,...t.contextNode.getFlowContextData()}:qt('NodeMaterial: "renderer.contextNode" must be an instance of `context()`.'),null!==this.contextNode&&(!0===this.contextNode.isContextNode?e.context={...e.context,...this.contextNode.getFlowContextData()}:qt('NodeMaterial: "material.contextNode" must be an instance of `context()`.')),e.addStack();const i=this.setupVertex(e),r=qv(this.vertexNode||i,"VERTEX");let s;e.context.clipSpace=r,e.stack.outputNode=r,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==n?!0===n.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const r=fg(i,Mg.a).max(0);s=this.setupOutput(e,r),jg.assign(s);const o=null!==this.outputNode;if(o&&(s=this.outputNode),e.context.getOutput&&(s=e.context.getOutput(s,e)),null!==n){const e=t.getMRT(),n=this.mrtNode;null!==e?(o&&jg.assign(s),s=e,null!==n&&(s=e.merge(n))):null!==n&&(s=n)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=fg(t)),s=this.setupOutput(e,t)}e.stack.outputNode=s,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:n}=e.clippingContext;let i=null;if(t.length>0||n.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?i=new fS(fS.ALPHA_TO_COVERAGE):e.stack.addToStack(new fS)}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new fS(fS.HARDWARE)),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:n}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=n.isPerspectiveCamera?hS(Db.z,db,pb):lS(Db.z,db,pb))}null!==i&&pS.assign(i).toStack()}setupPositionView(){return Sb.mul(Cb).xyz}setupModelViewProjection(){return fb.mul(Db)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),ET}setupPosition(e){const{object:t,geometry:n}=e;var i;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&XT(t).toStack(),!0===t.isSkinnedMesh&&(i=t,new zT(i)).toStack(),this.displacementMap){const e=dx("displacementMap","texture"),t=dx("displacementScale","float"),n=dx("displacementBias","float");Cb.addAssign(kb.normalize().mul(e.x.mul(t).add(n)))}return t.isBatchedMesh&&BT(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&FT(t).toStack(),null!==this.positionNode&&Cb.assign(qv(this.positionNode,"POSITION","vec3")),Cb}setupDiffuseColor(e){const{object:t,geometry:n}=e;null!==this.maskNode&&sg(this.maskNode).not().discard();let i=this.colorNode?fg(this.colorNode):Hx;if(!0===this.vertexColors&&n.hasAttribute("color")&&(i=i.mul(((e=0)=>new vS(e))())),t.instanceColor){i=Sg("vec3","vInstanceColor").mul(i)}if(t.isBatchedMesh&&t._colorsTexture){i=Sg("vec3","vBatchColor").mul(i)}Mg.assign(i);const r=this.opacityNode?ng(this.opacityNode):$x;Mg.a.assign(Mg.a.mul(r));let s=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(s=null!==this.alphaTestNode?ng(this.alphaTestNode):Gx,!0===this.alphaToCoverage?(Mg.a=Ov(s,s.add(gv(Mg.a)),Mg.a),Mg.a.lessThanEqual(0).discard()):Mg.a.lessThanEqual(s).discard()),!0===this.alphaHash&&Mg.a.lessThan(_S(Cb)).discard(),e.isOpaque()&&Mg.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?cg(0):Mg.rgb}setupNormal(){return this.normalNode?cg(this.normalNode):eT}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?dx("envMap","cubeTexture"):dx("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new QT(TT)),t}setupLights(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const i=this.setupLightMap(e);i&&i.isLightingNode&&t.push(i);let r=this.aoNode;null===r&&e.material.aoMap&&(r=ST),e.context.getAO&&(r=e.context.getAO(r,e)),r&&t.push(new YT(r));let s=this.lightsNode||e.lightsNode;return t.length>0&&(s=e.renderer.lighting.createNode([...s.getLights(),...t])),s}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:i,emissiveNode:r}=this,s=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(s&&s.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=ZT(s,t,n,i)}else null!==n&&(a=cg(null!==i?Dv(a,n,i):n));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(wg.assign(cg(r||Wx)),a=a.add(wg)),a}setupFog(e,t){const n=e.fogNode;return n&&(jg.assign(t),t=fg(n.toVar())),t}setupPremultipliedAlpha(e,t){return yS(t)}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),!0===this.premultipliedAlpha&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const t in e){const n=e[t];void 0===this[t]&&(this[t]=n,n&&n.clone&&(this[t]=n.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const n=Sr.prototype.toJSON.call(this,e);n.inputNodes={};for(const{property:t,childNode:i}of this._getNodeChildren())n.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(t){const t=i(e.textures),r=i(e.images),s=i(e.nodes);t.length>0&&(n.textures=t),r.length>0&&(n.images=r),s.length>0&&(n.nodes=s)}return n}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.maskShadowNode=e.maskShadowNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const xS=new as;class TS extends bS{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(xS),this.setValues(e)}}const SS=new na;class MS extends bS{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(SS),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?ng(this.offsetNode):yT,t=this.dashScaleNode?ng(this.dashScaleNode):gT,n=this.dashSizeNode?ng(this.dashSizeNode):_T,i=this.gapSizeNode?ng(this.gapSizeNode):vT;Wg.assign(n),$g.assign(i);const r=Kv(Ny("lineDistance").mul(t));(e?r.add(e):r).mod(Wg.add($g)).greaterThan(Wg).discard()}}const ES=new Zs;class wS extends bS{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(ES),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?ng(this.opacityNode):$x;Mg.assign(ty(fg(Vm(Hb).mul(.5).add(.5),e),bt))}}const AS=Km(([e=Lb])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),n=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return ag(t,n)});class RS extends Ln{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new _s(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r=new xs(5,5,5),s=AS(Lb),a=new bS;a.colorNode=zy(t,s,0),a.side=1,a.blending=0;const o=new Wr(r,a),l=new yi;l.add(o),t.minFilter===pe&&(t.minFilter=he);const u=new Fa(1,10,this),c=e.getMRT();return e.setMRT(null),u.update(e,l),e.setMRT(c),t.minFilter=n,t.currentGenerateMipmaps=i,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(r)}}const CS=new WeakMap;class NS extends tm{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=ax(null);const t=new _s;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Gf}updateBefore(e){const{renderer:t,material:n}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:n[i.property];if(e&&e.isTexture){const n=e.mapping;if(n===ne||n===ie){if(CS.has(e)){const t=CS.get(e);LS(t,e.mapping),this._cubeTexture=t}else{const n=e.image;if(function(e){return null!=e&&e.height>0}(n)){const i=new RS(n.height);i.fromEquirectangularTexture(t,e),LS(i.texture,e.mapping),this._cubeTexture=i.texture,CS.set(e,i.texture),e.addEventListener("dispose",PS)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function PS(e){const t=e.target;t.removeEventListener("dispose",PS);const n=CS.get(t);void 0!==n&&(CS.delete(t),n.dispose())}function LS(e,t){t===ne?e.mapping=ee:t===ie&&(e.mapping=te)}const DS=Wm(NS).setParameterLength(1);class IS extends qT{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=DS(this.envNode)}}class US extends qT{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=ng(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class FS{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class OS extends FS{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,i=e.irradianceLightMap;n.indirectDiffuse.assign(fg(0)),i?n.indirectDiffuse.addAssign(i):n.indirectDiffuse.addAssign(fg(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(Mg.rgb)}finish(e){const{material:t,context:n}=e,i=n.outgoingLight,r=e.context.environment;if(r)switch(t.combine){case 0:i.rgb.assign(Dv(i.rgb,i.rgb.mul(r.rgb),Kx.mul(Zx)));break;case 1:i.rgb.assign(Dv(i.rgb,r.rgb,Kx.mul(Zx)));break;case 2:i.rgb.addAssign(r.rgb.mul(Kx.mul(Zx)));break;default:Xt("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const BS=new Dr;class kS extends bS{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(BS),this.setValues(e)}setupNormal(){return Ob(Vb)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new IS(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new US(TT)),t}setupOutgoingLight(){return Mg.rgb}setupLightingModel(){return new OS}}const zS=Km(({f0:e,f90:t,dotVH:n})=>{const i=n.mul(-5.55473).sub(6.98316).mul(n).exp2();return e.mul(i.oneMinus()).add(t.mul(i))}),VS=Km(e=>e.diffuseColor.mul(1/Math.PI)),GS=Km(({dotNH:e})=>Hg.mul(ng(.5)).add(1).mul(ng(1/Math.PI)).mul(e.pow(Hg))),HS=Km(({lightDirection:e})=>{const t=e.add(Ib).normalize(),n=Hb.dot(t).clamp(),i=Ib.dot(t).clamp(),r=zS({f0:zg,f90:1,dotVH:i}),s=ng(.25),a=GS({dotNH:n});return r.mul(s).mul(a)});class jS extends OS{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=Hb.dot(e).clamp().mul(t);n.directDiffuse.addAssign(i.mul(VS({diffuseColor:Mg.rgb}))),!0===this.specular&&n.directSpecular.addAssign(i.mul(HS({lightDirection:e})).mul(Kx))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(VS({diffuseColor:Mg}))),i.indirectDiffuse.mulAssign(t)}}const WS=new Qs;class $S extends bS{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(WS),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new IS(t):null}setupLightingModel(){return new jS(!1)}}const XS=new Ys;class qS extends bS{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(XS),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new IS(t):null}setupLightingModel(){return new jS}setupVariants(){const e=(this.shininessNode?ng(this.shininessNode):jx).max(1e-4);Hg.assign(e);const t=this.specularNode||Xx;zg.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const YS=Km(e=>{if(!1===e.geometry.hasAttribute("normal"))return ng(0);const t=Vb.dFdx().abs().max(Vb.dFdy().abs());return t.x.max(t.y).max(t.z)}),KS=Km(e=>{const{roughness:t}=e,n=YS();let i=t.max(.0525);return i=i.add(n),i=i.min(1),i}),ZS=Km(({alpha:e,dotNL:t,dotNV:n})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(n.pow2())).sqrt()),s=n.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return m_(.5,r.add(s).max(B_))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),QS=Km(({alphaT:e,alphaB:t,dotTV:n,dotBV:i,dotTL:r,dotBL:s,dotNV:a,dotNL:o})=>{const l=o.mul(cg(e.mul(n),t.mul(i),a).length()),u=a.mul(cg(e.mul(r),t.mul(s),o).length());return m_(.5,l.add(u))}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),JS=Km(({alpha:e,dotNH:t})=>{const n=e.pow2(),i=t.pow2().mul(n.oneMinus()).oneMinus();return n.div(i.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),eM=ng(1/Math.PI),tM=Km(({alphaT:e,alphaB:t,dotNH:n,dotTH:i,dotBH:r})=>{const s=e.mul(t),a=cg(t.mul(i),e.mul(r),s.mul(n)),o=a.dot(a),l=s.div(o);return eM.mul(s.mul(l.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),nM=Km(({lightDirection:e,f0:t,f90:n,roughness:i,f:r,normalView:s=Hb,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const l=i.pow2(),u=e.add(Ib).normalize(),c=s.dot(e).clamp(),h=s.dot(Ib).clamp(),d=s.dot(u).clamp(),p=Ib.dot(u).clamp();let f,m,g=zS({f0:t,f90:n,dotVH:p});if(km(a)&&(g=Dg.mix(g,r)),km(o)){const t=Bg.dot(e),n=Bg.dot(Ib),i=Bg.dot(u),r=kg.dot(e),s=kg.dot(Ib),a=kg.dot(u);f=QS({alphaT:Fg,alphaB:l,dotTV:n,dotBV:s,dotTL:t,dotBL:r,dotNV:h,dotNL:c}),m=tM({alphaT:Fg,alphaB:l,dotNH:d,dotTH:i,dotBH:a})}else f=ZS({alpha:l,dotNL:c,dotNV:h}),m=JS({alpha:l,dotNH:d});return g.mul(f).mul(m)}),iM=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let rM=null;const sM=Km(({roughness:e,dotNV:t})=>{null===rM&&(rM=new Xr(iM,16,16,Ie,xe),rM.name="DFG_LUT",rM.minFilter=he,rM.magFilter=he,rM.wrapS=ae,rM.wrapT=ae,rM.generateMipmaps=!1,rM.needsUpdate=!0);const n=ag(e,t);return zy(rM,n).rg}),aM=Km(({lightDirection:e,f0:t,f90:n,roughness:i,f:r,USE_IRIDESCENCE:s,USE_ANISOTROPY:a})=>{const o=nM({lightDirection:e,f0:t,f90:n,roughness:i,f:r,USE_IRIDESCENCE:s,USE_ANISOTROPY:a}),l=Hb.dot(e).clamp(),u=Hb.dot(Ib).clamp(),c=sM({roughness:i,dotNV:u}),h=sM({roughness:i,dotNV:l}),d=t.mul(c.x).add(n.mul(c.y)),p=t.mul(h.x).add(n.mul(h.y)),f=c.x.add(c.y),m=h.x.add(h.y),g=ng(1).sub(f),_=ng(1).sub(m),v=t.add(t.oneMinus().mul(.047619)),y=d.mul(p).mul(v).div(ng(1).sub(g.mul(_).mul(v).mul(v)).add(B_)),b=g.mul(_),x=y.mul(b);return o.add(x)}),oM=Km(e=>{const{dotNV:t,specularColor:n,specularF90:i,roughness:r}=e,s=sM({dotNV:t,roughness:r});return n.mul(s.x).add(i.mul(s.y))}),lM=Km(({f:e,f90:t,dotVH:n})=>{const i=n.oneMinus().saturate(),r=i.mul(i),s=i.mul(r,r).clamp(0,.9999);return e.sub(cg(t).mul(s)).div(s.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),uM=Km(({roughness:e,dotNH:t})=>{const n=e.pow2(),i=ng(1).div(n),r=t.pow2().oneMinus().max(.0078125);return ng(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),cM=Km(({dotNV:e,dotNL:t})=>ng(1).div(ng(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),hM=Km(({lightDirection:e})=>{const t=e.add(Ib).normalize(),n=Hb.dot(e).clamp(),i=Hb.dot(Ib).clamp(),r=Hb.dot(t).clamp(),s=uM({roughness:Lg,dotNH:r}),a=cM({dotNV:i,dotNL:n});return Pg.mul(s).mul(a)}),dM=Km(({N:e,V:t,roughness:n})=>{const i=e.dot(t).saturate(),r=ag(n,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),pM=Km(({f:e})=>{const t=e.length();return xv(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),fM=Km(({v1:e,v2:t})=>{const n=e.dot(t),i=n.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),s=i.add(4.1616724).mul(i).add(3.417594).toVar(),a=r.div(s),o=n.greaterThan(0).select(a,xv(n.mul(n).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),mM=Km(({N:e,V:t,P:n,mInv:i,p0:r,p1:s,p2:a,p3:o})=>{const l=s.sub(r).toVar(),u=o.sub(r).toVar(),c=l.cross(u),h=cg().toVar();return Jm(c.dot(n.sub(r)).greaterThanEqual(0),()=>{const l=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(l).negate(),c=i.mul(yg(l,u,e).transpose()).toVar(),d=c.mul(r.sub(n)).normalize().toVar(),p=c.mul(s.sub(n)).normalize().toVar(),f=c.mul(a.sub(n)).normalize().toVar(),m=c.mul(o.sub(n)).normalize().toVar(),g=cg(0).toVar();g.addAssign(fM({v1:d,v2:p})),g.addAssign(fM({v1:p,v2:f})),g.addAssign(fM({v1:f,v2:m})),g.addAssign(fM({v1:m,v2:d})),h.assign(cg(pM({f:g})))}),h}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),gM=1/6,_M=e=>f_(gM,f_(e,f_(e,e.negate().add(3)).sub(3)).add(1)),vM=e=>f_(gM,f_(e,f_(e,f_(3,e).sub(6))).add(4)),yM=e=>f_(gM,f_(e,f_(e,f_(-3,e).add(3)).add(3)).add(1)),bM=e=>f_(gM,Rv(e,3)),xM=e=>_M(e).add(vM(e)),TM=e=>yM(e).add(bM(e)),SM=e=>d_(-1,vM(e).div(_M(e).add(vM(e)))),MM=e=>d_(1,bM(e).div(yM(e).add(bM(e)))),EM=(e,t,n)=>{const i=e.uvNode,r=f_(i,t.zw).add(.5),s=K_(r),a=J_(r),o=xM(a.x),l=TM(a.x),u=SM(a.x),c=MM(a.x),h=SM(a.y),d=MM(a.y),p=ag(s.x.add(u),s.y.add(h)).sub(.5).mul(t.xy),f=ag(s.x.add(c),s.y.add(h)).sub(.5).mul(t.xy),m=ag(s.x.add(u),s.y.add(d)).sub(.5).mul(t.xy),g=ag(s.x.add(c),s.y.add(d)).sub(.5).mul(t.xy),_=xM(a.y).mul(d_(o.mul(e.sample(p).level(n)),l.mul(e.sample(f).level(n)))),v=TM(a.y).mul(d_(o.mul(e.sample(m).level(n)),l.mul(e.sample(g).level(n))));return _.add(v)},wM=Km(([e,t])=>{const n=ag(e.size(ig(t))),i=ag(e.size(ig(t.add(1)))),r=m_(1,n),s=m_(1,i),a=EM(e,fg(r,n),K_(t)),o=EM(e,fg(s,i),Z_(t));return J_(t).mix(a,o)}),AM=Km(([e,t,n,i,r])=>{const s=cg(Fv(t.negate(),Q_(e),m_(1,i))),a=cg(lv(r[0].xyz),lv(r[1].xyz),lv(r[2].xyz));return Q_(s).mul(n.mul(a))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),RM=Km(([e,t])=>e.mul(Iv(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),CM=tS(),NM=iS(),PM=Km(([e,t,n],{material:i})=>{const r=(1===i.side?CM:NM).sample(e),s=X_(Jy.x).mul(RM(t,n));return wM(r,s)}),LM=Km(([e,t,n])=>(Jm(n.notEqual(0),()=>{const i=$_(t).negate().div(n);return j_(i.negate().mul(e))}),cg(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),DM=Km(([e,t,n,i,r,s,a,o,l,u,c,h,d,p,f])=>{let m,g;if(f){m=fg().toVar(),g=cg().toVar();const r=c.sub(1).mul(f.mul(.025)),s=cg(c.sub(r),c,c.add(r));GT({start:0,end:3},({i:r})=>{const c=s.element(r),f=AM(e,t,h,c,o),_=a.add(f),v=u.mul(l.mul(fg(_,1))),y=ag(v.xy.div(v.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(ag(y.x,y.y.oneMinus()));const b=PM(y,n,c);m.element(r).assign(b.element(r)),m.a.addAssign(b.a),g.element(r).assign(i.element(r).mul(LM(lv(f),d,p).element(r)))}),m.a.divAssign(3)}else{const r=AM(e,t,h,c,o),s=a.add(r),f=u.mul(l.mul(fg(s,1))),_=ag(f.xy.div(f.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(ag(_.x,_.y.oneMinus())),m=PM(_,n,c),g=i.mul(LM(lv(r),d,p))}const _=g.rgb.mul(m.rgb),v=e.dot(t).clamp(),y=cg(oM({dotNV:v,specularColor:r,specularF90:s,roughness:n})),b=g.r.add(g.g,g.b).div(3);return fg(y.oneMinus().mul(_),m.a.oneMinus().mul(b).oneMinus())}),IM=yg(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),UM=(e,t)=>e.sub(t).div(e.add(t)).pow2(),FM=Km(({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:i,baseF0:r})=>{const s=Dv(e,t,Ov(0,.03,i)),a=e.div(s).pow2().mul(n.pow2().oneMinus()).oneMinus();Jm(a.lessThan(0),()=>cg(1));const o=a.sqrt(),l=UM(s,e),u=zS({f0:l,f90:1,dotVH:n}),c=u.oneMinus(),h=s.lessThan(e).select(Math.PI,0),d=ng(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return cg(1).add(t).div(cg(1).sub(t))})(r.clamp(0,.9999)),f=UM(p,s.toVec3()),m=zS({f0:f,f90:1,dotVH:o}),g=cg(p.x.lessThan(s).select(Math.PI,0),p.y.lessThan(s).select(Math.PI,0),p.z.lessThan(s).select(Math.PI,0)),_=s.mul(i,o,2),v=cg(d).add(g),y=u.mul(m).clamp(1e-5,.9999),b=y.sqrt(),x=c.pow2().mul(m).div(cg(1).sub(y)),T=u.add(x).toVar(),S=x.sub(c).toVar();return GT({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{S.mulAssign(b);const t=((e,t)=>{const n=e.mul(2*Math.PI*1e-9),i=cg(54856e-17,44201e-17,52481e-17),r=cg(1681e3,1795300,2208400),s=cg(43278e5,93046e5,66121e5),a=ng(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(n.mul(2239900).add(t.x).cos()).mul(n.pow2().mul(-45282e5).exp());let o=i.mul(s.mul(2*Math.PI).sqrt()).mul(r.mul(n).add(t).cos()).mul(n.pow2().negate().mul(s).exp());return o=cg(o.x.add(a),o.y,o.z).div(1.0685e-7),IM.mul(o)})(ng(e).mul(_),ng(e).mul(v)).mul(2);T.addAssign(S.mul(t))}),T.max(cg(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),OM=Km(({normal:e,viewDir:t,roughness:n})=>{const i=e.dot(t).saturate(),r=n.mul(n),s=n.add(.1).reciprocal(),a=ng(-1.9362).add(n.mul(1.0678)).add(r.mul(.4573)).sub(s.mul(.8469)),o=ng(-.6014).add(n.mul(.5538)).sub(r.mul(.467)).sub(s.mul(.1255));return a.mul(i).add(o).exp().saturate()}),BM=cg(.04),kM=ng(1);class zM extends FS{constructor(e=!1,t=!1,n=!1,i=!1,r=!1,s=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=i,this.transmission=r,this.dispersion=s,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=cg().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=cg().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=cg().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=cg().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=cg().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Hb.dot(Ib).clamp(),t=FM({outsideIOR:ng(1),eta2:Ig,cosTheta1:e,thinFilmThickness:Ug,baseF0:zg}),n=FM({outsideIOR:ng(1),eta2:Ig,cosTheta1:e,thinFilmThickness:Ug,baseF0:Mg.rgb});this.iridescenceFresnel=Dv(t,n,Rg),this.iridescenceF0Dielectric=lM({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=lM({f:n,f90:1,dotVH:e}),this.iridescenceF0=Dv(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Rg)}if(!0===this.transmission){const t=Pb,n=_b.sub(Pb).normalize(),i=jb,r=e.context;r.backdrop=DM(i,n,Ag,Eg,Vg,Gg,t,xb,gb,fb,Xg,Yg,Zg,Kg,this.dispersion?Qg:null),r.backdropAlpha=qg,Mg.a.mulAssign(Dv(1,r.backdrop.a,qg))}super.start(e)}computeMultiscattering(e,t,n,i,r=null){const s=Hb.dot(Ib).clamp(),a=sM({roughness:Ag,dotNV:s}),o=r?Dg.mix(i,r):i,l=o.mul(a.x).add(n.mul(a.y)),u=a.x.add(a.y).oneMinus(),c=o.add(o.oneMinus().mul(.047619)),h=l.mul(c).div(u.mul(c).oneMinus());e.addAssign(l),t.addAssign(h.mul(u))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=Hb.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(i.mul(hM({lightDirection:e})));const t=OM({normal:Hb,viewDir:Ib,roughness:Lg}),n=OM({normal:Hb,viewDir:e,roughness:Lg}),r=Pg.r.max(Pg.g).max(Pg.b).mul(t.max(n)).oneMinus();i.mulAssign(r)}if(!0===this.clearcoat){const n=Wb.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(nM({lightDirection:e,f0:BM,f90:kM,roughness:Ng,normalView:Wb})))}n.directDiffuse.addAssign(i.mul(VS({diffuseColor:Eg}))),n.directSpecular.addAssign(i.mul(aM({lightDirection:e,f0:Vg,f90:1,roughness:Ag,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:i,reflectedLight:r,ltc_1:s,ltc_2:a}){const o=t.add(n).sub(i),l=t.sub(n).sub(i),u=t.sub(n).add(i),c=t.add(n).add(i),h=Hb,d=Ib,p=Db.toVar(),f=dM({N:h,V:d,roughness:Ag}),m=s.sample(f).toVar(),g=a.sample(f).toVar(),_=yg(cg(m.x,0,m.y),cg(0,1,0),cg(m.z,0,m.w)).toVar(),v=Vg.mul(g.x).add(Gg.sub(Vg).mul(g.y)).toVar();if(r.directSpecular.addAssign(e.mul(v).mul(mM({N:h,V:d,P:p,mInv:_,p0:o,p1:l,p2:u,p3:c}))),r.directDiffuse.addAssign(e.mul(Eg).mul(mM({N:h,V:d,P:p,mInv:yg(1,0,0,0,1,0,0,0,1),p0:o,p1:l,p2:u,p3:c}))),!0===this.clearcoat){const t=Wb,n=dM({N:t,V:d,roughness:Ng}),i=s.sample(n),r=a.sample(n),h=yg(cg(i.x,0,i.y),cg(0,1,0),cg(i.z,0,i.w)),f=BM.mul(r.x).add(kM.sub(BM).mul(r.y));this.clearcoatSpecularDirect.addAssign(e.mul(f).mul(mM({N:t,V:d,P:p,mInv:h,p0:o,p1:l,p2:u,p3:c})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:n}=e.context,i=t.mul(VS({diffuseColor:Eg})).toVar();if(!0===this.sheen){const e=OM({normal:Hb,viewDir:Ib,roughness:Lg}),t=Pg.r.max(Pg.g).max(Pg.b).mul(e).oneMinus();i.mulAssign(t)}n.indirectDiffuse.addAssign(i)}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(n.mul(Pg,OM({normal:Hb,viewDir:Ib,roughness:Lg}))),!0===this.clearcoat){const e=Wb.dot(Ib).clamp(),t=oM({dotNV:e,specularColor:BM,specularF90:kM,roughness:Ng});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=cg().toVar("singleScatteringDielectric"),s=cg().toVar("multiScatteringDielectric"),a=cg().toVar("singleScatteringMetallic"),o=cg().toVar("multiScatteringMetallic");this.computeMultiscattering(r,s,Gg,zg,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,Gg,Mg.rgb,this.iridescenceF0Metallic);const l=Dv(r,a,Rg),u=Dv(s,o,Rg),c=r.add(s),h=Eg.mul(c.oneMinus()),d=n.mul(1/Math.PI),p=t.mul(l).add(u.mul(d)).toVar(),f=h.mul(d).toVar();if(!0===this.sheen){const e=OM({normal:Hb,viewDir:Ib,roughness:Lg}),t=Pg.r.max(Pg.g).max(Pg.b).mul(e).oneMinus();p.mulAssign(t),f.mulAssign(t)}i.indirectSpecular.addAssign(p),i.indirectDiffuse.addAssign(f)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,i=Hb.dot(Ib).clamp().add(t),r=Ag.mul(-16).oneMinus().negate().exp2(),s=t.sub(i.pow(r).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(s)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Wb.dot(Ib).clamp(),n=zS({dotVH:e,f0:BM,f90:kM}),i=t.mul(Cg.mul(n).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Cg));t.assign(i)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const VM=ng(1),GM=ng(-2),HM=ng(.8),jM=ng(-1),WM=ng(.4),$M=ng(2),XM=ng(.305),qM=ng(3),YM=ng(.21),KM=ng(4),ZM=ng(4),QM=ng(16),JM=Km(([e])=>{const t=cg(av(e)).toVar(),n=ng(-1).toVar();return Jm(t.x.greaterThan(t.z),()=>{Jm(t.x.greaterThan(t.y),()=>{n.assign(Vv(e.x.greaterThan(0),0,3))}).Else(()=>{n.assign(Vv(e.y.greaterThan(0),1,4))})}).Else(()=>{Jm(t.z.greaterThan(t.y),()=>{n.assign(Vv(e.z.greaterThan(0),2,5))}).Else(()=>{n.assign(Vv(e.y.greaterThan(0),1,4))})}),n}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),eE=Km(([e,t])=>{const n=ag().toVar();return Jm(t.equal(0),()=>{n.assign(ag(e.z,e.y).div(av(e.x)))}).ElseIf(t.equal(1),()=>{n.assign(ag(e.x.negate(),e.z.negate()).div(av(e.y)))}).ElseIf(t.equal(2),()=>{n.assign(ag(e.x.negate(),e.y).div(av(e.z)))}).ElseIf(t.equal(3),()=>{n.assign(ag(e.z.negate(),e.y).div(av(e.x)))}).ElseIf(t.equal(4),()=>{n.assign(ag(e.x.negate(),e.z).div(av(e.y)))}).Else(()=>{n.assign(ag(e.x,e.y).div(av(e.z)))}),f_(.5,n.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),tE=Km(([e])=>{const t=ng(0).toVar();return Jm(e.greaterThanEqual(HM),()=>{t.assign(VM.sub(e).mul(jM.sub(GM)).div(VM.sub(HM)).add(GM))}).ElseIf(e.greaterThanEqual(WM),()=>{t.assign(HM.sub(e).mul($M.sub(jM)).div(HM.sub(WM)).add(jM))}).ElseIf(e.greaterThanEqual(XM),()=>{t.assign(WM.sub(e).mul(qM.sub($M)).div(WM.sub(XM)).add($M))}).ElseIf(e.greaterThanEqual(YM),()=>{t.assign(XM.sub(e).mul(KM.sub(qM)).div(XM.sub(YM)).add(qM))}).Else(()=>{t.assign(ng(-2).mul(X_(f_(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),nE=Km(([e,t])=>{const n=e.toVar();n.assign(f_(2,n).sub(1));const i=cg(n,1).toVar();return Jm(t.equal(0),()=>{i.assign(i.zyx)}).ElseIf(t.equal(1),()=>{i.assign(i.xzy),i.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{i.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{i.assign(i.zyx),i.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{i.assign(i.xzy),i.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{i.z.mulAssign(-1)}),i}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),iE=Km(([e,t,n,i,r,s])=>{const a=ng(n),o=cg(t),l=Iv(tE(a),GM,s),u=J_(l),c=K_(l),h=cg(rE(e,o,c,i,r,s)).toVar();return Jm(u.notEqual(0),()=>{const t=cg(rE(e,o,c.add(1),i,r,s)).toVar();h.assign(Dv(h,t,u))}),h}),rE=Km(([e,t,n,i,r,s])=>{const a=ng(n).toVar(),o=cg(t),l=ng(JM(o)).toVar(),u=ng(xv(ZM.sub(a),0)).toVar();a.assign(xv(a,ZM));const c=ng(W_(a)).toVar(),h=ag(eE(o,l).mul(c.sub(2)).add(1)).toVar();return Jm(l.greaterThan(2),()=>{h.y.addAssign(c),l.subAssign(3)}),h.x.addAssign(l.mul(c)),h.x.addAssign(u.mul(f_(3,QM))),h.y.addAssign(f_(4,W_(s).sub(c))),h.x.mulAssign(i),h.y.mulAssign(r),e.sample(h).grad(ag(),ag())}),sE=Km(({envMap:e,mipInt:t,outputDirection:n,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=tv(i),u=n.mul(l).add(r.cross(n).mul(ev(i))).add(r.mul(r.dot(n).mul(l.oneMinus())));return rE(e,u,t,s,a,o)}),aE=Km(({n:e,latitudinal:t,poleAxis:n,outputDirection:i,weights:r,samples:s,dTheta:a,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})=>{const d=cg(Vv(t,n,Av(n,i))).toVar();Jm(d.equal(cg(0)),()=>{d.assign(cg(i.z,0,i.x.negate()))}),d.assign(Q_(d));const p=cg().toVar();return p.addAssign(r.element(0).mul(sE({theta:0,axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),GT({start:ig(1),end:e},({i:e})=>{Jm(e.greaterThanEqual(s),()=>{My("break").toStack()});const t=ng(a.mul(ng(e))).toVar();p.addAssign(r.element(e).mul(sE({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),p.addAssign(r.element(e).mul(sE({theta:t,axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})))}),fg(p,1)}),oE=Km(([e])=>{const t=rg(e).toVar();return t.assign(t.shiftLeft(rg(16)).bitOr(t.shiftRight(rg(16)))),t.assign(t.bitAnd(rg(1431655765)).shiftLeft(rg(1)).bitOr(t.bitAnd(rg(2863311530)).shiftRight(rg(1)))),t.assign(t.bitAnd(rg(858993459)).shiftLeft(rg(2)).bitOr(t.bitAnd(rg(3435973836)).shiftRight(rg(2)))),t.assign(t.bitAnd(rg(252645135)).shiftLeft(rg(4)).bitOr(t.bitAnd(rg(4042322160)).shiftRight(rg(4)))),t.assign(t.bitAnd(rg(16711935)).shiftLeft(rg(8)).bitOr(t.bitAnd(rg(4278255360)).shiftRight(rg(8)))),ng(t).mul(2.3283064365386963e-10)}),lE=Km(([e,t])=>ag(ng(e).div(ng(t)),oE(e))),uE=Km(([e,t,n])=>{const i=n.mul(n).toConst(),r=cg(1,0,0).toConst(),s=Av(t,r).toConst(),a=q_(e.x).toConst(),o=f_(2,3.14159265359).mul(e.y).toConst(),l=a.mul(tv(o)).toConst(),u=a.mul(ev(o)).toVar(),c=f_(.5,t.z.add(1)).toConst();u.assign(c.oneMinus().mul(q_(l.mul(l).oneMinus())).add(c.mul(u)));const h=r.mul(l).add(s.mul(u)).add(t.mul(q_(xv(0,l.mul(l).add(u.mul(u)).oneMinus()))));return Q_(cg(i.mul(h.x),i.mul(h.y),xv(0,h.z)))}),cE=Km(({roughness:e,mipInt:t,envMap:n,N_immutable:i,GGX_SAMPLES:r,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=cg(i).toVar(),u=cg(0).toVar(),c=ng(0).toVar();return Jm(e.lessThan(.001),()=>{u.assign(rE(n,l,t,s,a,o))}).Else(()=>{const i=Vv(av(l.z).lessThan(.999),cg(0,0,1),cg(1,0,0)),h=Q_(Av(i,l)).toVar(),d=Av(l,h).toVar();GT({start:rg(0),end:r},({i:i})=>{const p=lE(i,r),f=uE(p,cg(0,0,1),e),m=Q_(h.mul(f.x).add(d.mul(f.y)).add(l.mul(f.z))),g=Q_(m.mul(wv(l,m).mul(2)).sub(l)),_=xv(wv(l,g),0);Jm(_.greaterThan(0),()=>{const e=rE(n,g,t,s,a,o);u.addAssign(e.mul(_)),c.addAssign(_)})}),Jm(c.greaterThan(0),()=>{u.assign(u.div(c))})}),fg(u,1)}),hE=[.125,.215,.35,.446,.526,.582],dE=20,pE=new Ra(-1,1,1,-1,0,1),fE=new Sa(90,1),mE=new _i;let gE=null,_E=0,vE=0;const yE=new dn,bE=new WeakMap,xE=[3,1,5,0,4,2],TE=nE(Py(),Ny("faceIndex")).normalize(),SE=cg(TE.x,TE.y,TE.z);class ME{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,i=100,r={}){const{size:s=256,position:a=yE,renderTarget:o=null}=r;if(this._setSize(s),!1===this._hasInitialized){Xt('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const s=o||this._allocateTarget();return r.renderTarget=s,this.fromSceneAsync(e,t,n,i,r),s}gE=this._renderer.getRenderTarget(),_E=this._renderer.getActiveCubeFace(),vE=this._renderer.getActiveMipmapLevel();const l=o||this._allocateTarget();return l.depthBuffer=!0,this._init(l),this._sceneToCubeUV(e,n,i,l,a),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,n=.1,i=100,r={}){return Yt('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,n,i,r)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){Xt('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const n=t||this._allocateTarget();return this.fromEquirectangularAsync(e,n),n}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Yt('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){Xt("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const n=t||this._allocateTarget();return this.fromCubemapAsync(e,t),n}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Yt('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=RE(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=CE(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===ee||e.mapping===te?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(gE,_E,vE),e.scissorTest=!1,wE(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),gE=this._renderer.getRenderTarget(),_E=this._renderer.getActiveCubeFace(),vE=this._renderer.getActiveMipmapLevel();const n=t||this._allocateTarget();return this._init(n),this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTarget(){return EE(3*Math.max(this._cubeSize,112),4*this._cubeSize)}_init(e){if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=EE(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=function(e){const t=[],n=[],i=[];let r=e;const s=e-4+1+hE.length;for(let a=0;a<s;a++){const s=Math.pow(2,r);t.push(s);let o=1/s;a>e-4?o=hE[a-e+4-1]:0===a&&(o=0),n.push(o);const l=1/(s-2),u=-l,c=1+l,h=[u,u,c,u,c,c,u,u,c,c,u,c],d=6,p=6,f=3,m=2,g=1,_=new Float32Array(f*p*d),v=new Float32Array(m*p*d),y=new Float32Array(g*p*d);for(let e=0;e<d;e++){const t=e%3*2/3-1,n=e>2?0:-1,i=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0],r=xE[e];_.set(i,f*p*r),v.set(h,m*p*r);const s=[r,r,r,r,r,r];y.set(s,g*p*r)}const b=new vr;b.setAttribute("position",new nr(_,f)),b.setAttribute("uv",new nr(v,m)),b.setAttribute("faceIndex",new nr(y,g)),i.push(new Wr(b,null)),r>4&&r--}return{lodMeshes:i,sizeLods:t,sigmas:n}}(t)),this._blurMaterial=function(e,t,n){const i=$y(new Array(dE).fill(0)),r=a_(new dn(0,1,0)),s=a_(0),a=ng(dE),o=a_(0),l=a_(1),u=zy(),c=a_(0),h=ng(1/t),d=ng(1/n),p=ng(e),f={n:a,latitudinal:o,weights:i,poleAxis:r,outputDirection:SE,dTheta:s,samples:l,envMap:u,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},m=AE("blur");return m.fragmentNode=aE({...f,latitudinal:o.equal(1)}),bE.set(m,f),m}(t,e.width,e.height),this._ggxMaterial=function(e,t,n){const i=zy(),r=a_(0),s=a_(0),a=ng(1/t),o=ng(1/n),l=ng(e),u={envMap:i,roughness:r,mipInt:s,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:l},c=AE("ggx");return c.fragmentNode=cE({...u,N_immutable:SE,GGX_SAMPLES:rg(512)}),bE.set(c,u),c}(t,e.width,e.height)}}async _compileMaterial(e){const t=new Wr(new vr,e);await this._renderer.compile(t,pE)}_sceneToCubeUV(e,t,n,i,r){const s=fE;s.near=t,s.far=n;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],l=this._renderer,u=l.autoClear;l.getClearColor(mE),l.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new Wr(new xs,new Dr({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const c=this._backgroundBox,h=c.material;let d=!1;const p=e.background;p?p.isColor&&(h.color.copy(p),e.background=null,d=!0):(h.color.copy(mE),d=!0),l.setRenderTarget(i),l.clear(),d&&l.render(c,s);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x+o[t],r.y,r.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y+o[t],r.z)):(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y,r.z+o[t]));const u=this._cubeSize;wE(i,n*u,t>2?u:0,u,u),l.render(e,s)}l.autoClear=u,e.background=p}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===ee||e.mapping===te;i?null===this._cubemapMaterial&&(this._cubemapMaterial=RE(e)):null===this._equirectMaterial&&(this._equirectMaterial=CE(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const s=this._lodMeshes[0];s.material=r;const a=this._cubeSize;wE(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,pE)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let t=1;t<i;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=n}_applyGGXFilter(e,t,n){const i=this._renderer,r=this._pingPongRenderTarget,s=this._ggxMaterial,a=this._lodMeshes[n];a.material=s;const o=bE.get(s),l=n/(this._lodMeshes.length-1),u=t/(this._lodMeshes.length-1),c=Math.sqrt(l*l-u*u)*(0+1.25*l),{_lodMax:h}=this,d=this._sizeLods[n],p=3*d*(n>h-4?n-h+4:0),f=4*(this._cubeSize-d);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=c,o.mipInt.value=h-t,wE(r,p,f,3*d,2*d),i.setRenderTarget(r),i.render(a,pE),r.texture.frame=(r.texture.frame||0)+1,o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=h-n,wE(e,p,f,3*d,2*d),i.setRenderTarget(e),i.render(a,pE)}_blur(e,t,n,i,r){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,n,i,"latitudinal",r),this._halfBlur(s,e,n,n,i,"longitudinal",r)}_halfBlur(e,t,n,i,r,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&qt("blur direction must be either latitudinal or longitudinal!");const u=this._lodMeshes[i];u.material=l;const c=bE.get(l),h=this._sizeLods[n]-1,d=isFinite(r)?Math.PI/(2*h):2*Math.PI/39,p=r/d,f=isFinite(r)?1+Math.floor(3*p):dE;f>dE&&Xt(`sigmaRadians, ${r}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let e=0;e<dE;++e){const t=e/p,n=Math.exp(-t*t/2);m.push(n),0===e?g+=n:e<f&&(g+=2*n)}for(let e=0;e<m.length;e++)m[e]=m[e]/g;e.texture.frame=(e.texture.frame||0)+1,c.envMap.value=e.texture,c.samples.value=f,c.weights.array=m,c.latitudinal.value="latitudinal"===s?1:0,a&&(c.poleAxis.value=a);const{_lodMax:_}=this;c.dTheta.value=d,c.mipInt.value=_-n;const v=this._sizeLods[i];wE(t,3*v*(i>_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,pE)}}function EE(e,t){const n=new Ln(e,t,{magFilter:he,minFilter:he,generateMipmaps:!1,type:xe,format:Ce,colorSpace:xt});return n.texture.mapping=re,n.texture.name="PMREM.cubeUv",n.texture.isPMREMTexture=!0,n.scissorTest=!0,n}function wE(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function AE(e){const t=new bS;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function RE(e){const t=AE("cubemap");return t.fragmentNode=ax(e,SE),t}function CE(e){const t=AE("equirect");return t.fragmentNode=zy(e,AS(SE),0),t}const NE=new WeakMap;function PE(e,t,n){const i=function(e){let t=NE.get(e);void 0===t&&(t=new WeakMap,NE.set(e,t));return t}(t);let r=i.get(e);if((void 0!==r?r.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const n=6;for(let i=0;i<n;i++)void 0!==e[i]&&t++;return t===n}(t))return null;r=n.fromCubemap(e,r)}else{if(!function(e){return null!=e&&e.height>0}(t))return null;r=n.fromEquirectangular(e,r)}r.pmremVersion=e.pmremVersion,i.set(e,r)}return r.texture}class LE extends tm{static get type(){return"PMREMNode"}constructor(e,t=null,n=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=n,this._generator=null;const i=new Nn;i.isRenderTargetTexture=!0,this._texture=zy(i),this._width=a_(0),this._height=a_(0),this._maxMip=a_(0),this.updateBeforeType=Gf}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=function(e){const t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const n=t?t.pmremVersion:-1,i=this._value;n!==i.pmremVersion&&(t=!0===i.isPMREMTexture?i:PE(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new ME(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=Qb.mul(cg(t.x,t.y.negate(),t.z));let n=this.levelNode;return null===n&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),iE(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const DE=Wm(LE).setParameterLength(1,3),IE=new WeakMap;class UE extends qT{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){const i=n.isTextureNode?n.value:t[n.property],r=this._getPMREMNodeCache(e.renderer);let s=r.get(i);void 0===s&&(s=DE(i),r.set(i,s)),n=s}const i=!0===t.useAnisotropy||t.anisotropy>0?Lx:Hb,r=n.context(FE(Ag,i)).mul(Zb),s=n.context(OE(jb)).mul(Math.PI).mul(Zb),a=vy(r),o=vy(s);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=n.context(FE(Ng,Wb)).mul(Zb),t=vy(e);l.addAssign(t)}}_getPMREMNodeCache(e){let t=IE.get(e);return void 0===t&&(t=new WeakMap,IE.set(e,t)),t}}const FE=(e,t)=>{let n=null;return{getUV:()=>(null===n&&(n=Ib.negate().reflect(t),n=Nv(e).mix(n,t).normalize(),n=n.transformDirection(gb)),n),getTextureLevel:()=>e}},OE=e=>({getUV:()=>e,getTextureLevel:()=>ng(1)}),BE=new Xs;class kE extends bS{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(BE),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new UE(t):null}setupLightingModel(){return new zM}setupSpecular(){const e=Dv(cg(.04),Mg.rgb,Rg);zg.assign(cg(.04)),Vg.assign(e),Gg.assign(1)}setupVariants(){const e=this.metalnessNode?ng(this.metalnessNode):Jx;Rg.assign(e);let t=this.roughnessNode?ng(this.roughnessNode):Qx;t=KS({roughness:t}),Ag.assign(t),this.setupSpecular(),Eg.assign(Mg.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const zE=new qs;class VE extends kE{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(zE),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?ng(this.iorNode):pT;Xg.assign(e),zg.assign(bv(Cv(Xg.sub(1).div(Xg.add(1))).mul(Yx),cg(1)).mul(qx)),Vg.assign(Dv(zg,Mg.rgb,Rg)),Gg.assign(Dv(qx,1,Rg))}setupLightingModel(){return new zM(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?ng(this.clearcoatNode):tT,t=this.clearcoatRoughnessNode?ng(this.clearcoatRoughnessNode):nT;Cg.assign(e),Ng.assign(KS({roughness:t}))}if(this.useSheen){const e=this.sheenNode?cg(this.sheenNode):sT,t=this.sheenRoughnessNode?ng(this.sheenRoughnessNode):aT;Pg.assign(e),Lg.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?ng(this.iridescenceNode):lT,t=this.iridescenceIORNode?ng(this.iridescenceIORNode):uT,n=this.iridescenceThicknessNode?ng(this.iridescenceThicknessNode):cT;Dg.assign(e),Ig.assign(t),Ug.assign(n)}if(this.useAnisotropy){const e=(this.anisotropyNode?ag(this.anisotropyNode):oT).toVar();Og.assign(e.length()),Jm(Og.equal(0),()=>{e.assign(ag(1,0))}).Else(()=>{e.divAssign(ag(Og)),Og.assign(Og.saturate())}),Fg.assign(Og.pow2().mix(Ag.pow2(),1)),Bg.assign(Px[0].mul(e.x).add(Px[1].mul(e.y))),kg.assign(Px[1].mul(e.x).sub(Px[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?ng(this.transmissionNode):hT,t=this.thicknessNode?ng(this.thicknessNode):dT,n=this.attenuationDistanceNode?ng(this.attenuationDistanceNode):fT,i=this.attenuationColorNode?cg(this.attenuationColorNode):mT;if(qg.assign(e),Yg.assign(t),Kg.assign(n),Zg.assign(i),this.useDispersion){const e=this.dispersionNode?ng(this.dispersionNode):xT;Qg.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?cg(this.clearcoatNormalNode):iT}setup(e){e.context.setupClearcoatNormal=()=>qv(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.iorNode=e.iorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const GE=Km(({normal:e,lightDirection:t,builder:n})=>{const i=e.dot(t),r=ag(i.mul(.5).add(.5),0);if(n.material.gradientMap){const e=dx("gradientMap","texture").context({getUV:()=>r});return cg(e.r)}{const e=r.fwidth().mul(.5);return Dv(cg(.7),cg(1),Ov(ng(.7).sub(e.x),ng(.7).add(e.x),r.x))}});class HE extends FS{direct({lightDirection:e,lightColor:t,reflectedLight:n},i){const r=GE({normal:Bb,lightDirection:e,builder:i}).mul(t);n.directDiffuse.addAssign(r.mul(VS({diffuseColor:Mg.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(VS({diffuseColor:Mg}))),i.indirectDiffuse.mulAssign(t)}}const jE=new Ks;class WE extends bS{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(jE),this.setValues(e)}setupLightingModel(){return new HE}}const $E=Km(()=>{const e=cg(Ib.z,0,Ib.x.negate()).normalize(),t=Ib.cross(e);return ag(e.dot(Hb),t.dot(Hb)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),XE=new ta;class qE extends bS{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(XE),this.setValues(e)}setupVariants(e){const t=$E;let n;n=e.material.matcap?dx("matcap","texture").context({getUV:()=>t}):cg(Dv(.2,.8,t.y)),Mg.rgb.mulAssign(n.rgb)}}class YE extends tm{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return vg(e,i,i.negate(),e).mul(n)}{const e=t,i=bg(fg(1,0,0,0),fg(0,tv(e.x),ev(e.x).negate(),0),fg(0,ev(e.x),tv(e.x),0),fg(0,0,0,1)),r=bg(fg(tv(e.y),0,ev(e.y),0),fg(0,1,0,0),fg(ev(e.y).negate(),0,tv(e.y),0),fg(0,0,0,1)),s=bg(fg(tv(e.z),ev(e.z).negate(),0,0),fg(ev(e.z),tv(e.z),0,0),fg(0,0,1,0),fg(0,0,0,1));return i.mul(r).mul(s).mul(fg(n,1)).xyz}}}const KE=Wm(YE).setParameterLength(2),ZE=new Mr;class QE extends bS{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(ZE),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,{positionNode:i,rotationNode:r,scaleNode:s,sizeAttenuation:a}=this,o=Sb.mul(cg(i||0));let l=ag(xb[0].xyz.length(),xb[1].xyz.length());null!==s&&(l=l.mul(ag(s))),n.isPerspectiveCamera&&!1===a&&(l=l.mul(o.z.negate()));let u=Rb.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,n)=>new iy(e,t,n))("center","vec2",t);u=u.sub(e.sub(.5))}u=u.mul(l);const c=ng(r||rT),h=KE(u,c);return fg(o.xy.add(h),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const JE=new ms,ew=new cn;class tw extends QE{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(JE),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Sb.mul(cg(e||Cb)).xyz}setupVertexSprite(e){const{material:t,camera:n}=e,{rotationNode:i,scaleNode:r,sizeNode:s,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let l=null!==s?ag(s):bT;l=l.mul(Zy),n.isPerspectiveCamera&&!0===a&&(l=l.mul(nw.div(Db.z.negate()))),r&&r.isNode&&(l=l.mul(ag(r)));let u=Rb.xy;if(i&&i.isNode){const e=ng(i);u=KE(u,e)}return u=u.mul(l),u=u.div(nb.div(2)),u=u.mul(o.w),o=o.add(fg(u,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const nw=a_(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(ew);this.value=.5*t.y});class iw extends FS{constructor(){super(),this.shadowNode=ng(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Mg.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Mg.rgb)}}const rw=new zs;class sw extends bS{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(rw),this.setValues(e)}setupLightingModel(){return new iw}}Tg("vec3"),Tg("vec3"),Tg("vec3");class aw{constructor(e,t,n){this.renderer=e,this.nodes=t,this.info=n,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,n),this.renderer._inspector.finish()};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class ow{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let n=this.weakMaps[t];return void 0===n&&(n=new WeakMap,this.weakMaps[t]=n),n}get(e){let t=this._getWeakMap(e);for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),void 0===t)return;return t.get(e[e.length-1])}set(e,t){let n=this._getWeakMap(e);for(let t=0;t<e.length-1;t++){const i=e[t];!1===n.has(i)&&n.set(i,new WeakMap),n=n.get(i)}return n.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),void 0===t)return!1;return t.delete(e[e.length-1])}}let lw=0;class uw{constructor(e,t,n,i,r,s,a,o,l,u){this.id=lw++,this._nodes=e,this._geometries=t,this.renderer=n,this.object=i,this.material=r,this.scene=s,this.camera=a,this.lightsNode=o,this.context=l,this.geometry=i.geometry,this.version=r.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=u,this.clippingContextCacheKey=null!==u?u.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],i=new Set,r={};for(const s of e){let e;if(s.node&&s.node.attribute?e=s.node.attribute:(e=t.getAttribute(s.name),r[s.name]=e.id),void 0===e)continue;n.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;i.add(a)}return this.attributes=n,this.attributesId=r,this.vertexBuffers=Array.from(i.values()),n}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:n,group:i,drawRange:r}=this,s=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let l=1;if(!0===n.isInstancedBufferGeometry?l=n.instanceCount:void 0!==e.count&&(l=Math.max(0,e.count)),0===l)return null;if(s.instanceCount=l,!0===e.isBatchedMesh)return s;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let c=r.start*u,h=(r.start+r.count)*u;null!==i&&(c=Math.max(c,i.start*u),h=Math.min(h,(i.start+i.count)*u));const d=n.attributes.position;let p=1/0;o?p=a.count:null!=d&&(p=d.count),c=Math.max(c,0),h=Math.min(h,p);const f=h-c;return f<0||f===1/0?null:(s.vertexCount=f,s.firstVertex=c,s)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const n of Object.keys(e.attributes).sort()){const i=e.attributes[n];t+=n+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const n of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[n];t+="morph-"+n+",";for(let e=0,n=i.length;e<n;e++){t+=i[e].id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:n}=this;let i=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let n=Object.getPrototypeOf(e);for(;n;){const e=Object.getOwnPropertyDescriptors(n);for(const n in e)if(void 0!==e[n]){const i=e[n];i&&"function"==typeof i.get&&t.push(n)}n=Object.getPrototypeOf(n)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const r=t[e];let s;if(null!==r){const e=typeof r;"number"===e?s=0!==r?"1":"0":"object"===e?(s="{",r.isTexture&&(s+=r.mapping,!0===n.backend.isWebGPUBackend&&(s+=r.magFilter,s+=r.minFilter,s+=r.wrapS,s+=r.wrapT,s+=r.wrapR)),s+="}"):s=String(r)}else s=String(r);i+=s+","}return i+=this.clippingContextCacheKey+",",e.geometry&&(i+=this.getGeometryCacheKey()),e.skeleton&&(i+=e.skeleton.bones.length+","),e.isBatchedMesh&&(i+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(i+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1||Array.isArray(e.morphTargetInfluences))&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",Nf(i)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(null!==this.attributes){const e=this.attributesId;for(const t in e){const n=this.geometry.getAttribute(t);if(void 0===n||e[t]!==n.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Lf(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Lf(e,1)),e=Lf(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const cw=[];class hw{constructor(e,t,n,i,r,s){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=i,this.bindings=r,this.info=s,this.chainMaps={}}get(e,t,n,i,r,s,a,o){const l=this.getChainMap(o);cw[0]=e,cw[1]=t,cw[2]=s,cw[3]=r;let u=l.get(cw);return void 0===u?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,i,r,s,a,o),l.set(cw,u)):(u.camera=i,u.updateClipping(a),u.needsGeometryUpdate&&u.setGeometry(e.geometry),(u.version!==t.version||u.needsUpdate)&&(u.initialCacheKey!==u.getCacheKey()?(u.dispose(),u=this.get(e,t,n,i,r,s,a,o)):u.version=t.version)),cw[0]=null,cw[1]=null,cw[2]=null,cw[3]=null,u}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new ow)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,i,r,s,a,o,l,u,c){const h=this.getChainMap(c),d=new uw(e,t,n,i,r,s,a,o,l,u);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.deleteForRender(d),this.nodes.delete(d),h.delete(d.getChainArray())},d}}class dw{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const pw=1,fw=2,mw=3,gw=4,_w=16;class vw extends dw{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const n=this.get(e);if(void 0===n.version)t===pw?this.backend.createAttribute(e):t===fw?this.backend.createIndexAttribute(e):t===mw?this.backend.createStorageAttribute(e):t===gw&&this.backend.createIndirectStorageAttribute(e),n.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(n.version<t.version||t.usage===It)&&(this.backend.updateAttribute(e),n.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function yw(e){return null!==e.index?e.index.version:e.attributes.position.version}function bw(e){return null!==e.index?e.index.id:e.attributes.position.id}function xw(e){const t=[],n=e.index,i=e.attributes.position;if(null!==n){const e=n.array;for(let n=0,i=e.length;n<i;n+=3){const i=e[n+0],r=e[n+1],s=e[n+2];t.push(i,r,r,s,s,i)}}else{for(let e=0,n=i.array.length/3-1;e<n;e+=3){const n=e+0,i=e+1,r=e+2;t.push(n,i,i,r,r,n)}}const r=new(i.count>=65535?rr:ir)(t,1);return r.version=yw(e),r.__id=bw(e),r}class Tw extends dw{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const n=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const s=this.wireframes.get(t);void 0!==s&&this.attributes.delete(s),t.removeEventListener("dispose",n),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",n),this._geometryDisposeListeners.set(t,n)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,mw):this.updateAttribute(e,pw);const n=this.getIndex(e);null!==n&&this.updateAttribute(n,fw);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,gw)}updateAttribute(e,t){const n=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,n)):this.attributeCall.get(e.data)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e.data,n),this.attributeCall.set(e,n)):this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:n}=e;let i=t.index;if(!0===n.wireframe){const e=this.wireframes;let n=e.get(t);void 0===n?(n=xw(t),e.set(t,n)):n.version===yw(t)&&n.__id===bw(t)||(this.attributes.delete(n),n=xw(t),e.set(t,n)),i=n}return i}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class Sw{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine?this.render.lines+=n*(t-1):qt("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class Mw{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Ew extends Mw{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class ww extends Mw{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Aw=0;class Rw{constructor(e,t,n,i=null,r=null){this.id=Aw++,this.code=e,this.stage=t,this.name=n,this.transforms=i,this.attributes=r,this.usedTimes=0}}class Cw extends dw{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:n}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const s=this.nodes.getForCompute(e);let a=this.programs.compute.get(s.computeShader);void 0===a&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),a=new Rw(s.computeShader,"compute",e.name,s.transforms,s.nodeAttributes),this.programs.compute.set(s.computeShader,a),n.createProgram(a));const o=this._getComputeCacheKey(e,a);let l=this.caches.get(o);void 0===l&&(r&&0===r.usedTimes&&this._releasePipeline(r),l=this._getComputePipeline(e,a,o,t)),l.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=l}return i.pipeline}getForRender(e,t=null){const{backend:n}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const s=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(s.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new Rw(s.vertexShader,"vertex",a),this.programs.vertex.set(s.vertexShader,o),n.createProgram(o));let l=this.programs.fragment.get(s.fragmentShader);void 0===l&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),l=new Rw(s.fragmentShader,"fragment",a),this.programs.fragment.set(s.fragmentShader,l),n.createProgram(l));const u=this._getRenderCacheKey(e,o,l);let c=this.caches.get(u);void 0===c?(r&&0===r.usedTimes&&this._releasePipeline(r),c=this._getRenderPipeline(e,o,l,u,t)):e.pipeline=c,c.usedTimes++,o.usedTimes++,l.usedTimes++,i.pipeline=c}return i.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,n,i){n=n||this._getComputeCacheKey(e,t);let r=this.caches.get(n);return void 0===r&&(r=new ww(n,t),this.caches.set(n,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,n,i,r){i=i||this._getRenderCacheKey(e,t,n);let s=this.caches.get(i);return void 0===s&&(s=new Ew(i,t,n),this.caches.set(i,s),e.pipeline=s,this.backend.createRenderPipeline(e,r)),s}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,n=e.stage;this.programs[n].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class Nw extends dw{constructor(e,t,n,i,r,s){super(),this.backend=e,this.textures=n,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=s,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?gw:mw;this.attributes.update(e,n)}}_update(e,t){const{backend:n}=this;let i=!1,r=!0,s=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?gw:mw,s=n.get(t);this.attributes.update(e,r),s.attribute!==e&&(s.attribute=e,i=!0)}if(t.isUniformBuffer){t.update()&&n.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),l=t.texture,u=this.textures.get(l);o&&(this.textures.updateTexture(l),t.generation!==u.generation&&(t.generation=u.generation,i=!0),u.bindGroups.add(e));if(void 0!==n.get(l).externalTexture||u.isDefaultTexture?r=!1:(s=10*s+l.id,a+=l.version),!0===l.isStorageTexture&&!0===l.mipmapsAutoUpdate){const e=this.get(l);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(l)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(l),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,i=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===i&&this.backend.updateBindings(e,t,r?s:0,a)}}function Pw(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?e.z-t.z:e.id-t.id}function Lw(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 Dw(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class Iw{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,n),this.lightsArray=[],this.scene=t,this.camera=n,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,n,i,r,s,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:n,groupOrder:i,renderOrder:e.renderOrder,z:r,group:s,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=n,o.groupOrder=i,o.renderOrder=e.renderOrder,o.z=r,o.group=s,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,n,i,r,s,a){const o=this.getNextRenderItem(e,t,n,i,r,s,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===n.transparent||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(Dw(n)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,n,i,r,s,a){const o=this.getNextRenderItem(e,t,n,i,r,s,a);!0===n.transparent||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(Dw(n)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||Pw),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Lw),this.transparent.length>1&&this.transparent.sort(t||Lw)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.groupOrder=null,t.renderOrder=null,t.z=null,t.group=null,t.clippingContext=null}}}const Uw=[];class Fw{constructor(e){this.lighting=e,this.lists=new ow}get(e,t){const n=this.lists;Uw[0]=e,Uw[1]=t;let i=n.get(Uw);return void 0===i&&(i=new Iw(this.lighting,e,t),n.set(Uw,i)),Uw[0]=null,Uw[1]=null,i}dispose(){this.lists=new ow}}let Ow=0;class Bw{constructor(){this.id=Ow++,this.mrt=null,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new Pn,this.scissor=!1,this.scissorValue=new Pn,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.isRenderContext=!0}getCacheKey(){return kw(this)}}function kw(e){const{textures:t,activeCubeFace:n,activeMipmapLevel:i}=e,r=[n,i];for(const e of t)r.push(e.id);return Pf(r)}class zw{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,n=0){let i;if(null===e)i="default";else{const t=e.texture.format,n=e.texture.type;i=`${e.textures.length}:${t}:${n}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const r=i+"-"+(null!==t?t.id:"default")+"-"+n;let s=this._renderContexts[r];return void 0===s&&(s=new Bw,s.mrt=t,this._renderContexts[r]=s),null!==e&&(s.sampleCount=0===e.samples?1:e.samples),s.clearDepthValue=this.renderer.getClearDepth(),s.clearStencilValue=this.renderer.getClearStencil(),s}dispose(){this._renderContexts={}}}const Vw=new dn;class Gw extends dw{constructor(e,t,n){super(),this.renderer=e,this.backend=t,this.info=n}updateRenderTarget(e,t=0){const n=this.get(e),i=0===e.samples?1:e.samples,r=n.depthTextureMips||(n.depthTextureMips={}),s=e.textures,a=this.getSize(s[0]),o=a.width>>t,l=a.height>>t;let u=e.depthTexture||r[t];const c=!0===e.depthBuffer||!0===e.stencilBuffer;let h=!1;void 0===u&&c&&(u=new vs,u.format=e.stencilBuffer?Pe:Ne,u.type=e.stencilBuffer?Me:ye,u.image.width=o,u.image.height=l,u.image.depth=a.depth,u.renderTarget=e,u.isArrayTexture=!0===e.multiview&&a.depth>1,r[t]=u),n.width===a.width&&a.height===n.height||(h=!0,u&&(u.needsUpdate=!0,u.image.width=o,u.image.height=l,u.image.depth=u.isArrayTexture?u.image.depth:1)),n.width=a.width,n.height=a.height,n.textures=s,n.depthTexture=u||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==i&&(h=!0,u&&(u.needsUpdate=!0),n.sampleCount=i);const d={sampleCount:i};if(!0!==e.isXRRenderTarget){for(let e=0;e<s.length;e++){const t=s[e];h&&(t.needsUpdate=!0),this.updateTexture(t,d)}u&&this.updateTexture(u,d)}!0!==n.initialized&&(n.initialized=!0,n.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",n.onDispose))}updateTexture(e,t={}){const n=this.get(e);if(!0===n.initialized&&n.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,r=this.backend;if(i&&!0===n.initialized&&r.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:fe}const{width:s,height:a,depth:o}=this.getSize(e);if(t.width=s,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,s,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,i||!0===e.isStorageTexture||!0===e.isExternalTexture)r.createTexture(e,t),n.generation=e.version;else if(e.version>0){const i=e.image;if(void 0===i)Xt("Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)Xt("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const n=[];for(const t of e.images)n.push(t);t.images=n}else t.image=i;void 0!==n.isDefaultTexture&&!0!==n.isDefaultTexture||(r.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t);const s=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!s&&r.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else r.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version;!0!==n.initialized&&(n.initialized=!0,n.generation=e.version,n.bindGroups=new Set,this.info.memory.textures++,e.isVideoTexture&&!0===bn.enabled&&bn.getTransfer(e.colorSpace)!==St&&Xt("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),n.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",n.onDispose)),n.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=Vw){let n=e.images?e.images[0]:e.image;return n?(void 0!==n.image&&(n=n.image),"undefined"!=typeof HTMLVideoElement&&n instanceof HTMLVideoElement?(t.width=n.videoWidth||1,t.height=n.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&n instanceof VideoFrame?(t.width=n.displayWidth||1,t.height=n.displayHeight||1,t.depth=1):(t.width=n.width||1,t.height=n.height||1,t.depth=e.isCubeTexture?6:n.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let i;return i=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,n)))+1,i}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),n=t.textures,i=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e<n.length;e++)this._destroyTexture(n[e]);i&&this._destroyTexture(i),this.delete(e),this.backend.delete(e)}}_destroyTexture(e){if(!0===this.has(e)){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const n=t.isDefaultTexture;if(this.backend.destroyTexture(e,n),t.bindGroups)for(const e of t.bindGroups){const t=this.backend.get(e);t.groups=void 0,t.versions=void 0}this.delete(e),this.info.memory.textures--}}}class Hw extends _i{constructor(e,t,n,i=1){super(e,t,n),this.a=i}set(e,t,n,i=1){return this.a=i,super.set(e,t,n)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class jw extends xg{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const n=this.getNodeType(e),i=e.getStructTypeNode(n);let r;return null!==i?r=i.getMemberType(e,t):(qt(`TSL: Member "${t}" not found in struct "${n}".`,new Rf),r="float"),r}getHash(){return this.uuid}generate(){return this.name}}class Ww extends Qf{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this.isStackNode=!0}getElementType(e){return this.hasOutput(e)?this.outputNode.getElementType(e):"void"}getNodeType(e){return this.hasOutput(e)?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput(e)?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=this.nodes.length){return!0!==e.isNode?(qt("TSL: Invalid node added to stack.",new Rf),this):(this.nodes.splice(t,0,e),this)}addToStackBefore(e){const t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){const n=new zm(t);return this._currentCond=Vv(e,n),this.addToStack(this._currentCond)}ElseIf(e,t){const n=new zm(t),i=Vv(e,n);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new zm(e),this}Switch(e){return this._expressionNode=Vm(e),this}Case(...e){const t=[];if(e.length>=2)for(let n=0;n<e.length-1;n++)t.push(this._expressionNode.equal(Vm(e[n])));else qt("TSL: Invalid parameter length. Case() requires at least two parameters.",new Rf);const n=new zm(e[e.length-1]);let i=t[0];for(let e=1;e<t.length;e++)i=i.or(t[e]);const r=Vv(i,n);return null===this._currentCond?(this._currentCond=r,this.addToStack(this._currentCond)):(this._currentCond.elseNode=r,this._currentCond=r,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let n=0;for(const i of this.getChildren())i.isVarNode&&i.isIntent(e)&&!0!==i.isAssign(e)||(t["node"+n++]=i);return t.outputNode||null}hasOutput(e){return this.outputNode&&this.outputNode.isNode&&"void"!==this.outputNode.getNodeType(e)}build(e,...t){const n=Qm(),i=e.buildStage;Zm(this),e.setActiveStack(this);const r=t=>{if(this._currentNode=t,!t.isVarNode||!t.isIntent(e)||!0===t.isAssign(e))if("setup"===i)t.build(e);else if("analyze"===i)t.build(e,this);else if("generate"===i){const n=e.getDataFromNode(t,"any").stages,i=n&&n[e.shaderStage];if(t.isVarNode&&i&&1===i.length&&i[0]&&i[0].isStackNode)return;t.build(e,"void")}},s=[...this.nodes];for(const e of s)r(e);this._currentNode=null;const a=this.nodes.filter(e=>-1===s.indexOf(e));for(const e of a)r(e);let o;return o=this.hasOutput(e)?this.outputNode.build(e,...t):super.build(e,...t),Zm(n),e.removeActiveStack(this),o}}const $w=Wm(Ww).setParameterLength(0,1);class Xw extends tm{static get type(){return"BitcastNode"}constructor(e,t,n=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=n,this.isBitcastNode=!0}getNodeType(e){if(null!==this.inputType){const t=this.valueNode.getNodeType(e),n=e.getTypeLength(t);return e.getTypeFromLength(n,this.conversionType)}return this.conversionType}generate(e){const t=this.getNodeType(e);let n="";if(null!==this.inputType){const t=this.valueNode.getNodeType(e);n=1===e.getTypeLength(t)?this.inputType:e.changeComponentType(t,this.inputType)}else n=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,n)}( ${this.valueNode.build(e,n)} )`}}const qw=Xm(Xw).setParameterLength(2),Yw={};class Kw extends O_{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,n){"int"===n?t.assign(qw(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return rg;case"int":return ig;case"uvec2":return lg;case"uvec3":return dg;case"uvec4":return gg;case"ivec2":return og;case"ivec3":return hg;case"ivec4":return mg}}_createTrailingZerosBaseLayout(e,t){const n=this._returnDataNode(t),i=Km(([e])=>{const i=rg(0);this._resolveElementType(e,i,t);const r=(e=>new Xw(e,"uint","float"))(ng(i.bitAnd(uv(i)))),s=r.shiftRight(23).sub(127);return n(s)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createLeadingZerosBaseLayout(e,t){const n=this._returnDataNode(t),i=Km(([e])=>{Jm(e.equal(rg(0)),()=>rg(32));const i=rg(0),r=rg(0);return this._resolveElementType(e,i,t),Jm(i.shiftRight(16).equal(0),()=>{r.addAssign(16),i.shiftLeftAssign(16)}),Jm(i.shiftRight(24).equal(0),()=>{r.addAssign(8),i.shiftLeftAssign(8)}),Jm(i.shiftRight(28).equal(0),()=>{r.addAssign(4),i.shiftLeftAssign(4)}),Jm(i.shiftRight(30).equal(0),()=>{r.addAssign(2),i.shiftLeftAssign(2)}),Jm(i.shiftRight(31).equal(0),()=>{r.addAssign(1)}),n(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createOneBitsBaseLayout(e,t){const n=this._returnDataNode(t),i=Km(([e])=>{const i=rg(0);this._resolveElementType(e,i,t),i.assign(i.sub(i.shiftRight(rg(1)).bitAnd(rg(1431655765)))),i.assign(i.bitAnd(rg(858993459)).add(i.shiftRight(rg(2)).bitAnd(rg(858993459))));const r=i.add(i.shiftRight(rg(4))).bitAnd(rg(252645135)).mul(rg(16843009)).shiftRight(rg(24));return n(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createMainLayout(e,t,n,i){const r=this._returnDataNode(t),s=Km(([e])=>{if(1===n)return r(i(e));{const t=r(0),s=["x","y","z","w"];for(let r=0;r<n;r++){const n=s[r];t[n].assign(i(e[n]))}return t}}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return s}setup(e){const{method:t,aNode:n}=this,{renderer:i}=e;if(i.backend.isWebGPUBackend)return super.setup(e);const r=this.getInputType(e),s=e.getElementType(r),a=e.getTypeLength(r),o=`${t}_base_${s}`,l=`${t}_${r}`;let u=Yw[o];if(void 0===u){switch(t){case Kw.COUNT_LEADING_ZEROS:u=this._createLeadingZerosBaseLayout(o,s);break;case Kw.COUNT_TRAILING_ZEROS:u=this._createTrailingZerosBaseLayout(o,s);break;case Kw.COUNT_ONE_BITS:u=this._createOneBitsBaseLayout(o,s)}Yw[o]=u}let c=Yw[l];void 0===c&&(c=this._createMainLayout(l,r,a,u),Yw[l]=c);return Km(()=>c(n))()}}Kw.COUNT_TRAILING_ZEROS="countTrailingZeros",Kw.COUNT_LEADING_ZEROS="countLeadingZeros",Kw.COUNT_ONE_BITS="countOneBits",new Qr,new dn,new dn,new dn,new Fn,new dn(0,0,-1),new Pn,new dn,new dn,new Pn,new cn;const Zw=new Ln;Qy.flipX(),Zw.depthTexture=new vs(1,1);const Qw=new Ra(-1,1,1,-1,0,1);class Jw extends vr{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new ar([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new ar(t,2))}}const eA=new Jw;class tA extends Wr{constructor(e=null){super(eA,e),this.camera=Qw,this.isQuadMesh=!0}async renderAsync(e){Yt('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,Qw)}render(e){e.render(this,Qw)}}const nA=Km(([e])=>J_(ng(52.9829189).mul(J_(wv(e,ag(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),iA=Km(([e,t,n])=>{const i=ng(2.399963229728653),r=q_(ng(e).add(.5).div(ng(t))),s=ng(e).mul(i).add(n);return ag(tv(s),ev(s)).mul(r)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class rA extends Qf{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===rA.OBJECT?this.updateType=Hf:e===rA.MATERIAL?this.updateType=Gf:e===rA.BEFORE_OBJECT?this.updateBeforeType=Hf:e===rA.BEFORE_MATERIAL&&(this.updateBeforeType=Gf)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}rA.OBJECT="object",rA.MATERIAL="material",rA.BEFORE_OBJECT="beforeObject",rA.BEFORE_MATERIAL="beforeMaterial";const sA=new $n,aA=new Fn,oA=a_(0).setGroup(i_).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),lA=a_(1).setGroup(i_).onRenderUpdate(({scene:e})=>e.backgroundIntensity),uA=a_(new Fn).setGroup(i_).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&300!==t.mapping?(sA.copy(e.backgroundRotation),sA.x*=-1,sA.y*=-1,sA.z*=-1,aA.makeRotationFromEuler(sA)):aA.identity(),aA}),cA=Km(({texture:e,uv:t})=>{const n=1e-4,i=cg().toVar();return Jm(t.x.lessThan(n),()=>{i.assign(cg(1,0,0))}).ElseIf(t.y.lessThan(n),()=>{i.assign(cg(0,1,0))}).ElseIf(t.z.lessThan(n),()=>{i.assign(cg(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{i.assign(cg(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{i.assign(cg(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{i.assign(cg(0,0,-1))}).Else(()=>{const n=.01,r=e.sample(t.add(cg(-.01,0,0))).r.sub(e.sample(t.add(cg(n,0,0))).r),s=e.sample(t.add(cg(0,-.01,0))).r.sub(e.sample(t.add(cg(0,n,0))).r),a=e.sample(t.add(cg(0,0,-.01))).r.sub(e.sample(t.add(cg(0,0,n))).r);i.assign(cg(r,s,a))}),i.normalize()});class hA extends By{static get type(){return"Texture3DNode"}constructor(e,t=null,n=null){super(e,t,n),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return cg(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return cA({texture:this,uv:e})}}const dA=Wm(hA).setParameterLength(1,3);Km(([e,t])=>e.mul(t).floor().div(t));const pA=new cn;class fA extends By{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){return e.getNodeProperties(this).passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class mA extends fA{static get type(){return"PassMultipleTextureNode"}constructor(e,t,n=!1){super(e,null),this.textureName=t,this.previousTexture=n,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class gA extends tm{static get type(){return"PassNode"}constructor(e,t,n,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new vs;r.isRenderTargetTexture=!0,r.name="depth";const s=new Ln(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:xe,...i});s.texture.name="output",s.depthTexture=r,this.renderTarget=s,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:s.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=a_(0),this._cameraFar=a_(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=Vf,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return Xt("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return Xt("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const n=this._textures[e],i=this.renderTarget.textures.indexOf(n);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=n,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=new mA(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new mA(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const n=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=cS(this.getTextureNode(e),n,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const n=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=lS(r,n,i)}return t}async compileAsync(e){const t=e.getRenderTarget(),n=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(n)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),this.scope===gA.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:n}=this;let i,r;const s=t.getOutputRenderTarget();s&&!0===s.isXRRenderTarget?(r=1,i=t.xr.getCamera(),t.xr.updateCamera(i),pA.set(s.width,s.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(pA)),this._pixelRatio=r,this.setSize(pA.width,pA.height);const a=t.getRenderTarget(),o=t.getMRT(),l=t.autoClear,u=t.transparent,c=t.opaque,h=i.layers.mask,d=t.contextNode,p=n.overrideMaterial;this._cameraNear.value=i.near,this._cameraFar.value=i.far,null!==this._layers&&(i.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);null!==this.overrideMaterial&&(n.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:Hv({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const f=n.name;n.name=this.name?this.name:n.name,t.render(n,i),n.name=f,n.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(o),t.autoClear=l,t.transparent=u,t.opaque=c,t.contextNode=d,i.layers.mask=h}setSize(e,t){this._width=e,this._height=t;const n=Math.floor(this._width*this._pixelRatio*this._resolutionScale),i=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(n,i),null!==this._scissor&&this.renderTarget.scissor.copy(this._scissor),null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport)}setScissor(e,t,n,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new Pn),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,n,i),this._scissor.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setViewport(e,t,n,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new Pn),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,n,i),this._viewport.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}gA.COLOR="color",gA.DEPTH="depth";const _A=Km(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),vA=Km(([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp()).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),yA=Km(([e,t])=>{const n=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return n.div(i).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),bA=Km(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),n=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(n)}),xA=Km(([e,t])=>{const n=yg(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=yg(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=bA(e),(e=i.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),TA=yg(cg(1.6605,-.1246,-.0182),cg(-.5876,1.1329,-.1006),cg(-.0728,-.0083,1.1187)),SA=yg(cg(.6274,.0691,.0164),cg(.3293,.9195,.088),cg(.0433,.0113,.8956)),MA=Km(([e])=>{const t=cg(e).toVar(),n=cg(t.mul(t)).toVar(),i=cg(n.mul(n)).toVar();return ng(15.5).mul(i.mul(n)).sub(f_(40.14,i.mul(t))).add(f_(31.96,i).sub(f_(6.868,n.mul(t))).add(f_(.4298,n).add(f_(.1191,t).sub(.00232))))}),EA=Km(([e,t])=>{const n=cg(e).toVar(),i=yg(cg(.856627153315983,.137318972929847,.11189821299995),cg(.0951212405381588,.761241990602591,.0767994186031903),cg(.0482516061458583,.101439036467562,.811302368396859)),r=yg(cg(1.1271005818144368,-.1413297634984383,-.14132976349843826),cg(-.11060664309660323,1.157823702216272,-.11060664309660294),cg(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=ng(-12.47393),a=ng(4.026069);return n.mulAssign(t),n.assign(SA.mul(n)),n.assign(i.mul(n)),n.assign(xv(n,1e-10)),n.assign(X_(n)),n.assign(n.sub(s).div(a.sub(s))),n.assign(Iv(n,0,1)),n.assign(MA(n)),n.assign(r.mul(n)),n.assign(Rv(xv(cg(0),n),cg(2.2))),n.assign(TA.mul(n)),n.assign(Iv(n,0,1)),n}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),wA=Km(([e,t])=>{const n=ng(.76),i=ng(.15);e=e.mul(t);const r=bv(e.r,bv(e.g,e.b)),s=Vv(r.lessThan(.08),r.sub(f_(6.25,r.mul(r))),.04);e.subAssign(s);const a=xv(e.r,xv(e.g,e.b));Jm(a.lessThan(n),()=>e);const o=p_(1,n),l=p_(1,o.mul(o).div(a.add(o.sub(n))));e.mulAssign(l.div(a));const u=p_(1,m_(1,i.mul(a.sub(l)).add(1)));return Dv(e,cg(l),u)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class AA extends Qf{static get type(){return"CodeNode"}constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=n}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const n of t)n.build(e);const n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}class RA extends AA{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}getNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let n=t.nodeFunction;return void 0===n&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),i=n.name,r=n.type,s=e.getCodeFromNode(this,r);""!==i&&(s.name=i);const a=e.getPropertyName(s),o=this.getNodeFunction(e).getCode(a);return s.code=o+"\n","property"===t?a:e.format(`${a}()`,r,t)}}function CA(e){let t;const n=e.context.getViewZ;return void 0!==n&&(t=n(this)),(t||Db.z).negate()}const NA=Km(([e,t],n)=>{const i=CA(n);return Ov(e,t,i)}),PA=Km(([e],t)=>{const n=CA(t);return e.mul(e,n,n).negate().exp().oneMinus()});Km(([e,t],n)=>{const i=CA(n),r=t.sub(Pb.y).max(0).toConst().mul(i).toConst();return e.mul(e,r,r).negate().exp().oneMinus()});const LA=Km(([e,t])=>fg(t.toFloat().mix(jg.rgb,e.toVec3()),jg.a));Wm(class extends Qf{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:n}=e;!0===n.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class DA extends Qf{static get type(){return"AtomicFunctionNode"}constructor(e,t,n){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=n,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),n=t.parents,i=this.method,r=this.getNodeType(e),s=this.getInputType(e),a=this.pointerNode,o=this.valueNode,l=[];l.push(`&${a.build(e,s)}`),null!==o&&l.push(o.build(e,s));const u=`${e.getMethod(i,r)}( ${l.join(", ")} )`;if(!(!!n&&(1===n.length&&!0===n[0].isStackNode)))return void 0===t.constNode&&(t.constNode=My(u,r).toConst()),t.constNode.build(e);e.addLineFlowCode(u,this)}}DA.ATOMIC_LOAD="atomicLoad",DA.ATOMIC_STORE="atomicStore",DA.ATOMIC_ADD="atomicAdd",DA.ATOMIC_SUB="atomicSub",DA.ATOMIC_MAX="atomicMax",DA.ATOMIC_MIN="atomicMin",DA.ATOMIC_AND="atomicAnd",DA.ATOMIC_OR="atomicOr",DA.ATOMIC_XOR="atomicXor",Wm(DA);class IA extends tm{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,n=null){super(),this.method=e,this.aNode=t,this.bNode=n}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,n=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(n)?0:e.getTypeLength(n))?t:n}getNodeType(e){const t=this.method;return t===IA.SUBGROUP_ELECT?"bool":t===IA.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const n=this.method,i=this.getNodeType(e),r=this.getInputType(e),s=this.aNode,a=this.bNode,o=[];if(n===IA.SUBGROUP_BROADCAST||n===IA.SUBGROUP_SHUFFLE||n===IA.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(s.build(e,i),a.build(e,"float"===t?"int":i))}else n===IA.SUBGROUP_SHUFFLE_XOR||n===IA.SUBGROUP_SHUFFLE_DOWN||n===IA.SUBGROUP_SHUFFLE_UP?o.push(s.build(e,i),a.build(e,"uint")):(null!==s&&o.push(s.build(e,r)),null!==a&&o.push(a.build(e,r)));const l=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(n,i)}${l}`,i,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}let UA;function FA(e){UA=UA||new WeakMap;let t=UA.get(e);return void 0===t&&UA.set(e,t={}),t}function OA(e){const t=FA(e);return t.shadowMatrix||(t.shadowMatrix=a_("mat4").setGroup(i_).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix)))}function BA(e){const t=FA(e);return t.position||(t.position=a_(new dn).setGroup(i_).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.matrixWorld)))}function kA(e){const t=FA(e);return t.viewPosition||(t.viewPosition=a_(new dn).setGroup(i_).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new dn,n.value.setFromMatrixPosition(e.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)}))}IA.SUBGROUP_ELECT="subgroupElect",IA.SUBGROUP_BALLOT="subgroupBallot",IA.SUBGROUP_ADD="subgroupAdd",IA.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",IA.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",IA.SUBGROUP_MUL="subgroupMul",IA.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",IA.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",IA.SUBGROUP_AND="subgroupAnd",IA.SUBGROUP_OR="subgroupOr",IA.SUBGROUP_XOR="subgroupXor",IA.SUBGROUP_MIN="subgroupMin",IA.SUBGROUP_MAX="subgroupMax",IA.SUBGROUP_ALL="subgroupAll",IA.SUBGROUP_ANY="subgroupAny",IA.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",IA.QUAD_SWAP_X="quadSwapX",IA.QUAD_SWAP_Y="quadSwapY",IA.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",IA.SUBGROUP_BROADCAST="subgroupBroadcast",IA.SUBGROUP_SHUFFLE="subgroupShuffle",IA.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",IA.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",IA.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",IA.QUAD_BROADCAST="quadBroadcast";const zA=e=>gb.transformDirection(BA(e).sub(function(e){const t=FA(e);return t.targetPosition||(t.targetPosition=a_(new dn).setGroup(i_).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),VA=(e,t)=>{for(const n of t)if(n.isAnalyticLightNode&&n.light.id===e)return n;return null},GA=new WeakMap,HA=[];class jA extends Qf{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Tg("vec3","totalDiffuse"),this.totalSpecularNode=Tg("vec3","totalSpecular"),this.outgoingLightNode=Tg("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;t<e.length;t++){const n=e[t];if(HA.push(n.id),HA.push(n.castShadow?1:0),!0===n.isSpotLight){const e=null!==n.map?n.map.id:-1,t=n.colorNode?n.colorNode.getCacheKey():-1;HA.push(e,t)}}const t=Pf(HA);return HA.length=0,t}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const n of t.nodes)n.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],n=this._lightNodes,i=(e=>e.sort((e,t)=>e.id-t.id))(this._lights),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(Vm(e));else{let i=null;if(null!==n&&(i=VA(e.id,n)),null===i){const n=r.getLightNodeClass(e.constructor);if(null===n){Xt(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;GA.has(e)?i=GA.get(e):(i=new n(e),GA.set(e,i)),t.push(i)}}this._lightNodes=t}setupDirectLight(e,t,n){const{lightingModel:i,reflectedLight:r}=e.context;i.direct({...n,lightNode:t,reflectedLight:r},e)}setupDirectRectAreaLight(e,t,n){const{lightingModel:i,reflectedLight:r}=e.context;i.directRectArea({...n,lightNode:t,reflectedLight:r},e)}setupLights(e,t){for(const n of t)n.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode;const i=e.context,r=i.lightingModel,s=e.getNodeProperties(this);if(r){const{totalDiffuseNode:t,totalSpecularNode:a}=this;i.outgoingLight=n;const o=e.addStack();s.nodes=o.nodes,r.start(e);const{backdrop:l,backdropAlpha:u}=i,{directDiffuse:c,directSpecular:h,indirectDiffuse:d,indirectSpecular:p}=i.reflectedLight;let f=c.add(d);null!==l&&(f=cg(null!==u?u.mix(f,l):l)),t.assign(f),a.assign(h.add(p)),n.assign(t.add(a)),r.finish(e),n=n.bypass(e.removeStack())}else s.nodes=[];return e.lightsNode=t,n}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class WA extends Qf{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Gf,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){$A.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Pb)}}const $A=Tg("vec3","shadowPositionWorld");function XA(e,t){return t=function(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new _i),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}const qA=new WeakMap,YA=Km(({depthTexture:e,shadowCoord:t,depthLayer:n})=>{let i=zy(e,t.xy).setName("t_basic");return e.isArrayTexture&&(i=i.depth(n)),i.compare(t.z)}),KA=Km(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:i})=>{const r=(t,n)=>{let r=zy(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(n)},s=ux("mapSize","vec2",n).setGroup(i_),a=ux("radius","float",n).setGroup(i_),o=ag(1).div(s),l=a.mul(o.x),u=nA(eb.xy).mul(6.28318530718);return d_(r(t.xy.add(iA(0,5,u).mul(l)),t.z),r(t.xy.add(iA(1,5,u).mul(l)),t.z),r(t.xy.add(iA(2,5,u).mul(l)),t.z),r(t.xy.add(iA(3,5,u).mul(l)),t.z),r(t.xy.add(iA(4,5,u).mul(l)),t.z)).mul(.2)}),ZA=Km(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:i})=>{const r=(t,n)=>{let r=zy(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(n)},s=ux("mapSize","vec2",n).setGroup(i_),a=ag(1).div(s),o=a.x,l=a.y,u=t.xy,c=J_(u.mul(s).add(.5));return u.subAssign(c.mul(a)),d_(r(u,t.z),r(u.add(ag(o,0)),t.z),r(u.add(ag(0,l)),t.z),r(u.add(a),t.z),Dv(r(u.add(ag(o.negate(),0)),t.z),r(u.add(ag(o.mul(2),0)),t.z),c.x),Dv(r(u.add(ag(o.negate(),l)),t.z),r(u.add(ag(o.mul(2),l)),t.z),c.x),Dv(r(u.add(ag(0,l.negate())),t.z),r(u.add(ag(0,l.mul(2))),t.z),c.y),Dv(r(u.add(ag(o,l.negate())),t.z),r(u.add(ag(o,l.mul(2))),t.z),c.y),Dv(Dv(r(u.add(ag(o.negate(),l.negate())),t.z),r(u.add(ag(o.mul(2),l.negate())),t.z),c.x),Dv(r(u.add(ag(o.negate(),l.mul(2))),t.z),r(u.add(ag(o.mul(2),l.mul(2))),t.z),c.x),c.y)).mul(1/9)}),QA=Km(({depthTexture:e,shadowCoord:t,depthLayer:n},i)=>{let r=zy(e).sample(t.xy);e.isArrayTexture&&(r=r.depth(n)),r=r.rg;const s=r.x,a=xv(1e-7,r.y.mul(r.y)),o=i.renderer.reversedDepthBuffer?Tv(s,t.z):Tv(t.z,s),l=ng(1).toVar();return Jm(o.notEqual(1),()=>{const e=t.z.sub(s);let n=a.div(a.add(e.mul(e)));n=Iv(p_(n,.3).div(.65)),l.assign(xv(o,n))}),l}),JA=new ow,eR=[],tR=Km(({samples:e,radius:t,size:n,shadowPass:i,depthLayer:r})=>{const s=ng(0).toVar("meanVertical"),a=ng(0).toVar("squareMeanVertical"),o=e.lessThanEqual(ng(1)).select(ng(0),ng(2).div(e.sub(1))),l=e.lessThanEqual(ng(1)).select(ng(0),ng(-1));GT({start:ig(0),end:ig(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(ng(e).mul(o));let c=i.sample(d_(eb.xy,ag(0,u).mul(t)).div(n));i.value.isArrayTexture&&(c=c.depth(r)),c=c.x,s.addAssign(c),a.addAssign(c.mul(c))}),s.divAssign(e),a.divAssign(e);const u=q_(a.sub(s.mul(s)).max(0));return ag(s,u)}),nR=Km(({samples:e,radius:t,size:n,shadowPass:i,depthLayer:r})=>{const s=ng(0).toVar("meanHorizontal"),a=ng(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(ng(1)).select(ng(0),ng(2).div(e.sub(1))),l=e.lessThanEqual(ng(1)).select(ng(0),ng(-1));GT({start:ig(0),end:ig(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(ng(e).mul(o));let c=i.sample(d_(eb.xy,ag(u,0).mul(t)).div(n));i.value.isArrayTexture&&(c=c.depth(r)),s.addAssign(c.x),a.addAssign(d_(c.y.mul(c.y),c.x.mul(c.x)))}),s.divAssign(e),a.divAssign(e);const u=q_(a.sub(s.mul(s)).max(0));return ag(s,u)}),iR=[YA,KA,ZA,QA];let rR;const sR=new tA;class aR extends WA{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:r,depthLayer:s}){const a=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),o=t({depthTexture:n,shadowCoord:i,shadow:r,depthLayer:s});return a.select(o,ng(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:i}=e,r=n.biasNode||ux("bias","float",n).setGroup(i_);let s,a=t;if(n.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)a=a.xyz.div(a.w),s=a.z;else{const e=a.w;a=a.xy.div(e);const t=ux("near","float",n.camera).setGroup(i_),i=ux("far","float",n.camera).setGroup(i_);s=hS(e.negate(),t,i)}return a=cg(a.x,a.y.oneMinus(),i.reversedDepthBuffer?s.sub(r):s.add(r)),a}getShadowFilterFn(e){return iR[e]}setupRenderTarget(e,t){const n=new vs(e.mapSize.width,e.mapSize.height);n.name="ShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?Pt:Rt;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=n,{shadowMap:i,depthTexture:n}}setupShadow(e){const{renderer:t,camera:n}=e,{light:i,shadow:r}=this,{depthTexture:s,shadowMap:a}=this.setupRenderTarget(r,e),o=t.shadowMap.type,l=t.hasCompatibility(zt);if(1!==o&&2!==o||!l?(s.minFilter=le,s.magFilter=le):(s.minFilter=he,s.magFilter=he),r.camera.coordinateSystem=n.coordinateSystem,r.camera.updateProjectionMatrix(),3===o&&!0!==r.isPointLightShadow){s.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Ie,type:xe,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Ie,type:xe,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Ie,type:xe,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Ie,type:xe,depthBuffer:!1}));let t=zy(s);s.isArrayTexture&&(t=t.depth(this.depthLayer));let n=zy(this.vsmShadowMapVertical.texture);s.isArrayTexture&&(n=n.depth(this.depthLayer));const i=ux("blurSamples","float",r).setGroup(i_),o=ux("radius","float",r).setGroup(i_),l=ux("mapSize","vec2",r).setGroup(i_);let u=this.vsmMaterialVertical||(this.vsmMaterialVertical=new bS);u.fragmentNode=tR({samples:i,radius:o,size:l,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMVertical",u=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new bS),u.fragmentNode=nR({samples:i,radius:o,size:l,shadowPass:n,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMHorizontal"}const u=ux("intensity","float",r).setGroup(i_),c=ux("normalBias","float",r).setGroup(i_),h=OA(i).mul($A.add(jb.mul(c))),d=this.setupShadowCoord(e,h),p=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===p)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const f=3===o&&!0!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:s,m=this.setupShadowFilter(e,{filterFn:p,shadowTexture:a.texture,depthTexture:f,shadowCoord:d,shadow:r,depthLayer:this.depthLayer});let g,_;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?g=ax(a.texture,d.xyz):(g=zy(a.texture,d),s.isArrayTexture&&(g=g.depth(this.depthLayer)))),_=g?Dv(1,m.rgb.mix(g,1),u.mul(g.a)).toVar():Dv(1,m,u).toVar(),this.shadowMap=a,this.shadow.map=a;const v=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return g&&_.toInspector(`${v} / Color`,()=>this.shadowMap.texture.isCubeTexture?ax(this.shadowMap.texture):zy(this.shadowMap.texture)),_.toInspector(`${v} / Depth`,()=>this.shadowMap.texture.isCubeTexture?ax(this.shadowMap.texture).r.oneMinus():Vy(this.shadowMap.depthTexture,Py().mul(Dy(zy(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Km(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let n=this._node;return this.setupShadowPosition(e),null===n&&(this._node=n=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(n=e.material.receivedShadowNode(n)),n})()}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:r,scene:s}=e;t.updateMatrices(i),n.setSize(t.mapSize.width,t.mapSize.height,n.depth);const a=s.name;s.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,r.render(s,t.camera),s.name=a}updateShadow(e){const{shadowMap:t,light:n,shadow:i}=this,{renderer:r,scene:s,camera:a}=e,o=r.shadowMap.type,l=t.depthTexture.version;this._depthVersionCached=l;const u=i.camera.layers.mask;4294967294&i.camera.layers.mask||(i.camera.layers.mask=a.layers.mask);const c=r.getRenderObjectFunction(),h=r.getMRT(),d=!!h&&h.has("velocity");rR=function(e,t,n){return n=function(e,t){return t=function(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}(t,n=XA(e,n)),n}(r,s,rR),s.overrideMaterial=(e=>{let t=qA.get(e);return void 0===t&&(t=new bS,t.colorNode=fg(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=0,t.fog=!1,qA.set(e,t)),t})(n),r.setRenderObjectFunction(((e,t,n,i)=>{eR[0]=e,eR[1]=t;let r=JA.get(eR);return void 0!==r&&r.shadowType===n&&r.useVelocity===i||(r=(r,s,a,o,l,u,...c)=>{(!0===r.castShadow||r.receiveShadow&&3===n)&&(i&&(Bf(r).useVelocity=!0),r.onBeforeShadow(e,r,a,t.camera,o,s.overrideMaterial,u),e.renderObject(r,s,a,o,l,u,...c),r.onAfterShadow(e,r,a,t.camera,o,s.overrideMaterial,u))},r.shadowType=n,r.useVelocity=i,JA.set(eR,r)),eR[0]=null,eR[1]=null,r})(r,i,o,d)),r.setClearColor(0,0),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(c),3===o&&!0!==i.isPointLightShadow&&this.vsmPass(r),i.camera.layers.mask=u,function(e,t,n){!function(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}(e,n),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,n)}(r,s,rR)}vsmPass(e){const{shadow:t}=this,n=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,n),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,n),e.setRenderTarget(this.vsmShadowMapVertical),sR.material=this.vsmMaterialVertical,sR.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),sR.material=this.vsmMaterialHorizontal,sR.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,(e=>{const t=qA.get(e);void 0!==t&&(t.dispose(),qA.delete(e))})(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId[e.camera]===e.frameId&&(n=!1),this._cameraFrameId[e.camera]=e.frameId),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const oR=new _i,lR=new Fn,uR=new dn,cR=new dn,hR=[new dn(1,0,0),new dn(-1,0,0),new dn(0,-1,0),new dn(0,1,0),new dn(0,0,1),new dn(0,0,-1)],dR=[new dn(0,-1,0),new dn(0,-1,0),new dn(0,0,-1),new dn(0,0,1),new dn(0,-1,0),new dn(0,-1,0)],pR=[new dn(1,0,0),new dn(-1,0,0),new dn(0,1,0),new dn(0,-1,0),new dn(0,0,1),new dn(0,0,-1)],fR=[new dn(0,-1,0),new dn(0,-1,0),new dn(0,0,1),new dn(0,0,-1),new dn(0,-1,0),new dn(0,-1,0)],mR=Km(({depthTexture:e,bd3D:t,dp:n})=>ax(e,t).compare(n)),gR=Km(({depthTexture:e,bd3D:t,dp:n,shadow:i})=>{const r=ux("radius","float",i).setGroup(i_),s=ux("mapSize","vec2",i).setGroup(i_),a=r.div(s.x),o=av(t),l=Q_(Av(t,o.x.greaterThan(o.z).select(cg(0,1,0),cg(1,0,0)))),u=Av(t,l),c=nA(eb.xy).mul(6.28318530718),h=iA(0,5,c),d=iA(1,5,c),p=iA(2,5,c),f=iA(3,5,c),m=iA(4,5,c);return ax(e,t.add(l.mul(h.x).add(u.mul(h.y)).mul(a))).compare(n).add(ax(e,t.add(l.mul(d.x).add(u.mul(d.y)).mul(a))).compare(n)).add(ax(e,t.add(l.mul(p.x).add(u.mul(p.y)).mul(a))).compare(n)).add(ax(e,t.add(l.mul(f.x).add(u.mul(f.y)).mul(a))).compare(n)).add(ax(e,t.add(l.mul(m.x).add(u.mul(m.y)).mul(a))).compare(n)).mul(.2)}),_R=Km(({filterFn:e,depthTexture:t,shadowCoord:n,shadow:i},r)=>{const s=n.xyz.toConst(),a=s.abs().toConst(),o=a.x.max(a.y).max(a.z),l=a_("float").setGroup(i_).onRenderUpdate(()=>i.camera.near),u=a_("float").setGroup(i_).onRenderUpdate(()=>i.camera.far),c=ux("bias","float",i).setGroup(i_),h=ng(1).toVar();return Jm(o.sub(u).lessThanEqual(0).and(o.sub(l).greaterThanEqual(0)),()=>{let n;r.renderer.reversedDepthBuffer?(n=((e,t,n)=>t.mul(e.add(n)).div(e.mul(t.sub(n))))(o.negate(),l,u),n.subAssign(c)):(n=uS(o.negate(),l,u),n.addAssign(c));const a=s.normalize();h.assign(e({depthTexture:t,bd3D:a,dp:n,shadow:i}))}),h});class vR extends aR{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?mR:gR}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:r}){return _R({filterFn:t,depthTexture:n,shadowCoord:i,shadow:r})}setupRenderTarget(e,t){const n=new ys(e.mapSize.width);n.name="PointShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?Pt:Rt;const i=t.createCubeRenderTarget(e.mapSize.width);return i.texture.name="PointShadowMap",i.depthTexture=n,{shadowMap:i,depthTexture:n}}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:r,scene:s}=e,a=t.camera,o=t.matrix,l=r.coordinateSystem===Ot,u=l?hR:pR,c=l?dR:fR;n.setSize(t.mapSize.width,t.mapSize.width);const h=r.autoClear,d=r.getClearColor(oR),p=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){r.setRenderTarget(n,e),r.clear();const l=i.distance||a.far;l!==a.far&&(a.far=l,a.updateProjectionMatrix()),uR.setFromMatrixPosition(i.matrixWorld),a.position.copy(uR),cR.copy(a.position),cR.add(u[e]),a.up.copy(c[e]),a.lookAt(cR),a.updateMatrixWorld(),o.makeTranslation(-uR.x,-uR.y,-uR.z),lR.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(lR,a.coordinateSystem,a.reversedDepth);const h=s.name;s.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${e+1}`,r.render(s,a),s.name=h}r.autoClear=h,r.setClearColor(d,p)}}class yR extends qT{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new _i,this.colorNode=e&&e.colorNode||a_(this.color).setGroup(i_),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Vf,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,null!==this.baseColorNode&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return kA(this.light).sub(e.context.positionView||Db)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>new aR(e,t))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let n=this.shadowColorNode;if(null===n){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?Vm(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=n=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(n=e.context.getShadow(this,e)),this.colorNode=n}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const bR=Km(({lightDistance:e,cutoffDistance:t,decayExponent:n})=>{const i=e.pow(n).max(.01).reciprocal();return t.greaterThan(0).select(i.mul(e.div(t).pow4().oneMinus().clamp().pow2()),i)});class xR extends yR{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=a_(0).setGroup(i_),this.decayExponentNode=a_(2).setGroup(i_)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>new vR(e,t))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:n,decayExponent:i})=>{const r=t.normalize(),s=t.length(),a=bR({lightDistance:s,cutoffDistance:n,decayExponent:i});return{lightDirection:r,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}Km(([e=Py()],{renderer:t,material:n})=>{const i=Lv(e.mul(2).sub(1));let r;if(n.alphaToCoverage&&t.currentSamples>0){const e=ng(i.fwidth()).toVar();r=Ov(e.oneMinus(),e.add(1),i).oneMinus()}else r=Vv(i.greaterThan(1),0,1);return r});const TR=Km(([e,t])=>{const n=e.x,i=e.y,r=e.z;let s=t.element(0).mul(.886227);return s=s.add(t.element(1).mul(1.023328).mul(i)),s=s.add(t.element(2).mul(1.023328).mul(r)),s=s.add(t.element(3).mul(1.023328).mul(n)),s=s.add(t.element(4).mul(.858086).mul(n).mul(i)),s=s.add(t.element(5).mul(.858086).mul(i).mul(r)),s=s.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),s=s.add(t.element(7).mul(.858086).mul(n).mul(r)),s=s.add(t.element(8).mul(.429043).mul(f_(n,n).sub(f_(i,i)))),s}),SR=new Hw;class MR extends dw{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let s=!1;if(null===r)i._clearColor.getRGB(SR),SR.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(SR),SR.a=1,s=!0;else if(!0===r.isNode){const o=this.get(e),l=r;SR.copy(i._clearColor);let u=o.backgroundMesh;if(void 0===u){const h=fg(l).mul(lA).context({getUV:()=>uA.mul(Gb),getTextureLevel:()=>oA}),d=fb.element(3).element(3).equal(1),p=m_(1,fb.element(1).element(1)).mul(3),f=d.select(Cb.mul(p),Cb),m=Sb.mul(fg(f,0));let g=fb.mul(fg(m.xyz,1));g=g.setZ(g.w);const _=new bS;function v(){r.removeEventListener("dispose",v),u.material.dispose(),u.geometry.dispose()}_.name="Background.material",_.side=1,_.depthTest=!1,_.depthWrite=!1,_.allowOverride=!1,_.fog=!1,_.lights=!1,_.vertexNode=g,_.colorNode=h,o.backgroundMeshNode=h,o.backgroundMesh=u=new Wr(new Bs(1,32,32),_),u.frustumCulled=!1,u.name="Background.mesh",r.addEventListener("dispose",v)}const c=l.getCacheKey();o.backgroundCacheKey!==c&&(o.backgroundMeshNode.node=fg(l).mul(lA),o.backgroundMeshNode.needsUpdate=!0,u.material.needsUpdate=!0,o.backgroundCacheKey=c),t.unshift(u,u.geometry,u.material,0,0,null,null)}else qt("Renderer: Unsupported background configuration.",r);const a=i.xr.getEnvironmentBlendMode();if("additive"===a?SR.set(0,0,0,1):"alpha-blend"===a&&SR.set(0,0,0,0),!0===i.autoClear||!0===s){const y=n.clearColorValue;y.r=SR.r,y.g=SR.g,y.b=SR.b,y.a=SR.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(y.r*=y.a,y.g*=y.a,y.b*=y.a),n.depthClearValue=i.getClearDepth(),n.stencilClearValue=i.getClearStencil(),n.clearColor=!0===i.autoClearColor,n.clearDepth=!0===i.autoClearDepth,n.clearStencil=!0===i.autoClearStencil}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}let ER=0;class wR{constructor(e="",t=[],n=0){this.name=e,this.bindings=t,this.index=n,this.id=ER++}}class AR{constructor(e,t,n,i,r,s,a,o,l,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=u,this.nodeAttributes=i,this.bindings=r,this.updateNodes=s,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=l,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const n=new wR(t.name,[],t.index);e.push(n);for(const e of t.bindings)n.bindings.push(e.clone())}else e.push(t)}return e}}class RR{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class CR{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class NR{constructor(e,t,n=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=i}}class PR extends NR{constructor(e,t,n=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=i}}class LR{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let DR=0;class IR{constructor(e=null){this.id=DR++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return void 0===t&&null!==this.parent&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class UR{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class FR{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}}class OR extends FR{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class BR extends FR{constructor(e,t=new cn){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class kR extends FR{constructor(e,t=new dn){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class zR extends FR{constructor(e,t=new Pn){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class VR extends FR{constructor(e,t=new _i){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class GR extends FR{constructor(e,t=new $a){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class HR extends FR{constructor(e,t=new mn){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class jR extends FR{constructor(e,t=new Fn){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class WR extends OR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class $R extends BR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class XR extends kR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class qR extends zR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class YR extends VR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class KR extends GR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ZR extends HR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class QR extends jR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let JR=0;const eC=new WeakMap,tC=new WeakMap,nC=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),iC=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class rC{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=n,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=$w(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new IR,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:JR++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&1===e.blending&&!1===e.alphaToCoverage}createRenderTarget(e,t,n){return new Ln(e,t,n)}createCubeRenderTarget(e,t){return new RS(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const n=t[0].groupNode;let i,r=n.shared;if(r)for(let e=1;e<t.length;e++)n!==t[e].groupNode&&(r=!1);if(r){let n="";for(const e of t)if(e.isNodeUniformsGroup){e.uniforms.sort((e,t)=>e.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)n+=t.nodeUniform.node.id}else n+=e.nodeUniform.id;const r=this.renderer._currentRenderContext||this.renderer;let s=eC.get(r);void 0===s&&(s=new Map,eC.set(r,s));const a=Nf(n);i=s.get(a),void 0===i&&(i=new wR(e,t,this.bindingsIndexes[e].group),s.set(a,i))}else i=new wR(e,t,this.bindingsIndexes[e].group);return i}getBindGroupArray(e,t){const n=this.bindings[t];let i=n[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},n=this.bindings;for(const e of qf)for(const i in n[e]){const r=n[e][i],s=t[i]||(t[i]=[]);for(const e of r)!1===s.includes(e)&&s.push(e)}e=[];for(const n in t){const i=t[n],r=this._getBindGroup(n,i);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const n=e[t];this.bindingsIndexes[n.name].group=t,n.index=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){const t=e.getUpdateBeforeType(),n=e.getUpdateAfterType();t===zf&&n===zf||!1===this.sequentialNodes.includes(e)&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==zf&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),n=e.getUpdateAfterType();t!==zf&&this.updateBeforeNodes.push(e),n!==zf&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===he||e.magFilter===de||e.magFilter===ce||e.magFilter===pe||e.minFilter===he||e.minFilter===de||e.minFilter===ce||e.minFilter===pe}getUniformBufferLimit(){return 16384}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){const e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const n=this.getDataFromNode(e);return void 0===n.cache&&(n.cache=new IR(t?this.getCache():null)),n.cache}isAvailable(){return!1}getVertexIndex(){Xt("Abstract function.")}getInstanceIndex(){Xt("Abstract function.")}getDrawIndex(){Xt("Abstract function.")}getFrontFacing(){Xt("Abstract function.")}getFragCoord(){Xt("Abstract function.")}isFlipY(){return!1}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,t.usageCount}generateTexture(){Xt("Abstract function.")}generateTextureLod(){Xt("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,n=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let r=0;r<t;r++){const s=n?n[r]:null;i+=null!==s?s.build(this,e):this.generateConst(e),r<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,n=null){const i=[];for(const e of t){const{name:t,type:r}=e;n&&n[t]&&n[t].isNode?i.push(n[t].build(this,r)):i.push(this.generateConst(r))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new _i:"vec2"===e||"uvec2"===e||"ivec2"===e?t=new cn:"vec3"===e||"uvec3"===e||"ivec3"===e?t=new dn:"vec4"!==e&&"uvec4"!==e&&"ivec4"!==e||(t=new Pn)),"float"===e)return iC(t);if("int"===e)return`${Math.round(t)}`;if("uint"===e)return t>=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${iC(t.r)}, ${iC(t.g)}, ${iC(t.b)} )`;const n=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===n&&"mat2"!==e)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(n>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const n=this.attributes;for(const t of n)if(t.name===e)return t;const i=new RR(e,t);return this.registerDeclaration(i),n.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===ve)return"int";if(t===ye)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let n=Uf(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(n=n.replace("vec","mat")),i+n}getTypeFromArray(e){return nC.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const n=t.array,i=e.itemSize,r=e.normalized;let s;return e instanceof sr||!0===r||(s=this.getTypeFromArray(n)),this.getTypeFromLength(i,s)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return null!==n?Number(n[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=$w(this.stack);const e=Qm();return this.stacks.push(e),Zm(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){this.getDataFromNode(t).stack=e}return this.stack=e.parent,Zm(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){let i=(n=null===n?e.isGlobal(this)?this.globalCache:this.cache:n).getData(e);void 0===i&&(i={},n.setData(e,i)),void 0===i[t]&&(i[t]={});let r=i[t];const s=i.any?i.any.subBuilds:null,a=this.getClosestSubBuild(s);return a&&(void 0===r.subBuildsCache&&(r.subBuildsCache={}),r=r.subBuildsCache[a]||(r.subBuildsCache[a]={}),r.subBuilds=s),r}getNodeProperties(e,t="any"){const n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const n=this.getDataFromNode(e,"vertex");let i=n.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new RR("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),n.bufferAttribute=i}return i}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,n=null,i=this.shaderStage){const r=this.getDataFromNode(e,i,this.globalCache);let s=r.structType;if(void 0===s){const a=this.structs.index++;null===n&&(n="StructType"+a),s=new UR(n,t),this.structs[i].push(s),this.types[i][n]=e,r.structType=s}return s}getOutputStructTypeFromNode(e,t){const n=this.getStructTypeFromNode(e,t,"OutputType","fragment");return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,i=null){const r=this.getDataFromNode(e,n,this.globalCache);let s=r.uniform;if(void 0===s){const a=this.uniforms.index++;s=new CR(i||"nodeUniform"+a,t,e),this.uniforms[n].push(s),this.registerDeclaration(s),r.uniform=s}return s}getVarFromNode(e,t=null,n=e.getNodeType(this),i=this.shaderStage,r=!1){const s=this.getDataFromNode(e,i),a=this.getSubBuildProperty("variable",s.subBuilds);let o=s[a];if(void 0===o){const l=r?"_const":"_var",u=this.vars[i]||(this.vars[i]=[]),c=this.vars[l]||(this.vars[l]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+c,this.vars[l]++),"variable"!==a&&(t=this.getSubBuildProperty(t,s.subBuilds));const h=e.getArrayCount(this);o=new NR(t,n,r,h),r||u.push(o),this.registerDeclaration(o),s[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,n=e.getNodeType(this),i=null,r=null){const s=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",s.subBuilds);let o=s[a];if(void 0===o){const e=this.varyings,l=e.length;null===t&&(t="nodeVarying"+l),"varying"!==a&&(t=this.getSubBuildProperty(t,s.subBuilds)),o=new PR(t,n,i,r),e.push(o),this.registerDeclaration(o),s[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),i=this.getPropertyName(e);let r=1,s=i;for(;void 0!==n[s];)s=i+"_"+r++;r>1&&(e.name=s,Xt(`TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${s}'.`)),n[s]=e}getCodeFromNode(e,t,n=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[n]||(this.codes[n]=[]),s=e.length;r=new LR("nodeCode"+s,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:n,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,s=t;for(;s;){if(!0===i.get(s)){r=!1;break}s=this.getDataFromNode(s).parentNodeBlock}if(r)for(const e of n)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,n){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),s=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),s.set(n,!0)}addLineFlowCode(e,t=null){return""===e||(null!==t&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new RA,n=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=n,t}flowShaderNode(e){const t=e.layout,n={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(const e of t.inputs)n[e.name]=new jw(e.type,e.name);e.layout=null;const i=e.call(n),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowBuildStage(e,t,n=null){const i=this.getBuildStage();this.setBuildStage(t);const r=e.build(this,n);return this.setBuildStage(i),r}flowStagesNode(e,t=null){const n=this.flow,i=this.vars,r=this.declarations,s=this.cache,a=this.buildStage,o=this.stack,l={code:""};this.flow=l,this.vars={},this.declarations={},this.cache=new IR,this.stack=$w();for(const n of Xf)this.setBuildStage(n),l.result=e.build(this,t);return l.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=i,this.declarations=r,this.cache=s,this.stack=o,this.setBuildStage(a),l}getFunctionOperator(){return null}buildFunctionCode(){Xt("Abstract function.")}flowChildNode(e,t=null){const n=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=n,i}flowNodeFromShaderStage(e,t,n=null,i=null){const r=this.tab,s=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const l={...this.context};delete l.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=l;let u=null;if("generate"===this.buildStage){const r=this.flowChildNode(t,n);null!==i&&(r.code+=`${this.tab+i} = ${r.result};\n`),this.flowCode[e]=this.flowCode[e]+r.code,u=r}else u=t.build(this);return this.setShaderStage(a),this.cache=s,this.tab=r,this.context=o,u}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){Xt("Abstract function.")}getVaryings(){Xt("Abstract function.")}getVar(e,t,n=null){return`${null!==n?this.generateArrayDeclaration(e,n):this.getType(e)} ${t}`}getVars(e){let t="";const n=this.vars[e];if(void 0!==n)for(const e of n)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){Xt("Abstract function.")}getCodes(e){const t=this.codes[e];let n="";if(void 0!==t)for(const e of t)n+=e.code+"\n";return n}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){Xt("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,"any").subBuilds:e instanceof Set?[...e]:e,!t)return null;const n=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const i=t[e];if(n.includes(i))return i}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let n,i;return n=null!==t?this.getClosestSubBuild(t):this.subBuildFn,i=n?e?n+"_"+e:n:e,i}build(){const{object:e,material:t,renderer:n}=this;if(null!==t){let e=n.library.fromMaterial(t);null===e&&(qt(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new bS),e.build(this)}else this.addFlow("compute",e);for(const e of Xf){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of qf){this.setShaderStage(t);const n=this.flowNodes[t];for(const t of n)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=tC.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const n=this.getSharedDataFromNode(e);let i=n.cache;if(void 0===i){if("float"===t||"int"===t||"uint"===t)i=new WR(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)i=new $R(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)i=new XR(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)i=new qR(e);else if("color"===t)i=new YR(e);else if("mat2"===t)i=new KR(e);else if("mat3"===t)i=new ZR(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);i=new QR(e)}n.cache=i}return i}format(e,t,n){if((t=this.getVectorType(t))===(n=this.getVectorType(n))||null===n||this.isReference(n))return e;const i=this.getTypeLength(t),r=this.getTypeLength(n);return 16===i&&9===r?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===i&&4===r?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||r>4||0===r?e:i===r?`${this.getType(n)}( ${e} )`:i>r?(e="bool"===n?`all( ${e} )`:`${e}.${"xyz".slice(0,r)}`,this.format(e,this.getTypeFromLength(r,this.getComponentType(t)),n)):4===r&&i>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${s} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||!0===Bf(this.object).useVelocity}}class sC{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let n=e.get(t);return void 0===n&&(n={renderId:0,frameId:0},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(),n=e.updateReference(this);if(t===Vf){const t=this._getMaps(this.updateBeforeMap,n);if(t.frameId!==this.frameId){const n=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=n)}}else if(t===Gf){const t=this._getMaps(this.updateBeforeMap,n);if(t.renderId!==this.renderId){const n=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=n)}}else t===Hf&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),n=e.updateReference(this);if(t===Vf){const t=this._getMaps(this.updateAfterMap,n);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===Gf){const t=this._getMaps(this.updateAfterMap,n);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===Hf&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),n=e.updateReference(this);if(t===Vf){const t=this._getMaps(this.updateMap,n);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===Gf){const t=this._getMaps(this.updateMap,n);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===Hf&&e.update(this)}update(){this.frameId++,void 0===this.lastTime&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class aC{constructor(e,t,n=null,i="",r=!1){this.type=e,this.name=t,this.count=n,this.qualifier=i,this.isConst=r}}aC.isNodeFunctionInput=!0;class oC extends yR{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class lC extends yR{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:zA(this.light),lightColor:e}}}class uC extends yR{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=BA(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=a_(new _i).setGroup(i_)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:n,lightDirectionNode:i}=this,r=jb.dot(i).mul(.5).add(.5),s=Dv(n,t,r);e.context.irradiance.addAssign(s)}}class cC extends yR{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=a_(0).setGroup(i_),this.penumbraCosNode=a_(0).setGroup(i_),this.cutoffDistanceNode=a_(0).setGroup(i_),this.decayExponentNode=a_(0).setGroup(i_),this.colorNode=a_(this.color).setGroup(i_)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:n,penumbraCosNode:i}=this;return Ov(n,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let n=t.projectionUV;return void 0===n&&(n=function(e,t=Pb){const n=OA(e).mul(t);return n.xyz.div(n.w)}(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:i,light:r}=this,s=this.getLightVector(e),a=s.normalize(),o=a.dot(zA(r)),l=this.getSpotAttenuation(e,o),u=s.length(),c=bR({lightDistance:u,cutoffDistance:n,decayExponent:i});let h,d,p=t.mul(l).mul(c);if(r.colorNode?(d=this.getLightCoord(e),h=r.colorNode(d)):r.map&&(d=this.getLightCoord(e),h=zy(r.map,d.xy).onRenderUpdate(()=>r.map)),h){p=d.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(h),p)}return{lightColor:p,lightDirection:a}}}class hC extends cC{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const n=this.light.iesMap;let i=null;if(n&&!0===n.isTexture){const e=t.acos().mul(1/Math.PI);i=zy(n,ag(e,0),0).r}else i=super.getSpotAttenuation(t);return i}}class dC extends yR{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new dn);this.lightProbe=$y(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=TR(jb,this.lightProbe);e.context.irradiance.addAssign(t)}}const pC=Km(([e,t])=>{const n=e.abs().sub(t);return lv(xv(n,0)).add(bv(xv(n.x,n.y),0))});class fC extends cC{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),null===t.aspect){let e=1;null!==t.map&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=ng(0),n=this.penumbraCosNode,i=OA(this.light).mul(e.context.positionWorld||Pb);return Jm(i.w.greaterThan(0),()=>{const e=i.xyz.div(i.w),r=pC(e.xy.sub(ag(.5)),ag(.5)),s=m_(-1,p_(1,rv(n)).sub(1));t.assign(Uv(r.mul(-2).mul(s)))}),t}}const mC=new Fn,gC=new Fn;let _C=null;class vC extends yR{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=a_(new dn).setGroup(i_),this.halfWidth=a_(new dn).setGroup(i_),this.updateType=Gf}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;gC.identity(),mC.copy(t.matrixWorld),mC.premultiply(n),gC.extractRotation(mC),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(gC),this.halfHeight.value.applyMatrix4(gC)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=zy(_C.LTC_FLOAT_1),n=zy(_C.LTC_FLOAT_2)):(t=zy(_C.LTC_HALF_1),n=zy(_C.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:kA(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){_C=e}}class yC{parseFunction(){Xt("Abstract function.")}}class bC{constructor(e,t,n="",i=""){this.type=e,this.inputs=t,this.name=n,this.precision=i}getCode(){Xt("Abstract function.")}}bC.isNodeFunction=!0;const xC=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,TC=/[a-z_0-9]+/gi,SC="#pragma main";class MC extends bC{constructor(e){const{type:t,inputs:n,name:i,precision:r,inputsCode:s,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(SC),n=-1!==t?e.slice(t+12):e,i=n.match(xC);if(null!==i&&5===i.length){const r=i[4],s=[];let a=null;for(;null!==(a=TC.exec(r));)s.push(a);const o=[];let l=0;for(;l<s.length;){const e="const"===s[l][0];!0===e&&l++;let t=s[l][0];"in"===t||"out"===t||"inout"===t?l++:t="";const n=s[l++][0];let i=Number.parseInt(s[l][0]);!1===Number.isNaN(i)?l++:i=null;const r=s[l++][0];o.push(new aC(n,r,i,t,e))}const u=n.substring(i[0].length),c=void 0!==i[3]?i[3]:"";return{type:i[2],inputs:o,name:c,precision:void 0!==i[1]?i[1]:"",inputsCode:r,blockCode:u,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("FunctionNode: Function is not a GLSL code.")})(e);super(t,n,i,r),this.inputsCode=s,this.blockCode=a,this.headerCode=o}getCode(e=this.name){let t;const n=this.blockCode;if(""!==n){const{type:i,inputsCode:r,headerCode:s,precision:a}=this;let o=`${i} ${e} ( ${r.trim()} )`;""!==a&&(o=`${a} ${o}`),t=s+o+n}else t="";return t}}class EC extends yC{parseFunction(e){return new MC(e)}}const wC=new WeakMap,AC=[],RC=[];class CC extends dw{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new sC,this.nodeBuilderCache=new Map,this.callHashCache=new ow,this.groupsData=new ow,this.cacheLib={}}updateGroup(e){const t=e.groupNode,n=t.name;if(n===r_.name)return!0;if(n===i_.name){const t=this.get(e),n=this.nodeFrame.renderId;return t.renderId!==n&&(t.renderId=n,!0)}if(n===n_.name){const t=this.get(e),n=this.nodeFrame.frameId;return t.frameId!==n&&(t.frameId=n,!0)}AC[0]=t,AC[1]=e;let i=this.groupsData.get(AC);return void 0===i&&this.groupsData.set(AC,i={}),AC[0]=null,AC[1]=null,i.version!==t.version&&(i.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let n=t.nodeBuilderState;if(void 0===n){const{nodeBuilderCache:i}=this,r=this.getForRenderCacheKey(e);if(n=i.get(r),void 0===n){const t=t=>{const n=this.backend.createNodeBuilder(e.object,this.renderer);return n.scene=e.scene,n.material=t,n.camera=e.camera,n.context.material=t,n.lightsNode=e.lightsNode,n.environmentNode=this.getEnvironmentNode(e.scene),n.fogNode=this.getFogNode(e.scene),n.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&n.enableMultiview(),n};let s=t(e.material);try{s.build()}catch(e){s=t(new bS),s.build();let n=e.stackTrace;!n&&e.stack&&(n=new Rf(e.stack)),qt("TSL: "+e,n)}n=this._createNodeBuilderState(s),i.set(r,n)}n.usedTimes++,t.nodeBuilderState=n}return n}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let n=t.nodeBuilderState;if(void 0===n){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),n=this._createNodeBuilderState(i),t.nodeBuilderState=n}return n}_createNodeBuilderState(e){return new AR(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const n=this.get(e);n.environmentNode&&(t=n.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const n=this.get(e);n.backgroundNode&&(t=n.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){AC[0]=e,AC[1]=t;const n=this.renderer.info.calls,i=this.callHashCache.get(AC)||{};if(i.callId!==n){const r=this.getEnvironmentNode(e),s=this.getFogNode(e);t&&RC.push(t.getCacheKey(!0)),r&&RC.push(r.getCacheKey()),s&&RC.push(s.getCacheKey()),RC.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),RC.push(this.renderer.shadowMap.enabled?1:0),RC.push(this.renderer.shadowMap.type),i.callId=n,i.cacheKey=Pf(RC),this.callHashCache.set(AC,i),RC.length=0}return AC[0]=null,AC[1]=null,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),n=e.background;if(n){const i=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==n||i){const r=this.getCacheNode("background",n,()=>{if(!0===n.isCubeTexture||n.mapping===ne||n.mapping===ie||n.mapping===re){if(e.backgroundBlurriness>0||n.mapping===re)return DE(n);{let e;return e=!0===n.isCubeTexture?ax(n):zy(n),DS(e)}}if(!0===n.isTexture)return zy(n,Qy.flipY()).setUpdateMatrix(!0);!0!==n.isColor&&qt("WebGPUNodes: Unsupported background configuration.",n)},i);t.backgroundNode=r,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,i=!1){const r=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let s=r.get(t);return(void 0===s||i)&&(s=n(),r.set(t,s)),s}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){const e=this.getCacheNode("fog",n,()=>{if(n.isFogExp2){const e=ux("color","color",n).setGroup(i_),t=ux("density","float",n).setGroup(i_);return LA(e,PA(t))}if(n.isFog){const e=ux("color","color",n).setGroup(i_),t=ux("near","float",n).setGroup(i_),i=ux("far","float",n).setGroup(i_);return LA(e,NA(t,i))}qt("Renderer: Unsupported fog configuration.",n)});t.fogNode=e,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),n=e.environment;if(n){if(t.environment!==n){const e=this.getCacheNode("environment",n,()=>!0===n.isCubeTexture?ax(n):!0===n.isTexture?zy(n):void qt("Nodes: Unsupported environment configuration.",n));t.environmentNode=e,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,i=null,r=null){const s=this.nodeFrame;return s.renderer=e,s.scene=t,s.object=n,s.camera=i,s.material=r,s}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return wC.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,n=this.getOutputCacheKey(),i=e.isArrayTexture?dA(e,cg(Qy,Xy("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):zy(e,Qy).renderOutput(t.toneMapping,t.currentColorSpace);return wC.set(e,n),i}updateBefore(e){const t=e.getNodeBuilderState();for(const n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){const t=e.getNodeBuilderState();for(const n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateForCompute(e){const t=this.getNodeFrame(),n=this.getForCompute(e);for(const e of n.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const e of n.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new sC,this.nodeBuilderCache=new Map,this.cacheLib={}}}const NC=new Qr;class PC{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new mn,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,n){const i=e.length;for(let r=0;r<i;r++){NC.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[n+r],s=NC.normal;i.x=-s.x,i.y=-s.y,i.z=-s.z,i.w=NC.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix=t.matrixWorldInverse,this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let n=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,r=i.length;let s,a;if(this.clipIntersection?(s=this.intersectionPlanes,a=e.intersectionPlanes.length):(s=this.unionPlanes,a=e.unionPlanes.length),s.length!==a+r){s.length=a+r;for(let e=0;e<r;e++)s[a+e]=new Pn;n=!0}this.projectPlanes(i,s,a),n&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return void 0===t&&(t=new PC(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class LC{constructor(e,t){this.bundleGroup=e,this.camera=t}}const DC=[];class IC{constructor(){this.bundles=new ow}get(e,t){const n=this.bundles;DC[0]=e,DC[1]=t;let i=n.get(DC);return void 0===i&&(i=new LC(e,t),n.set(DC,i)),DC[0]=null,DC[1]=null,i}dispose(){this.bundles=new ow}}class UC{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const n=this.getMaterialNodeClass(e.type);if(null!==n){t=new n;for(const n in e)t[n]=e[n]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,n){if(n.has(t))Xt(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`Base class ${t} is not a class.`);n.set(t,e)}}addClass(e,t,n){if(n.has(t))Xt(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`Base class ${t.name} is not a class.`);n.set(t,e)}}}const FC=new jA,OC=new WeakMap;class BC{createNode(e=[]){return(new jA).setLights(e)}getNode(e){if(e.isQuadMesh)return FC;let t=OC.get(e);return void 0===t&&(t=this.createNode(),OC.set(e,t)),t}}class kC extends Ln{constructor(e=1,t=1,n={}){super(e,t,n),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}}const zC=new dn,VC=new dn;class GC extends Zt{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Sa,this._cameraL.viewport=new Pn,this._cameraR=new Sa,this._cameraR.viewport=new Pn,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Oa,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding="undefined"!=typeof XRWebGLBinding,this._frameBufferTargets=null,this._createXRLayer=XC.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new cn,this._onSessionEvent=jC.bind(this),this._onSessionEnd=WC.bind(this),this._onInputSourcesChange=$C.bind(this),this._onAnimationFrame=qC.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){if(null!==this._glProjLayer||null!==this._glBaseLayer)return this._foveation}setFoveation(e){this._foveation=e,null!==this._glProjLayer&&(this._glProjLayer.fixedFoveation=e),null!==this._glBaseLayer&&void 0!==this._glBaseLayer.fixedFoveation&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,!0===this.isPresenting&&Xt("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&Xt("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(null!==this._session)return this._session.environmentBlendMode}getBinding(){return null===this._glBinding&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,n,i,r,s,a,o={}){const l=new Os(e,t),u=new kC(r,s,{format:Ce,type:fe,depthTexture:new vs(r,s,o.stencil?Me:ye,void 0,void 0,void 0,void 0,void 0,void 0,o.stencil?Pe:Ne),stencilBuffer:o.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u._autoAllocateDepthBuffer=!0;const c=new Dr({color:16777215,side:0});c.map=u.texture,c.map.offset.y=1,c.map.repeat.y=-1;const h=new Wr(l,c);h.position.copy(n),h.quaternion.copy(i);const d={type:"quad",width:e,height:t,translation:n,quaternion:i,pixelwidth:r,pixelheight:s,plane:h,material:c,rendercall:a,renderTarget:u};if(this._layers.push(d),null!==this._session){d.plane.material=new Dr({color:16777215,side:0}),d.plane.material.blending=5,d.plane.material.blendEquation=v,d.plane.material.blendSrc=x,d.plane.material.blendDst=x,d.xrlayer=this._createXRLayer(d);const e=this._session.renderState.layers;e.unshift(d.xrlayer),this._session.updateRenderState({layers:e})}else u.isXRRenderTarget=!1;return h}createCylinderLayer(e,t,n,i,r,s,a,o,l={}){const u=new Ts(e,e,e*t/n,64,64,!0,Math.PI-t/2,t),c=new kC(s,a,{format:Ce,type:fe,depthTexture:new vs(s,a,l.stencil?Me:ye,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?Pe:Ne),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});c._autoAllocateDepthBuffer=!0;const h=new Dr({color:16777215,side:1});h.map=c.texture,h.map.offset.y=1,h.map.repeat.y=-1;const d=new Wr(u,h);d.position.copy(i),d.quaternion.copy(r);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:n,translation:i,quaternion:r,pixelwidth:s,pixelheight:a,plane:d,material:h,rendercall:o,renderTarget:c};if(this._layers.push(p),null!==this._session){p.plane.material=new Dr({color:16777215,side:1}),p.plane.material.blending=5,p.plane.material.blendEquation=v,p.plane.material.blendSrc=x,p.plane.material.blendDst=x,p.xrlayer=this._createXRLayer(p);const e=this._session.renderState.layers;e.unshift(p.xrlayer),this._session.updateRenderState({layers:e})}else c.isXRRenderTarget=!1;return d}renderLayers(){const e=new dn,t=new hn,n=this._renderer,i=this.isPresenting,r=n.getOutputRenderTarget(),s=n._frameBufferTarget;this.isPresenting=!1;const a=new cn;n.getSize(a);const o=n._quad;for(const i of this._layers)if(i.renderTarget.isXRRenderTarget=null!==this._session,i.renderTarget._hasExternalTextures=i.renderTarget.isXRRenderTarget,i.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){i.xrlayer.transform=new XRRigidTransform(i.plane.getWorldPosition(e),i.plane.getWorldQuaternion(t));const r=this._glBinding.getSubImage(i.xrlayer,this._xrFrame);n.backend.setXRRenderTargetTextures(i.renderTarget,r.colorTexture,void 0),n._setXRLayerSize(i.renderTarget.width,i.renderTarget.height),n.setOutputRenderTarget(i.renderTarget),n.setRenderTarget(null),n._frameBufferTarget=null,this._frameBufferTargets||(this._frameBufferTargets=new WeakMap);const{frameBufferTarget:s,quad:a}=this._frameBufferTargets.get(i.renderTarget)||{frameBufferTarget:null,quad:null};s?(n._frameBufferTarget=s,n._quad=a):(n._quad=new tA(new bS),this._frameBufferTargets.set(i.renderTarget,{frameBufferTarget:n._getFrameBufferTarget(),quad:n._quad})),i.rendercall(),n._frameBufferTarget=null}else n.setRenderTarget(i.renderTarget),i.rendercall();n.setRenderTarget(null),n.setOutputRenderTarget(r),n._frameBufferTarget=s,n._setXRLayerSize(a.x,a.y),n._quad=o,this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer,n=t.backend;this._gl=t.getContext();const i=this._gl,r=i.getContextAttributes();if(this._session=e,null!==e){if(!0===n.isWebGPUBackend)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await n.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._supportsLayers){let n=null,s=null,a=null;t.depth&&(a=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,n=t.stencil?Pe:Ne,s=t.stencil?Me:ye);const o={colorFormat:i.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const l=this._glBinding.createProjectionLayer(o),u=[l];this._glProjLayer=l,t.setPixelRatio(1),t._setXRLayerSize(l.textureWidth,l.textureHeight);const c=this._useMultiview?2:1,h=new vs(l.textureWidth,l.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n,c);if(this._xrRenderTarget=new kC(l.textureWidth,l.textureHeight,{format:Ce,type:fe,colorSpace:t.outputColorSpace,depthTexture:h,stencilBuffer:t.stencil,samples:r.antialias?4:0,resolveDepthBuffer:!1===l.ignoreDepthValues,resolveStencilBuffer:!1===l.ignoreDepthValues,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(const e of this._layers)e.plane.material=new Dr({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=v,e.plane.material.blendSrc=x,e.plane.material.blendDst=x,e.xrlayer=this._createXRLayer(e),u.unshift(e.xrlayer);e.updateRenderState({layers:u})}else{const n={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},r=new XRWebGLLayer(e,i,n);this._glBaseLayer=r,e.updateRenderState({baseLayer:r}),t.setPixelRatio(1),t._setXRLayerSize(r.framebufferWidth,r.framebufferHeight),this._xrRenderTarget=new kC(r.framebufferWidth,r.framebufferHeight,{format:Ce,type:fe,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===r.ignoreDepthValues,resolveStencilBuffer:!1===r.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const n=e.near,i=e.far,r=this._cameraXR,s=this._cameraL,a=this._cameraR;r.near=a.near=s.near=n,r.far=a.far=s.far=i,r.isMultiViewCamera=this._useMultiview,this._currentDepthNear===r.near&&this._currentDepthFar===r.far||(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),r.layers.mask=6|e.layers.mask,s.layers.mask=-5&r.layers.mask,a.layers.mask=-3&r.layers.mask;const o=e.parent,l=r.cameras;HC(r,o);for(let e=0;e<l.length;e++)HC(l[e],o);2===l.length?function(e,t,n){zC.setFromMatrixPosition(t.matrixWorld),VC.setFromMatrixPosition(n.matrixWorld);const i=zC.distanceTo(VC),r=t.projectionMatrix.elements,s=n.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),l=(r[9]+1)/r[5],u=(r[9]-1)/r[5],c=(r[8]-1)/r[0],h=(s[8]+1)/s[0],d=a*c,p=a*h,f=i/(-c+h),m=f*-c;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(m),e.translateZ(f),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===r[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+f,n=o+f,r=d-m,s=p+(i-m),c=l*o/n*t,h=u*o/n*t;e.projectionMatrix.makePerspective(r,s,c,h,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(r,s,a):r.projectionMatrix.copy(s.projectionMatrix),function(e,t,n){null===n?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*tn*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,r,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new di,this._controllers[e]=t),t}}function HC(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function jC(e){const t=this._controllerInputSources.indexOf(e.inputSource);if(-1===t)return;const n=this._controllers[t];if(void 0!==n){const t=this.getReferenceSpace();n.update(e.inputSource,e.frame,t),n.dispatchEvent({type:e.type,data:e.inputSource})}}function WC(){const e=this._session,t=this._renderer;e.removeEventListener("select",this._onSessionEvent),e.removeEventListener("selectstart",this._onSessionEvent),e.removeEventListener("selectend",this._onSessionEvent),e.removeEventListener("squeeze",this._onSessionEvent),e.removeEventListener("squeezestart",this._onSessionEvent),e.removeEventListener("squeezeend",this._onSessionEvent),e.removeEventListener("end",this._onSessionEnd),e.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let e=0;e<this._controllers.length;e++){const t=this._controllerInputSources[e];null!==t&&(this._controllerInputSources[e]=null,this._controllers[e].disconnect(t))}if(this._currentDepthNear=null,this._currentDepthFar=null,t._resetXRState(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._glBaseLayer=null,this._glProjLayer=null,!0===this._sessionUsesLayers)for(const e of this._layers)e.renderTarget=new kC(e.pixelwidth,e.pixelheight,{format:Ce,type:fe,depthTexture:new vs(e.pixelwidth,e.pixelheight,e.stencilBuffer?Me:ye,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?Pe:Ne),stencilBuffer:e.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,e.material.map.offset.y=1,e.material.map.repeat.y=-1,delete e.xrlayer;this.isPresenting=!1,this._useMultiview=!1,t._animation.stop(),t._animation.setAnimationLoop(this._currentAnimationLoop),t._animation.setContext(this._currentAnimationContext),t._animation.start(),t.setPixelRatio(this._currentPixelRatio),t.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function $C(e){const t=this._controllers,n=this._controllerInputSources;for(let i=0;i<e.removed.length;i++){const r=e.removed[i],s=n.indexOf(r);s>=0&&(n[s]=null,t[s].disconnect(r))}for(let i=0;i<e.added.length;i++){const r=e.added[i];let s=n.indexOf(r);if(-1===s){for(let e=0;e<t.length;e++){if(e>=n.length){n.push(r),s=e;break}if(null===n[e]){n[e]=r,s=e;break}}if(-1===s)break}const a=t[s];a&&a.connect(r)}}function XC(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function qC(e,t){if(void 0===t)return;const n=this._cameraXR,i=this._renderer,r=i.backend,s=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.views;null!==this._glBaseLayer&&r.setXRTarget(s.framebuffer);let t=!1;e.length!==n.cameras.length&&(n.cameras.length=0,t=!0);for(let i=0;i<e.length;i++){const a=e[i];let o;if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,a);o=e.viewport,0===i&&r.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else o=s.getViewport(a);let l=this._cameras[i];void 0===l&&(l=new Sa,l.layers.enable(i),l.viewport=new Pn,this._cameras[i]=l),l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.quaternion,l.scale),l.projectionMatrix.fromArray(a.projectionMatrix),l.projectionMatrixInverse.copy(l.projectionMatrix).invert(),l.viewport.set(o.x,o.y,o.width,o.height),0===i&&(n.matrix.copy(l.matrix),n.matrix.decompose(n.position,n.quaternion,n.scale)),!0===t&&n.cameras.push(l)}i.setOutputRenderTarget(this._xrRenderTarget)}for(let e=0;e<this._controllers.length;e++){const n=this._controllerInputSources[e],i=this._controllers[e];null!==n&&void 0!==i&&i.update(n,t,a)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class YC extends Zt{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new Pn(0,0,this._width,this._height),this._scissor=new Pn(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new gs,this.depthTexture=new vs}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===n&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,n,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,n,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,i,r=0,s=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,i),a.minDepth=r,a.maxDepth=s}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const KC=new yi,ZC=new cn,QC=new Pn,JC=new ns,eN=new ss,tN=new Fn,nN=new Pn,iN={[m]:1,[g]:0,[_]:2};class rN{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:n=!1,reversedDepthBuffer:i=!1,alpha:r=!0,depth:s=!0,stencil:a=!1,antialias:o=!1,samples:l=0,getFallback:u=null,outputBufferType:c=xe,multiview:h=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=n,this.reversedDepthBuffer=i,this.outputColorSpace=bt,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=s,this.stencil=a,this.info=new Sw,this.contextNode=Hv(),this.library=new UC,this.lighting=new BC,this._samples=l||!0===o?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new YC(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new Ay,this._inspector.setRenderer(this),this._getFallback=u,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new tA(new bS),this._quad.name="Output Color Transform",this._quad.material.name="outputColorTransform",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const d=!0===this.alpha?0:1;this._clearColor=new Hw(0,0,0,d),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._outputBufferType=c,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:1},this.xr=new GC(this,h),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,n)=>{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(this._renderTarget,this._mrt),s=e.overrideMaterial||n.material,a=this._objects.get(n,s,e,t,i.lightsNode,r,r.clippingContext),{fragmentShader:o,vertexShader:l}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:l}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=n=this._getFallback(e),await n.init(this)}catch(e){return void t(e)}}this._nodes=new CC(this,n),this._animation=new aw(this,this._nodes,this.info),this._attributes=new vw(n),this._background=new MR(this,this._nodes),this._geometries=new Tw(this._attributes,this.info),this._textures=new Gw(this,n,this.info),this._pipelines=new Cw(n,this._nodes),this._bindings=new Nw(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new hw(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Fw(this.lighting),this._bundles=new IC,this._renderContexts=new zw(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,s=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._handleObjectFunction,l=this._compilationPromises,u=!0===e.isScene?e:KC;null===n&&(n=e);const c=this._renderTarget,h=this._renderContexts.get(c,this._mrt),d=this._activeMipmapLevel,p=[];this._currentRenderContext=h,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,i.renderId++,i.update(),h.depth=this.depth,h.stencil=this.stencil,h.clippingContext||(h.clippingContext=new PC),h.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,c);const f=this._renderLists.get(e,t);if(f.begin(),this._projectObject(e,t,0,f,h.clippingContext),n!==e&&n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&f.pushLight(e)}),f.finish(),null!==c){this._textures.updateRenderTarget(c,d);const e=this._textures.get(c);h.textures=e.textures,h.depthTexture=e.depthTexture}else h.textures=null,h.depthTexture=null;n!==e?this._background.update(n,f,h):this._background.update(u,f,h);const m=f.opaque,g=f.transparent,_=f.transparentDoublePass,v=f.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,u,v),!0===this.transparent&&g.length>0&&this._renderTransparents(g,_,t,u,v),i.renderId=r,this._currentRenderContext=s,this._currentRenderObjectFunction=a,this._handleObjectFunction=o,this._compilationPromises=l,await Promise.all(p)}async renderAsync(e,t){Yt('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){qt("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=Eb,t.modelNormalViewMatrix=wb):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Eb&&e.modelNormalViewMatrix===wb}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Yt('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),qt(t),this._isDeviceLost=!0}_renderBundle(e,t,n){const{bundleGroup:i,camera:r,renderList:s}=e,a=this._currentRenderContext,o=this._bundles.get(i,r),l=this.backend.get(o);void 0===l.renderContexts&&(l.renderContexts=new Set);const u=i.version!==l.version,c=!1===l.renderContexts.has(a)||u;if(l.renderContexts.add(a),c){this.backend.beginBundle(a),(void 0===l.renderObjects||u)&&(l.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:c,opaque:h}=s;!0===this.opaque&&h.length>0&&this._renderObjects(h,r,t,n),!0===this.transparent&&c.length>0&&this._renderTransparents(c,e,r,t,n),this._currentRenderBundle=null,this.backend.finishBundle(a,o),l.version=i.version}else{const{renderObjects:e}=l;for(let t=0,n=e.length;t<n;t++){const n=e[t];this._nodes.needsRefresh(n)&&(this._nodes.updateBefore(n),this._nodes.updateForRender(n),this._bindings.updateForRender(n),this._nodes.updateAfter(n))}}this.backend.addBundle(a,o)}render(e,t){if(!1===this._initialized)throw new Error('Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this,n=0!==e,i=t!==bn.workingColorSpace;if(!1===n&&!1===i)return null;const{width:r,height:s}=this.getDrawingBufferSize(ZC),{depth:a,stencil:o}=this;let l=this._frameBufferTarget;null===l&&(l=new Ln(r,s,{depthBuffer:a,stencilBuffer:o,type:this._outputBufferType,format:Ce,colorSpace:bn.workingColorSpace,generateMipmaps:!1,minFilter:he,magFilter:he,samples:this.samples}),l.isPostProcessingRenderTarget=!0,this._frameBufferTarget=l);const u=this.getOutputRenderTarget();l.depthBuffer=a,l.stencilBuffer=o,null!==u?l.setSize(u.width,u.height,u.depth):l.setSize(r,s,1);const c=this._canvasTarget;return l.viewport.copy(c._viewport),l.scissor.copy(c._scissor),l.viewport.multiplyScalar(c._pixelRatio),l.scissor.multiplyScalar(c._pixelRatio),l.scissorTest=c._scissorTest,l.multiview=null!==u&&u.multiview,l.resolveDepthBuffer=null===u||u.resolveDepthBuffer,l._autoAllocateDepthBuffer=null!==u&&u._autoAllocateDepthBuffer,l}_renderScene(e,t,n=!0){if(!0===this._isDeviceLost)return;const i=n?this._getFrameBufferTarget():null,r=this._nodes.nodeFrame,s=r.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,l=this._handleObjectFunction;this._callDepth++;const u=!0===e.isScene?e:KC,c=this._renderTarget||this._outputRenderTarget,h=this._activeCubeFace,d=this._activeMipmapLevel;let p;null!==i?(p=i,this.setRenderTarget(p)):p=c;const f=this._renderContexts.get(p,this._mrt,this._callDepth);this._currentRenderContext=f,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(f),this.inspector.beginRender(this.backend.getTimestampUID(f),e,t,p);const m=this.xr;if(!1===m.isPresenting){let e=!1;if(!0===this.reversedDepthBuffer&&!0!==t.reversedDepth){if(t._reversedDepth=!0,t.isArrayCamera)for(const e of t.cameras)e._reversedDepth=!0;e=!0}const n=this.coordinateSystem;if(t.coordinateSystem!==n){if(t.coordinateSystem=n,t.isArrayCamera)for(const e of t.cameras)e.coordinateSystem=n;e=!0}if(!0===e&&(t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.updateProjectionMatrix()}!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===m.enabled&&!0===m.isPresenting&&(!0===m.cameraAutoUpdate&&m.updateCamera(t),t=m.getCamera());const g=this._canvasTarget;let _=g._viewport,v=g._scissor,y=g._pixelRatio;null!==p&&(_=p.viewport,v=p.scissor,y=1),this.getDrawingBufferSize(ZC),QC.set(0,0,ZC.width,ZC.height);const b=void 0===_.minDepth?0:_.minDepth,x=void 0===_.maxDepth?1:_.maxDepth;f.viewportValue.copy(_).multiplyScalar(y).floor(),f.viewportValue.width>>=d,f.viewportValue.height>>=d,f.viewportValue.minDepth=b,f.viewportValue.maxDepth=x,f.viewport=!1===f.viewportValue.equals(QC),f.scissorValue.copy(v).multiplyScalar(y).floor(),f.scissor=g._scissorTest&&!1===f.scissorValue.equals(QC),f.scissorValue.width>>=d,f.scissorValue.height>>=d,f.clippingContext||(f.clippingContext=new PC),f.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,p);const T=t.isArrayCamera?eN:JC;t.isArrayCamera||(tN.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),T.setFromProjectionMatrix(tN,t.coordinateSystem,t.reversedDepth));const S=this._renderLists.get(e,t);if(S.begin(),this._projectObject(e,t,0,S,f.clippingContext),S.finish(),!0===this.sortObjects&&S.sort(this._opaqueSort,this._transparentSort),null!==p){this._textures.updateRenderTarget(p,d);const e=this._textures.get(p);f.textures=e.textures,f.depthTexture=e.depthTexture,f.width=e.width,f.height=e.height,f.renderTarget=p,f.depth=p.depthBuffer,f.stencil=p.stencilBuffer}else f.textures=null,f.depthTexture=null,f.width=ZC.width,f.height=ZC.height,f.depth=this.depth,f.stencil=this.stencil;f.width>>=d,f.height>>=d,f.activeCubeFace=h,f.activeMipmapLevel=d,f.occlusionQueryCount=S.occlusionQueryCount,f.scissorValue.max(nN.set(0,0,0,0)),f.scissorValue.x+f.scissorValue.width>f.width&&(f.scissorValue.width=Math.max(f.width-f.scissorValue.x,0)),f.scissorValue.y+f.scissorValue.height>f.height&&(f.scissorValue.height=Math.max(f.height-f.scissorValue.y,0)),this._background.update(u,S,f),f.camera=t,this.backend.beginRender(f);const{bundles:M,lightsNode:E,transparentDoublePass:w,transparent:A,opaque:R}=S;return M.length>0&&this._renderBundles(M,u,E),!0===this.opaque&&R.length>0&&this._renderObjects(R,t,u,E),!0===this.transparent&&A.length>0&&this._renderTransparents(A,w,t,u,E),this.backend.finishRender(f),r.renderId=s,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=l,this._callDepth--,null!==i&&(this.setRenderTarget(c,h,d),this._renderOutput(p)),u.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(f)),f}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const n=this.autoClear,i=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=n,this.xr.enabled=i}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,n)}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,n)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,n,i){this._canvasTarget.setScissor(e,t,n,i)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,n,i,r=0,s=1){this._canvasTarget.setViewport(e,t,n,i,r,s)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return!0===this.reversedDepthBuffer?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(!1===this._initialized)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i){this._textures.updateRenderTarget(i);const e=this._textures.get(i);r=this._renderContexts.get(i),r.textures=e.textures,r.depthTexture=e.depthTexture,r.width=e.width,r.height=e.height,r.renderTarget=i,r.depth=i.depthBuffer,r.stencil=i.stencilBuffer;const t=this.backend.getClearColor();r.clearColorValue.r=t.r,r.clearColorValue.g=t.g,r.clearColorValue.b=t.b,r.clearColorValue.a=t.a,r.clearDepthValue=this.getClearDepth(),r.clearStencilValue=this.getClearStencil(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,n,r),null!==i&&null===this._renderTarget&&this._renderOutput(i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){Yt('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,n)}async clearColorAsync(){Yt('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Yt('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Yt('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=0!==this.currentToneMapping,t=this.currentColorSpace!==bn.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:bn.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){!0===this._initialized&&(this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return Xt("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const n=this._nodes.nodeFrame,i=n.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const r=this.backend,s=this._pipelines,a=this._bindings,o=this._nodes,l=Array.isArray(e)?e:[e];if(void 0===l[0]||!0!==l[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const n of l){if(!1===s.has(n)){const e=()=>{n.removeEventListener("dispose",e),s.delete(n),a.deleteForCompute(n),o.delete(n)};n.addEventListener("dispose",e);const t=n.onInitFunction;null!==t&&t.call(n,{renderer:this})}o.updateForCompute(n),a.updateForCompute(n);const i=a.getForCompute(n),l=s.getForCompute(n,i);r.compute(e,n,i,l,t)}r.finishCompute(e),n.renderId=i,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){!1===this._initialized&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return Yt('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Yt('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),n=this._renderContexts.get(e);n.textures=t.textures,n.depthTexture=t.depthTexture,n.width=t.width,n.height=t.height,n.renderTarget=e,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,this.backend.initRenderTarget(n)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=nN.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void qt("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=nN.copy(t).floor()}else t=nN.set(0,0,e.image.width,e.image.height);let n,i=this._currentRenderContext;null!==i?n=i.renderTarget:(n=this._renderTarget||this._getFrameBufferTarget(),null!==n&&(this._textures.updateRenderTarget(n),i=this._textures.get(n))),this._textures.updateTexture(e,{renderTarget:n}),this.backend.copyFramebufferToTexture(e,i,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,n=null,i=null,r=0,s=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,i,r,s),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,n,i,r,s=0,a=0){return this.backend.copyTextureToBuffer(e.textures[s],t,n,i,r,a)}_projectObject(e,t,n,i,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(r=r.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const s=t.isArrayCamera?eN:JC;if(!e.frustumCulled||s.intersectsSprite(e,t)){!0===this.sortObjects&&nN.setFromMatrixPosition(e.matrixWorld).applyMatrix4(tN);const{geometry:t,material:s}=e;s.visible&&i.push(e,t,s,n,nN.z,null,r)}}else if(e.isLineLoop)qt("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const s=t.isArrayCamera?eN:JC;if(!e.frustumCulled||s.intersectsObject(e,t)){const{geometry:t,material:s}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),nN.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(tN)),Array.isArray(s)){const a=t.groups;for(let o=0,l=a.length;o<l;o++){const l=a[o],u=s[l.materialIndex];u&&u.visible&&i.push(e,t,u,n,nN.z,l,r)}}else s.visible&&i.push(e,t,s,n,nN.z,null,r)}}if(!0===e.isBundleGroup&&void 0!==this.backend.beginBundle){const n=i;(i=this._renderLists.get(e,t)).begin(),n.pushBundle({bundleGroup:e,camera:t,renderList:i}),i.finish()}const s=e.children;for(let e=0,a=s.length;e<a;e++)this._projectObject(s[e],t,n,i,r)}_renderBundles(e,t,n){for(const i of e)this._renderBundle(i,t,n)}_renderTransparents(e,t,n,i,r){if(t.length>0){for(const{material:e}of t)e.side=1;this._renderObjects(t,n,i,r,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,n,i,r);for(const{material:e}of t)e.side=2}else this._renderObjects(e,n,i,r)}_renderObjects(e,t,n,i,r=null){for(let s=0,a=e.length;s<a;s++){const{object:a,geometry:o,material:l,group:u,clippingContext:c}=e[s];this._currentRenderObjectFunction(a,n,t,o,l,u,i,c,r)}}_getShadowNodes(e){const t=e.version;let n=this._cacheShadowNodes.get(e);if(void 0===n||n.version!==t){const i=null!==e.map,r=e.colorNode&&e.colorNode.isNode,s=e.castShadowNode&&e.castShadowNode.isNode,a=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let o=null,l=null,u=null;if(i||r||s||a){let t,n;if(s?(t=e.castShadowNode.rgb,n=e.castShadowNode.a,!0!==this.shadowMap.transmitted&&Yt("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(t=cg(0),n=ng(1)),i&&(n=n.mul(ux("map","texture",e).a)),r&&(n=n.mul(e.colorNode.a)),l=fg(t,n),a){const t=e.maskShadowNode||e.maskNode;l=Km(([e])=>(t.not().discard(),e))(l)}}e.depthNode&&e.depthNode.isNode&&(u=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),n={version:t,colorNode:l,depthNode:u,positionNode:o},this._cacheShadowNodes.set(e,n)}return n}renderObject(e,t,n,i,r,s,a,o=null,l=null){let u,c,h,d,p=!1;if(e.onBeforeRender(this,t,n,i,r,s),!0===r.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;if(p=!0,u=e.isNodeMaterial?e.colorNode:null,c=e.isNodeMaterial?e.depthNode:null,h=e.isNodeMaterial?e.positionNode:null,d=t.overrideMaterial.side,r.positionNode&&r.positionNode.isNode&&(e.positionNode=r.positionNode),e.alphaTest=r.alphaTest,e.alphaMap=r.alphaMap,e.transparent=r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:n,positionNode:i}=this._getShadowNodes(r);3===this.shadowMap.type?e.side=null!==r.shadowSide?r.shadowSide:r.side:e.side=null!==r.shadowSide?r.shadowSide:iN[r.side],null!==t&&(e.colorNode=t),null!==n&&(e.depthNode=n),null!==i&&(e.positionNode=i)}r=e}!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,this._handleObjectFunction(e,r,t,n,a,s,o,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,n,a,s,o,l),r.side=2):this._handleObjectFunction(e,r,t,n,a,s,o,l),p&&(t.overrideMaterial.colorNode=u,t.overrideMaterial.depthNode=c,t.overrideMaterial.positionNode=h,t.overrideMaterial.side=d),e.onAfterRender(this,t,n,i,r,s)}hasCompatibility(e){return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,n,i,r,s,a,o){const l=this._objects.get(e,t,n,i,r,this._currentRenderContext,a,o);if(l.drawRange=e.geometry.drawRange,l.group=s,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup}const u=this._nodes.needsRefresh(l);u&&(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)),this._pipelines.updateForRender(l),this.backend.draw(l,this.info),u&&this._nodes.updateAfter(l)}_createObjectPipeline(e,t,n,i,r,s,a,o){const l=this._objects.get(e,t,n,i,r,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s,this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l),this._pipelines.getForRender(l,this._compilationPromises),this._nodes.updateAfter(l)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class sN{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}class aN extends sN{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return(e=this._buffer.byteLength)+(_w-e%_w)%_w;var e}get buffer(){return this._buffer}update(){return!0}}class oN extends aN{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let lN=0;class uN extends oN{constructor(e,t){super("UniformBuffer_"+lN++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class cN extends oN{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(!0!==this._updateRangeCache.has(t)){const n=this.updateRanges,i={start:e.offset,count:e.itemSize};n.push(i),this._updateRangeCache.set(t,i)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let n=0,i=this.uniforms.length;n<i;n++){const i=this.uniforms[n],r=i.boundary,s=i.itemSize*e,a=t%_w,o=a%r,l=a+o;t+=o,0!==l&&_w-l<s&&(t+=_w-l),i.offset=t/e,i.index=n,t+=s}return Math.ceil(t/_w)*_w}update(){let e=!1;for(const t of this.uniforms)!0===this.updateByType(t)&&(e=!0);return e}updateByType(e){return e.isNumberUniform?this.updateNumber(e):e.isVector2Uniform?this.updateVector2(e):e.isVector3Uniform?this.updateVector3(e):e.isVector4Uniform?this.updateVector4(e):e.isColorUniform?this.updateColor(e):e.isMatrix3Uniform?this.updateMatrix3(e):e.isMatrix4Uniform?this.updateMatrix4(e):void qt("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const n=this.values,i=e.getValue(),r=e.offset,s=e.getType();if(n[r]!==i){this._getBufferForType(s)[r]=n[r]=i,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1;const n=this.values,i=e.getValue(),r=e.offset,s=e.getType();if(n[r+0]!==i.x||n[r+1]!==i.y){const a=this._getBufferForType(s);a[r+0]=n[r+0]=i.x,a[r+1]=n[r+1]=i.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1;const n=this.values,i=e.getValue(),r=e.offset,s=e.getType();if(n[r+0]!==i.x||n[r+1]!==i.y||n[r+2]!==i.z){const a=this._getBufferForType(s);a[r+0]=n[r+0]=i.x,a[r+1]=n[r+1]=i.y,a[r+2]=n[r+2]=i.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1;const n=this.values,i=e.getValue(),r=e.offset,s=e.getType();if(n[r+0]!==i.x||n[r+1]!==i.y||n[r+2]!==i.z||n[r+4]!==i.w){const a=this._getBufferForType(s);a[r+0]=n[r+0]=i.x,a[r+1]=n[r+1]=i.y,a[r+2]=n[r+2]=i.z,a[r+3]=n[r+3]=i.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1;const n=this.values,i=e.getValue(),r=e.offset;if(n[r+0]!==i.r||n[r+1]!==i.g||n[r+2]!==i.b){const s=this.buffer;s[r+0]=n[r+0]=i.r,s[r+1]=n[r+1]=i.g,s[r+2]=n[r+2]=i.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1;const n=this.values,i=e.getValue().elements,r=e.offset;if(n[r+0]!==i[0]||n[r+1]!==i[1]||n[r+2]!==i[2]||n[r+4]!==i[3]||n[r+5]!==i[4]||n[r+6]!==i[5]||n[r+8]!==i[6]||n[r+9]!==i[7]||n[r+10]!==i[8]){const s=this.buffer;s[r+0]=n[r+0]=i[0],s[r+1]=n[r+1]=i[1],s[r+2]=n[r+2]=i[2],s[r+4]=n[r+4]=i[3],s[r+5]=n[r+5]=i[4],s[r+6]=n[r+6]=i[5],s[r+8]=n[r+8]=i[6],s[r+9]=n[r+9]=i[7],s[r+10]=n[r+10]=i[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1;const n=this.values,i=e.getValue().elements,r=e.offset;if(!1===function(e,t,n){for(let i=0,r=t.length;i<r;i++)if(e[n+i]!==t[i])return!1;return!0}(n,i,r)){this.buffer.set(i,r),function(e,t,n){for(let i=0,r=t.length;i<r;i++)e[n+i]=t[i]}(n,i,r),t=!0,this.addUniformUpdateRange(e)}return t}_getBufferForType(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e?new Int32Array(this.buffer.buffer):"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e?new Uint32Array(this.buffer.buffer):this.buffer}}let hN=0;class dN extends cN{constructor(e,t){super(e),this.id=hN++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class pN extends sN{constructor(e,t){super(e),this._texture=null,this._onTextureDispose=()=>{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=-1},e.texture=this.texture,e}}let fN=0;class mN extends pN{constructor(e,t){super(e,t),this.id=fN++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class gN extends mN{constructor(e,t,n,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=i}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class _N extends gN{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledCubeTexture=!0}}class vN extends gN{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledTexture3D=!0}}const yN={bitcast_int_uint:new AA("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new AA("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},bN={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},xN={low:"lowp",medium:"mediump",high:"highp"},TN={swizzleAssign:!0,storageBuffer:!1},SN={perspective:"smooth",linear:"noperspective"},MN={centroid:"centroid"},EN="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n";class wN extends rC{constructor(e,t){super(e,t,new EC),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==yt}_include(e){const t=yN[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==yN[e]&&this._include(e),bN[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,n){return`${e} ? ${t} : ${n}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) {\n\n\t${n.vars}\n\n${n.code}\n\treturn ${n.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,n=t.count*t.itemSize,{itemSize:i}=t,r=t.array.constructor.name.toLowerCase().includes("int");let s=r?De:Le;2===i?s=r?Ue:Ie:3===i?s=r?1032:Re:4===i&&(s=r?Fe:Ce);const a={Float32Array:be,Uint8Array:fe,Uint16Array:_e,Uint32Array:ye,Int8Array:me,Int16Array:ge,Int32Array:ve,Uint8ClampedArray:fe},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(n/i))));let l=Math.ceil(n/i/o);o*l*i<n&&l++;const u=o*l*i,c=new e.constructor(u);c.set(e,0),t.array=c;const h=new Xr(t.array,o,l,s,a[t.array.constructor.name]||be);h.needsUpdate=!0,h.isPBOTexture=!0;const d=new By(h,null,null);d.setPrecision("high"),t.pboNode=d,t.pbo=d.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:n}=e,i=t.value;if(this.renderer.backend.has(i)){this.renderer.backend.get(i).pbo=i.pbo}const r=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.nodeName),s=this.getPropertyName(r);this.increaseUsage(n);const a=n.build(this,"uint"),o=this.getDataFromNode(e);let l=o.propertyName;if(void 0===l){const n=this.getVarFromNode(e);l=this.getPropertyName(n);const r=this.getDataFromNode(t);let u=r.propertySizeName;void 0===u&&(u=l+"Size",this.getVarFromNode(t,u,"uint"),this.addLineFlowCode(`${u} = uint( textureSize( ${s}, 0 ).x )`,e),r.propertySizeName=u);const{itemSize:c}=i,h="."+Yf.join("").slice(0,c),d=`ivec2(${a} % ${u}, ${a} / ${u})`,p=this.generateTextureLoad(null,s,d,"0",null,null);let f="vec4";i.pbo.type===ye?f="uvec4":i.pbo.type===ve&&(f="ivec4"),this.addLineFlowCode(`${l} = ${f}(${p})${h}`,e),o.propertyName=l}return l}generateTextureLoad(e,t,n,i,r,s){let a;return null===i&&(i="0"),a=r?s?`texelFetchOffset( ${t}, ivec3( ${n}, ${r} ), ${i}, ${s} )`:`texelFetch( ${t}, ivec3( ${n}, ${r} ), ${i} )`:s?`texelFetchOffset( ${t}, ${n}, ${i}, ${s} )`:`texelFetch( ${t}, ${n}, ${i} )`,null!==e&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,n,i,r){return i&&(n=`vec3( ${n}, ${i} )`),e.isDepthTexture?r?`textureOffset( ${t}, ${n}, ${r} ).x`:`texture( ${t}, ${n} ).x`:r?`textureOffset( ${t}, ${n}, ${r} )`:`texture( ${t}, ${n} )`}generateTextureLevel(e,t,n,i,r,s){return r&&(n=`vec3( ${n}, ${r} )`),s?`textureLodOffset( ${t}, ${n}, ${i}, ${s} )`:`textureLod( ${t}, ${n}, ${i} )`}generateTextureBias(e,t,n,i,r,s){return r&&(n=`vec3( ${n}, ${r} )`),s?`textureOffset( ${t}, ${n}, ${s}, ${i} )`:`texture( ${t}, ${n}, ${i} )`}generateTextureGrad(e,t,n,i,r,s){return r&&(n=`vec3( ${n}, ${r} )`),s?`textureGradOffset( ${t}, ${n}, ${i[0]}, ${i[1]}, ${s} )`:`textureGrad( ${t}, ${n}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,n,i,r,s,a=this.shaderStage){if("fragment"===a)return e.isCubeTexture?`texture( ${t}, vec4( ${n}, ${i} ) )`:r?s?`textureOffset( ${t}, vec4( ${n}, ${r}, ${i} ), ${s} )`:`texture( ${t}, vec4( ${n}, ${r}, ${i} ) )`:s?`textureOffset( ${t}, vec3( ${n}, ${i} ), ${s} )`:`texture( ${t}, vec3( ${n}, ${i} ) )`;qt(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}getVars(e){const t=[],n=this.vars[e];if(void 0!==n)for(const e of n)t.push(`${this.getVar(e.type,e.name,e.count)};`);return t.join("\n\t")}getUniforms(e){const t=this.uniforms[e],n=[],i={};for(const e of t){let t=null,r=!1;if("texture"===e.type||"texture3D"===e.type){const n=e.node.value;let i="";!0!==n.isDataTexture&&!0!==n.isData3DTexture||(n.type===ye?i="u":n.type===ve&&(i="i")),t="texture3D"===e.type&&!1===n.isArrayTexture?`${i}sampler3D ${e.name};`:n.compareFunction?!0===n.isArrayTexture?`sampler2DArrayShadow ${e.name};`:`sampler2DShadow ${e.name};`:!0===n.isArrayTexture||!0===n.isDataArrayTexture||!0===n.isCompressedArrayTexture?`${i}sampler2DArray ${e.name};`:`${i}sampler2D ${e.name};`}else if("cubeTexture"===e.type)t=`samplerCube ${e.name};`;else if("cubeDepthTexture"===e.type){t=e.node.value.compareFunction?`samplerCubeShadow ${e.name};`:`samplerCube ${e.name};`}else if("buffer"===e.type){const n=e.node,i=this.getType(n.bufferType),r=n.bufferCount,s=r>0?r:"";t=`${n.name} {\n\t${i} ${e.name}[${s}];\n};\n`}else{const t=e.groupNode.name;if(void 0===i[t]){const e=this.uniformGroups[t];if(void 0!==e){const n=[];for(const t of e.uniforms){const e=t.getType(),i=this.getVectorType(e),r=t.nodeUniform.node.precision;let s=`${i} ${t.name};`;null!==r&&(s=xN[r]+" "+s),n.push("\t"+s)}i[t]=n}}r=!0}if(!r){const i=e.node.precision;null!==i&&(t=xN[i]+" "+t),t="uniform "+t,n.push(t)}}let r="";for(const e in i){const t=i[e];r+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return r+=n.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==ve){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const i=n.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let n=0;for(const i of e)t+=`layout( location = ${n++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[];for(const n of e.members)t.push(`\t${n.type} ${n.name};`);return t.join("\n")}getStructs(e){const t=[],n=this.structs[e],i=[];for(const e of n)if(e.output)for(const t of e.members)i.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let n="struct "+e.name+" {\n";n+=this.getStructMembers(e),n+="\n};\n",t.push(n)}return 0===i.length&&i.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+i.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const n=this.varyings;if("vertex"===e||"compute"===e)for(const i of n){"compute"===e&&(i.needsInterpolation=!0);const n=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){t+=`${SN[i.interpolationType]||i.interpolationType} ${MN[i.interpolationSampling]||""} out ${n} ${i.name};\n`}else{t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}out ${n} ${i.name};\n`}else t+=`${n} ${i.name};\n`}else if("fragment"===e)for(const e of n)if(e.needsInterpolation){const n=this.getType(e.type);if(e.interpolationType){t+=`${SN[e.interpolationType]||e.interpolationType} ${MN[e.interpolationSampling]||""} in ${n} ${e.name};\n`}else{t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}in ${n} ${e.name};\n`}}for(const n of this.builtins[e])t+=`${n};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){qt("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){qt("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){qt("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){const i=this.extensions[n]||(this.extensions[n]=new Map);!1===i.has(e)&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if("vertex"===e){const t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const n=this.extensions[e];if(void 0!==n)for(const{name:e,behavior:i}of n.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=TN[e];if(void 0===t){let n;switch(t=!1,e){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance"}if(void 0!==n){const e=this.renderer.backend.extensions;e.has(n)&&(e.get(n),t=!0)}TN[e]=t}return t}isFlipY(){return!0}getUniformBufferLimit(){const e=this.renderer.backend.gl;return e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE)}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let n=0;n<e.length;n++){const i=e[n],r=this.getPropertyName(i.attributeNode);r&&(t+=`${i.varyingName} = ${r};\n\t`)}return t}_getGLSLUniformStruct(e,t){return`\nlayout( std140 ) uniform ${e} {\n${t}\n};`}_getGLSLVertexCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${EN}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// transforms\n\t${e.transforms}\n\n\t// flow\n\t${e.flow}\n\n\tgl_PointSize = 1.0;\n\n}\n`}_getGLSLFragmentCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${EN}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let n="// code\n\n";n+=this.flowCode[t];const i=this.flowNodes[t],r=i[i.length-1];for(const e of i){const i=this.getFlowData(e),s=e.name;s&&(n.length>0&&(n+="\n"),n+=`\t// flow -> ${s}\n\t`),n+=`${i.code}\n\t`,e===r&&"compute"!==t&&(n+="// result\n\t","vertex"===t?(n+="gl_Position = ",n+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${i.result};`)))}const s=e[t];s.extensions=this.getExtensions(t),s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.vars=this.getVars(t),s.structs=this.getStructs(t),s.codes=this.getCodes(t),s.transforms=this.getTransforms(t),s.flow=n}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);let a=s.uniformGPU;if(void 0===a){const i=e.groupNode,o=i.name,l=this.getBindGroupArray(o,n);if("texture"===t)a=new gN(r.name,r.node,i),l.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new _N(r.name,r.node,i),l.push(a);else if("texture3D"===t)a=new vN(r.name,r.node,i),l.push(a);else if("buffer"===t){r.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let n=t.buffer;void 0===n&&(e.name=`NodeBuffer_${e.id}`,n=new uN(e,i),n.name=e.name,t.buffer=n),l.push(n),a=n}else{let e=this.uniformGroups[o];void 0===e?(e=new dN(o,i),this.uniformGroups[o]=e,l.push(e)):-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(r,t);const n=a.name,s=e.uniforms.some(e=>e.name===n);s||e.addUniform(a)}s.uniformGPU=a}return r}}let AN=null,RN=null;class CN{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[kt]:null,[Bt]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),n=this.renderer.info.frame;let i;i=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+e.id+":f"+n}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?Bt:kt;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void Yt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return AN=AN||new cn,this.renderer.getDrawingBufferSize(AN)}setScissorTest(){}getClearColor(){const e=this.renderer;return RN=RN||new Hw,e.getClearColor(RN),RN.getRGB(RN),RN}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Ht(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${s} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let NN,PN,LN=0;class DN{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class IN{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:i}=n,r=e.array,s=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=n.get(a);let l,u=o.bufferGPU;if(void 0===u&&(u=this._createBuffer(i,t,r,s),o.bufferGPU=u,o.bufferType=t,o.version=a.version),r instanceof Float32Array)l=i.FLOAT;else if("undefined"!=typeof Float16Array&&r instanceof Float16Array)l=i.HALF_FLOAT;else if(r instanceof Uint16Array)l=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)l=i.SHORT;else if(r instanceof Uint32Array)l=i.UNSIGNED_INT;else if(r instanceof Int32Array)l=i.INT;else if(r instanceof Int8Array)l=i.BYTE;else if(r instanceof Uint8Array)l=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);l=i.UNSIGNED_BYTE}let c={bufferGPU:u,bufferType:t,type:l,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===i.INT||l===i.UNSIGNED_INT||e.gpuType===ve,id:LN++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,s);c=new DN(c,e)}n.set(e,c)}updateAttribute(e){const t=this.backend,{gl:n}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,s=t.get(r),a=s.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,s.bufferGPU),0===o.length)n.bufferSubData(a,0,i);else{for(let e=0,t=o.length;e<t;e++){const t=o[e];n.bufferSubData(a,t.start*i.BYTES_PER_ELEMENT,i,t.start,t.count)}r.clearUpdateRanges()}n.bindBuffer(a,null),s.version=r.version}destroyAttribute(e){const t=this.backend,{gl:n}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const i=t.get(e);n.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,{gl:n}=t,i=e.isInterleavedBufferAttribute?e.data:e,{bufferGPU:r}=t.get(i),s=e.array,a=s.byteLength;n.bindBuffer(n.COPY_READ_BUFFER,r);const o=n.createBuffer();n.bindBuffer(n.COPY_WRITE_BUFFER,o),n.bufferData(n.COPY_WRITE_BUFFER,a,n.STREAM_READ),n.copyBufferSubData(n.COPY_READ_BUFFER,n.COPY_WRITE_BUFFER,0,0,a),await t.utils._clientWaitAsync();const l=new e.array.constructor(s.length);return n.bindBuffer(n.COPY_WRITE_BUFFER,o),n.getBufferSubData(n.COPY_WRITE_BUFFER,0,l),n.deleteBuffer(o),n.bindBuffer(n.COPY_READ_BUFFER,null),n.bindBuffer(n.COPY_WRITE_BUFFER,null),l.buffer}_createBuffer(e,t,n,i){const r=e.createBuffer();return e.bindBuffer(t,r),e.bufferData(t,n,i),e.bindBuffer(t,null),r}}class UN{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;NN={[v]:e.FUNC_ADD,[y]:e.FUNC_SUBTRACT,[b]:e.FUNC_REVERSE_SUBTRACT},PN={[x]:e.ZERO,[T]:e.ONE,[S]:e.SRC_COLOR,[E]:e.SRC_ALPHA,[P]:e.SRC_ALPHA_SATURATE,[C]:e.DST_COLOR,[A]:e.DST_ALPHA,[M]:e.ONE_MINUS_SRC_COLOR,[w]:e.ONE_MINUS_SRC_ALPHA,[N]:e.ONE_MINUS_DST_COLOR,[R]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),n=e.getParameter(e.VIEWPORT);this.currentScissor=(new Pn).fromArray(t),this.currentViewport=(new Pn).fromArray(n),this._tempVec4=new Pn}enable(e){const{enabled:t}=this;!0!==t[e]&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;!1!==t[e]&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;0!==e?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(1===e?t.cullFace(t.BACK):2===e?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:n}=this;e!==t&&(n.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,n){const i=this.gl,r=this.backend.drawBuffersIndexedExt;if(r)for(let s=0;s<e.length;s++){const a=e[s];let o=null;if(null!==t){const e=t.getBlendMode(a.name);6===e.blending?o=n:0!==e.blending&&(o=e)}else o=n;null!==o?this._setMRTBlendingIndex(s,o):r.blendFuncSeparateiOES(s,i.ONE,i.ZERO,i.ONE,i.ZERO)}else Yt("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.")}_setMRTBlendingIndex(e,t){const{gl:n}=this,i=this.backend.drawBuffersIndexedExt,r=t.blending,s=t.blendSrc,a=t.blendDst,o=t.blendEquation,l=t.premultipliedAlpha;if(5===r){const n=null!==t.blendSrcAlpha?t.blendSrcAlpha:s,r=null!==t.blendDstAlpha?t.blendDstAlpha:a,l=null!==t.blendEquationAlpha?t.blendEquationAlpha:o;i.blendEquationSeparateiOES(e,NN[o],NN[l]),i.blendFuncSeparateiOES(e,PN[s],PN[a],PN[n],PN[r])}else if(i.blendEquationSeparateiOES(e,n.FUNC_ADD,n.FUNC_ADD),l)switch(r){case 1:default:i.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,n.ONE,n.ONE,n.ONE,n.ONE);break;case 3:i.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case 4:i.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE)}else switch(r){case 1:default:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE,n.ONE,n.ONE);break;case 3:i.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case 4:i.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE)}}setBlending(e,t,n,i,r,s,a,o){const{gl:l}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(l.BLEND),this.currentBlendingEnabled=!0),5===e)r=r||t,s=s||n,a=a||i,t===this.currentBlendEquation&&r===this.currentBlendEquationAlpha||(l.blendEquationSeparate(NN[t],NN[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),n===this.currentBlendSrc&&i===this.currentBlendDst&&s===this.currentBlendSrcAlpha&&a===this.currentBlendDstAlpha||(l.blendFuncSeparate(PN[n],PN[i],PN[s],PN[a]),this.currentBlendSrc=n,this.currentBlendDst=i,this.currentBlendSrcAlpha=s,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||o!==this.currentPremultipledAlpha){if(this.currentBlendEquation===v&&this.currentBlendEquationAlpha===v||(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=v,this.currentBlendEquationAlpha=v),o)switch(e){case 1:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFunc(l.ONE,l.ONE);break;case 3:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case 4:l.blendFuncSeparate(l.DST_COLOR,l.ONE_MINUS_SRC_ALPHA,l.ZERO,l.ONE);break;default:qt("WebGLState: Invalid blending: ",e)}else switch(e){case 1:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE,l.ONE,l.ONE);break;case 3:qt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:qt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:qt("WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=o}}else!0===this.currentBlendingEnabled&&(this.disable(l.BLEND),this.currentBlendingEnabled=!1)}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setReversedDepth(e){if(this.currentDepthReversed!==e){const t=this.backend.extensions.get("EXT_clip_control");e?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT),this.currentDepthReversed=e}}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthReversed&&(e=Kt[e]),this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:default:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL)}this.currentDepthFunc=e}}scissor(e,t,n,i){const r=this._tempVec4.set(e,t,n,i);if(!1===this.currentScissor.equals(r)){const{gl:e}=this;e.scissor(r.x,r.y,r.z,r.w),this.currentScissor.copy(r)}}viewport(e,t,n,i){const r=this._tempVec4.set(e,t,n,i);if(!1===this.currentViewport.equals(r)){const{gl:e}=this;e.viewport(r.x,r.y,r.z,r.w),this.currentViewport.copy(r)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,n){this.currentStencilFunc===e&&this.currentStencilRef===t&&this.currentStencilFuncMask===n||(this.gl.stencilFunc(e,t,n),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=n)}setStencilOp(e,t,n){this.currentStencilFail===e&&this.currentStencilZFail===t&&this.currentStencilZPass===n||(this.gl.stencilOp(e,t,n),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=n)}setMaterial(e,t,n){const{gl:i}=this;2===e.side?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let r=1===e.side;t&&(r=!r),this.setFlipSided(r),1===e.blending&&!1===e.transparent?this.setBlending(0):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const s=e.stencilWrite;if(this.setStencilTest(s),s&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),!0===e.alphaToCoverage&&this.backend.renderer.currentSamples>0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),n>0&&this.currentClippingPlanes!==n){const e=12288;for(let t=0;t<8;t++)t<n?this.enable(e+t):this.disable(e+t)}}setPolygonOffset(e,t,n){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===n||(i.polygonOffset(t,n),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=n)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){const n=this.gl;return(this.currentVAO!==e||this.currentIndex!==t)&&(n.bindVertexArray(e),null!==t&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0)}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:n,currentBoundFramebuffers:i}=this;return i[e]!==t&&(n.bindFramebuffer(e,t),i[e]=t,e===n.DRAW_FRAMEBUFFER&&(i[n.FRAMEBUFFER]=t),e===n.FRAMEBUFFER&&(i[n.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:n}=this;let i=[],r=!1;if(null!==e.textures){i=this.currentDrawbuffers.get(t),void 0===i&&(i=[],this.currentDrawbuffers.set(t,i));const s=e.textures;if(i.length!==s.length||i[0]!==n.COLOR_ATTACHMENT0){for(let e=0,t=s.length;e<t;e++)i[e]=n.COLOR_ATTACHMENT0+e;i.length=s.length,r=!0}}else i[0]!==n.BACK&&(i[0]=n.BACK,r=!0);r&&n.drawBuffers(i)}activeTexture(e){const{gl:t,currentTextureSlot:n,maxTextures:i}=this;void 0===e&&(e=t.TEXTURE0+i-1),n!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,n){const{gl:i,currentTextureSlot:r,currentBoundTextures:s,maxTextures:a}=this;void 0===n&&(n=null===r?i.TEXTURE0+a-1:r);let o=s[n];void 0===o&&(o={type:void 0,texture:void 0},s[n]=o),o.type===e&&o.texture===t||(r!==n&&(i.activeTexture(n),this.currentTextureSlot=n),i.bindTexture(e,t),o.type=e,o.texture=t)}bindBufferBase(e,t,n){const{gl:i}=this,r=`${e}-${t}`;return this.currentBoundBufferBases[r]!==n&&(i.bindBufferBase(e,t,n),this.currentBoundBufferBases[r]=n,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:n}=this,i=n[t];void 0!==i&&void 0!==i.type&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}}class FN{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=""){const{gl:n,extensions:i}=this;let r;const s=bn.getTransfer(t);if(e===fe)return n.UNSIGNED_BYTE;if(e===Te)return n.UNSIGNED_SHORT_4_4_4_4;if(e===Se)return n.UNSIGNED_SHORT_5_5_5_1;if(e===Ee)return n.UNSIGNED_INT_5_9_9_9_REV;if(e===we)return n.UNSIGNED_INT_10F_11F_11F_REV;if(e===me)return n.BYTE;if(e===ge)return n.SHORT;if(e===_e)return n.UNSIGNED_SHORT;if(e===ve)return n.INT;if(e===ye)return n.UNSIGNED_INT;if(e===be)return n.FLOAT;if(e===xe)return n.HALF_FLOAT;if(e===Ae)return n.ALPHA;if(e===Re)return n.RGB;if(e===Ce)return n.RGBA;if(e===Ne)return n.DEPTH_COMPONENT;if(e===Pe)return n.DEPTH_STENCIL;if(e===Le)return n.RED;if(e===De)return n.RED_INTEGER;if(e===Ie)return n.RG;if(e===Ue)return n.RG_INTEGER;if(e===Fe)return n.RGBA_INTEGER;if(e===Oe||e===Be||e===ke||e===ze)if(s===St){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===Oe)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===Be)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===ke)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===ze)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=i.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===Oe)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===Be)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===ke)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===ze)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===Ve||e===Ge||e===He||e===je){if(r=i.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(e===Ve)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===Ge)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===He)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===je)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===We||e===$e||e===Xe||e===qe||e===Ye||e===Ke||e===Ze){if(r=i.get("WEBGL_compressed_texture_etc"),null===r)return null;if(e===We||e===$e)return s===St?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===Xe)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(e===qe)return r.COMPRESSED_R11_EAC;if(e===Ye)return r.COMPRESSED_SIGNED_R11_EAC;if(e===Ke)return r.COMPRESSED_RG11_EAC;if(e===Ze)return r.COMPRESSED_SIGNED_RG11_EAC}if(e===Qe||e===Je||e===et||e===tt||e===nt||e===it||e===rt||e===st||e===at||e===ot||e===lt||e===ut||e===ct||e===ht){if(r=i.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===Qe)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Je)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===et)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===tt)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===nt)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===it)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===rt)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===st)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===at)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===ot)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===lt)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===ut)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===ct)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===ht)return s===St?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===dt){if(r=i.get("EXT_texture_compression_bptc"),null===r)return null;if(e===dt)return s===St?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(e===mt||e===gt||e===_t||e===vt){if(r=i.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===mt)return r.COMPRESSED_RED_RGTC1_EXT;if(e===gt)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===_t)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===vt)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===Me?n.UNSIGNED_INT_24_8:void 0!==n[e]?n[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((n,i)=>{!function r(){const s=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(s===e.WAIT_FAILED)return e.deleteSync(t),void i();s!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),n()):requestAnimationFrame(r)}()})}}let ON,BN,kN,zN=!1;class VN{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===zN&&(this._init(),zN=!0)}_init(){const e=this.gl;ON={[se]:e.REPEAT,[ae]:e.CLAMP_TO_EDGE,[oe]:e.MIRRORED_REPEAT},BN={[le]:e.NEAREST,[ue]:e.NEAREST_MIPMAP_NEAREST,[ce]:e.NEAREST_MIPMAP_LINEAR,[he]:e.LINEAR,[de]:e.LINEAR_MIPMAP_NEAREST,[pe]:e.LINEAR_MIPMAP_LINEAR},kN={[Et]:e.NEVER,[Lt]:e.ALWAYS,[wt]:e.LESS,[Rt]:e.LEQUAL,[At]:e.EQUAL,[Pt]:e.GEQUAL,[Ct]:e.GREATER,[Nt]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let n;return n=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,n}getInternalFormat(e,t,n,i,r=!1){const{gl:s,extensions:a}=this;if(null!==e){if(void 0!==s[e])return s[e];Xt("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;if(t===s.RED&&(n===s.FLOAT&&(o=s.R32F),n===s.HALF_FLOAT&&(o=s.R16F),n===s.UNSIGNED_BYTE&&(o=s.R8),n===s.UNSIGNED_SHORT&&(o=s.R16),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RED_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.R8UI),n===s.UNSIGNED_SHORT&&(o=s.R16UI),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RG&&(n===s.FLOAT&&(o=s.RG32F),n===s.HALF_FLOAT&&(o=s.RG16F),n===s.UNSIGNED_BYTE&&(o=s.RG8),n===s.UNSIGNED_SHORT&&(o=s.RG16),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RG_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RG8UI),n===s.UNSIGNED_SHORT&&(o=s.RG16UI),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RGB){const e=r?Tt:bn.getTransfer(i);n===s.FLOAT&&(o=s.RGB32F),n===s.HALF_FLOAT&&(o=s.RGB16F),n===s.UNSIGNED_BYTE&&(o=s.RGB8),n===s.UNSIGNED_SHORT&&(o=s.RGB16),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I),n===s.UNSIGNED_BYTE&&(o=e===St?s.SRGB8:s.RGB8),n===s.UNSIGNED_SHORT_5_6_5&&(o=s.RGB565),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGB4),n===s.UNSIGNED_INT_5_9_9_9_REV&&(o=s.RGB9_E5),n===s.UNSIGNED_INT_10F_11F_11F_REV&&(o=s.R11F_G11F_B10F)}if(t===s.RGB_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGB8UI),n===s.UNSIGNED_SHORT&&(o=s.RGB16UI),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I)),t===s.RGBA){const e=r?Tt:bn.getTransfer(i);n===s.FLOAT&&(o=s.RGBA32F),n===s.HALF_FLOAT&&(o=s.RGBA16F),n===s.UNSIGNED_BYTE&&(o=s.RGBA8),n===s.UNSIGNED_SHORT&&(o=s.RGBA16),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I),n===s.UNSIGNED_BYTE&&(o=e===St?s.SRGB8_ALPHA8:s.RGBA8),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGBA4),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1)}return t===s.RGBA_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGBA8UI),n===s.UNSIGNED_SHORT&&(o=s.RGBA16UI),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I)),t===s.DEPTH_COMPONENT&&(n===s.UNSIGNED_SHORT&&(o=s.DEPTH_COMPONENT16),n===s.UNSIGNED_INT&&(o=s.DEPTH_COMPONENT24),n===s.FLOAT&&(o=s.DEPTH_COMPONENT32F)),t===s.DEPTH_STENCIL&&n===s.UNSIGNED_INT_24_8&&(o=s.DEPTH24_STENCIL8),o!==s.R16F&&o!==s.R32F&&o!==s.RG16F&&o!==s.RG32F&&o!==s.RGBA16F&&o!==s.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:n,extensions:i,backend:r}=this,s=bn.getPrimaries(bn.workingColorSpace),a=t.colorSpace===yt?null:bn.getPrimaries(t.colorSpace),o=t.colorSpace===yt||s===a?n.NONE:n.BROWSER_DEFAULT_WEBGL;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,o),n.texParameteri(e,n.TEXTURE_WRAP_S,ON[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,ON[t.wrapT]),e!==n.TEXTURE_3D&&e!==n.TEXTURE_2D_ARRAY||t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,ON[t.wrapR]),n.texParameteri(e,n.TEXTURE_MAG_FILTER,BN[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,u=t.minFilter===he&&l?pe:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,BN[u]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,kN[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===le)return;if(t.minFilter!==ce&&t.minFilter!==pe)return;if(t.type===be&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const s=i.get("EXT_texture_filter_anisotropic");n.texParameterf(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:i}=this,r=this.getGLTextureType(e);let s=i[r];void 0===s&&(s=t.createTexture(),n.state.bindTexture(r,s),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=s),n.set(e,{textureGPU:s,glTextureType:r})}createTexture(e,t){const{gl:n,backend:i}=this,{levels:r,width:s,height:a,depth:o}=t,l=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),c=this.getInternalFormat(e.internalFormat,l,u,e.colorSpace,e.isVideoTexture),h=n.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,h),this.setTextureParameters(d,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,r,c,s,a,o):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,r,c,s,a,o):e.isVideoTexture||n.texStorage2D(d,r,c,s,a),i.set(e,{textureGPU:h,glTextureType:d,glFormat:l,glType:u,glInternalFormat:c})}copyBufferToTexture(e,t){const{gl:n,backend:i}=this,{textureGPU:r,glTextureType:s,glFormat:a,glType:o}=i.get(t),{width:l,height:u}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(s,r),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(s,0,0,0,l,u,a,o,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:i,height:r}=t,{textureGPU:s,glTextureType:a,glFormat:o,glType:l,glInternalFormat:u}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==s)if(this.backend.state.bindTexture(a,s),this.setTextureParameters(a,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t<i.length;t++){const s=i[t];e.isCompressedArrayTexture?e.format!==n.RGBA?null!==o?n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,s.width,s.height,r.depth,o,s.data):Xt("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):n.texSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,s.width,s.height,r.depth,o,l,s.data):null!==o?n.compressedTexSubImage2D(n.TEXTURE_2D,t,0,0,s.width,s.height,o,s.data):Xt("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const s=t.images,a=e.mipmaps;for(let e=0;e<6;e++){const t=GN(s[e]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,i,r,o,l,t);for(let t=0;t<a.length;t++){const i=GN(a[t].images[e]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,i.width,i.height,o,l,i)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const i=t.image;if(e.layerUpdates.size>0){const t=qa(i.width,i.height,e.format,e.type);for(const r of e.layerUpdates){const e=i.data.subarray(r*t/i.data.BYTES_PER_ELEMENT,(r+1)*t/i.data.BYTES_PER_ELEMENT);n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,r,i.width,i.height,1,o,l,e)}e.clearLayerUpdates()}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,i.width,i.height,i.depth,o,l,i.data)}else if(e.isData3DTexture){const e=t.image;n.texSubImage3D(n.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,l,e.data)}else if(e.isVideoTexture)e.update(),n.texImage2D(a,0,u,o,l,t.image);else{const s=e.mipmaps;if(s.length>0)for(let e=0,t=s.length;e<t;e++){const t=s[e],i=GN(t);n.texSubImage2D(a,e,0,0,t.width,t.height,o,l,i)}else{const e=GN(t.image);n.texSubImage2D(a,0,0,0,i,r,o,l,e)}}}generateMipmaps(e){const{gl:t,backend:n}=this,{textureGPU:i,glTextureType:r}=n.get(e);n.state.bindTexture(r,i),t.generateMipmap(r)}deallocateRenderBuffers(e){const{gl:t,backend:n}=this;if(e){const i=n.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(const e in i.framebuffers)t.deleteFramebuffer(i.framebuffers[e]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let e=0;e<i.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(i.msaaRenderbuffers[e]);delete i.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:n,backend:i}=this,{textureGPU:r,renderTarget:s}=i.get(e);this.deallocateRenderBuffers(s),!1===t&&n.deleteTexture(r),i.delete(e)}copyTextureToTexture(e,t,n=null,i=null,r=0,s=0){const{gl:a,backend:o}=this,{state:l}=this.backend,{textureGPU:u,glTextureType:c,glType:h,glFormat:d}=o.get(t);let p,f,m,g,_,v,y,b,x;l.bindTexture(c,u);const T=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)p=n.max.x-n.min.x,f=n.max.y-n.min.y,m=n.isBox3?n.max.z-n.min.z:1,g=n.min.x,_=n.min.y,v=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-r);p=Math.floor(T.width*t),f=Math.floor(T.height*t),m=e.isDataArrayTexture||e.isArrayTexture?T.depth:e.isData3DTexture?Math.floor(T.depth*t):1,g=0,_=0,v=0}null!==i?(y=i.x,b=i.y,x=i.z):(y=0,b=0,x=0),a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),a.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const S=a.getParameter(a.UNPACK_ROW_LENGTH),M=a.getParameter(a.UNPACK_IMAGE_HEIGHT),E=a.getParameter(a.UNPACK_SKIP_PIXELS),w=a.getParameter(a.UNPACK_SKIP_ROWS),A=a.getParameter(a.UNPACK_SKIP_IMAGES);a.pixelStorei(a.UNPACK_ROW_LENGTH,T.width),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,T.height),a.pixelStorei(a.UNPACK_SKIP_PIXELS,g),a.pixelStorei(a.UNPACK_SKIP_ROWS,_),a.pixelStorei(a.UNPACK_SKIP_IMAGES,v);const R=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,C=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const n=o.get(e),i=o.get(t),c=o.get(n.renderTarget),h=o.get(i.renderTarget),d=c.framebuffers[n.cacheKey],T=h.framebuffers[i.cacheKey];l.bindFramebuffer(a.READ_FRAMEBUFFER,d),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,T);for(let e=0;e<m;e++)R&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,n.textureGPU,r,v+e),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,u,s,x+e)),a.blitFramebuffer(g,_,p,f,y,b,p,f,a.DEPTH_BUFFER_BIT,a.NEAREST);l.bindFramebuffer(a.READ_FRAMEBUFFER,null),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else if(0!==r||e.isRenderTargetTexture||o.has(e)){const t=o.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=a.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=a.createFramebuffer()),l.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let e=0;e<m;e++)R?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,t.textureGPU,r,v+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t.textureGPU,r),C?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,u,s,x+e):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,u,s),0!==r?a.blitFramebuffer(g,_,p,f,y,b,p,f,a.COLOR_BUFFER_BIT,a.NEAREST):C?a.copyTexSubImage3D(c,s,y,b,x+e,g,_,p,f):a.copyTexSubImage2D(c,s,y,b,g,_,p,f);l.bindFramebuffer(a.READ_FRAMEBUFFER,null),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else C?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(c,s,y,b,x,p,f,m,d,h,T.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(c,s,y,b,x,p,f,m,d,T.data):a.texSubImage3D(c,s,y,b,x,p,f,m,d,h,T):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,s,y,b,p,f,d,h,T.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,s,y,b,T.width,T.height,d,T.data):a.texSubImage2D(a.TEXTURE_2D,s,y,b,p,f,d,h,T);a.pixelStorei(a.UNPACK_ROW_LENGTH,S),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,M),a.pixelStorei(a.UNPACK_SKIP_PIXELS,E),a.pixelStorei(a.UNPACK_SKIP_ROWS,w),a.pixelStorei(a.UNPACK_SKIP_IMAGES,A),0===s&&t.generateMipmaps&&a.generateMipmap(c),l.unbindTexture()}copyFramebufferToTexture(e,t,n){const{gl:i}=this,{state:r}=this.backend,{textureGPU:s}=this.backend.get(e),{x:a,y:o,z:l,w:u}=n,c=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,h=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(c){const n=0!==a||0!==o;let c,d;if(!0===e.isDepthTexture?(c=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(c|=i.STENCIL_BUFFER_BIT)):(c=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),n){const e=this.backend.get(t.renderTarget),n=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,n),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=h-o-u;i.blitFramebuffer(a,p,a+l,p+u,a,p,a+l,p+u,c,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,n),r.bindTexture(i.TEXTURE_2D,s),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,p,l,u),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,s,0),i.blitFramebuffer(0,0,l,u,0,0,l,u,c,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,s),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,h-u-o,l,u),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,i=!1){const{gl:r}=this,s=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:l,width:u,height:c}=s;if(r.bindRenderbuffer(r.RENDERBUFFER,e),o&&!l){let t=r.DEPTH_COMPONENT24;if(!0===i){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,s.samples,t,u,c)}else n>0?(a&&a.isDepthTexture&&a.type===r.FLOAT&&(t=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,n,t,u,c)):r.renderbufferStorage(r.RENDERBUFFER,t,u,c);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else o&&l&&(n>0?r.renderbufferStorageMultisample(r.RENDERBUFFER,n,r.DEPTH24_STENCIL8,u,c):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,u,c),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,e));r.bindRenderbuffer(r.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,i,r,s){const{backend:a,gl:o}=this,{textureGPU:l,glFormat:u,glType:c}=this.backend.get(e),h=o.createFramebuffer();a.state.bindFramebuffer(o.READ_FRAMEBUFFER,h);const d=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+s:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,d,l,0);const p=this._getTypedArrayType(c),f=i*r*this._getBytesPerTexel(c,u),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,f,o.STREAM_READ),o.readPixels(t,n,i,r,u,c,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const g=new p(f/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,g),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteFramebuffer(h),g}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:n}=this;let i=0;return e===n.UNSIGNED_BYTE&&(i=1),e!==n.UNSIGNED_SHORT_4_4_4_4&&e!==n.UNSIGNED_SHORT_5_5_5_1&&e!==n.UNSIGNED_SHORT_5_6_5&&e!==n.UNSIGNED_SHORT&&e!==n.HALF_FLOAT||(i=2),e!==n.UNSIGNED_INT&&e!==n.FLOAT||(i=4),t===n.RGBA?4*i:t===n.RGB?3*i:t===n.ALPHA?i:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function GN(e){return e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas?e:e.data}class HN{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return void 0===t&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class jN{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const WN={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class $N{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:n,mode:i,object:r,type:s,info:a,index:o}=this;0!==o?n.drawElements(i,t,s,e):n.drawArrays(i,e,t),a.update(r,t,1)}renderInstances(e,t,n){const{gl:i,mode:r,type:s,index:a,object:o,info:l}=this;0!==n&&(0!==a?i.drawElementsInstanced(r,t,s,e,n):i.drawArraysInstanced(r,e,t,n),l.update(o,t,n))}renderMultiDraw(e,t,n){const{extensions:i,mode:r,object:s,info:a}=this;if(0===n)return;const o=i.get("WEBGL_multi_draw");if(null===o)for(let i=0;i<n;i++)this.render(e[i],t[i]);else{0!==this.index?o.multiDrawElementsWEBGL(r,t,0,this.type,e,0,n):o.multiDrawArraysWEBGL(r,e,0,t,0,n);let i=0;for(let e=0;e<n;e++)i+=t[e];a.update(s,i,1)}}renderMultiDrawInstances(e,t,n,i){const{extensions:r,mode:s,object:a,info:o}=this;if(0===n)return;const l=r.get("WEBGL_multi_draw");if(null===l)for(let r=0;r<n;r++)this.renderInstances(e[r],t[r],i[r]);else{0!==this.index?l.multiDrawElementsInstancedWEBGL(s,t,0,this.type,e,0,i,0,n):l.multiDrawArraysInstancedWEBGL(s,e,0,t,0,i,0,n);let r=0;for(let e=0;e<n;e++)r+=t[e]*i[e];o.update(a,r,1)}}}class XN{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return void 0===t&&(Xt(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestamp(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class qN extends XN{constructor(e,t,n=2048){if(super(n),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext)return Xt("EXT_disjoint_timer_query not supported; timestamps will be disabled."),void(this.trackTimestamp=!1);this.queries=[];for(let t=0;t<this.maxQueries;t++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return Yt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const n=this.queries[t];if(n)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){qt("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){qt("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[t,n]of this.queryOffsets){if("ended"===this.queryStates.get(n)){const i=this.queries[n];e.set(t,this.resolveQuery(i))}}if(0===e.size)return this.lastValue;const t={},n=[];for(const[i,r]of e){const e=i.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===n.includes(s)&&n.push(s),void 0===t[s]&&(t[s]=0);const a=await r;this.timestamps.set(i,a),t[s]+=a}const i=t[n[n.length-1]];return this.lastValue=i,this.frames=n,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,i}catch(e){return qt("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed)return void t(this.lastValue);let n,i=!1;const r=e=>{i||(i=!0,n&&(clearTimeout(n),n=null),t(e))},s=()=>{if(this.isDisposed)r(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void r(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(n=setTimeout(s,1));const i=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(i)/1e6)}catch(e){qt("Error checking query:",e),t(this.lastValue)}};s()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class YN extends CN{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,n={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=void 0!==t.context?t.context:e.domElement.getContext("webgl2",n);function r(t){t.preventDefault();const n={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(n)}this._onContextLost=r,e.domElement.addEventListener("webglcontextlost",r,!1),this.gl=i,this.extensions=new HN(this),this.capabilities=new jN(this),this.attributeUtils=new IN(this),this.textureUtils=new VN(this),this.bufferRenderer=new $N(this),this.state=new UN(this),this.utils=new FN(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.extensions.get("EXT_clip_control"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed"),!0===t.reversedDepthBuffer&&this.extensions.has("EXT_clip_control")&&this.state.setReversedDepth(!0)}get coordinateSystem(){return Ft}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),null!==n){const t=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&Xt("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new qN(this.gl,e,2048));const n=this.timestampQueryPool[e];null!==n.allocateQueriesForContext(t)&&n.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,n=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:n}=this.getDrawingBufferSize();t.viewport(0,0,e,n)}if(e.scissor)this.updateScissor(e);else{const{width:e,height:n}=this.getDrawingBufferSize();t.scissor(0,0,e,n)}this.initTimestampQuery(kt,this.getTimestampUID(e)),n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0&&(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(i),n.occlusionQueryObjects=new Array(i),n.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:n}=this,i=this.get(e),r=i.previousContext;n.resetVertexState();const s=e.occlusionQueryCount;s>0&&(s>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e<a.length;e++){const t=a[e];t.generateMipmaps&&this.generateMipmaps(t)}if(this._currentContext=r,this._resolveRenderTarget(e),null!==r){if(this._setFramebuffer(r),r.viewport)this.updateViewport(r);else{const{width:e,height:t}=this.getDrawingBufferSize();n.viewport(0,0,e,t)}if(r.scissor)this.updateScissor(r);else{const{width:e,height:t}=this.getDrawingBufferSize();n.scissor(0,0,e,t)}}this.prepareTimestampBuffer(kt,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:i}=t;if(n&&i){const e=new WeakSet,{gl:r}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const s=()=>{let a=0;for(let t=0;t<n.length;t++){const s=n[t];null!==s&&(r.getQueryParameter(s,r.QUERY_RESULT_AVAILABLE)&&(0===r.getQueryParameter(s,r.QUERY_RESULT)&&e.add(i[t]),n[t]=null,r.deleteQuery(s),a++))}a<n.length?requestAnimationFrame(s):t.occluded=e};s()}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:n,y:i,width:r,height:s}=e.viewportValue;t.viewport(n,e.height-s-i,r,s)}updateScissor(e){const{state:t}=this,{x:n,y:i,width:r,height:s}=e.scissorValue;t.scissor(n,e.height-s-i,r,s)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,n,i=null,r=!0,s=!0){const{gl:a,renderer:o}=this;if(null===i){i={textures:null,clearColorValue:this.getClearColor()}}let l=0;if(e&&(l|=a.COLOR_BUFFER_BIT),t&&(l|=a.DEPTH_BUFFER_BIT),n&&(l|=a.STENCIL_BUFFER_BIT),0!==l){let u;u=i.clearColorValue?i.clearColorValue:this.getClearColor();const c=o.getClearDepth(),h=o.getClearStencil();if(t&&this.state.setDepthMask(!0),null===i.textures)a.clearColor(u.r,u.g,u.b,u.a),a.clear(l);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++)0===e?a.clearBufferfv(a.COLOR,e,[u.r,u.g,u.b,u.a]):a.clearBufferfv(a.COLOR,e,[0,0,0,1]);t&&n?a.clearBufferfi(a.DEPTH_STENCIL,0,c,h):t?a.clearBufferfv(a.DEPTH,0,[c]):n&&a.clearBufferiv(a.STENCIL,0,[h]),r&&s&&this._resolveRenderTarget(i)}}}beginCompute(e){const{state:t,gl:n}=this;t.bindFramebuffer(n.FRAMEBUFFER,null),this.initTimestampQuery(Bt,this.getTimestampUID(e))}compute(e,t,n,i,r=null){const{state:s,gl:a}=this;!1===this.discard&&(s.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformBuffers:l,attributes:u}=this.get(i),c=this._getVaoKey(u),h=this.vaoCache[c];void 0===h?this.vaoCache[c]=this._createVao(u):s.setVertexState(h),s.useProgram(o),this._bindUniforms(n);const d=this._getTransformFeedback(l);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,d),a.beginTransformFeedback(a.POINTS),r=null!==r?r:t.count,Array.isArray(r)?(Yt("WebGLBackend.compute(): The count parameter must be a single number, not an array."),r=r[0]):r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute&&(Yt("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),r=t.count),u[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,r):a.drawArrays(a.POINTS,0,r),a.endTransformFeedback(),a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,null);for(let e=0;e<l.length;e++){const t=l[e];t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const{state:t,gl:n}=this;this.discard=!1,t.disable(n.RASTERIZER_DISCARD),this.prepareTimestampBuffer(Bt,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}draw(e){const{object:t,pipeline:n,material:i,context:r,hardwareClippingPlanes:s}=e,{programGPU:a}=this.get(n),{gl:o,state:l}=this,u=this.get(r),c=e.getDrawParameters();if(null===c)return;this._bindUniforms(e.getBindings());const h=t.isMesh&&t.matrixWorld.determinant()<0;l.setMaterial(i,h,s),null!==r.mrt&&null!==r.textures&&l.setMRTBlending(r.textures,r.mrt,i),l.useProgram(a);const d=e.getAttributes(),p=this.get(d);let f=p.vaoGPU;if(void 0===f){const e=this._getVaoKey(d);f=this.vaoCache[e],void 0===f&&(f=this._createVao(d),this.vaoCache[e]=f,p.vaoGPU=f)}const m=e.getIndex(),g=null!==m?this.get(m).bufferGPU:null;l.setVertexState(f,g);const _=u.lastOcclusionObject;if(_!==t&&void 0!==_){if(null!==_&&!0===_.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),u.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),u.occlusionQueries[u.occlusionQueryIndex]=e,u.occlusionQueryObjects[u.occlusionQueryIndex]=t}u.lastOcclusionObject=t}const v=this.bufferRenderer;t.isPoints?v.mode=o.POINTS:t.isLineSegments?v.mode=o.LINES:t.isLine?v.mode=o.LINE_STRIP:t.isLineLoop?v.mode=o.LINE_LOOP:!0===i.wireframe?(l.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),v.mode=o.LINES):v.mode=o.TRIANGLES;const{vertexCount:y,instanceCount:b}=c;let{firstVertex:x}=c;if(v.object=t,null!==m){x*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);v.index=m.count,v.type=e.type}else v.index=0;const T=()=>{t.isBatchedMesh?null!==t._multiDrawInstances?(Yt("WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),v.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?v.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):Yt("WebGLBackend: WEBGL_multi_draw not supported."):b>1?v.renderInstances(x,y,b):v.render(x,y)};if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const n=this.get(e.camera),i=e.camera.cameras,r=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===n.indexesGPU||n.indexesGPU.length!==i.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let n=0,r=i.length;n<r;n++){const i=o.createBuffer();e[0]=n,o.bindBuffer(o.UNIFORM_BUFFER,i),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(i)}n.indexesGPU=t}const s=this.get(r),a=this.renderer.getPixelRatio(),u=this._currentContext.renderTarget,c=this._isRenderCameraDepthArray(this._currentContext),h=this._currentContext.activeCubeFace;if(c){const e=this.get(u.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:t}=u;for(let e=0,n=i.length;e<n;e++)this.renderer._activeCubeFace=e,this._currentContext.activeCubeFace=e,this._setFramebuffer(this._currentContext),this.clear(!1,!0,t,this._currentContext,!1,!1);this.renderer._activeCubeFace=h,this._currentContext.activeCubeFace=h}}for(let r=0,u=i.length;r<u;r++){const u=i[r];if(t.layers.test(u.layers)){c&&(this.renderer._activeCubeFace=r,this._currentContext.activeCubeFace=r,this._setFramebuffer(this._currentContext));const t=u.viewport;if(void 0!==t){const n=t.x*a,i=t.y*a,r=t.width*a,s=t.height*a;l.viewport(Math.floor(n),Math.floor(e.context.height-s-i),Math.floor(r),Math.floor(s))}l.bindBufferBase(o.UNIFORM_BUFFER,s.index,n.indexesGPU[r]),T()}this._currentContext.activeCubeFace=h,this.renderer._activeCubeFace=h}}else T()}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,i,r,s){return this.textureUtils.copyTextureToBuffer(e,t,n,i,r,s)}updateSampler(){return""}createNodeBuilder(e,t){return new wN(e,t)}createProgram(e){const t=this.gl,{stage:n,code:i}=e,r="fragment"===n?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const n=this.gl,i=e.pipeline,{fragmentProgram:r,vertexProgram:s}=i,a=n.createProgram(),o=this.get(r).shaderGPU,l=this.get(s).shaderGPU;if(n.attachShader(a,o),n.attachShader(a,l),n.linkProgram(a),this.set(i,{programGPU:a,fragmentShader:o,vertexShader:l}),null!==t&&this.parallel){const r=new Promise(t=>{const r=this.parallel,s=()=>{n.getProgramParameter(a,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(s)};s()});return void t.push(r)}this._completeCompile(e,i)}_handleSource(e,t){const n=e.split("\n"),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let e=r;e<s;e++){const r=e+1;i.push(`${r===t?">":" "} ${r}: ${n[e]}`)}return i.join("\n")}_getShaderErrors(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(i&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const i=parseInt(s[1]);return n.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=(i.getProgramInfoLog(e)||"").trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,n,t);else{const s=this._getShaderErrors(i,n,"vertex"),a=this._getShaderErrors(i,t,"fragment");qt("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+s+"\n"+a)}else""!==r&&Xt("WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:n,gl:i}=this,r=this.get(t),{programGPU:s,fragmentShader:a,vertexShader:o}=r;!1===i.getProgramParameter(s,i.LINK_STATUS)&&this._logProgramError(s,a,o),n.useProgram(s);const l=e.getBindings();this._setupBindings(l,s),this.set(t,{programGPU:s})}createComputePipeline(e,t){const{state:n,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:s}=e,a=i.createProgram(),o=this.get(r).shaderGPU,l=this.get(s).shaderGPU,u=s.transforms,c=[],h=[];for(let e=0;e<u.length;e++){const t=u[e];c.push(t.varyingName),h.push(t.attributeNode)}i.attachShader(a,o),i.attachShader(a,l),i.transformFeedbackVaryings(a,c,i.SEPARATE_ATTRIBS),i.linkProgram(a),!1===i.getProgramParameter(a,i.LINK_STATUS)&&this._logProgramError(a,o,l),n.useProgram(a),this._setupBindings(t,a);const d=s.attributes,p=[],f=[];for(let e=0;e<d.length;e++){const t=d[e].node.attribute;p.push(t),this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER)}for(let e=0;e<h.length;e++){const t=h[e].attribute;this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER);const n=this.get(t);f.push(n)}this.set(e,{programGPU:a,transformBuffers:f,attributes:p})}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,n=0;for(const i of t){this.set(i,{textures:n,uniformBuffers:e});for(const t of i.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&n++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this,n=this.get(e);let i=n.uniformBuffers,r=n.textures;for(const n of e.bindings){const e=this.get(n);if(n.isUniformsGroup||n.isUniformBuffer){const r=n.buffer;let{bufferGPU:s}=this.get(r);void 0===s?(s=t.createBuffer(),t.bindBuffer(t.UNIFORM_BUFFER,s),t.bufferData(t.UNIFORM_BUFFER,r.byteLength,t.DYNAMIC_DRAW),this.set(r,{bufferGPU:s})):t.bindBuffer(t.UNIFORM_BUFFER,s);const a=n.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,s),0===a.length)t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW);else{const e=Vt(r),n=e?1:r.BYTES_PER_ELEMENT;for(let i=0,s=a.length;i<s;i++){const s=a[i],o=s.start*n,l=s.count*n,u=o*(e?r.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,u,r,o,l)}}e.index=i++,e.bufferGPU=s,this.set(n,e)}else if(n.isSampledTexture){const{textureGPU:t,glTextureType:i}=this.get(n.texture);e.index=r++,e.textureGPU=t,e.glTextureType=i,this.set(n,e)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const n=this.get(e).bufferGPU,i=e.buffer,r=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,n),0===r.length)t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW);else{const e=Vt(i),n=e?1:i.BYTES_PER_ELEMENT;for(let s=0,a=r.length;s<a;s++){const a=r[s],o=a.start*n,l=a.count*n,u=o*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,u,i,o,l)}}}}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(WN).filter(t=>WN[t]===e),n=this.extensions;for(let e=0;e<t.length;e++)if(n.has(t[e]))return!0;return!1}getMaxAnisotropy(){return this.capabilities.getMaxAnisotropy()}copyTextureToTexture(e,t,n=null,i=null,r=0,s=0){this.textureUtils.copyTextureToTexture(e,t,n,i,r,s)}copyFramebufferToTexture(e,t,n){this.textureUtils.copyFramebufferToTexture(e,t,n)}hasCompatibility(e){return e===zt||super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:n}=this;this._setFramebuffer(e),n.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:n}=this;let i=null;if(null!==e.textures){const r=e.renderTarget,s=this.get(r),{samples:a,depthBuffer:o,stencilBuffer:l}=r,u=!0===r.isCubeRenderTarget,c=!0===r.isRenderTarget3D,h=r.depth>1,d=!0===r.isXRRenderTarget,p=!0===d&&!0===r._hasExternalTextures;let f=s.msaaFrameBuffer,m=s.depthRenderbuffer;const g=this.extensions.get("WEBGL_multisampled_render_to_texture"),_=this.extensions.get("OVR_multiview2"),v=this._useMultisampledExtension(r),y=kw(e);let b;if(u?(s.cubeFramebuffers||(s.cubeFramebuffers={}),b=s.cubeFramebuffers[y]):d&&!1===p?b=this._xrFramebuffer:(s.framebuffers||(s.framebuffers={}),b=s.framebuffers[y]),void 0===b){b=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,b);const i=e.textures,o=[];if(u){s.cubeFramebuffers[y]=b;const{textureGPU:e}=this.get(i[0]),n=this.renderer._activeCubeFace,r=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,e,r)}else{s.framebuffers[y]=b;for(let n=0;n<i.length;n++){const s=i[n],o=this.get(s);o.renderTarget=e.renderTarget,o.cacheKey=y;const l=t.COLOR_ATTACHMENT0+n;if(r.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,l,o.textureGPU,0,a,0,2);else if(c||h){const e=this.renderer._activeCubeFace,n=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,l,o.textureGPU,n,e)}else if(v)g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,l,t.TEXTURE_2D,o.textureGPU,0,a);else{const e=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,l,t.TEXTURE_2D,o.textureGPU,e)}}}const d=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const n=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(n,e,0,v),s.xrDepthRenderbuffer=n,o.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,n),t.framebufferRenderbuffer(t.FRAMEBUFFER,d,t.RENDERBUFFER,n)}else if(null!==e.depthTexture){o.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const n=this.get(e.depthTexture);if(n.renderTarget=e.renderTarget,n.cacheKey=y,r.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,d,n.textureGPU,0,a,0,2);else if(p&&v)g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,d,t.TEXTURE_2D,n.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,d,n.textureGPU,0,e)}else if(e.depthTexture.isCubeTexture){const e=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_CUBE_MAP_POSITIVE_X+e,n.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_2D,n.textureGPU,0)}s.depthInvalidationArray=o}else{if(this._isRenderCameraDepthArray(e)){n.bindFramebuffer(t.FRAMEBUFFER,b);const i=this.renderer._activeCubeFace,r=this.get(e.depthTexture),s=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,s,r.textureGPU,0,i)}if((d||v||r.multiview)&&!0!==r._isOpaqueFramebuffer){n.bindFramebuffer(t.FRAMEBUFFER,b);const i=this.get(e.textures[0]);r.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,i.textureGPU,0,a,0,2):v?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0);const o=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const e=s.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,o,t.RENDERBUFFER,e)}else{const n=this.get(e.depthTexture);r.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,n.textureGPU,0,a,0,2):v?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,n.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,n.textureGPU,0)}}}if(a>0&&!1===v&&!r.multiview){if(void 0===f){const i=[];f=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,f);const r=[],u=e.textures;for(let n=0;n<u.length;n++){r[n]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,r[n]),i.push(t.COLOR_ATTACHMENT0+n);const s=e.textures[n],o=this.get(s);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,o.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+n,t.RENDERBUFFER,r[n])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),s.msaaFrameBuffer=f,s.msaaRenderbuffers=r,o&&void 0===m){m=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(m,e,a),s.depthRenderbuffer=m;const n=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;i.push(n)}s.invalidationArray=i}i=s.msaaFrameBuffer}else i=b;n.drawBuffers(e,b)}n.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let n=0;n<e.length;n++){t+=":"+this.get(e[n]).id}return t}_createVao(e){const{gl:t}=this,n=t.createVertexArray();t.bindVertexArray(n);for(let n=0;n<e.length;n++){const i=e[n],r=this.get(i);let s,a;t.bindBuffer(t.ARRAY_BUFFER,r.bufferGPU),t.enableVertexAttribArray(n),!0===i.isInterleavedBufferAttribute?(s=i.data.stride*r.bytesPerElement,a=i.offset*r.bytesPerElement):(s=0,a=0),r.isInteger?t.vertexAttribIPointer(n,i.itemSize,r.type,s,a):t.vertexAttribPointer(n,i.itemSize,r.type,i.normalized,s,a),i.isInstancedBufferAttribute&&!i.isInterleavedBufferAttribute?t.vertexAttribDivisor(n,i.meshPerAttribute):i.isInterleavedBufferAttribute&&i.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(n,i.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),n}_getTransformFeedback(e){let t="";for(let n=0;n<e.length;n++)t+=":"+e[n].id;let n=this.transformFeedbackCache[t];if(void 0!==n)return n;const{gl:i}=this;n=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,n);for(let t=0;t<e.length;t++){const n=e[t];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,t,n.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=n,n}_setupBindings(e,t){const n=this.gl;for(const i of e)for(const e of i.bindings){const i=this.get(e).index;if(e.isUniformsGroup||e.isUniformBuffer){const r=n.getUniformBlockIndex(t,e.name);n.uniformBlockBinding(t,r,i)}else if(e.isSampledTexture){const r=n.getUniformLocation(t,e.name);n.uniform1i(r,i)}}}_bindUniforms(e){const{gl:t,state:n}=this;for(const i of e)for(const e of i.bindings){const i=this.get(e),r=i.index;e.isUniformsGroup||e.isUniformBuffer?n.bindBufferBase(t.UNIFORM_BUFFER,r,i.bufferGPU):e.isSampledTexture&&n.bindTexture(i.glTextureType,i.textureGPU,t.TEXTURE0+r)}}_resolveRenderTarget(e){const{gl:t,state:n}=this,i=e.renderTarget;if(null!==e.textures&&i){const r=this.get(i);if(i.samples>0&&!1===this._useMultisampledExtension(i)){const s=r.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=r.msaaFrameBuffer,l=r.msaaRenderbuffers,u=e.textures,c=u.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,o),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,s),c)for(let e=0;e<u.length;e++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);for(let n=0;n<u.length;n++){if(c){const{textureGPU:e}=this.get(u[n]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,l[n]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:n,y:i,width:r,height:s}=e.scissorValue,o=e.height-s-i;t.blitFramebuffer(n,o,n+r,o+s,n,o,n+r,o+s,a,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,a,t.NEAREST)}if(c)for(let e=0;e<u.length;e++){const{textureGPU:n}=this.get(u[e]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,l[e]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,n,0)}!0===this._supportsInvalidateFramebuffer&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,r.invalidationArray)}else if(!1===i.resolveDepthBuffer&&r.framebuffers){const i=r.framebuffers[e.getCacheKey()];n.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,r.depthInvalidationArray)}}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const KN="point-list",ZN="line-list",QN="line-strip",JN="triangle-list",eP="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},tP="never",nP="less",iP="equal",rP="less-equal",sP="greater",aP="not-equal",oP="greater-equal",lP="always",uP="store",cP="load",hP="clear",dP="ccw",pP="cw",fP="none",mP="back",gP="uint16",_P="uint32",vP="r8unorm",yP="r8snorm",bP="r8uint",xP="r8sint",TP="r16uint",SP="r16sint",MP="r16float",EP="rg8unorm",wP="rg8snorm",AP="rg8uint",RP="rg8sint",CP="r32uint",NP="r32sint",PP="r32float",LP="rg16uint",DP="rg16sint",IP="rg16float",UP="rgba8unorm",FP="rgba8unorm-srgb",OP="rgba8snorm",BP="rgba8uint",kP="rgba8sint",zP="bgra8unorm",VP="bgra8unorm-srgb",GP="rgb9e5ufloat",HP="rgb10a2unorm",jP="rg11b10ufloat",WP="rg32uint",$P="rg32sint",XP="rg32float",qP="rgba16uint",YP="rgba16sint",KP="rgba16float",ZP="rgba32uint",QP="rgba32sint",JP="rgba32float",eL="depth16unorm",tL="depth24plus",nL="depth24plus-stencil8",iL="depth32float",rL="depth32float-stencil8",sL="bc1-rgba-unorm",aL="bc1-rgba-unorm-srgb",oL="bc2-rgba-unorm",lL="bc2-rgba-unorm-srgb",uL="bc3-rgba-unorm",cL="bc3-rgba-unorm-srgb",hL="bc4-r-unorm",dL="bc4-r-snorm",pL="bc5-rg-unorm",fL="bc5-rg-snorm",mL="bc6h-rgb-ufloat",gL="bc6h-rgb-float",_L="bc7-rgba-unorm",vL="bc7-rgba-unorm-srgb",yL="etc2-rgb8unorm",bL="etc2-rgb8unorm-srgb",xL="etc2-rgb8a1unorm",TL="etc2-rgb8a1unorm-srgb",SL="etc2-rgba8unorm",ML="etc2-rgba8unorm-srgb",EL="eac-r11unorm",wL="eac-r11snorm",AL="eac-rg11unorm",RL="eac-rg11snorm",CL="astc-4x4-unorm",NL="astc-4x4-unorm-srgb",PL="astc-5x4-unorm",LL="astc-5x4-unorm-srgb",DL="astc-5x5-unorm",IL="astc-5x5-unorm-srgb",UL="astc-6x5-unorm",FL="astc-6x5-unorm-srgb",OL="astc-6x6-unorm",BL="astc-6x6-unorm-srgb",kL="astc-8x5-unorm",zL="astc-8x5-unorm-srgb",VL="astc-8x6-unorm",GL="astc-8x6-unorm-srgb",HL="astc-8x8-unorm",jL="astc-8x8-unorm-srgb",WL="astc-10x5-unorm",$L="astc-10x5-unorm-srgb",XL="astc-10x6-unorm",qL="astc-10x6-unorm-srgb",YL="astc-10x8-unorm",KL="astc-10x8-unorm-srgb",ZL="astc-10x10-unorm",QL="astc-10x10-unorm-srgb",JL="astc-12x10-unorm",eD="astc-12x10-unorm-srgb",tD="astc-12x12-unorm",nD="astc-12x12-unorm-srgb",iD="clamp-to-edge",rD="repeat",sD="mirror-repeat",aD="linear",oD="nearest",lD="zero",uD="one",cD="src",hD="one-minus-src",dD="src-alpha",pD="one-minus-src-alpha",fD="dst",mD="one-minus-dst",gD="dst-alpha",_D="one-minus-dst-alpha",vD="src-alpha-saturated",yD="constant",bD="one-minus-constant",xD="add",TD="subtract",SD="reverse-subtract",MD="min",ED="max",wD=0,AD=15,RD="keep",CD="zero",ND="replace",PD="invert",LD="increment-clamp",DD="decrement-clamp",ID="increment-wrap",UD="decrement-wrap",FD="storage",OD="read-only-storage",BD="write-only",kD="read-only",zD="read-write",VD="non-filtering",GD="comparison",HD="float",jD="unfilterable-float",WD="depth",$D="sint",XD="uint",qD="2d",YD="3d",KD="2d",ZD="2d-array",QD="cube",JD="3d",eI="all",tI="vertex",nI="instance",iI={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},rI={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class sI extends pN{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class aI extends aN{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let oI=0;class lI extends aI{constructor(e,t){super("StorageBuffer_"+oI++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:$f,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class uI extends dw{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:aD}),this.flipYSampler=e.createSampler({minFilter:oD}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar<uniform> flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d<f32>;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array<f32>;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube<f32>;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n"})}getTransferPipeline(e,t){const n=`${e}-${t=t||"2d-array"}`;let i=this.transferPipelines[n];return void 0===i&&(i=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[n]=i),i}flipY(e,t,n=0){const i=t.format,{width:r,height:s}=t.size,a=this.device.createTexture({size:{width:r,height:s},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),o=this.getTransferPipeline(i,e.textureBindingViewDimension),l=this.getTransferPipeline(i,a.textureBindingViewDimension),u=this.device.createCommandEncoder({}),c=(e,t,n,i,r,s)=>{const a=e.getBindGroupLayout(0),o=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t.createView({dimension:t.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:s?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),l=u.beginRenderPass({colorAttachments:[{view:i.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:r,arrayLayerCount:1}),loadOp:hP,storeOp:uP}]});l.setPipeline(e),l.setBindGroup(0,o),l.draw(3,1,0,n),l.end()};c(o,e,n,a,0,!1),c(l,a,0,e,n,!0),this.device.queue.submit([u.finish()]),a.destroy()}generateMipmaps(e,t=null){const n=this.get(e),i=n.layers||this._mipmapCreateBundles(e),r=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(r,i),null===t&&this.device.queue.submit([r.finish()]),n.layers=i}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",n=this.getTransferPipeline(e.format,t),i=n.getBindGroupLayout(0),r=[];for(let s=1;s<e.mipLevelCount;s++)for(let a=0;a<e.depthOrArrayLayers;a++){const o=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:e.createView({dimension:t,baseMipLevel:s-1,mipLevelCount:1})},{binding:2,resource:{buffer:this.noFlipUniformBuffer}}]}),l={colorAttachments:[{view:e.createView({dimension:"2d",baseMipLevel:s,mipLevelCount:1,baseArrayLayer:a,arrayLayerCount:1}),loadOp:hP,storeOp:uP}]},u=this.device.createRenderBundleEncoder({colorFormats:[e.format]});u.setPipeline(n),u.setBindGroup(0,o),u.draw(3,1,0,a),r.push({renderBundles:[u.finish()],passDescriptor:l})}return r}_mipmapRunBundles(e,t){const n=t.length;for(let i=0;i<n;i++){const n=t[i],r=e.beginRenderPass(n.passDescriptor);r.executeBundles(n.renderBundles),r.end()}}}const cI={[Et]:"never",[wt]:"less",[At]:"equal",[Rt]:"less-equal",[Ct]:"greater",[Pt]:"greater-equal",[Lt]:"always",[Nt]:"not-equal"},hI=[0,1,3,2,4,5];class dI{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){const t=this.backend,n=e.minFilter+"-"+e.magFilter+"-"+e.wrapS+"-"+e.wrapT+"-"+(e.wrapR||"0")+"-"+e.anisotropy+"-"+(e.compareFunction||0);let i=this._samplerCache.get(n);if(void 0===i){const r={addressModeU:this._convertAddressMode(e.wrapS),addressModeV:this._convertAddressMode(e.wrapT),addressModeW:this._convertAddressMode(e.wrapR),magFilter:this._convertFilterMode(e.magFilter),minFilter:this._convertFilterMode(e.minFilter),mipmapFilter:this._convertFilterMode(e.minFilter),maxAnisotropy:1};e.isDepthTexture&&null===e.compareFunction&&(r.magFilter=oD,r.minFilter=oD,r.mipmapFilter=oD),r.magFilter===aD&&r.minFilter===aD&&r.mipmapFilter===aD&&(r.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&t.hasCompatibility(zt)&&(r.compare=cI[e.compareFunction]);i={sampler:t.device.createSampler(r),usedTimes:0},this._samplerCache.set(n,i)}const r=t.get(e);if(r.sampler!==i.sampler){if(void 0!==r.sampler){const e=this._samplerCache.get(r.samplerKey);e.usedTimes--,0===e.usedTimes&&this._samplerCache.delete(r.samplerKey)}r.samplerKey=n,r.sampler=i.sampler,i.usedTimes++}return n}createDefaultTexture(e){let t;const n=pI(e);t=e.isCubeTexture?this._getDefaultCubeTextureGPU(n):this._getDefaultTextureGPU(n),this.backend.get(e).texture=t}createTexture(e,t={}){const n=this.backend,i=n.get(e);if(i.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");if(e.isExternalTexture)return i.texture=e.sourceTexture,void(i.initialized=!0);void 0===t.needsMipmaps&&(t.needsMipmaps=!1),void 0===t.levels&&(t.levels=1),void 0===t.depth&&(t.depth=1);const{width:r,height:s,depth:a,levels:o}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const l=this._getDimension(e),u=e.internalFormat||t.format||pI(e,n.device);i.format=u;const{samples:c,primarySamples:h,isMSAA:d}=n.utils.getTextureSampleData(e);let p=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(p|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&!0!==e.isCompressedArrayTexture&&u!==GP&&(p|=GPUTextureUsage.RENDER_ATTACHMENT);const f={label:e.name,size:{width:r,height:s,depthOrArrayLayers:a},mipLevelCount:o,sampleCount:h,dimension:l,format:u,usage:p};if(void 0===u)return Xt("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(f.textureBindingViewDimension=QD);try{i.texture=n.device.createTexture(f)}catch(t){return Xt("WebGPURenderer: Failed to create texture with descriptor:",f),void this.createDefaultTexture(e)}if(d){const e=Object.assign({},f);e.label=e.label+"-msaa",e.sampleCount=c,e.mipLevelCount=1,i.msaaTexture=n.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=f}destroyTexture(e,t=!1){const n=this.backend,i=n.get(e);void 0!==i.texture&&!1===t&&i.texture.destroy(),void 0!==i.msaaTexture&&i.msaaTexture.destroy(),n.delete(e)}generateMipmaps(e,t=null){const n=this.backend.get(e);this._generateMipmaps(n.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:n,height:i}=e.getDrawingBufferSize(),r=e.renderer.currentSamples,s=t.colorTexture,a=e.get(s);if(s.width===n&&s.height===i&&s.samples===r)return a.texture;let o=a.texture;return o&&o.destroy(),o=e.device.createTexture({label:"colorBuffer",size:{width:n,height:i,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.currentSamples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),s.source.width=n,s.source.height=i,s.samples=r,a.texture=o,o}getDepthBuffer(e=!0,t=!1){const n=this.backend,i=n.renderer.getCanvasTarget(),{width:r,height:s}=n.getDrawingBufferSize(),a=n.renderer.currentSamples,o=i.depthTexture;if(o.width===r&&o.height===s&&o.samples===a&&o.depth===e&&o.stencil===t)return n.get(o).texture;const l=n.get(o).texture;let u,c;if(t?(u=Pe,c=Me):e&&(u=Ne,c=ye),void 0!==l){if(o.image.width===r&&o.image.height===s&&o.format===u&&o.type===c&&o.samples===a)return l;this.destroyTexture(o)}return o.name="depthBuffer",o.format=u,o.type=c,o.image.width=r,o.image.height=s,o.samples=a,this.createTexture(o,{width:r,height:s}),n.get(o).texture}updateTexture(e,t){const n=this.backend.get(e),i=e.mipmaps,{textureDescriptorGPU:r}=n;if(!e.isRenderTargetTexture&&void 0!==r){if(e.isDataTexture)if(i.length>0)for(let t=0,s=i.length;t<s;t++){const s=i[t];this._copyBufferToTexture(s,n.texture,r,0,e.flipY,0,t)}else this._copyBufferToTexture(t.image,n.texture,r,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let i=0;i<t.image.depth;i++)this._copyBufferToTexture(t.image,n.texture,r,i,e.flipY,i);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,n.texture,r);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,n.texture,r);else if(i.length>0)for(let t=0,s=i.length;t<s;t++){const s=i[t];this._copyImageToTexture(s,n.texture,r,0,e.flipY,e.premultiplyAlpha,t)}else this._copyImageToTexture(t.image,n.texture,r,0,e.flipY,e.premultiplyAlpha);n.version=e.version}}async copyTextureToBuffer(e,t,n,i,r,s){const a=this.backend.device,o=this.backend.get(e),l=o.texture,u=o.textureDescriptorGPU.format,c=this._getBytesPerTexel(u);let h=i*c;h=256*Math.ceil(h/256);const d=a.createBuffer({size:(r-1)*h+i*c,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=a.createCommandEncoder();p.copyTextureToBuffer({texture:l,origin:{x:t,y:n,z:s}},{buffer:d,bytesPerRow:h},{width:i,height:r});const f=this._getTypedArrayType(u);a.queue.submit([p.finish()]),await d.mapAsync(GPUMapMode.READ);return new f(d.getMappedRange())}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const n=new Nn;n.minFilter=le,n.magFilter=le,this.createTexture(n,{width:1,height:1,format:e}),this.defaultTexture[e]=t=n}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const n=new _s;n.minFilter=le,n.magFilter=le,this.createTexture(n,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=n}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,n){const i=e.images,r=e.mipmaps;for(let s=0;s<6;s++){const a=i[s],o=!0===e.flipY?hI[s]:s;a.isDataTexture?this._copyBufferToTexture(a.image,t,n,o,e.flipY):this._copyImageToTexture(a,t,n,o,e.flipY,e.premultiplyAlpha);for(let i=0;i<r.length;i++){const a=r[i].images[s];a.isDataTexture?this._copyBufferToTexture(a.image,t,n,o,e.flipY,0,i+1):this._copyImageToTexture(a,t,n,o,e.flipY,e.premultiplyAlpha,i+1)}}}_copyImageToTexture(e,t,n,i,r,s,a=0){const o=this.backend.device,l=a>0?e.width:n.size.width,u=a>0?e.height:n.size.height;try{o.queue.copyExternalImageToTexture({source:e,flipY:r},{texture:t,mipLevel:a,origin:{x:0,y:0,z:i},premultipliedAlpha:s},{width:l,height:u,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new uI(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,i,r,s=0,a=0){const o=this.backend.device,l=e.data,u=this._getBytesPerTexel(n.format),c=e.width*u;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:i}},l,{offset:e.width*e.height*u*s,bytesPerRow:c},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===r&&this._flipY(t,n,i)}_copyCompressedBufferToTexture(e,t,n){const i=this.backend.device,r=this._getBlockData(n.format),s=n.size.depthOrArrayLayers>1;for(let a=0;a<e.length;a++){const o=e[a],l=o.width,u=o.height,c=s?n.size.depthOrArrayLayers:1,h=Math.ceil(l/r.width)*r.byteLength,d=h*Math.ceil(u/r.height);for(let e=0;e<c;e++)i.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:e}},o.data,{offset:e*d,bytesPerRow:h,rowsPerImage:Math.ceil(u/r.height)},{width:Math.ceil(l/r.width)*r.width,height:Math.ceil(u/r.height)*r.height,depthOrArrayLayers:1})}}_getBlockData(e){return e===sL||e===aL?{byteLength:8,width:4,height:4}:e===oL||e===lL||e===uL||e===cL?{byteLength:16,width:4,height:4}:e===hL||e===dL?{byteLength:8,width:4,height:4}:e===pL||e===fL||e===mL||e===gL||e===_L||e===vL?{byteLength:16,width:4,height:4}:e===yL||e===bL||e===xL||e===TL?{byteLength:8,width:4,height:4}:e===SL||e===ML?{byteLength:16,width:4,height:4}:e===EL||e===wL?{byteLength:8,width:4,height:4}:e===AL||e===RL||e===CL||e===NL?{byteLength:16,width:4,height:4}:e===PL||e===LL?{byteLength:16,width:5,height:4}:e===DL||e===IL?{byteLength:16,width:5,height:5}:e===UL||e===FL?{byteLength:16,width:6,height:5}:e===OL||e===BL?{byteLength:16,width:6,height:6}:e===kL||e===zL?{byteLength:16,width:8,height:5}:e===VL||e===GL?{byteLength:16,width:8,height:6}:e===HL||e===jL?{byteLength:16,width:8,height:8}:e===WL||e===$L?{byteLength:16,width:10,height:5}:e===XL||e===qL?{byteLength:16,width:10,height:6}:e===YL||e===KL?{byteLength:16,width:10,height:8}:e===ZL||e===QL?{byteLength:16,width:10,height:10}:e===JL||e===eD?{byteLength:16,width:12,height:10}:e===tD||e===nD?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=iD;return e===se?t=rD:e===oe&&(t=sD),t}_convertFilterMode(e){let t=aD;return e!==le&&e!==ue&&e!==ce||(t=oD),t}_getBytesPerTexel(e){return e===vP||e===yP||e===bP||e===xP?1:e===TP||e===SP||e===MP||e===EP||e===wP||e===AP||e===RP?2:e===CP||e===NP||e===PP||e===LP||e===DP||e===IP||e===UP||e===FP||e===OP||e===BP||e===kP||e===zP||e===VP||e===GP||e===HP||e===jP||e===iL||e===tL||e===nL||e===rL?4:e===WP||e===$P||e===XP||e===qP||e===YP||e===KP?8:e===ZP||e===QP||e===JP?16:void 0}_getTypedArrayType(e){return e===bP?Uint8Array:e===xP?Int8Array:e===vP?Uint8Array:e===yP?Int8Array:e===AP?Uint8Array:e===RP?Int8Array:e===EP?Uint8Array:e===wP?Int8Array:e===BP?Uint8Array:e===kP?Int8Array:e===UP||e===FP?Uint8Array:e===OP?Int8Array:e===TP?Uint16Array:e===SP?Int16Array:e===LP?Uint16Array:e===DP?Int16Array:e===qP?Uint16Array:e===YP?Int16Array:e===MP||e===IP||e===KP?Uint16Array:e===CP?Uint32Array:e===NP?Int32Array:e===PP?Float32Array:e===WP?Uint32Array:e===$P?Int32Array:e===XP?Float32Array:e===ZP?Uint32Array:e===QP?Int32Array:e===JP?Float32Array:e===zP||e===VP?Uint8Array:e===HP||e===GP||e===jP?Uint32Array:e===iL?Float32Array:e===tL||e===nL?Uint32Array:e===rL?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?YD:qD,t}}function pI(e,t=null){const n=e.format,i=e.type,r=e.colorSpace,s=bn.getTransfer(r);let a;if(!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(n){case Oe:case Be:a=s===St?aL:sL;break;case ke:a=s===St?lL:oL;break;case ze:a=s===St?cL:uL;break;case mt:a=hL;break;case gt:a=dL;break;case _t:a=pL;break;case vt:a=fL;break;case dt:a=s===St?vL:_L;break;case $e:case We:a=s===St?bL:yL;break;case Xe:a=s===St?ML:SL;break;case qe:a=EL;break;case Ye:a=wL;break;case Ke:a=AL;break;case Ze:a=RL;break;case Qe:a=s===St?NL:CL;break;case Je:a=s===St?LL:PL;break;case et:a=s===St?IL:DL;break;case tt:a=s===St?FL:UL;break;case nt:a=s===St?BL:OL;break;case it:a=s===St?zL:kL;break;case rt:a=s===St?GL:VL;break;case st:a=s===St?jL:HL;break;case at:a=s===St?$L:WL;break;case ot:a=s===St?qL:XL;break;case lt:a=s===St?KL:YL;break;case ut:a=s===St?QL:ZL;break;case ct:a=s===St?eD:JL;break;case ht:a=s===St?nD:tD;break;case Ce:a=s===St?FP:UP;break;default:qt("WebGPURenderer: Unsupported texture format.",n)}else switch(n){case Ce:switch(i){case me:a=OP;break;case ge:a=YP;break;case _e:a=qP;break;case ye:a=ZP;break;case ve:a=QP;break;case fe:a=s===St?FP:UP;break;case xe:a=KP;break;case be:a=JP;break;default:qt("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case Re:switch(i){case Ee:a=GP;break;case we:a=jP;break;default:qt("WebGPURenderer: Unsupported texture type with RGBFormat.",i)}break;case Le:switch(i){case me:a=yP;break;case ge:a=SP;break;case _e:a=TP;break;case ye:a=CP;break;case ve:a=NP;break;case fe:a=vP;break;case xe:a=MP;break;case be:a=PP;break;default:qt("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case Ie:switch(i){case me:a=wP;break;case ge:a=DP;break;case _e:a=LP;break;case ye:a=WP;break;case ve:a=$P;break;case fe:a=EP;break;case xe:a=IP;break;case be:a=XP;break;default:qt("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case Ne:switch(i){case _e:a=eL;break;case ye:a=tL;break;case be:a=iL;break;default:qt("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case Pe:switch(i){case Me:a=nL;break;case be:t&&!1===t.features.has(iI.Depth32FloatStencil8)&&qt('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),a=rL;break;default:qt("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case De:switch(i){case ve:a=NP;break;case ye:a=CP;break;default:qt("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case Ue:switch(i){case ve:a=$P;break;case ye:a=WP;break;default:qt("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case Fe:switch(i){case ve:a=QP;break;case ye:a=ZP;break;default:qt("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:qt("WebGPURenderer: Unsupported texture format.",n)}return a}const fI=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,mI=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,gI={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class _I extends bC{constructor(e){const{type:t,inputs:n,name:i,inputsCode:r,blockCode:s,outputType:a}=(e=>{const t=(e=e.trim()).match(fI);if(null!==t&&4===t.length){const n=t[2],i=[];let r=null;for(;null!==(r=mI.exec(n));)i.push({name:r[1],type:r[2]});const s=[];for(let e=0;e<i.length;e++){const{name:t,type:n}=i[e];let r=n;r.startsWith("ptr")?r="pointer":(r.startsWith("texture")&&(r=n.split("<")[0]),r=gI[r]),s.push(new aC(r,t))}const a=e.substring(t[0].length),o=t[3]||"void",l=void 0!==t[1]?t[1]:"";return{type:gI[o]||o,inputs:s,name:l,inputsCode:n,blockCode:a,outputType:o}}throw new Error("FunctionNode: Function is not a WGSL code.")})(e);super(t,n,i),this.inputsCode=r,this.blockCode=s,this.outputType=a}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class vI extends yC{parseFunction(e){return new _I(e)}}const yI={[jf]:"read",[Wf]:"write",[$f]:"read_write"},bI={[se]:"repeat",[ae]:"clamp",[oe]:"mirror"},xI={vertex:eP.VERTEX,fragment:eP.FRAGMENT,compute:eP.COMPUTE},TI={instance:!0,swizzleAssign:!1,storageBuffer:!0},SI={"^^":"tsl_xor"},MI={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},EI={},wI={tsl_xor:new AA("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new AA("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new AA("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new AA("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new AA("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new AA("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new AA("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new AA("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new AA("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new AA("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new AA("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new AA("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new AA("\nfn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n"),biquadraticTextureArray:new AA("\nfn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},AI={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let RI="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(RI+="diagnostic( off, derivative_uniformity );\n");class CI extends rC{constructor(e,t){super(e,t,new vI),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map}_generateTextureSample(e,t,n,i,r,s=this.shaderStage){return"fragment"===s?i?r?`textureSample( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:r?`textureSample( ${t}, ${t}_sampler, ${n}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureSampleLevel(e,t,n,"0",i)}generateTextureSampleLevel(e,t,n,i,r,s){return!1===this.isUnfilterable(e)?r?s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,s,i,r):this.generateTextureLod(e,t,n,r,s,i)}generateWrapFunction(e){const t=`tsl_coord_${bI[e.wrapS]}S_${bI[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let n=EI[t];if(void 0===n){const i=[],r=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let s=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const a=(e,t)=>{e===se?(i.push(wI.repeatWrapping_float),s+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===ae?(i.push(wI.clampWrapping_float),s+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===oe?(i.push(wI.mirrorWrapping_float),s+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(s+=`\t\tcoord.${t}`,Xt(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),s+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(s+=",\n",a(e.wrapR,"z")),s+="\n\t);\n\n}\n",EI[t]=n=new AA(s,i)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){const i=this.getDataFromNode(e,this.shaderStage,this.globalCache);void 0===i.dimensionsSnippet&&(i.dimensionsSnippet={});let r=i.dimensionsSnippet[n];if(void 0===i.dimensionsSnippet[n]){let s,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),l=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3<u32>":"vec2<u32>",s=l||e.isStorageTexture?t:`${t}${n?`, u32( ${n} )`:""}`,r=new Wv(new Sy(`textureDimensions( ${s} )`,a)),i.dimensionsSnippet[n]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new Wv(new Sy(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new Wv(new Sy("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,n,i,r="0u",s){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,r);return i&&(n=`${n} + vec2<f32>(${i}) / ${o}`),s?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${n} ), ${o}, u32( ${s} ), u32( ${r} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${n} ), ${o}, u32( ${r} ) )`)}generateTextureLod(e,t,n,i,r,s="0u"){if(!0===e.isCubeTexture){r&&(n=`${n} + vec3<f32>(${r})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${e.isDepthTexture?"u32":"f32"}( ${s} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,s),l=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";r&&(n=`${n} + ${l}<f32>(${r}) / ${l}<f32>( ${o} )`);return n=`${l}<u32>( clamp( floor( ${a}( ${n} ) * ${l}<f32>( ${o} ) ), ${`${l}<f32>( 0 )`}, ${`${l}<f32>( ${o} - ${"vec3"===l?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,n,s,i,null)}generateStorageTextureLoad(e,t,n,i,r,s){let a;return s&&(n=`${n} + ${s}`),a=r?`textureLoad( ${t}, ${n}, ${r} )`:`textureLoad( ${t}, ${n} )`,a}generateTextureLoad(e,t,n,i,r,s){let a;return null===i&&(i="0u"),s&&(n=`${n} + ${s}`),r?a=`textureLoad( ${t}, ${n}, ${r}, u32( ${i} ) )`:(a=`textureLoad( ${t}, ${n}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,n,i,r){let s;return s=i?`textureStore( ${t}, ${n}, ${i}, ${r} )`:`textureStore( ${t}, ${n}, ${r} )`,s}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction&&this.renderer.hasCompatibility(zt)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===be||!1===this.isSampleCompare(e)&&e.minFilter===le&&e.magFilter===le||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,n,i,r,s=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,n,i,r,"0",s):this._generateTextureSample(e,t,n,i,r,s),a}generateTextureGrad(e,t,n,i,r,s,a=this.shaderStage){if("fragment"===a)return r?s?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r}, ${i[0]}, ${i[1]}, ${s} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r}, ${i[0]}, ${i[1]} )`:s?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]}, ${s} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]} )`;qt(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,n,i,r,s,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?s?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i} )`;qt(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,n,i,r,s){return!1===this.isUnfilterable(e)?r?s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,s,i,r):this.generateTextureLod(e,t,n,r,s,i)}generateTextureBias(e,t,n,i,r,s,a=this.shaderStage){if("fragment"===a)return r?s?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i} )`;qt(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,n=e.type;return"texture"===n||"cubeTexture"===n||"cubeDepthTexture"===n||"storageTexture"===n||"texture3D"===n?t:"buffer"===n||"storageBuffer"===n||"indirectStorageBuffer"===n?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=SI[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(Xt("WebGPURenderer: Atomic operations are only supported in compute shaders."),$f):jf:e.access}getStorageAccess(e,t){return yI[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);if(void 0===s.uniformGPU){let a;const o=e.groupNode,l=o.name,u=this.getBindGroupArray(l,n);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let i=null;const s=this.getNodeAccess(e,n);"texture"===t||"storageTexture"===t?i=!0===e.value.is3DTexture?new vN(r.name,r.node,o,s):new gN(r.name,r.node,o,s):"cubeTexture"===t||"cubeDepthTexture"===t?i=new _N(r.name,r.node,o,s):"texture3D"===t&&(i=new vN(r.name,r.node,o,s)),i.store=!0===e.isStorageTextureNode,i.mipLevel=i.store?e.mipLevel:0,i.setVisibility(xI[n]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===i.store){const e=new sI(`${r.name}_sampler`,r.node,o);e.setVisibility(xI[n]),u.push(e,i),a=[e,i]}else u.push(i),a=[i]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const s=this.getSharedDataFromNode(e);let l=s.buffer;if(void 0===l){l=new("buffer"===t?uN:lI)(e,o),s.buffer=l}l.setVisibility(l.getVisibility()|xI[n]),u.push(l),a=l,r.name=i||"NodeBuffer_"+r.id}else{let e=this.uniformGroups[l];void 0===e&&(e=new dN(l,o),e.setVisibility(eP.VERTEX|eP.FRAGMENT|eP.COMPUTE),this.uniformGroups[l]=e),-1===u.indexOf(e)&&u.push(e),a=this.getNodeUniform(r,t);const n=a.name,i=e.uniforms.some(e=>e.name===n);i||e.addUniform(a)}s.uniformGPU=a}return r}getBuiltin(e,t,n,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:n}),t}hasBuiltin(e,t=this.shaderStage){return void 0!==this.builtins[t]&&this.builtins[t].has(e)}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${n.vars}\n${n.code}\n`;return n.result&&(r+=`\treturn ${n.result};\n`),r+="\n}\n",r}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],n=this.directives[e];if(void 0!==n)for(const e of n)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${e} >`,"vertex")}getBuiltins(e){const t=[],n=this.builtins[e];if(void 0!==n)for(const{name:e,property:i,type:r}of n.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,n,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:n,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const s=this.getType(i);t.push(`var<${n}> ${e}: array< ${s}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const n=this.getAttributesArray();for(let e=0,i=n.length;e<i;e++){const i=n[e],r=i.name,s=this.getType(i.type);t.push(`@location( ${e} ) ${r} : ${s}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const n of e.members){const i=e.output?"@location( "+n.index+" ) ":"";let r=this.getType(n.type);n.atomic&&(r="atomic< "+r+" >"),t.push(`\t${i+n.name} : ${r}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const n=this.structs[e];if(n.length>0){const e=[];for(const t of n){let n=`struct ${t.name} {\n`;n+=this.getStructMembers(t),n+="\n};",e.push(n)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,n=null){let i=`var ${t} : `;return i+=null!==n?this.generateArrayDeclaration(e,n):this.getType(e),i}getVars(e){const t=[],n=this.vars[e];if(void 0!==n)for(const e of n)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const n=this.varyings,i=this.vars[e];for(let r=0;r<n.length;r++){const s=n[r];if(s.needsInterpolation){let e=`@location( ${r} )`;if(s.interpolationType){const t=null!==s.interpolationSampling?`, ${s.interpolationSampling} )`:" )";e+=` @interpolate( ${s.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(s.type)&&(e+=" @interpolate(flat, either)");t.push(`${e} ${s.name} : ${this.getType(s.type)}`)}else"vertex"===e&&!1===i.includes(s)&&i.push(s)}}const n=this.getBuiltins(e);n&&t.push(n);const i=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+i):i}isCustomStruct(e){const t=e.value,n=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&null!==n.structTypeNode,r=n.value&&n.value.array&&"number"==typeof n.value.itemSize&&n.value.array.length>n.value.itemSize;return i&&!r}getUniforms(e){const t=this.uniforms[e],n=[],i=[],r=[],s={};for(const r of t){const t=r.groupNode.name,a=this.bindingsIndexes[t];if("texture"===r.type||"cubeTexture"===r.type||"cubeDepthTexture"===r.type||"storageTexture"===r.type||"texture3D"===r.type){const t=r.node.value;let i;(!0===t.isCubeTexture||!1===this.isUnfilterable(t)&&!0!==r.node.isStorageTextureNode)&&(this.isSampleCompare(t)?n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${r.name}_sampler : sampler_comparison;`):n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${r.name}_sampler : sampler;`));let s="";const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(t);if(o>1&&(s="_multisampled"),!0===t.isCubeTexture&&!0===t.isDepthTexture)i="texture_depth_cube";else if(!0===t.isCubeTexture)i="texture_cube<f32>";else if(!0===t.isDepthTexture)i=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${s}_2d<f32>`:`texture_depth${s}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===r.node.isStorageTextureNode){const n=pI(t),s=this.getStorageAccess(r.node,e),a=r.node.value.is3DTexture,o=r.node.value.isArrayTexture;i=`texture_storage_${a?"3d":"2d"+(o?"_array":"")}<${n}, ${s}>`}else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array<f32>";else if(!0===t.is3DTexture||!0===t.isData3DTexture)i="texture_3d<f32>";else{i=`texture${s}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type||"indirectStorageBuffer"===r.type){const t=r.node,n=this.getType(t.getNodeType(this)),s=t.bufferCount,o=s>0&&"buffer"===r.type?", "+s:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(r))i.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${l}> ${r.name} : ${n};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${n}>`:`${n}`}${o} >`;i.push(this._getWGSLStructBinding(r.name,e,l,a.binding++,a.group))}}else{const e=r.groupNode.name;if(void 0===s[e]){const t=this.uniformGroups[e];if(void 0!==t){const n=[];for(const e of t.uniforms){const t=e.getType(),i=this.getType(this.getVectorType(t));n.push(`\t${e.name} : ${i}`)}let i=this.uniformGroupsBindings[e];void 0===i&&(i={index:a.binding++,id:a.group},this.uniformGroupsBindings[e]=i),s[e]={index:i.index,id:i.id,snippets:n}}}}}for(const e in s){const t=s[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...n,...i,...r].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const n=e[t];n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.structs=this.getStructs(t),n.vars=this.getVars(t),n.codes=this.getCodes(t),n.directives=this.getDirectives(t),n.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],s=r[r.length-1],a=s.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),l=e.name;if(l&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${l}\n`),i+=`${r.code}\n\t`,e===s&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.builtinClipSpace = ${r.result};`;else if("fragment"===t)if(o)n.returnType=a.getNodeType(this),n.structs+="var<private> output : "+n.returnType+";",i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4<f32>";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),n.returnType="OutputStruct",n.structs+=this._getWGSLStruct("OutputStruct",e),n.structs+="\nvar<private> output : OutputStruct;",i+=`output.color = ${r.result};\n\n\treturn output;`}}n.flow=i}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let n;return null!==t&&(n=this._getWGSLMethod(e+"_"+t)),void 0===n&&(n=this._getWGSLMethod(e)),n||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,n){return`select( ${n}, ${t}, ${e} )`}getType(e){return MI[e]||e}isAvailable(e){let t=TI[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),TI[e]=t),t}getUniformBufferLimit(){return this.renderer.backend.device.limits.maxUniformBufferBindingSize}_getWGSLMethod(e){return void 0!==wI[e]&&this._include(e),AI[e]}_include(e){const t=wI[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar<private> varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${RI}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[n,i,r]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar<private> instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${n}, ${i}, ${r} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${n} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${n} * numWorkgroups.x ) * ( ${i} * numWorkgroups.y );\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,n,i=0,r=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${n}> ${e} : ${s};`}}class NI{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?nL:tL),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,n=e.getRenderTarget();t=n?n.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const n=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:n?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return null!==e.textures?e.textures.map(e=>this.getTextureFormatGPU(e)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?KN:e.isLineSegments||e.isMesh&&!0===t.wireframe?ZN:e.isLine?QN:e.isMesh?JN:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===fe)return zP;if(e===xe)return KP;throw new Error("Unsupported output buffer type.")}}const PI=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&PI.set(Float16Array,["float16"]);const LI=new Map([[sr,["float16"]]]),DI=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class II{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),i=this.backend,r=i.get(n);let s=r.buffer;if(void 0===s){const a=i.device;let o=n.array;if(!1===e.normalized)if(o.constructor===Int16Array||o.constructor===Int8Array)o=new Int32Array(o);else if((o.constructor===Uint16Array||o.constructor===Uint8Array)&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e<o.length;e++)65535===o[e]&&(o[e]=4294967295);if(n.array=o,(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&3===n.itemSize){o=new o.constructor(4*n.count);for(let e=0;e<n.count;e++)o.set(n.array.subarray(3*e,3*e+3),4*e);n.itemSize=4,n.array=o,r._force3to4BytesAlignment=!0}const l=o.byteLength,u=l+(4-l%4)%4;s=a.createBuffer({label:n.name,size:u,usage:t,mappedAtCreation:!0}),new o.constructor(s.getMappedRange()).set(o),s.unmap(),r.buffer=s}}updateAttribute(e){const t=this._getBufferAttribute(e),n=this.backend,i=n.device,r=n.get(t),s=n.get(t).buffer;let a=t.array;if(!0===r._force3to4BytesAlignment){a=new a.constructor(4*t.count);for(let e=0;e<t.count;e++)a.set(t.array.subarray(3*e,3*e+3),4*e);t.array=a}const o=t.updateRanges;if(0===o.length)i.queue.writeBuffer(s,0,a,0);else{const e=Vt(a),n=e?1:a.BYTES_PER_ELEMENT;for(let t=0,l=o.length;t<l;t++){const l=o[t];let u,c;if(!0===r._force3to4BytesAlignment){u=4*Math.floor(l.start/3)*n,c=4*Math.ceil(l.count/3)*n}else u=l.start*n,c=l.count*n;const h=u*(e?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(s,h,a,u,c)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),n=new Map;for(let e=0;e<t.length;e++){const i=t[e],r=i.array.BYTES_PER_ELEMENT,s=this._getBufferAttribute(i);let a=n.get(s);if(void 0===a){let e,t;!0===i.isInterleavedBufferAttribute?(e=i.data.stride*r,t=i.data.isInstancedInterleavedBuffer?nI:tI):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?nI:tI),!1!==i.normalized||i.array.constructor!==Int16Array&&i.array.constructor!==Uint16Array||(e=4),a={arrayStride:e,attributes:[],stepMode:t},n.set(s,a)}const o=this._getVertexFormat(i),l=!0===i.isInterleavedBufferAttribute?i.offset*r:0;a.attributes.push({shaderLocation:e,offset:l,format:o})}return Array.from(n.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,n=t.device,i=t.get(this._getBufferAttribute(e)).buffer,r=i.size,s=n.createBuffer({label:`${e.name}_readback`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=n.createCommandEncoder({label:`readback_encoder_${e.name}`});a.copyBufferToBuffer(i,0,s,0,r);const o=a.finish();n.queue.submit([o]),await s.mapAsync(GPUMapMode.READ);const l=s.getMappedRange(),u=new e.array.constructor(l.slice(0));return s.unmap(),u.buffer}_getVertexFormat(e){const{itemSize:t,normalized:n}=e,i=e.array.constructor,r=e.constructor;let s;if(1===t)s=DI.get(i);else{const e=(LI.get(r)||PI.get(i))[n?1:0];if(e){const n=i.BYTES_PER_ELEMENT*t,r=4*Math.floor((n+3)/4)/i.BYTES_PER_ELEMENT;if(r%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");s=`${e}x${r}`}}return s||qt("WebGPUAttributeUtils: Vertex format not supported yet."),s}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class UI{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class FI{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,n=t.device,i=t.get(e);if(i.layout)return i.layout.layoutGPU;const r=this._createLayoutEntries(e),s=Nf(JSON.stringify(r));let a=this._bindGroupLayoutCache.get(s);return void 0===a&&(a=new UI(n.createBindGroupLayout({entries:r})),this._bindGroupLayoutCache.set(s,a)),a.usedTimes++,i.layout=a,i.layoutKey=s,a.layoutGPU}createBindings(e,t,n,i=0){const{backend:r}=this,s=r.get(e),a=this.createBindingsLayout(e);let o;n>0&&(void 0===s.groups&&(s.groups=[],s.versions=[]),s.versions[n]===i&&(o=s.groups[n])),void 0===o&&(o=this.createBindGroup(e,a),n>0&&(s.groups[n]=o,s.versions[n]=i)),s.group=o}updateBinding(e){const t=this.backend,n=t.device,i=e.buffer,r=t.get(e).buffer,s=e.updateRanges;if(0===s.length)n.queue.writeBuffer(r,0,i,0);else{const e=Vt(i),t=e?1:i.BYTES_PER_ELEMENT;for(let a=0,o=s.length;a<o;a++){const o=s[a],l=o.start*t,u=o.count*t,c=l*(e?i.BYTES_PER_ELEMENT:1);n.queue.writeBuffer(r,c,i,l,u)}}}createBindGroupIndex(e,t){const n=this.backend.device,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0],s=n.createBuffer({label:"bindingCameraIndex_"+r,size:16,usage:i});n.queue.writeBuffer(s,0,e,0);const a=[{binding:0,resource:{buffer:s}}];return n.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:a})}createBindGroup(e,t){const n=this.backend,i=n.device;let r=0;const s=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=n.get(t);if(void 0===e.buffer){const n=t.byteLength,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,s=[];t.visibility&eP.VERTEX&&s.push("vertex"),t.visibility&eP.FRAGMENT&&s.push("fragment"),t.visibility&eP.COMPUTE&&s.push("compute");const a=`(${s.join(",")})`,o=i.createBuffer({label:`bindingBuffer${t.id}_${t.name}_${a}`,size:n,usage:r});e.buffer=o}s.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=n.get(t.attribute).buffer;s.push({binding:r,resource:{buffer:e}})}else if(t.isSampledTexture){const e=n.get(t.texture);let a;if(void 0!==e.externalTexture)a=i.importExternalTexture({source:e.externalTexture});else{const n=t.store?1:e.texture.mipLevelCount,i=t.store?t.mipLevel:0;let r=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(r+=`-${e.texture.depthOrArrayLayers}`),r+=`-${n}-${i}`,a=e[r],void 0===a){const s=eI;let o;o=t.isSampledCubeTexture?QD:t.isSampledTexture3D?JD:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?ZD:KD,a=e[r]=e.texture.createView({aspect:s,dimension:o,mipLevelCount:n,baseMipLevel:i})}}s.push({binding:r,resource:a})}else if(t.isSampler){const e=n.get(t.texture);s.push({binding:r,resource:e.sampler})}r++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:s})}_createLayoutEntries(e){const t=[];let n=0;for(const i of e.bindings){const e=this.backend,r={binding:n,visibility:i.visibility};if(i.isUniformBuffer||i.isStorageBuffer){const e={};i.isStorageBuffer&&(i.visibility&eP.COMPUTE&&(i.access===$f||i.access===Wf)?e.type=FD:e.type=OD),r.buffer=e}else if(i.isSampledTexture&&i.store){const e={};e.format=this.backend.get(i.texture).texture.format;const t=i.access;e.access=t===$f?zD:t===Wf?BD:kD,i.texture.isArrayTexture?e.viewDimension=ZD:i.texture.is3DTexture&&(e.viewDimension=JD),r.storageTexture=e}else if(i.isSampledTexture){const t={},{primarySamples:n}=e.utils.getTextureSampleData(i.texture);if(n>1&&(t.multisampled=!0,i.texture.isDepthTexture||(t.sampleType=jD)),i.texture.isDepthTexture)e.compatibilityMode&&null===i.texture.compareFunction?t.sampleType=jD:t.sampleType=WD;else if(i.texture.isDataTexture||i.texture.isDataArrayTexture||i.texture.isData3DTexture){const e=i.texture.type;e===ve?t.sampleType=$D:e===ye?t.sampleType=XD:e===be&&(this.backend.hasFeature("float32-filterable")?t.sampleType=HD:t.sampleType=jD)}i.isSampledCubeTexture?t.viewDimension=QD:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?t.viewDimension=ZD:i.isSampledTexture3D&&(t.viewDimension=JD),r.texture=t}else if(i.isSampler){const t={};i.texture.isDepthTexture&&(null!==i.texture.compareFunction&&e.hasCompatibility(zt)?t.type=GD:t.type=VD),r.sampler=t}else qt(`WebGPUBindingUtils: Unsupported binding "${i}".`);t.push(r),n++}return t}deleteBindGroupData(e){const{backend:t}=this,n=t.get(e);n.layout&&(n.layout.usedTimes--,0===n.layout.usedTimes&&this._bindGroupLayoutCache.delete(n.layoutKey),n.layout=void 0,n.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class OI{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:n,material:i,geometry:r,pipeline:s}=e,{vertexProgram:a,fragmentProgram:o}=s,l=this.backend,u=l.device,c=l.utils,h=l.get(s),d=[];for(const t of e.getBindings()){const e=l.get(t),{layoutGPU:n}=e.layout;d.push(n)}const p=l.attributeUtils.createShaderVertexBuffers(e);let f;0===i.blending||1===i.blending&&!1===i.transparent||(f=this._getBlending(i));let m={};!0===i.stencilWrite&&(m={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const g=this._getColorWriteMask(i),_=[];if(null!==e.context.textures){const t=e.context.textures,n=e.context.mrt;for(let e=0;e<t.length;e++){const i=t[e],r=c.getTextureFormatGPU(i);let s;if(null!==n)if(!0!==this.backend.compatibilityMode){const e=n.getBlendMode(i.name);6===e.blending?s=f:0!==e.blending&&(s=this._getBlending(e))}else Yt("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets."),s=f;else s=f;_.push({format:r,blend:s,writeMask:g})}}else{const t=c.getCurrentColorFormat(e.context);_.push({format:t,blend:f,writeMask:g})}const v=l.get(a).module,y=l.get(o).module,b=this._getPrimitiveState(n,r,i),x=this._getDepthCompare(i),T=c.getCurrentDepthStencilFormat(e.context),S=this._getSampleCount(e.context),M={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},v,{buffers:p}),fragment:Object.assign({},y,{targets:_}),primitive:b,multisample:{count:S,alphaToCoverageEnabled:i.alphaToCoverage&&S>1},layout:u.createPipelineLayout({bindGroupLayouts:d})},E={},w=e.context.depth,A=e.context.stencil;if(!0!==w&&!0!==A||(!0===w&&(E.format=T,E.depthWriteEnabled=i.depthWrite,E.depthCompare=x),!0===A&&(E.stencilFront=m,E.stencilBack=m,E.stencilReadMask=i.stencilFuncMask,E.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(E.depthBias=i.polygonOffsetUnits,E.depthBiasSlopeScale=i.polygonOffsetFactor,E.depthBiasClamp=0),M.depthStencil=E),u.pushErrorScope("validation"),null===t)h.pipeline=u.createRenderPipeline(M),u.popErrorScope().then(e=>{null!==e&&(h.error=!0,qt(e.message))});else{const e=new Promise(async e=>{try{h.pipeline=await u.createRenderPipelineAsync(M)}catch(e){}const t=await u.popErrorScope();null!==t&&(h.error=!0,qt(t.message)),e()});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const n=this.backend,{utils:i,device:r}=n,s=i.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:i.getCurrentColorFormats(e),depthStencilFormat:s,sampleCount:this._getSampleCount(e)};return r.createRenderBundleEncoder(a)}createComputePipeline(e,t){const n=this.backend,i=n.device,r=n.get(e.computeProgram).module,s=n.get(e),a=[];for(const e of t){const t=n.get(e),{layoutGPU:i}=t.layout;a.push(i)}s.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,n;const i=e.blending,r=e.blendSrc,s=e.blendDst,a=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,o=null!==e.blendDstAlpha?e.blendDstAlpha:s,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(s),operation:this._getBlendOperation(a)},n={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(l)}}else{const r=(e,i,r,s)=>{t={srcFactor:e,dstFactor:i,operation:xD},n={srcFactor:r,dstFactor:s,operation:xD}};if(e.premultipliedAlpha)switch(i){case 1:r(uD,pD,uD,pD);break;case 2:r(uD,uD,uD,uD);break;case 3:r(lD,hD,lD,uD);break;case 4:r(fD,pD,lD,uD)}else switch(i){case 1:r(dD,pD,uD,pD);break;case 2:r(dD,uD,uD,uD);break;case 3:qt(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case 4:qt(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==n)return{color:t,alpha:n};qt("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case x:t=lD;break;case 201:t=uD;break;case 202:t=cD;break;case 203:t=hD;break;case E:t=dD;break;case w:t=pD;break;case 208:t=fD;break;case 209:t=mD;break;case 206:t=gD;break;case 207:t=_D;break;case 210:t=vD;break;case 211:t=yD;break;case 212:t=bD;break;default:qt("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case 512:t=tP;break;case 519:t=lP;break;case 513:t=nP;break;case 515:t=rP;break;case 514:t=iP;break;case 518:t=oP;break;case 516:t=sP;break;case 517:t=aP;break;default:qt("WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case Mt:t=RD;break;case 0:t=CD;break;case 7681:t=ND;break;case 5386:t=PD;break;case 7682:t=LD;break;case 7683:t=DD;break;case 34055:t=ID;break;case 34056:t=UD;break;default:qt("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case v:t=xD;break;case 101:t=TD;break;case 102:t=SD;break;case 103:t=MD;break;case 104:t=ED;break;default:qt("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const i={},r=this.backend.utils;i.topology=r.getPrimitiveTopology(e,n),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?gP:_P);let s=1===n.side;return e.isMesh&&e.matrixWorld.determinant()<0&&(s=!s),i.frontFace=!0===s?pP:dP,i.cullMode=2===n.side?fP:mP,i}_getColorWriteMask(e){return!0===e.colorWrite?AD:wD}_getDepthCompare(e){let t;if(!1===e.depthTest)t=lP;else{const n=this.backend.parameters.reversedDepthBuffer?Kt[e.depthFunc]:e.depthFunc;switch(n){case 0:t=tP;break;case 1:t=lP;break;case 2:t=nP;break;case 3:t=rP;break;case 4:t=iP;break;case 5:t=oP;break;case 6:t=sP;break;case 7:t=aP;break;default:qt("WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class BI extends XN{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const i=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Yt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,n=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);const r=i.finish();if(this.device.queue.submit([r]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const s=new BigUint64Array(this.resultBuffer.getMappedRange(0,n)),a={},o=[];for(const[t,n]of e){const e=t.match(/^(.*):f(\d+)$/),i=parseInt(e[2]);!1===o.includes(i)&&o.push(i),void 0===a[i]&&(a[i]=0);const r=s[n],l=s[n+1],u=Number(l-r)/1e6;this.timestamps.set(t,u),a[i]+=u}const l=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=l,this.frames=o,l}catch(e){return qt("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){qt("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){qt("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class kI extends CN{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new NI(this),this.attributeUtils=new II(this),this.bindingUtils=new FI(this),this.pipelineUtils=new OI(this),this.textureUtils=new dI(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[zt]:t}}async init(e){await super.init(e);const t=this.parameters;let n;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:"compatibility"},i="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(iI),s=[];for(const e of r)i.features.has(e)&&s.push(e);const a={requiredFeatures:s,requiredLimits:t.requiredLimits};n=await i.requestDevice(a)}else n=t.device;this.compatibilityMode=!n.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),n.lost.then(t=>{if("destroyed"===t.reason)return;const n={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(n)}),this.device=n,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(iI.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let n=t.context;if(void 0===n){const i=this.parameters;n=!0===e.isDefaultCanvasTarget&&void 0!==i.context?i.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${s} webgpu`);const r=i.alpha?"premultiplied":"opaque",a=i.outputType===xe?"extended":"standard";n.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r,toneMapping:{mode:a}}),t.context=n}return n}get coordinateSystem(){return Ot}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),n=this.get(t),i=e.currentSamples;let r=n.descriptor;if(void 0===r||n.samples!==i){r={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(r.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=r.colorAttachments[0];i>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,n.descriptor=r,n.samples=i}const s=r.colorAttachments[0];return i>0?s.resolveTarget=this.context.getCurrentTexture().createView():s.view=this.context.getCurrentTexture().createView(),r}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const n=e.renderTarget,i=this.get(n);let r=i.descriptors;void 0!==r&&i.width===n.width&&i.height===n.height&&i.samples===n.samples||(r={},i.descriptors=r);const s=e.getCacheKey();let a=r[s];if(void 0===a){const t=e.textures,o=[];let l;const u=this._isRenderCameraDepthArray(e);for(let i=0;i<t.length;i++){const r=this.get(t[i]),s={label:`colorAttachment_${i}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:KD};if(n.isRenderTarget3D)l=e.activeCubeFace,s.baseArrayLayer=0,s.dimension=JD,s.depthOrArrayLayers=t[i].image.depth;else if(n.isRenderTarget&&t[i].image.depth>1)if(!0===u){const t=e.camera.cameras;for(let e=0;e<t.length;e++){const t={...s,baseArrayLayer:e,arrayLayerCount:1,dimension:KD},n=r.texture.createView(t);o.push({view:n,resolveTarget:void 0,depthSlice:void 0})}}else s.dimension=ZD,s.depthOrArrayLayers=t[i].image.depth;if(!0!==u){const e=r.texture.createView(s);let t,n;void 0!==r.msaaTexture?(t=r.msaaTexture.createView(),n=e):(t=e,n=void 0),o.push({view:t,resolveTarget:n,depthSlice:l})}}if(a={textureViews:o},e.depth){const t=this.get(e.depthTexture),n={};(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(n.dimension=KD,n.arrayLayerCount=1,n.baseArrayLayer=e.activeCubeFace),a.depthStencilView=t.texture.createView(n)}r[s]=a,i.width=n.width,i.height=n.height,i.samples=n.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}const o={colorAttachments:[]};for(let e=0;e<a.textureViews.length;e++){const n=a.textureViews[e];let i={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(i=t.clearValue),o.colorAttachments.push({view:n.view,depthSlice:n.depthSlice,resolveTarget:n.resolveTarget,loadOp:t.loadOp||cP,storeOp:t.storeOp||uP,clearValue:i})}return a.depthStencilView&&(o.depthStencilAttachment={view:a.depthStencilView}),o}beginRender(e){const t=this.get(e),n=this.device,i=e.occlusionQueryCount;let r,s;i>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=n.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),s=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:cP}),this.initTimestampQuery(kt,this.getTimestampUID(e),s),s.occlusionQuerySet=r;const a=s.depthStencilAttachment;if(null!==e.textures){const t=s.colorAttachments;for(let n=0;n<t.length;n++){const i=t[n];e.clearColor?(i.clearValue=0===n?e.clearColorValue:{r:0,g:0,b:0,a:1},i.loadOp=hP):i.loadOp=cP,i.storeOp=uP}}else{const t=s.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=hP):t.loadOp=cP,t.storeOp=uP}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=hP):a.depthLoadOp=cP,a.depthStoreOp=uP),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=hP):a.stencilLoadOp=cP,a.stencilStoreOp=uP);const o=n.createCommandEncoder({label:"renderContext_"+e.id});if(!0===this._isRenderCameraDepthArray(e)){const n=e.camera.cameras;t.layerDescriptors&&t.layerDescriptors.length===n.length?this._updateDepthLayerDescriptors(e,t,n):this._createDepthLayerDescriptors(e,t,s,n),t.bundleEncoders=[],t.bundleSets=[];for(let i=0;i<n.length;i++){const n=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+i),r={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(n),t.bundleSets.push(r)}t.currentPass=null}else{const n=o.beginRenderPass(s);t.currentPass=n,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=s,t.encoder=o,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,n,i){const r=n.depthStencilAttachment;t.layerDescriptors=[];const s=this.get(e.depthTexture);s.viewCache||(s.viewCache=[]);for(let a=0;a<i.length;a++){const i={...n,colorAttachments:[{...n.colorAttachments[0],view:n.colorAttachments[a].view}]};if(n.depthStencilAttachment){const t=a;s.viewCache[t]||(s.viewCache[t]=s.texture.createView({dimension:KD,baseArrayLayer:a,arrayLayerCount:1})),i.depthStencilAttachment={view:s.viewCache[t],depthLoadOp:r.depthLoadOp||hP,depthStoreOp:r.depthStoreOp||uP,depthClearValue:r.depthClearValue||1},e.stencil&&(i.depthStencilAttachment.stencilLoadOp=r.stencilLoadOp,i.depthStencilAttachment.stencilStoreOp=r.stencilStoreOp,i.depthStencilAttachment.stencilClearValue=r.stencilClearValue)}else i.depthStencilAttachment={...r};t.layerDescriptors.push(i)}}_updateDepthLayerDescriptors(e,t,n){for(let i=0;i<n.length;i++){const n=t.layerDescriptors[i];if(n.depthStencilAttachment){const t=n.depthStencilAttachment;e.depth&&(e.clearDepth?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=hP):t.depthLoadOp=cP),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=hP):t.stencilLoadOp=cP)}}}finishRender(e){const t=this.get(e),n=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),n>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const i=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const n=[];for(let e=0;e<t.bundleEncoders.length;e++){const i=t.bundleEncoders[e];n.push(i.finish())}for(let r=0;r<t.layerDescriptors.length;r++)if(r<n.length){const s=t.layerDescriptors[r],a=i.beginRenderPass(s);if(e.viewport){const{x:t,y:n,width:i,height:r,minDepth:s,maxDepth:o}=e.viewportValue;a.setViewport(t,n,i,r,s,o)}if(e.scissor){const{x:t,y:n,width:i,height:r}=e.scissorValue;a.setScissorRect(t,n,i,r)}a.executeBundles([n[r]]),a.end()}}else t.currentPass&&t.currentPass.end();if(n>0){const i=8*n;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const s=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,r,0),t.encoder.copyBufferToBuffer(r,0,s,0,i),t.occlusionQueryBuffer=s,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;e<t.length;e++){const n=t[e];!0===n.generateMipmaps&&this.textureUtils.generateMipmaps(n)}}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:n,currentOcclusionQueryObjects:i}=t;if(n&&i){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await n.mapAsync(GPUMapMode.READ);const r=n.getMappedRange(),s=new BigUint64Array(r);for(let t=0;t<i.length;t++)s[t]===BigInt(0)&&e.add(i[t]);n.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:n,y:i,width:r,height:s,minDepth:a,maxDepth:o}=e.viewportValue;t.setViewport(n,i,r,s,a,o)}updateScissor(e){const{currentPass:t}=this.get(e),{x:n,y:i,width:r,height:s}=e.scissorValue;t.setScissorRect(n,i,r,s)}getClearColor(){const e=super.getClearColor();return!0===this.renderer.alpha&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,n,i=null){const r=this.device,s=this.renderer;let a,o,l,u,c=[];if(e){const e=this.getClearColor();o={r:e.r,g:e.g,b:e.b,a:e.a}}if(null===i){l=s.depth,u=s.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){c=t.colorAttachments;const e=c[0];e.clearValue=o,e.loadOp=hP,e.storeOp=uP}(l||u)&&(a=t.depthStencilAttachment)}else{l=i.depth,u=i.stencil;const r={loadOp:e?hP:cP,clearValue:e?o:void 0};l&&(r.depthLoadOp=t?hP:cP,r.depthClearValue=t?s.getClearDepth():void 0,r.depthStoreOp=uP),u&&(r.stencilLoadOp=n?hP:cP,r.stencilClearValue=n?s.getClearStencil():void 0,r.stencilStoreOp=uP);const h=this._getRenderPassDescriptor(i,r);c=h.colorAttachments,a=h.depthStencilAttachment}l&&a&&(t?(a.depthLoadOp=hP,a.depthClearValue=s.getClearDepth(),a.depthStoreOp=uP):(a.depthLoadOp=cP,a.depthStoreOp=uP)),u&&a&&(n?(a.stencilLoadOp=hP,a.stencilClearValue=s.getClearStencil(),a.stencilStoreOp=uP):(a.stencilLoadOp=cP,a.stencilStoreOp=uP));const h=r.createCommandEncoder({label:"clear"});h.beginRenderPass({colorAttachments:c,depthStencilAttachment:a}).end(),r.queue.submit([h.finish()])}beginCompute(e){const t=this.get(e),n={label:"computeGroup_"+e.id};this.initTimestampQuery(Bt,this.getTimestampUID(e),n),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(n)}compute(e,t,n,i,r=null){const s=this.get(t),{passEncoderGPU:a}=this.get(e),o=this.get(i).pipeline;this.pipelineUtils.setPipeline(a,o);for(let e=0,t=n.length;e<t;e++){const t=n[e],i=this.get(t);a.setBindGroup(e,i.group)}if(null===r&&(r=t.count),r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute){const e=this.get(r).buffer;return void a.dispatchWorkgroupsIndirect(e,0)}if("number"==typeof r){const e=r;if(void 0===s.dispatchSize||s.count!==e){s.dispatchSize=[0,1,1],s.count=e;const n=t.workgroupSize;let i=n[0];for(let e=1;e<n.length;e++)i*=n[e];const a=Math.ceil(e/i),o=this.device.limits.maxComputeWorkgroupsPerDimension;r=[a,1,1],a>o&&(r[0]=Math.min(a,o),r[1]=Math.ceil(a/o)),s.dispatchSize=r}r=s.dispatchSize}a.dispatchWorkgroups(r[0],r[1]||1,r[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:n,material:i,context:r,pipeline:s}=e,a=e.getBindings(),o=this.get(r),l=this.get(s),u=l.pipeline;if(!0===l.error)return;const c=e.getIndex(),h=null!==c,d=e.getDrawParameters();if(null===d)return;const p=(t,n)=>{this.pipelineUtils.setPipeline(t,u),n.pipeline=u;const s=n.bindingGroups;for(let e=0,n=a.length;e<n;e++){const n=a[e],i=this.get(n);s[n.index]!==n.id&&(t.setBindGroup(n.index,i.group),s[n.index]=n.id)}if(!0===h&&n.index!==c){const e=this.get(c).buffer,i=c.array instanceof Uint16Array?gP:_P;t.setIndexBuffer(e,i),n.index=c}const l=e.getVertexBuffers();for(let e=0,i=l.length;e<i;e++){const i=l[e];if(n.attributes[e]!==i){const r=this.get(i).buffer;t.setVertexBuffer(e,r),n.attributes[e]=i}}!0===r.stencil&&!0===i.stencilWrite&&o.currentStencilRef!==i.stencilRef&&(t.setStencilReference(i.stencilRef),o.currentStencilRef=i.stencilRef)},f=(r,s)=>{if(p(r,s),!0===n.isBatchedMesh){const e=n._multiDrawStarts,s=n._multiDrawCounts,a=n._multiDrawCount,o=n._multiDrawInstances;null!==o&&Yt("WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");let l=!0===h?c.array.BYTES_PER_ELEMENT:1;i.wireframe&&(l=n.geometry.attributes.position.count>65535?4:2);for(let i=0;i<a;i++){const a=o?o[i]:1,u=a>1?0:i;!0===h?r.drawIndexed(s[i],a,e[i]/l,0,u):r.draw(s[i],a,e[i],u),t.update(n,s[i],a)}}else if(!0===h){const{vertexCount:i,instanceCount:s,firstVertex:a}=d,o=e.getIndirect();if(null!==o){const t=this.get(o).buffer,n=e.getIndirectOffset(),i=Array.isArray(n)?n:[n];for(let e=0;e<i.length;e++)r.drawIndexedIndirect(t,i[e])}else r.drawIndexed(i,s,a,0,0);t.update(n,i,s)}else{const{vertexCount:i,instanceCount:s,firstVertex:a}=d,o=e.getIndirect();if(null!==o){const t=this.get(o).buffer,n=e.getIndirectOffset(),i=Array.isArray(n)?n:[n];for(let e=0;e<i.length;e++)r.drawIndirect(t,i[e])}else r.draw(i,s,a,0);t.update(n,i,s)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),i=e.camera.cameras,s=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==i.length){const e=this.get(s),n=[],r=new Uint32Array([0,0,0,0]);for(let t=0,s=i.length;t<s;t++){r[0]=t;const{layoutGPU:i}=e.layout,s=this.bindingUtils.createBindGroupIndex(r,i);n.push(s)}t.indexesGPU=n}const a=this.renderer.getPixelRatio();for(let e=0,l=i.length;e<l;e++){const l=i[e];if(n.layers.test(l.layers)){const n=l.viewport;let i=o.currentPass,u=o.currentSets;if(o.bundleEncoders){i=o.bundleEncoders[e],u=o.bundleSets[e]}n&&i.setViewport(Math.floor(n.x*a),Math.floor(n.y*a),Math.floor(n.width*a),Math.floor(n.height*a),r.viewportValue.minDepth,r.viewportValue.maxDepth),s&&t.indexesGPU&&(i.setBindGroup(s.index,t.indexesGPU[e]),u.bindingGroups[s.index]=s.id),f(i,u)}}}else if(o.currentPass){if(void 0!==o.occlusionQuerySet){const e=o.lastOcclusionObject;e!==n&&(null!==e&&!0===e.occlusionTest&&(o.currentPass.endOcclusionQuery(),o.occlusionQueryIndex++),!0===n.occlusionTest&&(o.currentPass.beginOcclusionQuery(o.occlusionQueryIndex),o.occlusionQueryObjects[o.occlusionQueryIndex]=n),o.lastOcclusionObject=n)}f(o.currentPass,o.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:n,material:i}=e,r=this.utils,s=r.getSampleCountRenderContext(e.context),a=r.getCurrentColorSpace(e.context),o=r.getCurrentColorFormat(e.context),l=r.getCurrentDepthStencilFormat(e.context),u=r.getPrimitiveTopology(n,i);let c=!1;return t.material===i&&t.materialVersion===i.version&&t.transparent===i.transparent&&t.blending===i.blending&&t.premultipliedAlpha===i.premultipliedAlpha&&t.blendSrc===i.blendSrc&&t.blendDst===i.blendDst&&t.blendEquation===i.blendEquation&&t.blendSrcAlpha===i.blendSrcAlpha&&t.blendDstAlpha===i.blendDstAlpha&&t.blendEquationAlpha===i.blendEquationAlpha&&t.colorWrite===i.colorWrite&&t.depthWrite===i.depthWrite&&t.depthTest===i.depthTest&&t.depthFunc===i.depthFunc&&t.stencilWrite===i.stencilWrite&&t.stencilFunc===i.stencilFunc&&t.stencilFail===i.stencilFail&&t.stencilZFail===i.stencilZFail&&t.stencilZPass===i.stencilZPass&&t.stencilFuncMask===i.stencilFuncMask&&t.stencilWriteMask===i.stencilWriteMask&&t.side===i.side&&t.alphaToCoverage===i.alphaToCoverage&&t.sampleCount===s&&t.colorSpace===a&&t.colorFormat===o&&t.depthStencilFormat===l&&t.primitiveTopology===u&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=s,t.colorSpace=a,t.colorFormat=o,t.depthStencilFormat=l,t.primitiveTopology=u,t.clippingContextCacheKey=e.clippingContextCacheKey,c=!0),c}getRenderCacheKey(e){const{object:t,material:n}=e,i=this.utils,r=e.context,s=t.isMesh&&t.matrixWorld.determinant()<0;return[n.transparent,n.blending,n.premultipliedAlpha,n.blendSrc,n.blendDst,n.blendEquation,n.blendSrcAlpha,n.blendDstAlpha,n.blendEquationAlpha,n.colorWrite,n.depthWrite,n.depthTest,n.depthFunc,n.stencilWrite,n.stencilFunc,n.stencilFail,n.stencilZFail,n.stencilZPass,n.stencilFuncMask,n.stencilWriteMask,n.side,s,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,n),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,i,r,s){return this.textureUtils.copyTextureToBuffer(e,t,n,i,r,s)}initTimestampQuery(e,t,n){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new BI(this.device,e,2048));const i=this.timestampQueryPool[e],r=i.allocateQueriesForContext(t);n.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:r,endOfPassWriteIndex:r+1}}createNodeBuilder(e,t){return new CI(e,t)}createProgram(e){this.get(e).module={module:this.device.createShaderModule({code:e.code,label:e.stage+(""!==e.name?`_${e.name}`:"")}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const n=this.get(e),i=n.currentPass.finish();this.get(t).bundleGPU=i,n.currentSets=n._currentSets,n.currentPass=n._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,n,i){this.bindingUtils.createBindings(e,t,n,i)}updateBindings(e,t,n,i){this.bindingUtils.createBindings(e,t,n,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}getMaxAnisotropy(){return 16}hasFeature(e){return void 0!==rI[e]&&(e=rI[e]),this.device.features.has(e)}copyTextureToTexture(e,t,n=null,i=null,r=0,s=0){let a=0,o=0,l=0,u=0,c=0,h=0,d=e.image.width,p=e.image.height,f=1;null!==n&&(!0===n.isBox3?(u=n.min.x,c=n.min.y,h=n.min.z,d=n.max.x-n.min.x,p=n.max.y-n.min.y,f=n.max.z-n.min.z):(u=n.min.x,c=n.min.y,d=n.max.x-n.min.x,p=n.max.y-n.min.y,f=1)),null!==i&&(a=i.x,o=i.y,l=i.z||0);const m=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),g=this.get(e).texture,_=this.get(t).texture;m.copyTextureToTexture({texture:g,mipLevel:r,origin:{x:u,y:c,z:h}},{texture:_,mipLevel:s,origin:{x:a,y:o,z:l}},[d,p,f]),this.device.queue.submit([m.finish()]),0===s&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,n){const i=this.get(t);let r=null;r=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const s=this.get(e).texture;if(r.format!==s.format)return void qt("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",r.format,s.format);let a;if(i.currentPass?(i.currentPass.end(),a=i.encoder):a=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),a.copyTextureToTexture({texture:r,origin:[n.x,n.y,0]},{texture:s},[n.z,n.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,a),i.currentPass){const{descriptor:e}=i;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=cP;t.depth&&(e.depthStencilAttachment.depthLoadOp=cP),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=cP),i.currentPass=a.beginRenderPass(e),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else this.device.queue.submit([a.finish()])}hasCompatibility(e){return void 0!==this._compatibility[zt]?this._compatibility[zt]:super.hasCompatibility(e)}dispose(){if(this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}if(this.timestampQueryPool)for(const e of Object.values(this.timestampQueryPool))null!==e&&e.dispose();void 0===this.parameters.device&&null!==this.device&&this.device.destroy()}}class zI extends Ea{constructor(e,t,n,i,r,s){super(e,t,n,i,r,s),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class VI extends Ea{constructor(e,t,n,i,r,s){super(e,t,n,i,r,s),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class GI extends UC{constructor(){super(),this.addMaterial(qS,"MeshPhongMaterial"),this.addMaterial(kE,"MeshStandardMaterial"),this.addMaterial(VE,"MeshPhysicalMaterial"),this.addMaterial(WE,"MeshToonMaterial"),this.addMaterial(kS,"MeshBasicMaterial"),this.addMaterial($S,"MeshLambertMaterial"),this.addMaterial(wS,"MeshNormalMaterial"),this.addMaterial(qE,"MeshMatcapMaterial"),this.addMaterial(TS,"LineBasicMaterial"),this.addMaterial(MS,"LineDashedMaterial"),this.addMaterial(tw,"PointsMaterial"),this.addMaterial(QE,"SpriteMaterial"),this.addMaterial(sw,"ShadowMaterial"),this.addLight(xR,Aa),this.addLight(lC,Na),this.addLight(vC,La),this.addLight(cC,Ea),this.addLight(oC,Pa),this.addLight(uC,ha),this.addLight(dC,Ia),this.addLight(hC,zI),this.addLight(fC,VI),this.addToneMapping(_A,1),this.addToneMapping(vA,2),this.addToneMapping(yA,3),this.addToneMapping(xA,4),this.addToneMapping(EA,6),this.addToneMapping(wA,7)}}class HI extends rN{constructor(e={}){let t;e.forceWebGL?t=YN:(t=kI,e.getFallback=()=>(Xt("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new YN(e)));super(new t(e),e),this.library=new GI,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const jI={type:"change"},WI={type:"start"},$I={type:"end"},XI=1e-6,qI=-1,YI=0,KI=1,ZI=2,QI=3,JI=4,eU=new cn,tU=new cn,nU=new dn,iU=new dn,rU=new dn,sU=new hn,aU=new dn,oU=new dn,lU=new dn,uU=new dn;class cU extends Xa{constructor(e,t=null){super(e,t),this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=["KeyA","KeyS","KeyD"],this.mouseButtons={LEFT:a,MIDDLE:o,RIGHT:l},this.target=new dn,this.state=qI,this.keyState=qI,this._lastPosition=new dn,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new dn,this._movePrev=new cn,this._moveCurr=new cn,this._lastAxis=new dn,this._zoomStart=new cn,this._zoomEnd=new cn,this._panStart=new cn,this._panEnd=new cn,this._pointers=[],this._pointerPositions={},this._onPointerMove=dU.bind(this),this._onPointerDown=hU.bind(this),this._onPointerUp=pU.bind(this),this._onPointerCancel=fU.bind(this),this._onContextMenu=xU.bind(this),this._onMouseWheel=bU.bind(this),this._onKeyDown=gU.bind(this),this._onKeyUp=mU.bind(this),this._onTouchStart=TU.bind(this),this._onTouchMove=SU.bind(this),this._onTouchEnd=MU.bind(this),this._onMouseDown=_U.bind(this),this._onMouseMove=vU.bind(this),this._onMouseUp=yU.bind(this),this._target0=this.target.clone(),this._position0=this.object.position.clone(),this._up0=this.object.up.clone(),this._zoom0=this.object.zoom,null!==t&&(this.connect(t),this.handleResize()),this.update()}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){this._eye.subVectors(this.object.position,this.target),this.noRotate||this._rotateCamera(),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this._checkDistances(),this.object.lookAt(this.target),this._lastPosition.distanceToSquared(this.object.position)>XI&&(this.dispatchEvent(jI),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>XI||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(jI),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=qI,this.keyState=qI,this.target.copy(this._target0),this.object.position.copy(this._position0),this.object.up.copy(this._up0),this.object.zoom=this._zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(jI),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(tU.copy(this._panEnd).sub(this._panStart),tU.lengthSq()){if(this.object.isOrthographicCamera){const e=(this.object.right-this.object.left)/this.object.zoom/this.domElement.clientWidth,t=(this.object.top-this.object.bottom)/this.object.zoom/this.domElement.clientWidth;tU.x*=e,tU.y*=t}tU.multiplyScalar(this._eye.length()*this.panSpeed),iU.copy(this._eye).cross(this.object.up).setLength(tU.x),iU.add(nU.copy(this.object.up).setLength(tU.y)),this.object.position.add(iU),this.target.add(iU),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(tU.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){uU.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=uU.length();e?(this._eye.copy(this.object.position).sub(this.target),aU.copy(this._eye).normalize(),oU.copy(this.object.up).normalize(),lU.crossVectors(oU,aU).normalize(),oU.setLength(this._moveCurr.y-this._movePrev.y),lU.setLength(this._moveCurr.x-this._movePrev.x),uU.copy(oU.add(lU)),rU.crossVectors(uU,this._eye).normalize(),e*=this.rotateSpeed,sU.setFromAxisAngle(rU,e),this._eye.applyQuaternion(sU),this.object.up.applyQuaternion(sU),this._lastAxis.copy(rU),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),sU.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(sU),this.object.up.applyQuaternion(sU)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let e;this.state===JI?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=un.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(e=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,1!==e&&e>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=un.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor)}_getMouseOnScreen(e,t){return eU.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),eU}_getMouseOnCircle(e,t){return eU.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),eU}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId==e.pointerId)return void this._pointers.splice(t,1)}_trackPointer(e){let t=this._pointerPositions[e.pointerId];void 0===t&&(t=new cn,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0].pointerId?this._pointers[1]:this._pointers[0];return this._pointerPositions[t.pointerId]}_checkDistances(){this.noZoom&&this.noPan||(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}}function hU(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e))}function dU(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function pU(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchEnd(e):this._onMouseUp(),this._removePointer(e),0===this._pointers.length&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp)))}function fU(e){this._removePointer(e)}function mU(){!1!==this.enabled&&(this.keyState=qI,window.addEventListener("keydown",this._onKeyDown))}function gU(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===qI&&(e.code!==this.keys[YI]||this.noRotate?e.code!==this.keys[KI]||this.noZoom?e.code!==this.keys[ZI]||this.noPan||(this.keyState=ZI):this.keyState=KI:this.keyState=YI))}function _U(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case o:this.state=KI;break;case a:this.state=YI;break;case l:this.state=ZI;break;default:this.state=qI}const n=this.keyState!==qI?this.keyState:this.state;n!==YI||this.noRotate?n!==KI||this.noZoom?n!==ZI||this.noPan||(this._panStart.copy(this._getMouseOnScreen(e.pageX,e.pageY)),this._panEnd.copy(this._panStart)):(this._zoomStart.copy(this._getMouseOnScreen(e.pageX,e.pageY)),this._zoomEnd.copy(this._zoomStart)):(this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr)),this.dispatchEvent(WI)}function vU(e){const t=this.keyState!==qI?this.keyState:this.state;t!==YI||this.noRotate?t!==KI||this.noZoom?t!==ZI||this.noPan||this._panEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):this._zoomEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):(this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)))}function yU(){this.state=qI,this.dispatchEvent($I)}function bU(e){if(!1!==this.enabled&&!0!==this.noZoom){switch(e.preventDefault(),e.deltaMode){case 2:this._zoomStart.y-=.025*e.deltaY;break;case 1:this._zoomStart.y-=.01*e.deltaY;break;default:this._zoomStart.y-=25e-5*e.deltaY}this.dispatchEvent(WI),this.dispatchEvent($I)}}function xU(e){!1!==this.enabled&&e.preventDefault()}function TU(e){if(this._trackPointer(e),1===this._pointers.length)this.state=QI,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=JI;const e=this._pointers[0].pageX-this._pointers[1].pageX,t=this._pointers[0].pageY-this._pointers[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(e*e+t*t);const n=(this._pointers[0].pageX+this._pointers[1].pageX)/2,i=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(n,i)),this._panEnd.copy(this._panStart)}this.dispatchEvent(WI)}function SU(e){if(this._trackPointer(e),1===this._pointers.length)this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY));else{const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y;this._touchZoomDistanceEnd=Math.sqrt(n*n+i*i);const r=(e.pageX+t.x)/2,s=(e.pageY+t.y)/2;this._panEnd.copy(this._getMouseOnScreen(r,s))}}function MU(e){switch(this._pointers.length){case 0:this.state=qI;break;case 1:this.state=QI,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=JI;for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId!==e.pointerId){const e=this._pointerPositions[this._pointers[t].pointerId];this._moveCurr.copy(this._getMouseOnCircle(e.x,e.y)),this._movePrev.copy(this._moveCurr);break}}this.dispatchEvent($I)}const EU={type:"change"},wU={type:"start"},AU={type:"end"},RU=new Lr,CU=new Qr,NU=Math.cos(70*un.DEG2RAD),PU=new dn,LU=2*Math.PI,DU=-1,IU=0,UU=1,FU=2,OU=3,BU=4,kU=5,zU=6,VU=1e-6;class GU extends Xa{constructor(e,t=null){super(e,t),this.state=DU,this.target=new dn,this.cursor=new dn,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:a,MIDDLE:o,RIGHT:l},this.touches={ONE:u,TWO:h},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new dn,this._lastQuaternion=new hn,this._lastTargetPosition=new dn,this._quat=(new hn).setFromUnitVectors(e.up,new dn(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Wa,this._sphericalDelta=new Wa,this._scale=1,this._panOffset=new dn,this._rotateStart=new cn,this._rotateEnd=new cn,this._rotateDelta=new cn,this._panStart=new cn,this._panEnd=new cn,this._panDelta=new cn,this._dollyStart=new cn,this._dollyEnd=new cn,this._dollyDelta=new cn,this._dollyDirection=new dn,this._mouse=new cn,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=jU.bind(this),this._onPointerDown=HU.bind(this),this._onPointerUp=WU.bind(this),this._onContextMenu=QU.bind(this),this._onMouseWheel=qU.bind(this),this._onKeyDown=YU.bind(this),this._onTouchStart=KU.bind(this),this._onTouchMove=ZU.bind(this),this._onMouseDown=$U.bind(this),this._onMouseMove=XU.bind(this),this._interceptControlDown=JU.bind(this),this._interceptControlUp=eF.bind(this),null!==this.domElement&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,this.domElement.style.cursor="grab"===e?"grab":"auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1});this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){null!==this._domElementKeyEvents&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(EU),this.update(),this.state=DU}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;PU.copy(t).sub(this.target),PU.applyQuaternion(this._quat),this._spherical.setFromVector3(PU),this.autoRotate&&this.state===DU&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(n)&&isFinite(i)&&(n<-Math.PI?n+=LU:n>Math.PI&&(n-=LU),i<-Math.PI?i+=LU:i>Math.PI&&(i-=LU),this._spherical.theta=n<=i?Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),!0===this.enableDamping?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=e!=this._spherical.radius}if(PU.setFromSpherical(this._spherical),PU.applyQuaternion(this._quatInverse),t.copy(this.target).add(PU),this.object.lookAt(this.target),!0===this.enableDamping?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let e=null;if(this.object.isPerspectiveCamera){const t=PU.length();e=this._clampDistance(t*this._scale);const n=t-e;this.object.position.addScaledVector(this._dollyDirection,n),this.object.updateMatrixWorld(),r=!!n}else if(this.object.isOrthographicCamera){const t=new dn(this._mouse.x,this._mouse.y,0);t.unproject(this.object);const n=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=n!==this.object.zoom;const i=new dn(this._mouse.x,this._mouse.y,0);i.unproject(this.object),this.object.position.sub(i).add(t),this.object.updateMatrixWorld(),e=PU.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==e&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position):(RU.origin.copy(this.object.position),RU.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(RU.direction))<NU?this.object.lookAt(this.target):(CU.setFromNormalAndCoplanarPoint(this.object.up,this.target),RU.intersectPlane(CU,this.target))))}else if(this.object.isOrthographicCamera){const e=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),e!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,!!(r||this._lastPosition.distanceToSquared(this.object.position)>VU||8*(1-this._lastQuaternion.dot(this.object.quaternion))>VU||this._lastTargetPosition.distanceToSquared(this.target)>VU)&&(this.dispatchEvent(EU),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?LU/60*this.autoRotateSpeed*e:LU/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(.01*e);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){PU.setFromMatrixColumn(t,0),PU.multiplyScalar(-e),this._panOffset.add(PU)}_panUp(e,t){!0===this.screenSpacePanning?PU.setFromMatrixColumn(t,1):(PU.setFromMatrixColumn(t,0),PU.crossVectors(this.object.up,PU)),PU.multiplyScalar(e),this._panOffset.add(PU)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;PU.copy(i).sub(this.target);let r=PU.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),i=e-n.left,r=t-n.top,s=n.width,a=n.height;this._mouse.x=i/s*2-1,this._mouse.y=-r/a*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(LU*this._rotateDelta.x/t.clientHeight),this._rotateUp(LU*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(LU*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-LU*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(LU*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-LU*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(1===this._pointers.length)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateEnd.set(n,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(LU*this._rotateDelta.x/t.clientHeight),this._rotateUp(LU*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const s=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(s,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return void this._pointers.splice(t,1)}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];void 0===t&&(t=new cn,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function HU(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e),"grab"===this._cursorStyle&&(this.domElement.style.cursor="grabbing")))}function jU(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function WU(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(AU),this.state=DU,"grab"===this._cursorStyle&&(this.domElement.style.cursor="grab");break;case 1:const t=this._pointers[0],n=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:n.x,pageY:n.y})}}function $U(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case o:if(!1===this.enableZoom)return;this._handleMouseDownDolly(e),this.state=UU;break;case a:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=FU}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=IU}break;case l:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=IU}else{if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=FU}break;default:this.state=DU}this.state!==DU&&this.dispatchEvent(wU)}function XU(e){switch(this.state){case IU:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case UU:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case FU:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function qU(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===DU&&(e.preventDefault(),this.dispatchEvent(wU),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(AU))}function YU(e){!1!==this.enabled&&this._handleKeyDown(e)}function KU(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case u:if(!1===this.enableRotate)return;this._handleTouchStartRotate(e),this.state=OU;break;case c:if(!1===this.enablePan)return;this._handleTouchStartPan(e),this.state=BU;break;default:this.state=DU}break;case 2:switch(this.touches.TWO){case h:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(e),this.state=kU;break;case d:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(e),this.state=zU;break;default:this.state=DU}break;default:this.state=DU}this.state!==DU&&this.dispatchEvent(wU)}function ZU(e){switch(this._trackPointer(e),this.state){case OU:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case BU:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case kU:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case zU:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=DU}}function QU(e){!1!==this.enabled&&e.preventDefault()}function JU(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function eF(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const tF={type:"change"},nF=1e-6,iF=new hn;class rF extends Xa{constructor(e,t=null){super(e,t),this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1,this._moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this._moveVector=new dn(0,0,0),this._rotationVector=new dn(0,0,0),this._lastQuaternion=new hn,this._lastPosition=new dn,this._status=0,this._onKeyDown=sF.bind(this),this._onKeyUp=aF.bind(this),this._onPointerMove=lF.bind(this),this._onPointerDown=oF.bind(this),this._onPointerUp=uF.bind(this),this._onPointerCancel=cF.bind(this),this._onContextMenu=hF.bind(this),null!==t&&this.connect(t)}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu)}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu)}dispose(){this.disconnect()}update(e){if(!1===this.enabled)return;const t=this.object,n=e*this.movementSpeed,i=e*this.rollSpeed;t.translateX(this._moveVector.x*n),t.translateY(this._moveVector.y*n),t.translateZ(this._moveVector.z*n),iF.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply(iF),(this._lastPosition.distanceToSquared(t.position)>nF||8*(1-this._lastQuaternion.dot(t.quaternion))>nF)&&(this.dispatchEvent(tF),this._lastQuaternion.copy(t.quaternion),this._lastPosition.copy(t.position))}_updateMovementVector(){const e=this._moveState.forward||this.autoForward&&!this._moveState.back?1:0;this._moveVector.x=-this._moveState.left+this._moveState.right,this._moveVector.y=-this._moveState.down+this._moveState.up,this._moveVector.z=-e+this._moveState.back}_updateRotationVector(){this._rotationVector.x=-this._moveState.pitchDown+this._moveState.pitchUp,this._rotationVector.y=-this._moveState.yawRight+this._moveState.yawLeft,this._rotationVector.z=-this._moveState.rollRight+this._moveState.rollLeft}_getContainerDimensions(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}}}function sF(e){if(!e.altKey&&!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this._moveState.forward=1;break;case"KeyS":this._moveState.back=1;break;case"KeyA":this._moveState.left=1;break;case"KeyD":this._moveState.right=1;break;case"KeyR":this._moveState.up=1;break;case"KeyF":this._moveState.down=1;break;case"ArrowUp":this._moveState.pitchUp=1;break;case"ArrowDown":this._moveState.pitchDown=1;break;case"ArrowLeft":this._moveState.yawLeft=1;break;case"ArrowRight":this._moveState.yawRight=1;break;case"KeyQ":this._moveState.rollLeft=1;break;case"KeyE":this._moveState.rollRight=1}this._updateMovementVector(),this._updateRotationVector()}}function aF(e){if(!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this._moveState.forward=0;break;case"KeyS":this._moveState.back=0;break;case"KeyA":this._moveState.left=0;break;case"KeyD":this._moveState.right=0;break;case"KeyR":this._moveState.up=0;break;case"KeyF":this._moveState.down=0;break;case"ArrowUp":this._moveState.pitchUp=0;break;case"ArrowDown":this._moveState.pitchDown=0;break;case"ArrowLeft":this._moveState.yawLeft=0;break;case"ArrowRight":this._moveState.yawRight=0;break;case"KeyQ":this._moveState.rollLeft=0;break;case"KeyE":this._moveState.rollRight=0}this._updateMovementVector(),this._updateRotationVector()}}function oF(e){if(!1!==this.enabled)if(this.dragToLook)this._status++;else{switch(e.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1}this._updateMovementVector()}}function lF(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),n=t.size[0]/2,i=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-n)/n,this._moveState.pitchDown=(e.pageY-t.offset[1]-i)/i,this._updateRotationVector()}}function uF(e){if(!1!==this.enabled){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(e.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0}this._updateMovementVector()}this._updateRotationVector()}}function cF(){!1!==this.enabled&&(this.dragToLook?(this._status=0,this._moveState.yawLeft=this._moveState.pitchDown=0):(this._moveState.forward=0,this._moveState.back=0,this._updateMovementVector()),this._updateRotationVector())}function hF(e){!1!==this.enabled&&e.preventDefault()}const dF={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 pF{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 fF=new Ra(-1,1,1,-1,0,1);const mF=new class extends vr{constructor(){super(),this.setAttribute("position",new ar([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new ar([0,2,0,0,2,0],2))}};class gF{constructor(e){this._mesh=new Wr(mF,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,fF)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class _F extends pF{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof Ws?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=js.clone(e.uniforms),this.material=new Ws({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 gF(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.texture),this._fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}class vF extends pF{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const i=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(i.REPLACE,i.REPLACE,i.REPLACE),r.buffers.stencil.setFunc(i.ALWAYS,s,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(n),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),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(i.EQUAL,1,4294967295),r.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),r.buffers.stencil.setLocked(!0)}}class yF extends pF{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class bF{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),void 0===t){const n=e.getSize(new cn);this._width=n.width,this._height=n.height,(t=new Dn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:xe})).texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new _F(dF),this.copyPass.material.blending=0,this.timer=new Ba}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){this.timer.update(),void 0===e&&(e=this.timer.getDelta());const t=this.renderer.getRenderTarget();let n=!1;for(let t=0,i=this.passes.length;t<i;t++){const i=this.passes[t];if(!1!==i.enabled){if(i.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),i.render(this.renderer,this.writeBuffer,this.readBuffer,e,n),i.needsSwap){if(n){const t=this.renderer.getContext(),n=this.renderer.state.buffers.stencil;n.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),n.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}void 0!==vF&&(i instanceof vF?n=!0:i instanceof yF&&(n=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(void 0===e){const t=this.renderer.getSize(new cn);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 n=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget1.setSize(n,i),this.renderTarget2.setSize(n,i);for(let e=0;e<this.passes.length;e++)this.passes[e].setSize(n,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class xF extends pF{constructor(e,t,n=null,i=null,r=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=n,this.clearColor=i,this.clearAlpha=r,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new _i}render(e,t,n){const i=e.autoClear;let r,s;e.autoClear=!1,null!==this.overrideMaterial&&(s=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),null!==this.clearColor&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),null!==this.clearAlpha&&(r=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),1==this.clearDepth&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:n),!0===this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),null!==this.clearColor&&e.setClearColor(this._oldClearColor),null!==this.clearAlpha&&e.setClearAlpha(r),null!==this.overrideMaterial&&(this.scene.overrideMaterial=s),e.autoClear=i}}function TF(){return TF=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},TF.apply(null,arguments)}function SF(e,t){return SF=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},SF(e,t)}function MF(e){return MF=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},MF(e)}function EF(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(EF=function(){return!!e})()}function wF(e){var t="function"==typeof Map?new Map:void 0;return wF=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return function(e,t,n){if(EF())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return n&&SF(r,n.prototype),r}(e,arguments,MF(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),SF(n,e)},wF(e)}var AF={1:"Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).\n\n",2:"Passed invalid arguments to hsla, please pass multiple numbers e.g. hsla(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).\n\n",3:"Passed an incorrect argument to a color function, please pass a string representation of a color.\n\n",4:"Couldn't generate valid rgb string from %s, it returned %s.\n\n",5:"Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.\n\n",6:"Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).\n\n",7:"Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).\n\n",8:"Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.\n\n",9:"Please provide a number of steps to the modularScale helper.\n\n",10:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",11:'Invalid value passed as base to modularScale, expected number or em string but got "%s"\n\n',12:'Expected a string ending in "px" or a number passed as the first argument to %s(), got "%s" instead.\n\n',13:'Expected a string ending in "px" or a number passed as the second argument to %s(), got "%s" instead.\n\n',14:'Passed invalid pixel value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',15:'Passed invalid base value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',16:"You must provide a template to this method.\n\n",17:"You passed an unsupported selector state to this method.\n\n",18:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",19:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",20:"expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",21:"expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.\n\n",22:"expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.\n\n",23:"fontFace expects a name of a font-family.\n\n",24:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",25:"fontFace expects localFonts to be an array.\n\n",26:"fontFace expects fileFormats to be an array.\n\n",27:"radialGradient requries at least 2 color-stops to properly render.\n\n",28:"Please supply a filename to retinaImage() as the first argument.\n\n",29:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",30:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",31:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation\n\n",32:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')\n\n",33:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation\n\n",34:"borderRadius expects a radius value as a string or number as the second argument.\n\n",35:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',36:"Property must be a string value.\n\n",37:"Syntax Error at %s.\n\n",38:"Formula contains a function that needs parentheses at %s.\n\n",39:"Formula is missing closing parenthesis at %s.\n\n",40:"Formula has too many closing parentheses at %s.\n\n",41:"All values in a formula must have the same unit or be unitless.\n\n",42:"Please provide a number of steps to the modularScale helper.\n\n",43:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",44:"Invalid value passed as base to modularScale, expected number or em/rem string but got %s.\n\n",45:"Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.\n\n",46:"Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.\n\n",47:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",48:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",49:"Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",50:"Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.\n\n",51:"Expects the first argument object to have the properties prop, fromSize, and toSize.\n\n",52:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",53:"fontFace expects localFonts to be an array.\n\n",54:"fontFace expects fileFormats to be an array.\n\n",55:"fontFace expects a name of a font-family.\n\n",56:"linearGradient requries at least 2 color-stops to properly render.\n\n",57:"radialGradient requries at least 2 color-stops to properly render.\n\n",58:"Please supply a filename to retinaImage() as the first argument.\n\n",59:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",60:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",61:"Property must be a string value.\n\n",62:"borderRadius expects a radius value as a string or number as the second argument.\n\n",63:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',64:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.\n\n",65:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s').\n\n",66:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.\n\n",67:"You must provide a template to this method.\n\n",68:"You passed an unsupported selector state to this method.\n\n",69:'Expected a string ending in "px" or a number passed as the first argument to %s(), got %s instead.\n\n',70:'Expected a string ending in "px" or a number passed as the second argument to %s(), got %s instead.\n\n',71:'Passed invalid pixel value %s to %s(), please pass a value like "12px" or 12.\n\n',72:'Passed invalid base value %s to %s(), please pass a value like "12px" or 12.\n\n',73:"Please provide a valid CSS variable.\n\n",74:"CSS variable not found and no default was provided.\n\n",75:"important requires a valid style object, got a %s instead.\n\n",76:"fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.\n\n",77:'remToPx expects a value in "rem" but you provided it in "%s".\n\n',78:'base must be set in "px" or "%" but you set it in "%s".\n'};function RF(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var i,r=t[0],s=[];for(i=1;i<t.length;i+=1)s.push(t[i]);return s.forEach(function(e){r=r.replace(/%[a-z]/,e)}),r}var CF=function(e){function t(t){var n;if("production"===process.env.NODE_ENV)n=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+t+" for more information.")||this;else{for(var i=arguments.length,r=new Array(i>1?i-1:0),s=1;s<i;s++)r[s-1]=arguments[s];n=e.call(this,RF.apply(void 0,[AF[t]].concat(r)))||this}return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(n)}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,SF(e,t)}(t,e),t}(wF(Error));function NF(e){return Math.round(255*e)}function PF(e,t,n){return NF(e)+","+NF(t)+","+NF(n)}function LF(e,t,n,i){if(void 0===i&&(i=PF),0===t)return i(n,n,n);var r=(e%360+360)%360/60,s=(1-Math.abs(2*n-1))*t,a=s*(1-Math.abs(r%2-1)),o=0,l=0,u=0;r>=0&&r<1?(o=s,l=a):r>=1&&r<2?(o=a,l=s):r>=2&&r<3?(l=s,u=a):r>=3&&r<4?(l=a,u=s):r>=4&&r<5?(o=a,u=s):r>=5&&r<6&&(o=s,u=a);var c=n-s/2;return i(o+c,l+c,u+c)}var DF={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};var IF=/^#[a-fA-F0-9]{6}$/,UF=/^#[a-fA-F0-9]{8}$/,FF=/^#[a-fA-F0-9]{3}$/,OF=/^#[a-fA-F0-9]{4}$/,BF=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,kF=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,zF=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,VF=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function GF(e){if("string"!=typeof e)throw new CF(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return DF[t]?"#"+DF[t]:e}(e);if(t.match(IF))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(UF)){var n=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:n}}if(t.match(FF))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(OF)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var r=BF.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var s=kF.exec(t.substring(0,50));if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10),alpha:parseFloat(""+s[4])>1?parseFloat(""+s[4])/100:parseFloat(""+s[4])};var a=zF.exec(t);if(a){var o="rgb("+LF(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",l=BF.exec(o);if(!l)throw new CF(4,t,o);return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)}}var u=VF.exec(t.substring(0,50));if(u){var c="rgb("+LF(parseInt(""+u[1],10),parseInt(""+u[2],10)/100,parseInt(""+u[3],10)/100)+")",h=BF.exec(c);if(!h)throw new CF(4,t,c);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+u[4])>1?parseFloat(""+u[4])/100:parseFloat(""+u[4])}}throw new CF(5)}function HF(e){return function(e){var t,n=e.red/255,i=e.green/255,r=e.blue/255,s=Math.max(n,i,r),a=Math.min(n,i,r),o=(s+a)/2;if(s===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var l=s-a,u=o>.5?l/(2-s-a):l/(s+a);switch(s){case n:t=(i-r)/l+(i<r?6:0);break;case i:t=(r-n)/l+2;break;default:t=(n-i)/l+4}return t*=60,void 0!==e.alpha?{hue:t,saturation:u,lightness:o,alpha:e.alpha}:{hue:t,saturation:u,lightness:o}}(GF(e))}var jF=function(e){return 7===e.length&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function WF(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function $F(e){return WF(Math.round(255*e))}function XF(e,t,n){return jF("#"+$F(e)+$F(t)+$F(n))}function qF(e,t,n){return LF(e,t,n,XF)}function YF(e,t,n){if("number"==typeof e&&"number"==typeof t&&"number"==typeof n)return jF("#"+WF(e)+WF(t)+WF(n));if("object"==typeof e&&void 0===t&&void 0===n)return jF("#"+WF(e.red)+WF(e.green)+WF(e.blue));throw new CF(6)}function KF(e,t,n,i){if("object"==typeof e&&void 0===t&&void 0===n&&void 0===i)return e.alpha>=1?YF(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new CF(7)}function ZF(e){if("object"!=typeof e)throw new CF(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return KF(e);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return YF(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&"number"==typeof e.alpha}(e))return function(e,t,n,i){if("object"==typeof e&&void 0===t&&void 0===n&&void 0===i)return e.alpha>=1?qF(e.hue,e.saturation,e.lightness):"rgba("+LF(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new CF(2)}(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return function(e,t,n){if("object"==typeof e&&void 0===t&&void 0===n)return qF(e.hue,e.saturation,e.lightness);throw new CF(1)}(e);throw new CF(8)}function QF(e,t,n){return function(){var i=n.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):QF(e,t,i)}}function JF(e){return QF(e,e.length,[])}function eO(e,t,n){return Math.max(e,Math.min(t,n))}JF(function(e,t){if("transparent"===t)return t;var n=HF(t);return ZF(TF({},n,{hue:n.hue+parseFloat(e)}))}),JF(function(e,t){if("transparent"===t)return t;var n=HF(t);return ZF(TF({},n,{lightness:eO(0,1,n.lightness-parseFloat(e))}))}),JF(function(e,t){if("transparent"===t)return t;var n=HF(t);return ZF(TF({},n,{saturation:eO(0,1,n.saturation-parseFloat(e))}))}),JF(function(e,t){if("transparent"===t)return t;var n=HF(t);return ZF(TF({},n,{lightness:eO(0,1,n.lightness+parseFloat(e))}))});var tO=JF(function(e,t,n){if("transparent"===t)return n;if("transparent"===n)return t;if(0===e)return n;var i=GF(t),r=TF({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),s=GF(n),a=TF({},s,{alpha:"number"==typeof s.alpha?s.alpha:1}),o=r.alpha-a.alpha,l=2*parseFloat(e)-1,u=((l*o===-1?l:l+o)/(1+l*o)+1)/2,c=1-u;return KF({red:Math.floor(r.red*u+a.red*c),green:Math.floor(r.green*u+a.green*c),blue:Math.floor(r.blue*u+a.blue*c),alpha:r.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})}),nO=tO;var iO=JF(function(e,t){if("transparent"===t)return t;var n=GF(t);return KF(TF({},n,{alpha:eO(0,1,(100*("number"==typeof n.alpha?n.alpha:1)+100*parseFloat(e))/100)}))}),rO=iO;JF(function(e,t){if("transparent"===t)return t;var n=HF(t);return ZF(TF({},n,{saturation:eO(0,1,n.saturation+parseFloat(e))}))}),JF(function(e,t){return"transparent"===t?t:ZF(TF({},HF(t),{hue:parseFloat(e)}))}),JF(function(e,t){return"transparent"===t?t:ZF(TF({},HF(t),{lightness:parseFloat(e)}))}),JF(function(e,t){return"transparent"===t?t:ZF(TF({},HF(t),{saturation:parseFloat(e)}))}),JF(function(e,t){return"transparent"===t?t:nO(parseFloat(e),"rgb(0, 0, 0)",t)}),JF(function(e,t){return"transparent"===t?t:nO(parseFloat(e),"rgb(255, 255, 255)",t)}),JF(function(e,t){if("transparent"===t)return t;var n=GF(t);return KF(TF({},n,{alpha:eO(0,1,+(100*("number"==typeof n.alpha?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var sO=Object.freeze({Linear:Object.freeze({None:function(e){return e},In:function(e){return e},Out:function(e){return e},InOut:function(e){return e}}),Quadratic:Object.freeze({In:function(e){return e*e},Out:function(e){return e*(2-e)},InOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)}}),Cubic:Object.freeze({In:function(e){return e*e*e},Out:function(e){return--e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)}}),Quartic:Object.freeze({In:function(e){return e*e*e*e},Out:function(e){return 1- --e*e*e*e},InOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)}}),Quintic:Object.freeze({In:function(e){return e*e*e*e*e},Out:function(e){return--e*e*e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)}}),Sinusoidal:Object.freeze({In:function(e){return 1-Math.sin((1-e)*Math.PI/2)},Out:function(e){return Math.sin(e*Math.PI/2)},InOut:function(e){return.5*(1-Math.sin(Math.PI*(.5-e)))}}),Exponential:Object.freeze({In:function(e){return 0===e?0:Math.pow(1024,e-1)},Out:function(e){return 1===e?1:1-Math.pow(2,-10*e)},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?.5*Math.pow(1024,e-1):.5*(2-Math.pow(2,-10*(e-1)))}}),Circular:Object.freeze({In:function(e){return 1-Math.sqrt(1-e*e)},Out:function(e){return Math.sqrt(1- --e*e)},InOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)}}),Elastic:Object.freeze({In:function(e){return 0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)},Out:function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(5*(e-.1)*Math.PI)+1},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?-.5*Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI):.5*Math.pow(2,-10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)+1}}),Back:Object.freeze({In:function(e){var t=1.70158;return 1===e?1:e*e*((t+1)*e-t)},Out:function(e){var t=1.70158;return 0===e?0:--e*e*((t+1)*e+t)+1},InOut:function(e){var t=2.5949095;return(e*=2)<1?e*e*((t+1)*e-t)*.5:.5*((e-=2)*e*((t+1)*e+t)+2)}}),Bounce:Object.freeze({In:function(e){return 1-sO.Bounce.Out(1-e)},Out:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},InOut:function(e){return e<.5?.5*sO.Bounce.In(2*e):.5*sO.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e<Number.EPSILON?Number.EPSILON:e)>1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),aO=function(){return performance.now()},oO=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._tweens={},this._tweensAddedDuringUpdate={},this.add.apply(this,e)}return e.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},e.prototype.removeAll=function(){this._tweens={}},e.prototype.add=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];for(var i=0,r=t;i<r.length;i++){var s=r[i];null===(e=s._group)||void 0===e||e.remove(s),s._group=this,this._tweens[s.getId()]=s,this._tweensAddedDuringUpdate[s.getId()]=s}},e.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=0,i=e;n<i.length;n++){var r=i[n];r._group=void 0,delete this._tweens[r.getId()],delete this._tweensAddedDuringUpdate[r.getId()]}},e.prototype.allStopped=function(){return this.getAll().every(function(e){return!e.isPlaying()})},e.prototype.update=function(e,t){void 0===e&&(e=aO()),void 0===t&&(t=!0);var n=Object.keys(this._tweens);if(0!==n.length)for(;n.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<n.length;i++){var r=this._tweens[n[i]],s=!t;r&&!1===r.update(e,s)&&!t&&this.remove(r)}n=Object.keys(this._tweensAddedDuringUpdate)}},e}(),lO={Linear:function(e,t){var n=e.length-1,i=n*t,r=Math.floor(i),s=lO.Utils.Linear;return t<0?s(e[0],e[1],i):t>1?s(e[n],e[n-1],n-i):s(e[r],e[r+1>n?n:r+1],i-r)},Utils:{Linear:function(e,t,n){return(t-e)*n+e}}},uO=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),cO=new oO,hO=function(){function e(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=sO.Linear.None,this._interpolationFunction=lO.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=uO.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,"object"==typeof t?(this._group=t,t.add(this)):!0===t&&(this._group=cO,cO.add(this))}return e.prototype.getId=function(){return this._id},e.prototype.isPlaying=function(){return this._isPlaying},e.prototype.isPaused=function(){return this._isPaused},e.prototype.getDuration=function(){return this._duration},e.prototype.to=function(e,t){if(void 0===t&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},e.prototype.duration=function(e){return void 0===e&&(e=1e3),this._duration=e<0?0:e,this},e.prototype.dynamic=function(e){return void 0===e&&(e=!1),this._isDynamic=e,this},e.prototype.start=function(e,t){if(void 0===e&&(e=aO()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var n in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var r in this._valuesEnd)i[r]=this._valuesEnd[r];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},e.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},e.prototype._setupProperties=function(e,t,n,i,r){for(var s in n){var a=e[s],o=Array.isArray(a),l=o?"array":typeof a,u=!o&&Array.isArray(n[s]);if("undefined"!==l&&"function"!==l){if(u){if(0===(g=n[s]).length)continue;for(var c=[a],h=0,d=g.length;h<d;h+=1){var p=this._handleRelativeValue(a,g[h]);if(isNaN(p)){u=!1,console.warn("Found invalid interpolation list. Skipping.");break}c.push(p)}u&&(n[s]=c)}if("object"!==l&&!o||!a||u)(void 0===t[s]||r)&&(t[s]=a),o||(t[s]*=1),i[s]=u?n[s].slice().reverse():t[s]||0;else{t[s]=o?[]:{};var f=a;for(var m in f)t[s][m]=f[m];i[s]=o?[]:{};var g=n[s];if(!this._isDynamic){var _={};for(var m in g)_[m]=g[m];n[s]=g=_}this._setupProperties(f,t[s],g,i[s],r)}}}},e.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},e.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},e.prototype.pause=function(e){return void 0===e&&(e=aO()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=aO()),this._isPaused&&this._isPlaying?(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this):this},e.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},e.prototype.group=function(e){return e?(e.add(this),this):(console.warn("tween.group() without args has been removed, use group.add(tween) instead."),this)},e.prototype.remove=function(){var e;return null===(e=this._group)||void 0===e||e.remove(this),this},e.prototype.delay=function(e){return void 0===e&&(e=0),this._delayTime=e,this},e.prototype.repeat=function(e){return void 0===e&&(e=0),this._initialRepeat=e,this._repeat=e,this},e.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},e.prototype.yoyo=function(e){return void 0===e&&(e=!1),this._yoyo=e,this},e.prototype.easing=function(e){return void 0===e&&(e=sO.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=lO.Linear),this._interpolationFunction=e,this},e.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},e.prototype.onStart=function(e){return this._onStartCallback=e,this},e.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},e.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},e.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},e.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},e.prototype.onStop=function(e){return this._onStopCallback=e,this},e.prototype.update=function(t,n){var i,r,s=this;if(void 0===t&&(t=aO()),void 0===n&&(n=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!n)return!1;this.start(t,!0)}if(this._goToEnd=!1,t<this._startTime)return!0;!1===this._onStartCallbackFired&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),!1===this._onEveryStartCallbackFired&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=t-this._startTime,o=this._duration+(null!==(i=this._repeatDelayTime)&&void 0!==i?i:this._delayTime),l=this._duration+this._repeat*o,u=function(){if(0===s._duration)return 1;if(a>l)return 1;var e=Math.trunc(a/o),t=a-e*o,n=Math.min(t/s._duration,1);return 0===n&&a===s._duration?1:n}(),c=this._easingFunction(u);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,c),this._onUpdateCallback&&this._onUpdateCallback(this._object,u),0===this._duration||a>=this._duration){if(this._repeat>0){var h=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(r in isFinite(this._repeat)&&(this._repeat-=h),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[r]||(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*h,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d<p;d++)this._chainedTweens[d].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},e.prototype._updateProperties=function(e,t,n,i){for(var r in n)if(void 0!==t[r]){var s=t[r]||0,a=n[r],o=Array.isArray(e[r]),l=Array.isArray(a);!o&&l?e[r]=this._interpolationFunction(a,i):"object"==typeof a&&a?this._updateProperties(e[r],s,a,i):"number"==typeof(a=this._handleRelativeValue(s,a))&&(e[r]=s+(a-s)*i)}},e.prototype._handleRelativeValue=function(e,t){return"string"!=typeof t?t:"+"===t.charAt(0)||"-"===t.charAt(0)?e+parseFloat(t):parseFloat(t)},e.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],n=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof n?this._valuesStartRepeat[e]+parseFloat(n):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();uO.nextId;var dO=cO;dO.getAll.bind(dO),dO.removeAll.bind(dO),dO.add.bind(dO),dO.remove.bind(dO),dO.update.bind(dO);var pO="http://www.w3.org/1999/xhtml",fO={svg:"http://www.w3.org/2000/svg",xhtml:pO,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function mO(e){var t=e+="",n=t.indexOf(":");return n>=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),fO.hasOwnProperty(t)?{space:fO[t],local:e}:e}function gO(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===pO&&t.documentElement.namespaceURI===pO?t.createElement(e):t.createElementNS(n,e)}}function _O(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function vO(e){var t=mO(e);return(t.local?_O:gO)(t)}function yO(){}function bO(e){return null==e?yO:function(){return this.querySelector(e)}}function xO(){return[]}function TO(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function SO(e){return function(t){return t.matches(e)}}var MO=Array.prototype.find;function EO(){return this.firstElementChild}var wO=Array.prototype.filter;function AO(){return Array.from(this.children)}function RO(e){return new Array(e.length)}function CO(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function NO(e,t,n,i,r,s){for(var a,o=0,l=t.length,u=s.length;o<u;++o)(a=t[o])?(a.__data__=s[o],i[o]=a):n[o]=new CO(e,s[o]);for(;o<l;++o)(a=t[o])&&(r[o]=a)}function PO(e,t,n,i,r,s,a){var o,l,u,c=new Map,h=t.length,d=s.length,p=new Array(h);for(o=0;o<h;++o)(l=t[o])&&(p[o]=u=a.call(l,l.__data__,o,t)+"",c.has(u)?r[o]=l:c.set(u,l));for(o=0;o<d;++o)u=a.call(e,s[o],o,s)+"",(l=c.get(u))?(i[o]=l,l.__data__=s[o],c.delete(u)):n[o]=new CO(e,s[o]);for(o=0;o<h;++o)(l=t[o])&&c.get(p[o])===l&&(r[o]=l)}function LO(e){return e.__data__}function DO(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function IO(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function UO(e){return function(){this.removeAttribute(e)}}function FO(e){return function(){this.removeAttributeNS(e.space,e.local)}}function OO(e,t){return function(){this.setAttribute(e,t)}}function BO(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function kO(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function zO(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function VO(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function GO(e){return function(){this.style.removeProperty(e)}}function HO(e,t,n){return function(){this.style.setProperty(e,t,n)}}function jO(e,t,n){return function(){var i=t.apply(this,arguments);null==i?this.style.removeProperty(e):this.style.setProperty(e,i,n)}}function WO(e){return function(){delete this[e]}}function $O(e,t){return function(){this[e]=t}}function XO(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function qO(e){return e.trim().split(/^|\s+/)}function YO(e){return e.classList||new KO(e)}function KO(e){this._node=e,this._names=qO(e.getAttribute("class")||"")}function ZO(e,t){for(var n=YO(e),i=-1,r=t.length;++i<r;)n.add(t[i])}function QO(e,t){for(var n=YO(e),i=-1,r=t.length;++i<r;)n.remove(t[i])}function JO(e){return function(){ZO(this,e)}}function eB(e){return function(){QO(this,e)}}function tB(e,t){return function(){(t.apply(this,arguments)?ZO:QO)(this,e)}}function nB(){this.textContent=""}function iB(e){return function(){this.textContent=e}}function rB(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function sB(){this.innerHTML=""}function aB(e){return function(){this.innerHTML=e}}function oB(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function lB(){this.nextSibling&&this.parentNode.appendChild(this)}function uB(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function cB(){return null}function hB(){var e=this.parentNode;e&&e.removeChild(this)}function dB(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function pB(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function fB(e){return function(){var t=this.__on;if(t){for(var n,i=0,r=-1,s=t.length;i<s;++i)n=t[i],e.type&&n.type!==e.type||n.name!==e.name?t[++r]=n:this.removeEventListener(n.type,n.listener,n.options);++r?t.length=r:delete this.__on}}}function mB(e,t,n){return function(){var i,r=this.__on,s=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(r)for(var a=0,o=r.length;a<o;++a)if((i=r[a]).type===e.type&&i.name===e.name)return this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=s,i.options=n),void(i.value=t);this.addEventListener(e.type,s,n),i={type:e.type,name:e.name,value:t,listener:s,options:n},r?r.push(i):this.__on=[i]}}function gB(e,t,n){var i=VO(e),r=i.CustomEvent;"function"==typeof r?r=new r(t,n):(r=i.document.createEvent("Event"),n?(r.initEvent(t,n.bubbles,n.cancelable),r.detail=n.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}function _B(e,t){return function(){return gB(this,e,t)}}function vB(e,t){return function(){return gB(this,e,t.apply(this,arguments))}}CO.prototype={constructor:CO,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}},KO.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var yB=[null];function bB(e,t){this._groups=e,this._parents=t}bB.prototype={constructor:bB,select:function(e){"function"!=typeof e&&(e=bO(e));for(var t=this._groups,n=t.length,i=new Array(n),r=0;r<n;++r)for(var s,a,o=t[r],l=o.length,u=i[r]=new Array(l),c=0;c<l;++c)(s=o[c])&&(a=e.call(s,s.__data__,c,o))&&("__data__"in s&&(a.__data__=s.__data__),u[c]=a);return new bB(i,this._parents)},selectAll:function(e){e="function"==typeof e?TO(e):function(e){return null==e?xO:function(){return this.querySelectorAll(e)}}(e);for(var t=this._groups,n=t.length,i=[],r=[],s=0;s<n;++s)for(var a,o=t[s],l=o.length,u=0;u<l;++u)(a=o[u])&&(i.push(e.call(a,a.__data__,u,o)),r.push(a));return new bB(i,r)},selectChild:function(e){return this.select(null==e?EO:function(e){return function(){return MO.call(this.children,e)}}("function"==typeof e?e:SO(e)))},selectChildren:function(e){return this.selectAll(null==e?AO:function(e){return function(){return wO.call(this.children,e)}}("function"==typeof e?e:SO(e)))},filter:function(e){"function"!=typeof e&&(e=function(e){return function(){return this.matches(e)}}(e));for(var t=this._groups,n=t.length,i=new Array(n),r=0;r<n;++r)for(var s,a=t[r],o=a.length,l=i[r]=[],u=0;u<o;++u)(s=a[u])&&e.call(s,s.__data__,u,a)&&l.push(s);return new bB(i,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,LO);var n=t?PO:NO,i=this._parents,r=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var s=r.length,a=new Array(s),o=new Array(s),l=new Array(s),u=0;u<s;++u){var c=i[u],h=r[u],d=h.length,p=DO(e.call(c,c&&c.__data__,u,i)),f=p.length,m=o[u]=new Array(f),g=a[u]=new Array(f);n(c,h,m,g,l[u]=new Array(d),p,t);for(var _,v,y=0,b=0;y<f;++y)if(_=m[y]){for(y>=b&&(b=y+1);!(v=g[b])&&++b<f;);_._next=v||null}}return(a=new bB(a,i))._enter=o,a._exit=l,a},enter:function(){return new bB(this._enter||this._groups.map(RO),this._parents)},exit:function(){return new bB(this._exit||this._groups.map(RO),this._parents)},join:function(e,t,n){var i=this.enter(),r=this,s=this.exit();return"function"==typeof e?(i=e(i))&&(i=i.selection()):i=i.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==n?s.remove():n(s),i&&r?i.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,n=this._groups,i=t._groups,r=n.length,s=i.length,a=Math.min(r,s),o=new Array(r),l=0;l<a;++l)for(var u,c=n[l],h=i[l],d=c.length,p=o[l]=new Array(d),f=0;f<d;++f)(u=c[f]||h[f])&&(p[f]=u);for(;l<r;++l)o[l]=n[l];return new bB(o,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var i,r=e[t],s=r.length-1,a=r[s];--s>=0;)(i=r[s])&&(a&&4^i.compareDocumentPosition(a)&&a.parentNode.insertBefore(i,a),a=i);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||(e=IO);for(var n=this._groups,i=n.length,r=new Array(i),s=0;s<i;++s){for(var a,o=n[s],l=o.length,u=r[s]=new Array(l),c=0;c<l;++c)(a=o[c])&&(u[c]=a);u.sort(t)}return new bB(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var i=e[t],r=0,s=i.length;r<s;++r){var a=i[r];if(a)return a}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,n=0,i=t.length;n<i;++n)for(var r,s=t[n],a=0,o=s.length;a<o;++a)(r=s[a])&&e.call(r,r.__data__,a,s);return this},attr:function(e,t){var n=mO(e);if(arguments.length<2){var i=this.node();return n.local?i.getAttributeNS(n.space,n.local):i.getAttribute(n)}return this.each((null==t?n.local?FO:UO:"function"==typeof t?n.local?zO:kO:n.local?BO:OO)(n,t))},style:function(e,t,n){return arguments.length>1?this.each((null==t?GO:"function"==typeof t?jO:HO)(e,t,null==n?"":n)):function(e,t){return e.style.getPropertyValue(t)||VO(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?WO:"function"==typeof t?XO:$O)(e,t)):this.node()[e]},classed:function(e,t){var n=qO(e+"");if(arguments.length<2){for(var i=YO(this.node()),r=-1,s=n.length;++r<s;)if(!i.contains(n[r]))return!1;return!0}return this.each(("function"==typeof t?tB:t?JO:eB)(n,t))},text:function(e){return arguments.length?this.each(null==e?nB:("function"==typeof e?rB:iB)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?sB:("function"==typeof e?oB:aB)(e)):this.node().innerHTML},raise:function(){return this.each(lB)},lower:function(){return this.each(uB)},append:function(e){var t="function"==typeof e?e:vO(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var n="function"==typeof e?e:vO(e),i=null==t?cB:"function"==typeof t?t:bO(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),i.apply(this,arguments)||null)})},remove:function(){return this.each(hB)},clone:function(e){return this.select(e?pB:dB)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,n){var i,r,s=function(e){return e.trim().split(/^|\s+/).map(function(e){var t="",n=e.indexOf(".");return n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}(e+""),a=s.length;if(!(arguments.length<2)){for(o=t?mB:fB,i=0;i<a;++i)this.each(o(s[i],t,n));return this}var o=this.node().__on;if(o)for(var l,u=0,c=o.length;u<c;++u)for(i=0,l=o[u];i<a;++i)if((r=s[i]).type===l.type&&r.name===l.name)return l.value},dispatch:function(e,t){return this.each(("function"==typeof t?vB:_B)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var i,r=e[t],s=0,a=r.length;s<a;++s)(i=r[s])&&(yield i)}};var xB,TB,SB,MB,EB,wB,AB,RB,CB,NB,PB,LB,DB,IB,UB,FB={},OB=[],BB=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,kB=Array.isArray;function zB(e,t){for(var n in t)e[n]=t[n];return e}function VB(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function GB(e,t,n,i,r){var s={type:e,props:t,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++SB:r,__i:-1,__u:0};return null==r&&null!=TB.vnode&&TB.vnode(s),s}function HB(e){return e.children}function jB(e,t){this.props=e,this.context=t}function WB(e,t){if(null==t)return e.__?WB(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?WB(e):null}function $B(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,i=[],r=[],s=zB({},t);s.__v=t.__v+1,TB.vnode&&TB.vnode(s),ik(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,i,null==n?WB(t):n,!!(32&t.__u),r),s.__v=t.__v,s.__.__k[s.__i]=s,sk(i,s,r),t.__e=t.__=null,s.__e!=n&&XB(s)}}function XB(e){if(null!=(e=e.__)&&null!=e.__c)return e.__e=e.__c.base=null,e.__k.some(function(t){if(null!=t&&null!=t.__e)return e.__e=e.__c.base=t.__e}),XB(e)}function qB(e){(!e.__d&&(e.__d=!0)&&EB.push(e)&&!YB.__r++||wB!=TB.debounceRendering)&&((wB=TB.debounceRendering)||AB)(YB)}function YB(){try{for(var e,t=1;EB.length;)EB.length>t&&EB.sort(RB),e=EB.shift(),t=EB.length,$B(e)}finally{EB.length=YB.__r=0}}function KB(e,t,n,i,r,s,a,o,l,u,c){var h,d,p,f,m,g,_,v=i&&i.__k||OB,y=t.length;for(l=ZB(n,t,v,l,y),h=0;h<y;h++)null!=(p=n.__k[h])&&(d=-1!=p.__i&&v[p.__i]||FB,p.__i=h,g=ik(e,p,d,r,s,a,o,l,u,c),f=p.__e,p.ref&&d.ref!=p.ref&&(d.ref&&lk(d.ref,null,p),c.push(p.ref,p.__c||f,p)),null==m&&null!=f&&(m=f),(_=!!(4&p.__u))||d.__k===p.__k?(l=QB(p,l,e,_),_&&d.__e&&(d.__e=null)):"function"==typeof p.type&&void 0!==g?l=g:f&&(l=f.nextSibling),p.__u&=-7);return n.__e=m,l}function ZB(e,t,n,i,r){var s,a,o,l,u,c=n.length,h=c,d=0;for(e.__k=new Array(r),s=0;s<r;s++)null!=(a=t[s])&&"boolean"!=typeof a&&"function"!=typeof a?("string"==typeof a||"number"==typeof a||"bigint"==typeof a||a.constructor==String?a=e.__k[s]=GB(null,a,null,null,null):kB(a)?a=e.__k[s]=GB(HB,{children:a},null,null,null):void 0===a.constructor&&a.__b>0?a=e.__k[s]=GB(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[s]=a,l=s+d,a.__=e,a.__b=e.__b+1,o=null,-1!=(u=a.__i=JB(a,n,l,h))&&(h--,(o=n[u])&&(o.__u|=2)),null==o||null==o.__v?(-1==u&&(r>c?d--:r<c&&d++),"function"!=typeof a.type&&(a.__u|=4)):u!=l&&(u==l-1?d--:u==l+1?d++:(u>l?d--:d++,a.__u|=4))):e.__k[s]=null;if(h)for(s=0;s<c;s++)null!=(o=n[s])&&!(2&o.__u)&&(o.__e==i&&(i=WB(o)),uk(o,o));return i}function QB(e,t,n,i){var r,s;if("function"==typeof e.type){for(r=e.__k,s=0;r&&s<r.length;s++)r[s]&&(r[s].__=e,t=QB(r[s],t,n,i));return t}e.__e!=t&&(i&&(t&&e.type&&!t.parentNode&&(t=WB(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function JB(e,t,n,i){var r,s,a,o=e.key,l=e.type,u=t[n],c=null!=u&&!(2&u.__u);if(null===u&&null==o||c&&o==u.key&&l==u.type)return n;if(i>(c?1:0))for(r=n-1,s=n+1;r>=0||s<t.length;)if(null!=(u=t[a=r>=0?r--:s++])&&!(2&u.__u)&&o==u.key&&l==u.type)return a;return-1}function ek(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||BB.test(t)?n:n+"px"}function tk(e,t,n,i,r){var s,a;e:if("style"==t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof i&&(e.style.cssText=i=""),i)for(t in i)n&&t in n||ek(e.style,t,"");if(n)for(t in n)i&&n[t]==i[t]||ek(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])s=t!=(t=t.replace(LB,"$1")),a=t.toLowerCase(),t=a in e||"onFocusOut"==t||"onFocusIn"==t?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=n,n?i?n[PB]=i[PB]:(n[PB]=DB,e.addEventListener(t,s?UB:IB,s)):e.removeEventListener(t,s?UB:IB,s);else{if("http://www.w3.org/2000/svg"==r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function nk(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t[NB])t[NB]=DB++;else if(t[NB]<n[PB])return;return n(TB.event?TB.event(t):t)}}}function ik(e,t,n,i,r,s,a,o,l,u){var c,h,d,p,f,m,g,_,v,y,b,x,T,S,M,E=t.type;if(void 0!==t.constructor)return null;128&n.__u&&(l=!!(32&n.__u),s=[o=t.__e=n.__e]),(c=TB.__b)&&c(t);e:if("function"==typeof E)try{if(_=t.props,v=E.prototype&&E.prototype.render,y=(c=E.contextType)&&i[c.__c],b=c?y?y.props.value:c.__:i,n.__c?g=(h=t.__c=n.__c).__=h.__E:(v?t.__c=h=new E(_,b):(t.__c=h=new jB(_,b),h.constructor=E,h.render=ck),y&&y.sub(h),h.state||(h.state={}),h.__n=i,d=h.__d=!0,h.__h=[],h._sb=[]),v&&null==h.__s&&(h.__s=h.state),v&&null!=E.getDerivedStateFromProps&&(h.__s==h.state&&(h.__s=zB({},h.__s)),zB(h.__s,E.getDerivedStateFromProps(_,h.__s))),p=h.props,f=h.state,h.__v=t,d)v&&null==E.getDerivedStateFromProps&&null!=h.componentWillMount&&h.componentWillMount(),v&&null!=h.componentDidMount&&h.__h.push(h.componentDidMount);else{if(v&&null==E.getDerivedStateFromProps&&_!==p&&null!=h.componentWillReceiveProps&&h.componentWillReceiveProps(_,b),t.__v==n.__v||!h.__e&&null!=h.shouldComponentUpdate&&!1===h.shouldComponentUpdate(_,h.__s,b)){t.__v!=n.__v&&(h.props=_,h.state=h.__s,h.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(e){e&&(e.__=t)}),OB.push.apply(h.__h,h._sb),h._sb=[],h.__h.length&&a.push(h);break e}null!=h.componentWillUpdate&&h.componentWillUpdate(_,h.__s,b),v&&null!=h.componentDidUpdate&&h.__h.push(function(){h.componentDidUpdate(p,f,m)})}if(h.context=b,h.props=_,h.__P=e,h.__e=!1,x=TB.__r,T=0,v)h.state=h.__s,h.__d=!1,x&&x(t),c=h.render(h.props,h.state,h.context),OB.push.apply(h.__h,h._sb),h._sb=[];else do{h.__d=!1,x&&x(t),c=h.render(h.props,h.state,h.context),h.state=h.__s}while(h.__d&&++T<25);h.state=h.__s,null!=h.getChildContext&&(i=zB(zB({},i),h.getChildContext())),v&&!d&&null!=h.getSnapshotBeforeUpdate&&(m=h.getSnapshotBeforeUpdate(p,f)),S=null!=c&&c.type===HB&&null==c.key?ak(c.props.children):c,o=KB(e,kB(S)?S:[S],t,n,i,r,s,a,o,l,u),h.base=t.__e,t.__u&=-161,h.__h.length&&a.push(h),g&&(h.__E=h.__=null)}catch(e){if(t.__v=null,l||null!=s)if(e.then){for(t.__u|=l?160:128;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;s[s.indexOf(o)]=null,t.__e=o}else{for(M=s.length;M--;)VB(s[M]);rk(t)}else t.__e=n.__e,t.__k=n.__k,e.then||rk(t);TB.__e(e,t,n)}else null==s&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):o=t.__e=ok(n.__e,t,n,i,r,s,a,l,u);return(c=TB.diffed)&&c(t),128&t.__u?void 0:o}function rk(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(rk))}function sk(e,t,n){for(var i=0;i<n.length;i++)lk(n[i],n[++i],n[++i]);TB.__c&&TB.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){TB.__e(e,t.__v)}})}function ak(e){return"object"!=typeof e||null==e||e.__b>0?e:kB(e)?e.map(ak):zB({},e)}function ok(e,t,n,i,r,s,a,o,l){var u,c,h,d,p,f,m,g=n.props||FB,_=t.props,v=t.type;if("svg"==v?r="http://www.w3.org/2000/svg":"math"==v?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=s)for(u=0;u<s.length;u++)if((p=s[u])&&"setAttribute"in p==!!v&&(v?p.localName==v:3==p.nodeType)){e=p,s[u]=null;break}if(null==e){if(null==v)return document.createTextNode(_);e=document.createElementNS(r,v,_.is&&_),o&&(TB.__m&&TB.__m(t,s),o=!1),s=null}if(null==v)g===_||o&&e.data==_||(e.data=_);else{if(s=s&&xB.call(e.childNodes),!o&&null!=s)for(g={},u=0;u<e.attributes.length;u++)g[(p=e.attributes[u]).name]=p.value;for(u in g)p=g[u],"dangerouslySetInnerHTML"==u?h=p:"children"==u||u in _||"value"==u&&"defaultValue"in _||"checked"==u&&"defaultChecked"in _||tk(e,u,null,p,r);for(u in _)p=_[u],"children"==u?d=p:"dangerouslySetInnerHTML"==u?c=p:"value"==u?f=p:"checked"==u?m=p:o&&"function"!=typeof p||g[u]===p||tk(e,u,p,g[u],r);if(c)o||h&&(c.__html==h.__html||c.__html==e.innerHTML)||(e.innerHTML=c.__html),t.__k=[];else if(h&&(e.innerHTML=""),KB("template"==t.type?e.content:e,kB(d)?d:[d],t,n,i,"foreignObject"==v?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:n.__k&&WB(n,0),o,l),null!=s)for(u=s.length;u--;)VB(s[u]);o||(u="value","progress"==v&&null==f?e.removeAttribute("value"):null!=f&&(f!==e[u]||"progress"==v&&!f||"option"==v&&f!=g[u])&&tk(e,u,f,g[u],r),u="checked",null!=m&&m!=e[u]&&tk(e,u,m,g[u],r))}return e}function lk(e,t,n){try{if("function"==typeof e){var i="function"==typeof e.__u;i&&e.__u(),i&&null==t||(e.__u=e(t))}else e.current=t}catch(e){TB.__e(e,n)}}function uk(e,t,n){var i,r;if(TB.unmount&&TB.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||lk(i,null,t)),null!=(i=e.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(e){TB.__e(e,t)}i.base=i.__P=null}if(i=e.__k)for(r=0;r<i.length;r++)i[r]&&uk(i[r],t,n||"function"!=typeof e.type);n||VB(e.__e),e.__c=e.__=e.__e=void 0}function ck(e,t,n){return this.constructor(e,n)}function hk(e,t,n){var i,r,s;t==document&&(t=document.documentElement),TB.__&&TB.__(e,t),i=!1?null:t.__k,r=[],s=[],ik(t,e=t.__k=function(e,t,n){var i,r,s,a={};for(s in t)"key"==s?i=t[s]:"ref"==s?r=t[s]:a[s]=t[s];if(arguments.length>2&&(a.children=arguments.length>3?xB.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return GB(e,a,i,r,null)}(HB,null,[e]),i||FB,FB,t.namespaceURI,i?null:t.firstChild?xB.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,s),sk(r,e,s)}function dk(e,t,n){var i,r,s,a,o=zB({},e.props);for(s in e.type&&e.type.defaultProps&&(a=e.type.defaultProps),t)"key"==s?i=t[s]:"ref"==s?r=t[s]:o[s]=void 0===t[s]&&null!=a?a[s]:t[s];return arguments.length>2&&(o.children=arguments.length>3?xB.call(arguments,2):n),GB(e.type,o,i||e.key,r||e.ref,null)}function pk(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function fk(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function mk(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,i)}return n}function gk(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(i=s.call(n)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,r=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return pk(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?pk(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _k(e){return _k="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_k(e)}xB=OB.slice,TB={__e:function(e,t,n,i){for(var r,s,a;t=t.__;)if((r=t.__c)&&!r.__)try{if((s=r.constructor)&&null!=s.getDerivedStateFromError&&(r.setState(s.getDerivedStateFromError(e)),a=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(e,i||{}),a=r.__d),a)return r.__E=r}catch(t){e=t}throw e}},SB=0,MB=function(e){return null!=e&&void 0===e.constructor},jB.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=zB({},this.state),"function"==typeof e&&(e=e(zB({},n),this.props)),e&&zB(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),qB(this))},jB.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),qB(this))},jB.prototype.render=HB,EB=[],AB="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,RB=function(e,t){return e.__v.__b-t.__v.__b},YB.__r=0,CB=Math.random().toString(8),NB="__d"+CB,PB="__a"+CB,LB=/(PointerCapture)$|Capture$/i,DB=0,IB=nk(!1),UB=nk(!0);var vk=function(e){if("object"!==_k(e))return e;var t,n=dk(e);n.props&&(n.props=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?mk(Object(n),!0).forEach(function(t){fk(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mk(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({},n.props),null!=n&&null!==(t=n.props)&&void 0!==t&&t.children&&(n.props.children=Array.isArray(n.props.children)?n.props.children.map(vk):vk(n.props.children)));return n};!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===n&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".float-tooltip-kap {\n position: absolute;\n width: max-content; /* prevent shrinking near right edge */\n max-width: max(50%, 150px);\n padding: 3px 5px;\n border-radius: 3px;\n font: 12px sans-serif;\n color: #eee;\n background: rgba(0,0,0,0.6);\n pointer-events: none;\n}\n");var yk=Pd({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},init:function(e,t){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).style,i=void 0===n?{}:n,r=function(e){return"string"==typeof e?new bB([[document.querySelector(e)]],[document.documentElement]):new bB([[e]],yB)}(!!e&&"object"===_k(e)&&!!e.node&&"function"==typeof e.node?e.node():e);"static"===r.style("position")&&r.style("position","relative"),t.tooltipEl=r.append("div").attr("class","float-tooltip-kap"),Object.entries(i).forEach(function(e){var n=gk(e,2),i=n[0],r=n[1];return t.tooltipEl.style(i,r)}),t.tooltipEl.style("left","-10000px").style("display","none");var s="tooltip-".concat(Math.round(1e12*Math.random()));t.mouseInside=!1,r.on("mousemove.".concat(s),function(e){t.mouseInside=!0;var n=function(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var i=n.createSVGPoint();return i.x=e.clientX,i.y=e.clientY,[(i=i.matrixTransform(t.getScreenCTM().inverse())).x,i.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}(e),i=r.node(),s=i.offsetWidth,a=i.offsetHeight,o=[null===t.offsetX||void 0===t.offsetX?"-".concat(n[0]/s*100,"%"):"number"==typeof t.offsetX?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,null===t.offsetY||void 0===t.offsetY?a>130&&a-n[1]<100?"calc(-100% - 6px)":"21px":"number"==typeof t.offsetY?t.offsetY<0?"calc(-100% - ".concat(Math.abs(t.offsetY),"px)"):"".concat(t.offsetY,"px"):t.offsetY];t.tooltipEl.style("left",n[0]+"px").style("top",n[1]+"px").style("transform","translate(".concat(o.join(","),")")),t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseover.".concat(s),function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseout.".concat(s),function(){t.mouseInside=!1,t.tooltipEl.style("display","none")})},update:function(e){var t,n;e.tooltipEl.style("display",e.content&&e.mouseInside?"inline":"none"),e.content?e.content instanceof HTMLElement?(e.tooltipEl.text(""),e.tooltipEl.append(function(){return e.content})):"string"==typeof e.content?e.tooltipEl.html(e.content):!function(e){return MB(dk(e))}(e.content)?(e.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",e.content,e.content.toString())):(e.tooltipEl.text(""),t=e.content,delete(n=e.tooltipEl.node()).__k,hk(vk(t),n)):e.tooltipEl.text("")}});function bk(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function xk(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Tk(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(i=s.call(n)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){u=!0,r=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw r}}return o}}(e,t)||Mk(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Sk(e){return function(e){if(Array.isArray(e))return bk(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||Mk(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Mk(e,t){if(e){if("string"==typeof e)return bk(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?bk(e,t):void 0}}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===n&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".scene-nav-info {\n position: absolute;\n bottom: 5px;\n width: 100%;\n text-align: center;\n color: slategrey;\n opacity: 0.7;\n font-size: 10px;\n font-family: sans-serif;\n pointer-events: none;\n user-select: none;\n}\n\n.scene-container canvas:focus {\n outline: none;\n}");var Ek=function(e){e instanceof Array?e.forEach(Ek):(e.map&&e.map.dispose(),e.dispose())},wk=function(e){e.geometry&&e.geometry.dispose(),e.material&&Ek(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(wk)},Ak=window.THREE?window.THREE:{WebGLRenderer:class{constructor(e={}){const{canvas:t=Ht(),context:n=null,depth:i=!0,stencil:r=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:u=!1,powerPreference:c="default",failIfMajorPerformanceCaveat:h=!1,reversedDepthBuffer:d=!1,outputBufferType:p=fe}=e;let f;if(this.isWebGLRenderer=!0,null!==n){if("undefined"!=typeof WebGLRenderingContext&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=n.getContextAttributes().alpha}else f=a;const m=p,g=new Set([Fe,Ue,De]),_=new Set([fe,ye,_e,Me,Te,Se]),v=new Uint32Array(4),y=new Int32Array(4);let b=null,x=null;const T=[],S=[];let M=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const E=this;let w=!1;this._outputColorSpace=bt;let A=0,R=0,C=null,N=-1,P=null;const L=new Pn,D=new Pn;let I=null;const U=new _i(0);let F=0,O=t.width,B=t.height,k=1,z=null,V=null;const G=new Pn(0,0,O,B),H=new Pn(0,0,O,B);let j=!1;const W=new ns;let $=!1,X=!1;const q=new Fn,Y=new dn,K=new Pn,Z={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Q=!1;function J(){return null===C?k:1}let ee,te,ne,ie,re,se,oe,le,ue,ce,de,me,ge,ve,be,Ee,we,Ae,Re,Ce,Ne,Pe,Le,Oe=n;function Be(e,n){return t.getContext(e,n)}try{const e={alpha:!0,depth:i,stencil:r,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:u,powerPreference:c,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${s}`),t.addEventListener("webglcontextlost",Ve,!1),t.addEventListener("webglcontextrestored",Ge,!1),t.addEventListener("webglcontextcreationerror",He,!1),null===Oe){const t="webgl2";if(Oe=Be(t,e),null===Oe)throw Be(t)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(e){throw qt("WebGLRenderer: "+e.message),e}function ke(){ee=new wo(Oe),ee.init(),Ne=new Du(Oe,ee),te=new ao(Oe,ee,e,Ne),ne=new Pu(Oe,ee),te.reversedDepthBuffer&&d&&ne.buffers.depth.setReversed(!0),ie=new Co(Oe),re=new fu,se=new Lu(Oe,ee,ne,re,te,Ne,ie),oe=new Eo(E),le=new Ka(Oe),Pe=new ro(Oe,le),ue=new Ao(Oe,le,ie,Pe),ce=new Po(Oe,ue,le,Pe,ie),Ae=new No(Oe,te,se),be=new oo(re),de=new pu(E,oe,ee,te,Pe,be),me=new Bu(E,re),ge=new vu,ve=new Mu(ee),we=new io(E,oe,ne,ce,f,l),Ee=new Nu(E,ce,te),Le=new ku(Oe,ie,te,ne),Re=new so(Oe,ee,ie),Ce=new Ro(Oe,ee,ie),ie.programs=de.programs,E.capabilities=te,E.extensions=ee,E.properties=re,E.renderLists=ge,E.shadowMap=Ee,E.state=ne,E.info=ie}ke(),m!==fe&&(M=new Do(m,t.width,t.height,i,r));const ze=new Uu(E,Oe);function Ve(e){e.preventDefault(),Wt("WebGLRenderer: Context Lost."),w=!0}function Ge(){Wt("WebGLRenderer: Context Restored."),w=!1;const e=ie.autoReset,t=Ee.enabled,n=Ee.autoUpdate,i=Ee.needsUpdate,r=Ee.type;ke(),ie.autoReset=e,Ee.enabled=t,Ee.autoUpdate=n,Ee.needsUpdate=i,Ee.type=r}function He(e){qt("WebGLRenderer: A WebGL context could not be created. Reason: ",e.statusMessage)}function je(e){const t=e.target;t.removeEventListener("dispose",je),function(e){(function(e){const t=re.get(e).programs;void 0!==t&&(t.forEach(function(e){de.releaseProgram(e)}),e.isShaderMaterial&&de.releaseShaderCache(e))})(e),re.remove(e)}(t)}function We(e,t,n){!0===e.transparent&&2===e.side&&!1===e.forceSinglePass?(e.side=1,e.needsUpdate=!0,tt(e,t,n),e.side=0,e.needsUpdate=!0,tt(e,t,n),e.side=2):tt(e,t,n)}this.xr=ze,this.getContext=function(){return Oe},this.getContextAttributes=function(){return Oe.getContextAttributes()},this.forceContextLoss=function(){const e=ee.get("WEBGL_lose_context");e&&e.loseContext()},this.forceContextRestore=function(){const e=ee.get("WEBGL_lose_context");e&&e.restoreContext()},this.getPixelRatio=function(){return k},this.setPixelRatio=function(e){void 0!==e&&(k=e,this.setSize(O,B,!1))},this.getSize=function(e){return e.set(O,B)},this.setSize=function(e,n,i=!0){ze.isPresenting?Xt("WebGLRenderer: Can't change size while VR device is presenting."):(O=e,B=n,t.width=Math.floor(e*k),t.height=Math.floor(n*k),!0===i&&(t.style.width=e+"px",t.style.height=n+"px"),null!==M&&M.setSize(t.width,t.height),this.setViewport(0,0,e,n))},this.getDrawingBufferSize=function(e){return e.set(O*k,B*k).floor()},this.setDrawingBufferSize=function(e,n,i){O=e,B=n,k=i,t.width=Math.floor(e*i),t.height=Math.floor(n*i),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(m!==fe){if(e)for(let t=0;t<e.length;t++)if(!0===e[t].isOutputPass){console.warn("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}M.setEffects(e||[])}else console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.")},this.getCurrentViewport=function(e){return e.copy(L)},this.getViewport=function(e){return e.copy(G)},this.setViewport=function(e,t,n,i){e.isVector4?G.set(e.x,e.y,e.z,e.w):G.set(e,t,n,i),ne.viewport(L.copy(G).multiplyScalar(k).round())},this.getScissor=function(e){return e.copy(H)},this.setScissor=function(e,t,n,i){e.isVector4?H.set(e.x,e.y,e.z,e.w):H.set(e,t,n,i),ne.scissor(D.copy(H).multiplyScalar(k).round())},this.getScissorTest=function(){return j},this.setScissorTest=function(e){ne.setScissorTest(j=e)},this.setOpaqueSort=function(e){z=e},this.setTransparentSort=function(e){V=e},this.getClearColor=function(e){return e.copy(we.getClearColor())},this.setClearColor=function(){we.setClearColor(...arguments)},this.getClearAlpha=function(){return we.getClearAlpha()},this.setClearAlpha=function(){we.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let i=0;if(e){let e=!1;if(null!==C){const t=C.texture.format;e=g.has(t)}if(e){const e=C.texture.type,t=_.has(e),n=we.getClearColor(),i=we.getClearAlpha(),r=n.r,s=n.g,a=n.b;t?(v[0]=r,v[1]=s,v[2]=a,v[3]=i,Oe.clearBufferuiv(Oe.COLOR,0,v)):(y[0]=r,y[1]=s,y[2]=a,y[3]=i,Oe.clearBufferiv(Oe.COLOR,0,y))}else i|=Oe.COLOR_BUFFER_BIT}t&&(i|=Oe.DEPTH_BUFFER_BIT),n&&(i|=Oe.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),0!==i&&Oe.clear(i)},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",Ve,!1),t.removeEventListener("webglcontextrestored",Ge,!1),t.removeEventListener("webglcontextcreationerror",He,!1),we.dispose(),ge.dispose(),ve.dispose(),re.dispose(),oe.dispose(),ce.dispose(),Pe.dispose(),Le.dispose(),de.dispose(),ze.dispose(),ze.removeEventListener("sessionstart",Xe),ze.removeEventListener("sessionend",qe),Ye.stop()},this.renderBufferDirect=function(e,t,n,i,r,s){null===t&&(t=Z);const a=r.isMesh&&r.matrixWorld.determinant()<0,o=function(e,t,n,i,r){!0!==t.isScene&&(t=Z);se.resetTextureUnits();const s=t.fog,a=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?t.environment:null,o=null===C?E.outputColorSpace:!0===C.isXRRenderTarget?C.texture.colorSpace:xt,l=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,u=oe.get(i.envMap||a,l),c=!0===i.vertexColors&&!!n.attributes.color&&4===n.attributes.color.itemSize,h=!!n.attributes.tangent&&(!!i.normalMap||i.anisotropy>0),d=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,f=!!n.morphAttributes.color;let m=0;i.toneMapped&&(null!==C&&!0!==C.isXRRenderTarget||(m=E.toneMapping));const g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=void 0!==g?g.length:0,v=re.get(i),y=x.state.lights;if(!0===$&&(!0===X||e!==P)){const t=e===P&&i.id===N;be.setState(i,e,t)}let b=!1;i.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version||v.outputColorSpace!==o||r.isBatchedMesh&&!1===v.batching?b=!0:r.isBatchedMesh||!0!==v.batching?r.isBatchedMesh&&!0===v.batchingColor&&null===r.colorTexture||r.isBatchedMesh&&!1===v.batchingColor&&null!==r.colorTexture||r.isInstancedMesh&&!1===v.instancing?b=!0:r.isInstancedMesh||!0!==v.instancing?r.isSkinnedMesh&&!1===v.skinning?b=!0: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!==u||!0===i.fog&&v.fog!==s?b=!0:void 0===v.numClippingPlanes||v.numClippingPlanes===be.numPlanes&&v.numIntersection===be.numIntersection?(v.vertexAlphas!==c||v.vertexTangents!==h||v.morphTargets!==d||v.morphNormals!==p||v.morphColors!==f||v.toneMapping!==m||v.morphTargetsCount!==_)&&(b=!0):b=!0:b=!0:b=!0:b=!0:(b=!0,v.__version=i.version);let T=v.currentProgram;!0===b&&(T=tt(i,t,r));let S=!1,M=!1,w=!1;const A=T.getUniforms(),R=v.uniforms;ne.useProgram(T.program)&&(S=!0,M=!0,w=!0);i.id!==N&&(N=i.id,M=!0);if(S||P!==e){ne.buffers.depth.getReversed()&&!0!==e.reversedDepth&&(e._reversedDepth=!0,e.updateProjectionMatrix()),A.setValue(Oe,"projectionMatrix",e.projectionMatrix),A.setValue(Oe,"viewMatrix",e.matrixWorldInverse);const t=A.map.cameraPosition;void 0!==t&&t.setValue(Oe,Y.setFromMatrixPosition(e.matrixWorld)),te.logarithmicDepthBuffer&&A.setValue(Oe,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&A.setValue(Oe,"isOrthographic",!0===e.isOrthographicCamera),P!==e&&(P=e,M=!0,w=!0)}v.needsLights&&(y.state.directionalShadowMap.length>0&&A.setValue(Oe,"directionalShadowMap",y.state.directionalShadowMap,se),y.state.spotShadowMap.length>0&&A.setValue(Oe,"spotShadowMap",y.state.spotShadowMap,se),y.state.pointShadowMap.length>0&&A.setValue(Oe,"pointShadowMap",y.state.pointShadowMap,se));if(r.isSkinnedMesh){A.setOptional(Oe,r,"bindMatrix"),A.setOptional(Oe,r,"bindMatrixInverse");const e=r.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),A.setValue(Oe,"boneTexture",e.boneTexture,se))}r.isBatchedMesh&&(A.setOptional(Oe,r,"batchingTexture"),A.setValue(Oe,"batchingTexture",r._matricesTexture,se),A.setOptional(Oe,r,"batchingIdTexture"),A.setValue(Oe,"batchingIdTexture",r._indirectTexture,se),A.setOptional(Oe,r,"batchingColorTexture"),null!==r._colorsTexture&&A.setValue(Oe,"batchingColorTexture",r._colorsTexture,se));const L=n.morphAttributes;void 0===L.position&&void 0===L.normal&&void 0===L.color||Ae.update(r,n,T);(M||v.receiveShadow!==r.receiveShadow)&&(v.receiveShadow=r.receiveShadow,A.setValue(Oe,"receiveShadow",r.receiveShadow));(i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial)&&null===i.envMap&&null!==t.environment&&(R.envMapIntensity.value=t.environmentIntensity);void 0!==R.dfgLUT&&(R.dfgLUT.value=(null===Vu&&(Vu=new Xr(zu,16,16,Ie,xe),Vu.name="DFG_LUT",Vu.minFilter=he,Vu.magFilter=he,Vu.wrapS=ae,Vu.wrapT=ae,Vu.generateMipmaps=!1,Vu.needsUpdate=!0),Vu));M&&(A.setValue(Oe,"toneMappingExposure",E.toneMappingExposure),v.needsLights&&(I=w,(D=R).ambientLightColor.needsUpdate=I,D.lightProbe.needsUpdate=I,D.directionalLights.needsUpdate=I,D.directionalLightShadows.needsUpdate=I,D.pointLights.needsUpdate=I,D.pointLightShadows.needsUpdate=I,D.spotLights.needsUpdate=I,D.spotLightShadows.needsUpdate=I,D.rectAreaLights.needsUpdate=I,D.hemisphereLights.needsUpdate=I),s&&!0===i.fog&&me.refreshFogUniforms(R,s),me.refreshMaterialUniforms(R,i,k,B,x.state.transmissionRenderTarget[e.id]),Bl.upload(Oe,nt(v),R,se));var D,I;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(Bl.upload(Oe,nt(v),R,se),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&A.setValue(Oe,"center",r.center);if(A.setValue(Oe,"modelViewMatrix",r.modelViewMatrix),A.setValue(Oe,"normalMatrix",r.normalMatrix),A.setValue(Oe,"modelMatrix",r.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const e=i.uniformsGroups;for(let t=0,n=e.length;t<n;t++){const n=e[t];Le.update(n,T),Le.bind(n,T)}}return T}(e,t,n,i,r);ne.setMaterial(i,a);let l=n.index,u=1;if(!0===i.wireframe){if(l=ue.getWireframeAttribute(n),void 0===l)return;u=2}const c=n.drawRange,h=n.attributes.position;let d=c.start*u,p=(c.start+c.count)*u;null!==s&&(d=Math.max(d,s.start*u),p=Math.min(p,(s.start+s.count)*u)),null!==l?(d=Math.max(d,0),p=Math.min(p,l.count)):null!=h&&(d=Math.max(d,0),p=Math.min(p,h.count));const f=p-d;if(f<0||f===1/0)return;let m;Pe.setup(r,i,o,n,l);let g=Re;if(null!==l&&(m=le.get(l),g=Ce,g.setIndex(m)),r.isMesh)!0===i.wireframe?(ne.setLineWidth(i.wireframeLinewidth*J()),g.setMode(Oe.LINES)):g.setMode(Oe.TRIANGLES);else if(r.isLine){let e=i.linewidth;void 0===e&&(e=1),ne.setLineWidth(e*J()),r.isLineSegments?g.setMode(Oe.LINES):r.isLineLoop?g.setMode(Oe.LINE_LOOP):g.setMode(Oe.LINE_STRIP)}else r.isPoints?g.setMode(Oe.POINTS):r.isSprite&&g.setMode(Oe.TRIANGLES);if(r.isBatchedMesh)if(null!==r._multiDrawInstances)Yt("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),g.renderMultiDrawInstances(r._multiDrawStarts,r._multiDrawCounts,r._multiDrawCount,r._multiDrawInstances);else if(ee.get("WEBGL_multi_draw"))g.renderMultiDraw(r._multiDrawStarts,r._multiDrawCounts,r._multiDrawCount);else{const e=r._multiDrawStarts,t=r._multiDrawCounts,n=r._multiDrawCount,s=l?le.get(l).bytesPerElement:1,a=re.get(i).currentProgram.getUniforms();for(let i=0;i<n;i++)a.setValue(Oe,"_gl_DrawID",i),g.render(e[i]/s,t[i])}else if(r.isInstancedMesh)g.renderInstances(d,f,r.count);else if(n.isInstancedBufferGeometry){const e=void 0!==n._maxInstanceCount?n._maxInstanceCount:1/0,t=Math.min(n.instanceCount,e);g.renderInstances(d,f,t)}else g.render(d,f)},this.compile=function(e,t,n=null){null===n&&(n=e),x=ve.get(n),x.init(t),S.push(x),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(x.pushLight(e),e.castShadow&&x.pushShadow(e))}),x.setupLights();const i=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;const t=e.material;if(t)if(Array.isArray(t))for(let r=0;r<t.length;r++){const s=t[r];We(s,n,e),i.add(s)}else We(t,n,e),i.add(t)}),x=S.pop(),i},this.compileAsync=function(e,t,n=null){const i=this.compile(e,t,n);return new Promise(t=>{function n(){i.forEach(function(e){re.get(e).currentProgram.isReady()&&i.delete(e)}),0!==i.size?setTimeout(n,10):t(e)}null!==ee.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)})};let $e=null;function Xe(){Ye.stop()}function qe(){Ye.start()}const Ye=new Ya;function Ke(e,t,n,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||W.intersectsSprite(e)){i&&K.setFromMatrixPosition(e.matrixWorld).applyMatrix4(q);const t=ce.update(e),r=e.material;r.visible&&b.push(e,t,r,n,K.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||W.intersectsObject(e))){const t=ce.update(e),r=e.material;if(i&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),K.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),K.copy(t.boundingSphere.center)),K.applyMatrix4(e.matrixWorld).applyMatrix4(q)),Array.isArray(r)){const i=t.groups;for(let s=0,a=i.length;s<a;s++){const a=i[s],o=r[a.materialIndex];o&&o.visible&&b.push(e,t,o,n,K.z,a)}}else r.visible&&b.push(e,t,r,n,K.z,null)}const r=e.children;for(let e=0,s=r.length;e<s;e++)Ke(r[e],t,n,i)}function Ze(e,t,n,i){const{opaque:r,transmissive:s,transparent:a}=e;x.setupLightsView(n),!0===$&&be.setGlobalState(E.clippingPlanes,n),i&&ne.viewport(L.copy(i)),r.length>0&&Je(r,t,n),s.length>0&&Je(s,t,n),a.length>0&&Je(a,t,n),ne.buffers.depth.setTest(!0),ne.buffers.depth.setMask(!0),ne.buffers.color.setMask(!0),ne.setPolygonOffset(!1)}function Qe(e,t,n,i){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;if(void 0===x.state.transmissionRenderTarget[i.id]){const e=ee.has("EXT_color_buffer_half_float")||ee.has("EXT_color_buffer_float");x.state.transmissionRenderTarget[i.id]=new Dn(1,1,{generateMipmaps:!0,type:e?xe:fe,minFilter:pe,samples:Math.max(4,te.samples),stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:bn.workingColorSpace})}const s=x.state.transmissionRenderTarget[i.id],a=i.viewport||L;s.setSize(a.z*E.transmissionResolutionScale,a.w*E.transmissionResolutionScale);const o=E.getRenderTarget(),l=E.getActiveCubeFace(),u=E.getActiveMipmapLevel();E.setRenderTarget(s),E.getClearColor(U),F=E.getClearAlpha(),F<1&&E.setClearColor(16777215,.5),E.clear(),Q&&we.render(n);const c=E.toneMapping;E.toneMapping=0;const h=i.viewport;if(void 0!==i.viewport&&(i.viewport=void 0),x.setupLightsView(i),!0===$&&be.setGlobalState(E.clippingPlanes,i),Je(e,n,i),se.updateMultisampleRenderTarget(s),se.updateRenderTargetMipmap(s),!1===ee.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let r=0,s=t.length;r<s;r++){const s=t[r],{object:a,geometry:o,material:l,group:u}=s;if(2===l.side&&a.layers.test(i.layers)){const t=l.side;l.side=1,l.needsUpdate=!0,et(a,n,i,o,l,u),l.side=t,l.needsUpdate=!0,e=!0}}!0===e&&(se.updateMultisampleRenderTarget(s),se.updateRenderTargetMipmap(s))}E.setRenderTarget(o,l,u),E.setClearColor(U,F),void 0!==h&&(i.viewport=h),E.toneMapping=c}function Je(e,t,n){const i=!0===t.isScene?t.overrideMaterial:null;for(let r=0,s=e.length;r<s;r++){const s=e[r],{object:a,geometry:o,group:l}=s;let u=s.material;!0===u.allowOverride&&null!==i&&(u=i),a.layers.test(n.layers)&&et(a,t,n,o,u,l)}}function et(e,t,n,i,r,s){e.onBeforeRender(E,t,n,i,r,s),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),r.onBeforeRender(E,t,n,i,e,s),!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,r.needsUpdate=!0,E.renderBufferDirect(n,t,i,r,e,s),r.side=0,r.needsUpdate=!0,E.renderBufferDirect(n,t,i,r,e,s),r.side=2):E.renderBufferDirect(n,t,i,r,e,s),e.onAfterRender(E,t,n,i,r,s)}function tt(e,t,n){!0!==t.isScene&&(t=Z);const i=re.get(e),r=x.state.lights,s=x.state.shadowsArray,a=r.state.version,o=de.getParameters(e,r.state,s,t,n),l=de.getProgramCacheKey(o);let u=i.programs;i.environment=e.isMeshStandardMaterial||e.isMeshLambertMaterial||e.isMeshPhongMaterial?t.environment:null,i.fog=t.fog;const c=e.isMeshStandardMaterial||e.isMeshLambertMaterial&&!e.envMap||e.isMeshPhongMaterial&&!e.envMap;i.envMap=oe.get(e.envMap||i.environment,c),i.envMapRotation=null!==i.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation,void 0===u&&(e.addEventListener("dispose",je),u=new Map,i.programs=u);let h=u.get(l);if(void 0!==h){if(i.currentProgram===h&&i.lightsStateVersion===a)return it(e,o),h}else o.uniforms=de.getUniforms(e),e.onBeforeCompile(o,E),h=de.acquireProgram(o,l),u.set(l,h),i.uniforms=o.uniforms;const d=i.uniforms;return(e.isShaderMaterial||e.isRawShaderMaterial)&&!0!==e.clipping||(d.clippingPlanes=be.uniform),it(e,o),i.needsLights=function(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&!0===e.lights}(e),i.lightsStateVersion=a,i.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.directionalShadowMatrix.value=r.state.directionalShadowMatrix,d.spotLightMatrix.value=r.state.spotLightMatrix,d.spotLightMap.value=r.state.spotLightMap,d.pointShadowMatrix.value=r.state.pointShadowMatrix),i.currentProgram=h,i.uniformsList=null,h}function nt(e){if(null===e.uniformsList){const t=e.currentProgram.getUniforms();e.uniformsList=Bl.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function it(e,t){const n=re.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}Ye.setAnimationLoop(function(e){$e&&$e(e)}),"undefined"!=typeof self&&Ye.setContext(self),this.setAnimationLoop=function(e){$e=e,ze.setAnimationLoop(e),null===e?Ye.stop():Ye.start()},ze.addEventListener("sessionstart",Xe),ze.addEventListener("sessionend",qe),this.render=function(e,t){if(void 0!==t&&!0!==t.isCamera)return void qt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(!0===w)return;const n=!0===ze.enabled&&!0===ze.isPresenting,i=null!==M&&(null===C||n)&&M.begin(E,C);if(!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0!==ze.enabled||!0!==ze.isPresenting||null!==M&&!1!==M.isCompositing()||(!0===ze.cameraAutoUpdate&&ze.updateCamera(t),t=ze.getCamera()),!0===e.isScene&&e.onBeforeRender(E,e,t,C),x=ve.get(e,S.length),x.init(t),S.push(x),q.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),W.setFromProjectionMatrix(q,Ft,t.reversedDepth),X=this.localClippingEnabled,$=be.init(this.clippingPlanes,X),b=ge.get(e,T.length),b.init(),T.push(b),!0===ze.enabled&&!0===ze.isPresenting){const e=E.xr.getDepthSensingMesh();null!==e&&Ke(e,t,-1/0,E.sortObjects)}Ke(e,t,0,E.sortObjects),b.finish(),!0===E.sortObjects&&b.sort(z,V),Q=!1===ze.enabled||!1===ze.isPresenting||!1===ze.hasDepthSensing(),Q&&we.addToRenderList(b,e),this.info.render.frame++,!0===$&&be.beginShadows();const r=x.state.shadowsArray;Ee.render(r,e,t),!0===$&&be.endShadows(),!0===this.info.autoReset&&this.info.reset();if(!1===(i&&M.hasRenderPass())){const n=b.opaque,i=b.transmissive;if(x.setupLights(),t.isArrayCamera){const r=t.cameras;if(i.length>0)for(let t=0,s=r.length;t<s;t++){Qe(n,i,e,r[t])}Q&&we.render(e);for(let t=0,n=r.length;t<n;t++){const n=r[t];Ze(b,e,n,n.viewport)}}else i.length>0&&Qe(n,i,e,t),Q&&we.render(e),Ze(b,e,t)}null!==C&&0===R&&(se.updateMultisampleRenderTarget(C),se.updateRenderTargetMipmap(C)),i&&M.end(E),!0===e.isScene&&e.onAfterRender(E,e,t),Pe.resetDefaultState(),N=-1,P=null,S.pop(),S.length>0?(x=S[S.length-1],!0===$&&be.setGlobalState(E.clippingPlanes,x.state.camera)):x=null,T.pop(),b=T.length>0?T[T.length-1]:null},this.getActiveCubeFace=function(){return A},this.getActiveMipmapLevel=function(){return R},this.getRenderTarget=function(){return C},this.setRenderTargetTextures=function(e,t,n){const i=re.get(e);i.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===i.__autoAllocateDepthBuffer&&(i.__useRenderToTexture=!1),re.get(e.texture).__webglTexture=t,re.get(e.depthTexture).__webglTexture=i.__autoAllocateDepthBuffer?void 0:n,i.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){const n=re.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t};const rt=Oe.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){C=e,A=t,R=n;let i=null,r=!1,s=!1;if(e){const a=re.get(e);if(void 0!==a.__useDefaultFramebuffer)return ne.bindFramebuffer(Oe.FRAMEBUFFER,a.__webglFramebuffer),L.copy(e.viewport),D.copy(e.scissor),I=e.scissorTest,ne.viewport(L),ne.scissor(D),ne.setScissorTest(I),void(N=-1);if(void 0===a.__webglFramebuffer)se.setupRenderTarget(e);else if(a.__hasExternalTextures)se.rebindTextures(e,re.get(e.texture).__webglTexture,re.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(a.__boundDepthTexture!==t){if(null!==t&&re.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");se.setupDepthRenderbuffer(e)}}const o=e.texture;(o.isData3DTexture||o.isDataArrayTexture||o.isCompressedArrayTexture)&&(s=!0);const l=re.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(l[t])?l[t][n]:l[t],r=!0):i=e.samples>0&&!1===se.useMultisampledRTT(e)?re.get(e).__webglMultisampledFramebuffer:Array.isArray(l)?l[n]:l,L.copy(e.viewport),D.copy(e.scissor),I=e.scissorTest}else L.copy(G).multiplyScalar(k).floor(),D.copy(H).multiplyScalar(k).floor(),I=j;0!==n&&(i=rt);if(ne.bindFramebuffer(Oe.FRAMEBUFFER,i)&&ne.drawBuffers(e,i),ne.viewport(L),ne.scissor(D),ne.setScissorTest(I),r){const i=re.get(e.texture);Oe.framebufferTexture2D(Oe.FRAMEBUFFER,Oe.COLOR_ATTACHMENT0,Oe.TEXTURE_CUBE_MAP_POSITIVE_X+t,i.__webglTexture,n)}else if(s){const i=t;for(let t=0;t<e.textures.length;t++){const r=re.get(e.textures[t]);Oe.framebufferTextureLayer(Oe.FRAMEBUFFER,Oe.COLOR_ATTACHMENT0+t,r.__webglTexture,n,i)}}else if(null!==e&&0!==n){const t=re.get(e.texture);Oe.framebufferTexture2D(Oe.FRAMEBUFFER,Oe.COLOR_ATTACHMENT0,Oe.TEXTURE_2D,t.__webglTexture,n)}N=-1},this.readRenderTargetPixels=function(e,t,n,i,r,s,a,o=0){if(!e||!e.isWebGLRenderTarget)return void qt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=re.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){ne.bindFramebuffer(Oe.FRAMEBUFFER,l);try{const a=e.textures[o],l=a.format,u=a.type;if(e.textures.length>1&&Oe.readBuffer(Oe.COLOR_ATTACHMENT0+o),!te.textureFormatReadable(l))return void qt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!te.textureTypeReadable(u))return void qt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r&&Oe.readPixels(t,n,i,r,Ne.convert(l),Ne.convert(u),s)}finally{const e=null!==C?re.get(C).__webglFramebuffer:null;ne.bindFramebuffer(Oe.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,i,r,s,a,o=0){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=re.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){if(t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r){ne.bindFramebuffer(Oe.FRAMEBUFFER,l);const a=e.textures[o],u=a.format,c=a.type;if(e.textures.length>1&&Oe.readBuffer(Oe.COLOR_ATTACHMENT0+o),!te.textureFormatReadable(u))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!te.textureTypeReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const h=Oe.createBuffer();Oe.bindBuffer(Oe.PIXEL_PACK_BUFFER,h),Oe.bufferData(Oe.PIXEL_PACK_BUFFER,s.byteLength,Oe.STREAM_READ),Oe.readPixels(t,n,i,r,Ne.convert(u),Ne.convert(c),0);const d=null!==C?re.get(C).__webglFramebuffer:null;ne.bindFramebuffer(Oe.FRAMEBUFFER,d);const p=Oe.fenceSync(Oe.SYNC_GPU_COMMANDS_COMPLETE,0);return Oe.flush(),await function(e,t,n){return new Promise(function(i,r){setTimeout(function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:r();break;case e.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:i()}},n)})}(Oe,p,4),Oe.bindBuffer(Oe.PIXEL_PACK_BUFFER,h),Oe.getBufferSubData(Oe.PIXEL_PACK_BUFFER,0,s),Oe.deleteBuffer(h),Oe.deleteSync(p),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,n=0){const i=Math.pow(2,-n),r=Math.floor(e.image.width*i),s=Math.floor(e.image.height*i),a=null!==t?t.x:0,o=null!==t?t.y:0;se.setTexture2D(e,0),Oe.copyTexSubImage2D(Oe.TEXTURE_2D,n,0,0,a,o,r,s),ne.unbindTexture()};const st=Oe.createFramebuffer(),at=Oe.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,i=null,r=0,s=0){let a,o,l,u,c,h,d,p,f;const m=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)a=n.max.x-n.min.x,o=n.max.y-n.min.y,l=n.isBox3?n.max.z-n.min.z:1,u=n.min.x,c=n.min.y,h=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-r);a=Math.floor(m.width*t),o=Math.floor(m.height*t),l=e.isDataArrayTexture?m.depth:e.isData3DTexture?Math.floor(m.depth*t):1,u=0,c=0,h=0}null!==i?(d=i.x,p=i.y,f=i.z):(d=0,p=0,f=0);const g=Ne.convert(t.format),_=Ne.convert(t.type);let v;t.isData3DTexture?(se.setTexture3D(t,0),v=Oe.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(se.setTexture2DArray(t,0),v=Oe.TEXTURE_2D_ARRAY):(se.setTexture2D(t,0),v=Oe.TEXTURE_2D),Oe.pixelStorei(Oe.UNPACK_FLIP_Y_WEBGL,t.flipY),Oe.pixelStorei(Oe.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),Oe.pixelStorei(Oe.UNPACK_ALIGNMENT,t.unpackAlignment);const y=Oe.getParameter(Oe.UNPACK_ROW_LENGTH),b=Oe.getParameter(Oe.UNPACK_IMAGE_HEIGHT),x=Oe.getParameter(Oe.UNPACK_SKIP_PIXELS),T=Oe.getParameter(Oe.UNPACK_SKIP_ROWS),S=Oe.getParameter(Oe.UNPACK_SKIP_IMAGES);Oe.pixelStorei(Oe.UNPACK_ROW_LENGTH,m.width),Oe.pixelStorei(Oe.UNPACK_IMAGE_HEIGHT,m.height),Oe.pixelStorei(Oe.UNPACK_SKIP_PIXELS,u),Oe.pixelStorei(Oe.UNPACK_SKIP_ROWS,c),Oe.pixelStorei(Oe.UNPACK_SKIP_IMAGES,h);const M=e.isDataArrayTexture||e.isData3DTexture,E=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=re.get(e),i=re.get(t),m=re.get(n.__renderTarget),g=re.get(i.__renderTarget);ne.bindFramebuffer(Oe.READ_FRAMEBUFFER,m.__webglFramebuffer),ne.bindFramebuffer(Oe.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<l;n++)M&&(Oe.framebufferTextureLayer(Oe.READ_FRAMEBUFFER,Oe.COLOR_ATTACHMENT0,re.get(e).__webglTexture,r,h+n),Oe.framebufferTextureLayer(Oe.DRAW_FRAMEBUFFER,Oe.COLOR_ATTACHMENT0,re.get(t).__webglTexture,s,f+n)),Oe.blitFramebuffer(u,c,a,o,d,p,a,o,Oe.DEPTH_BUFFER_BIT,Oe.NEAREST);ne.bindFramebuffer(Oe.READ_FRAMEBUFFER,null),ne.bindFramebuffer(Oe.DRAW_FRAMEBUFFER,null)}else if(0!==r||e.isRenderTargetTexture||re.has(e)){const n=re.get(e),i=re.get(t);ne.bindFramebuffer(Oe.READ_FRAMEBUFFER,st),ne.bindFramebuffer(Oe.DRAW_FRAMEBUFFER,at);for(let e=0;e<l;e++)M?Oe.framebufferTextureLayer(Oe.READ_FRAMEBUFFER,Oe.COLOR_ATTACHMENT0,n.__webglTexture,r,h+e):Oe.framebufferTexture2D(Oe.READ_FRAMEBUFFER,Oe.COLOR_ATTACHMENT0,Oe.TEXTURE_2D,n.__webglTexture,r),E?Oe.framebufferTextureLayer(Oe.DRAW_FRAMEBUFFER,Oe.COLOR_ATTACHMENT0,i.__webglTexture,s,f+e):Oe.framebufferTexture2D(Oe.DRAW_FRAMEBUFFER,Oe.COLOR_ATTACHMENT0,Oe.TEXTURE_2D,i.__webglTexture,s),0!==r?Oe.blitFramebuffer(u,c,a,o,d,p,a,o,Oe.COLOR_BUFFER_BIT,Oe.NEAREST):E?Oe.copyTexSubImage3D(v,s,d,p,f+e,u,c,a,o):Oe.copyTexSubImage2D(v,s,d,p,u,c,a,o);ne.bindFramebuffer(Oe.READ_FRAMEBUFFER,null),ne.bindFramebuffer(Oe.DRAW_FRAMEBUFFER,null)}else E?e.isDataTexture||e.isData3DTexture?Oe.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m.data):t.isCompressedArrayTexture?Oe.compressedTexSubImage3D(v,s,d,p,f,a,o,l,g,m.data):Oe.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m):e.isDataTexture?Oe.texSubImage2D(Oe.TEXTURE_2D,s,d,p,a,o,g,_,m.data):e.isCompressedTexture?Oe.compressedTexSubImage2D(Oe.TEXTURE_2D,s,d,p,m.width,m.height,g,m.data):Oe.texSubImage2D(Oe.TEXTURE_2D,s,d,p,a,o,g,_,m);Oe.pixelStorei(Oe.UNPACK_ROW_LENGTH,y),Oe.pixelStorei(Oe.UNPACK_IMAGE_HEIGHT,b),Oe.pixelStorei(Oe.UNPACK_SKIP_PIXELS,x),Oe.pixelStorei(Oe.UNPACK_SKIP_ROWS,T),Oe.pixelStorei(Oe.UNPACK_SKIP_IMAGES,S),0===s&&t.generateMipmaps&&Oe.generateMipmap(v),ne.unbindTexture()},this.initRenderTarget=function(e){void 0===re.get(e).__webglFramebuffer&&se.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?se.setTextureCube(e,0):e.isData3DTexture?se.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?se.setTexture2DArray(e,0):se.setTexture2D(e,0),ne.unbindTexture()},this.resetState=function(){A=0,R=0,C=null,ne.reset(),Pe.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Ft}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=bn._getDrawingBufferColorSpace(e),t.unpackColorSpace=bn._getUnpackColorSpace()}},Scene:yi,PerspectiveCamera:Sa,Raycaster:Ga,SRGBColorSpace:bt,TextureLoader:class extends oa{constructor(e){super(e)}load(e,t,n,i){const r=new Nn,s=new ua(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(e){r.image=e,r.needsUpdate=!0,void 0!==t&&t(r)},n,i),r}},Vector2:cn,Vector3:dn,Box3:Ii,Color:_i,Mesh:Wr,SphereGeometry:Bs,MeshBasicMaterial:Dr,BackSide:1,Timer:Ba},Rk=Pd({props:{width:{default:window.innerWidth,onChange:function(e,t,n){isNaN(e)&&(t.width=n)}},height:{default:window.innerHeight,onChange:function(e,t,n){isNaN(e)&&(t.height=n)}},viewOffset:{default:[0,0]},backgroundColor:{default:"#000011"},backgroundImageUrl:{},onBackgroundImageLoaded:{},showNavInfo:{default:!0},skyRadius:{default:5e4},objects:{default:[]},lights:{default:[]},enablePointerInteraction:{default:!0,onChange:function(e,t){t.hoverObj=null,t.tooltip&&t.tooltip.content(null)},triggerUpdate:!1},pointerRaycasterThrottleMs:{default:50,triggerUpdate:!1},lineHoverPrecision:{default:1,triggerUpdate:!1},pointsHoverPrecision:{default:1,triggerUpdate:!1},hoverOrderComparator:{triggerUpdate:!1},hoverFilter:{default:function(){return!0},triggerUpdate:!1},tooltipContent:{triggerUpdate:!1},hoverDuringDrag:{default:!1,triggerUpdate:!1},clickAfterDrag:{default:!1,triggerUpdate:!1},onHover:{default:function(){},triggerUpdate:!1},onClick:{default:function(){},triggerUpdate:!1},onRightClick:{triggerUpdate:!1}},methods:{tick:function(e){if(e.initialised){e.controls.enabled&&e.controls.update&&e.controls.update(Math.min(1,e.timer.update().getDelta())),e.postProcessingComposer?e.postProcessingComposer.render():e.renderer.render(e.scene,e.camera),e.extraRenderers.forEach(function(t){return t.render(e.scene,e.camera)});var t=+new Date;if(e.enablePointerInteraction&&t-e.lastRaycasterCheck>=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;var n=null;if(e.hoverDuringDrag||!e.isPointerDragging){var i=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&i.sort(function(t,n){return e.hoverOrderComparator(t.object,n.object)});var r=i.find(function(t){return e.hoverFilter(t.object)})||null;n=r?r.object:null,e.intersection=r||null}n!==e.hoverObj&&(e.onHover(n,e.hoverObj,e.intersection),e.tooltip.content(n&&Ld(e.tooltipContent)(n,e.intersection)||null),e.hoverObj=n)}e.tweenGroup.update()}return this},getPointerPos:function(e){var t=e.pointerPos;return{x:t.x,y:t.y}},cameraPosition:function(e,t,n,i){var r=e.camera;if(t&&e.initialised){var s=t,a=n||{x:0,y:0,z:0};if(i){var o=Object.assign({},r.position),l=h();e.tweenGroup.add(new hO(o).to(s,i).easing(sO.Quadratic.Out).onUpdate(u).onComplete(function(){e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(new hO(l).to(a,i/3).easing(sO.Quadratic.Out).onUpdate(c).onComplete(function(){e.tweenGroup.remove(this)}).start())}else u(s),c(a);return this}return Object.assign({},r.position,{lookAt:h()});function u(e){var t=e.x,n=e.y,i=e.z;void 0!==t&&(r.position.x=t),void 0!==n&&(r.position.y=n),void 0!==i&&(r.position.z=i)}function c(t){var n=new Ak.Vector3(t.x,t.y,t.z);e.controls.enabled&&e.controls.target?e.controls.target=n:r.lookAt(n)}function h(){return Object.assign(new Ak.Vector3(0,0,-1e3).applyQuaternion(r.quaternion).add(r.position))}},zoomToFit:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10,i=arguments.length,r=new Array(i>3?i-3:0),s=3;s<i;s++)r[s-3]=arguments[s];return this.fitToBbox(this.getBbox.apply(this,r),t,n)},fitToBbox:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:10,r=e.camera;if(t){var s=new Ak.Vector3(0,0,0),a=2*Math.max.apply(Math,Sk(Object.entries(t).map(function(e){var t=Tk(e,2),n=t[0],i=t[1];return Math.max.apply(Math,Sk(i.map(function(e){return Math.abs(s[n]-e)})))}))),o=(1-2*i/e.height)*r.fov,l=a/Math.atan(o*Math.PI/180),u=l/r.aspect,c=Math.max(l,u);if(c>0){var h=s.clone().sub(r.position).normalize().multiplyScalar(-c);this.cameraPosition(h,s,n)}}return this},getBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0},n=new Ak.Box3(new Ak.Vector3(0,0,0),new Ak.Vector3(0,0,0)),i=e.objects.filter(t);return i.length?(i.forEach(function(e){return n.expandByObject(e)}),Object.assign.apply(Object,Sk(["x","y","z"].map(function(e){return xk({},e,[n.min[e],n.max[e]])})))):null},getScreenCoords:function(e,t,n,i){var r=new Ak.Vector3(t,n,i);return r.project(this.camera()),{x:(r.x+1)*e.width/2,y:-(r.y-1)*e.height/2}},getSceneCoords:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=new Ak.Vector2(t/e.width*2-1,-n/e.height*2+1),s=new Ak.Raycaster;return s.setFromCamera(r,e.camera),Object.assign({},s.ray.at(i,new Ak.Vector3))},intersectingObjects:function(e,t,n){var i=new Ak.Vector2(t/e.width*2-1,-n/e.height*2+1),r=new Ak.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,r.params.Points.threshold=e.pointsHoverPrecision,r.setFromCamera(i,e.camera),r.intersectObjects(e.objects,!0)},renderer:function(e){return e.renderer},scene:function(e){return e.scene},camera:function(e){return e.camera},postProcessingComposer:function(e){return e.postProcessingComposer},controls:function(e){return e.controls},tbControls:function(e){return e.controls},_destructor:function(e){var t,n,i;!function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),wk(t)}}(e.scene),null===(t=e.controls)||void 0===t||t.dispose(),null===(n=e.renderer)||void 0===n||n.dispose(),null===(i=e.postProcessingComposer)||void 0===i||i.dispose()}},stateInit:function(){return{scene:new Ak.Scene,camera:new Ak.PerspectiveCamera,timer:new Ak.Timer,tweenGroup:new oO,lastRaycasterCheck:0}},init:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=n.controlType,r=void 0===i?"trackball":i,s=n.useWebGPU,a=void 0!==s&&s,o=n.rendererConfig,l=void 0===o?{}:o,u=n.extraRenderers,c=void 0===u?[]:u,h=n.waitForLoadComplete,d=void 0===h||h;e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[r]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new yk(t.container),t.pointerPos=new Ak.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(function(e){return t.container.addEventListener(e,function(n){if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===n.type&&(n.pressure>0||t.isPointerPressed)&&("mouse"===n.pointerType||void 0===n.movementX||[n.movementX,n.movementY].some(function(e){return Math.abs(e)>1}))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var i=(r=t.container,s=r.getBoundingClientRect(),a=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,{top:s.top+o,left:s.left+a});t.pointerPos.x=n.pageX-i.left,t.pointerPos.y=n.pageY-i.top}var r,s,a,o},{passive:!0})}),t.container.addEventListener("pointerup",function(e){t.isPointerPressed&&(t.isPointerPressed=!1,t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag)||requestAnimationFrame(function(){0===e.button&&t.onClick(t.hoverObj||null,e,t.intersection),2===e.button&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",function(e){t.onRightClick&&e.preventDefault()}),t.renderer=new(a?HI:Ak.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},l)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=c,t.extraRenderers.forEach(function(e){e.domElement.style.position="absolute",e.domElement.style.top="0px",e.domElement.style.pointerEvents="none",t.container.appendChild(e.domElement)}),t.postProcessingComposer=new bF(t.renderer),t.postProcessingComposer.addPass(new xF(t.scene,t.camera)),t.controls=new{trackball:cU,orbit:GU,fly:rF}[r](t.camera,t.renderer.domElement),"fly"===r&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==r&&"orbit"!==r||(t.controls.minDistance=.1,t.controls.maxDistance=t.skyRadius,t.controls.addEventListener("start",function(){t.controlsEngaged=!0}),t.controls.addEventListener("change",function(){t.controlsEngaged&&(t.controlsDragging=!0)}),t.controls.addEventListener("end",function(){t.controlsEngaged=!1,t.controlsDragging=!1})),[t.renderer,t.postProcessingComposer].concat(Sk(t.extraRenderers)).forEach(function(e){return e.setSize(t.width,t.height)}),t.camera.aspect=t.width/t.height,t.camera.updateProjectionMatrix(),t.camera.position.z=1e3,t.scene.add(t.skysphere=new Ak.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!d,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var n,i=e.width,r=e.height;e.container.style.width="".concat(i,"px"),e.container.style.height="".concat(r,"px"),[e.renderer,e.postProcessingComposer].concat(Sk(e.extraRenderers)).forEach(function(e){return e.setSize(i,r)}),e.camera.aspect=i/r;var s=e.viewOffset.slice(0,2);s.some(function(e){return e})&&(n=e.camera).setViewOffset.apply(n,[i,r].concat(Sk(s),[i,r])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var a,o=e.width,l=e.height,u=e.viewOffset.slice(0,2);u.some(function(e){return e})?(a=e.camera).setViewOffset.apply(a,[o,l].concat(Sk(u),[o,l])):e.camera.clearViewOffset()}if(t.hasOwnProperty("skyRadius")&&e.skyRadius&&(e.controls.hasOwnProperty("maxDistance")&&t.skyRadius&&(e.controls.maxDistance=Math.min(e.controls.maxDistance,e.skyRadius)),e.camera.far=2.5*e.skyRadius,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new Ak.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=GF(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new Ak.Color(rO(1,e.backgroundColor)),c)}function h(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new Ak.TextureLoader).load(e.backgroundImageUrl,function(t){t.colorSpace=Ak.SRGBColorSpace,e.skysphere.material=new Ak.MeshBasicMaterial({map:t,side:Ak.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&h()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&h())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach(function(t){return e.scene.remove(t)}),e.lights.forEach(function(t){return e.scene.add(t)})),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(function(t){return e.scene.remove(t)}),e.objects.forEach(function(t){return e.scene.add(t)}))}});function Ck(e,t){var n=new t;return n._destructor&&n._destructor(),{linkProp:function(t){return{default:n[t](),onChange:function(n,i){i[e][t](n)},triggerUpdate:!1}},linkMethod:function(t){return function(n){for(var i=n[e],r=arguments.length,s=new Array(r>1?r-1:0),a=1;a<r;a++)s[a-1]=arguments[a];var o=i[t].apply(i,s);return o===i?this:o}}}}var Nk=window.THREE?window.THREE:{AmbientLight:Pa,DirectionalLight:Na,REVISION:s},Pk=Ck("forceGraph",Sf),Lk=Object.assign.apply(Object,r(["jsonUrl","graphData","numDimensions","dagMode","dagLevelDistance","dagNodeFilter","onDagError","nodeRelSize","nodeId","nodeVal","nodeResolution","nodeColor","nodeAutoColorBy","nodeOpacity","nodeVisibility","nodeThreeObject","nodeThreeObjectExtend","nodePositionUpdate","linkSource","linkTarget","linkVisibility","linkColor","linkAutoColorBy","linkOpacity","linkWidth","linkResolution","linkCurvature","linkCurveRotation","linkMaterial","linkThreeObject","linkThreeObjectExtend","linkPositionUpdate","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowRelPos","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleSpeed","linkDirectionalParticleOffset","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject","forceEngine","d3AlphaDecay","d3VelocityDecay","d3AlphaMin","ngraphPhysics","warmupTicks","cooldownTicks","cooldownTime","onEngineTick","onEngineStop"].map(function(e){return t({},e,Pk.linkProp(e))}))),Dk=Object.assign.apply(Object,r(["refresh","getGraphBbox","d3Force","d3ReheatSimulation","emitParticle"].map(function(e){return t({},e,Pk.linkMethod(e))}))),Ik=Ck("renderObjs",Rk),Uk=Object.assign.apply(Object,r(["width","height","backgroundColor","showNavInfo","enablePointerInteraction"].map(function(e){return t({},e,Ik.linkProp(e))}))),Fk=Object.assign.apply(Object,r(["lights","cameraPosition","postProcessingComposer"].map(function(e){return t({},e,Ik.linkMethod(e))})).concat([{graph2ScreenCoords:Ik.linkMethod("getScreenCoords"),screen2GraphCoords:Ik.linkMethod("getSceneCoords")}])),Ok=Pd({props:i(i({nodeLabel:{default:"name",triggerUpdate:!1},linkLabel:{default:"name",triggerUpdate:!1},linkHoverPrecision:{default:1,onChange:function(e,t){return t.renderObjs.lineHoverPrecision(e)},triggerUpdate:!1},enableNavigationControls:{default:!0,onChange:function(e,t){var n=t.renderObjs.controls();n&&(n.enabled=e,e&&n.domElement&&n.domElement.dispatchEvent(new PointerEvent("pointerup")))},triggerUpdate:!1},enableNodeDrag:{default:!0,triggerUpdate:!1},onNodeDrag:{default:function(){},triggerUpdate:!1},onNodeDragEnd:{default:function(){},triggerUpdate:!1},onNodeClick:{triggerUpdate:!1},onNodeRightClick:{triggerUpdate:!1},onNodeHover:{triggerUpdate:!1},onLinkClick:{triggerUpdate:!1},onLinkRightClick:{triggerUpdate:!1},onLinkHover:{triggerUpdate:!1},onBackgroundClick:{triggerUpdate:!1},onBackgroundRightClick:{triggerUpdate:!1},showPointerCursor:{default:!0,triggerUpdate:!1}},Lk),Uk),methods:i(i({zoomToFit:function(e,t,n){for(var i,r=arguments.length,s=new Array(r>3?r-3:0),a=3;a<r;a++)s[a-3]=arguments[a];return e.renderObjs.fitToBbox((i=e.forceGraph).getGraphBbox.apply(i,s),t,n),this},pauseAnimation:function(e){return null!==e.animationFrameRequestId&&(cancelAnimationFrame(e.animationFrameRequestId),e.animationFrameRequestId=null),this},resumeAnimation:function(e){return null===e.animationFrameRequestId&&this._animationCycle(),this},_animationCycle:function(e){e.enablePointerInteraction&&(this.renderer().domElement.style.cursor=null),e.forceGraph.tickFrame(),e.renderObjs.tick(),e.animationFrameRequestId=requestAnimationFrame(this._animationCycle)},scene:function(e){return e.renderObjs.scene()},camera:function(e){return e.renderObjs.camera()},renderer:function(e){return e.renderObjs.renderer()},controls:function(e){return e.renderObjs.controls()},_destructor:function(e){var t,n;this.pauseAnimation(),this.graphData({nodes:[],links:[]}),null===(t=(n=e.forceGraph)._destructor)||void 0===t||t.call(n),e.renderObjs._destructor()}},Dk),Fk),stateInit:function(e){var t=e.controlType,n=e.rendererConfig,i=e.extraRenderers,r=new Sf;return{forceGraph:r,renderObjs:Rk({controlType:t,rendererConfig:n,extraRenderers:i}).objects([r]).lights([new Nk.AmbientLight(13421772,Math.PI),new Nk.DirectionalLight(16777215,.6*Math.PI)])}},init:function(e,t){e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.style.position="relative";var n=document.createElement("div");t.container.appendChild(n),t.renderObjs(n);var i,r=t.renderObjs.camera(),s=t.renderObjs.renderer(),a=t.renderObjs.controls();a.enabled=!!t.enableNavigationControls,t.lastSetCameraZ=r.position.z,t.container.appendChild(i=document.createElement("div")),i.className="graph-info-msg",i.textContent="",t.forceGraph.onLoading(function(){i.textContent="Loading..."}).onFinishLoading(function(){i.textContent=""}).onUpdate(function(){t.graphData=t.forceGraph.graphData(),0===r.position.x&&0===r.position.y&&r.position.z===t.lastSetCameraZ&&t.graphData.nodes.length&&(r.lookAt(t.forceGraph.position),t.lastSetCameraZ=r.position.z=170*Math.cbrt(t.graphData.nodes.length))}).onFinishUpdate(function(){if(t._dragControls){var e=t.graphData.nodes.find(function(e){return e.__initialFixedPos&&!e.__disposeControlsAfterDrag});e?e.__disposeControlsAfterDrag=!0:t._dragControls.dispose(),t._dragControls=void 0}if(t.enableNodeDrag&&t.enablePointerInteraction&&"d3"===t.forceEngine){var n=t._dragControls=new rc(t.graphData.nodes.map(function(e){return e.__threeObj}).filter(function(e){return e}),r,s.domElement);n.addEventListener("dragstart",function(e){var t=Bk(e.object);if(t){a.enabled=!1,e.object.__initialPos=e.object.position.clone(),e.object.__prevPos=e.object.position.clone();var n=t.__data;!n.__initialFixedPos&&(n.__initialFixedPos={fx:n.fx,fy:n.fy,fz:n.fz}),!n.__initialPos&&(n.__initialPos={x:n.x,y:n.y,z:n.z}),["x","y","z"].forEach(function(e){return n["f".concat(e)]=n[e]}),s.domElement.classList.add("grabbable")}}),n.addEventListener("drag",function(e){var n=Bk(e.object);if(n){if(!e.object.hasOwnProperty("__graphObjType")){var i=e.object.__initialPos,r=e.object.__prevPos,s=e.object.position;n.position.add(s.clone().sub(r)),r.copy(s),s.copy(i)}var a=n.__data,o=n.position,l={x:o.x-a.x,y:o.y-a.y,z:o.z-a.z};["x","y","z"].forEach(function(e){return a["f".concat(e)]=a[e]=o[e]}),t.forceGraph.d3AlphaTarget(.3).resetCountdown(),a.__dragged=!0,t.onNodeDrag(a,l)}}),n.addEventListener("dragend",function(e){var i=Bk(e.object);if(i){delete e.object.__initialPos,delete e.object.__prevPos;var r=i.__data;r.__disposeControlsAfterDrag&&(n.dispose(),delete r.__disposeControlsAfterDrag);var o,l=r.__initialFixedPos,u=r.__initialPos,c={x:u.x-r.x,y:u.y-r.y,z:u.z-r.z};if(l&&(["x","y","z"].forEach(function(e){var t="f".concat(e);void 0===l[t]&&delete r[t]}),delete r.__initialFixedPos,delete r.__initialPos,r.__dragged&&(delete r.__dragged,t.onNodeDragEnd(r,c))),t.forceGraph.d3AlphaTarget(0).resetCountdown(),t.enableNavigationControls)a.enabled=!0,a._status&&(null===(o=a._onPointerCancel)||void 0===o||o.call(a)),a.domElement&&a.domElement.ownerDocument&&a.domElement.ownerDocument.dispatchEvent(new PointerEvent("pointerup",{pointerType:"touch"}));s.domElement.classList.remove("grabbable")}})}}),Nk.REVISION<155&&(t.renderObjs.renderer().useLegacyLights=!1),t.renderObjs.hoverOrderComparator(function(e,t){var n=Bk(e);if(!n)return 1;var i=Bk(t);if(!i)return-1;var r=function(e){return"node"===e.__graphObjType};return r(i)-r(n)}).tooltipContent(function(e){var n=Bk(e);return n&&Ld(t["".concat(n.__graphObjType,"Label")])(n.__data)||""}).hoverDuringDrag(!1).onHover(function(e){var n=Bk(e);if(n!==t.hoverObj){var i=t.hoverObj?t.hoverObj.__graphObjType:null,r=t.hoverObj?t.hoverObj.__data:null,a=n?n.__graphObjType:null,o=n?n.__data:null;if(i&&i!==a){var l=t["on".concat("node"===i?"Node":"Link","Hover")];l&&l(null,r)}if(a){var u=t["on".concat("node"===a?"Node":"Link","Hover")];u&&u(o,i===a?r:null)}s.domElement.classList[(n&&t["on".concat("node"===a?"Node":"Link","Click")]||!n&&t.onBackgroundClick)&&Ld(t.showPointerCursor)(o)?"add":"remove"]("clickable"),t.hoverObj=n}}).clickAfterDrag(!1).onClick(function(e,n){var i=Bk(e);if(i){var r=t["on".concat("node"===i.__graphObjType?"Node":"Link","Click")];r&&r(i.__data,n)}else t.onBackgroundClick&&t.onBackgroundClick(n)}).onRightClick(function(e,n){var i=Bk(e);if(i){var r=t["on".concat("node"===i.__graphObjType?"Node":"Link","RightClick")];r&&r(i.__data,n)}else t.onBackgroundRightClick&&t.onBackgroundRightClick(n)}),this._animationCycle()}});function Bk(e){for(var t=e;t&&!t.hasOwnProperty("__graphObjType");)t=t.parent;return t}return Ok});
|